diff --git "a/swe-bench-verified/mwaskom#seaborn#54cab15bdacfaa05a88fbc5502a5b322d99f148e.graph.json" "b/swe-bench-verified/mwaskom#seaborn#54cab15bdacfaa05a88fbc5502a5b322d99f148e.graph.json" new file mode 100644--- /dev/null +++ "b/swe-bench-verified/mwaskom#seaborn#54cab15bdacfaa05a88fbc5502a5b322d99f148e.graph.json" @@ -0,0 +1 @@ +{"edges":[{"edgeType":"contains","source":1160,"target":1896},{"edgeType":"calls","source":2286,"target":384},{"edgeType":"calls","source":848,"target":566},{"edgeType":"calls","source":4310,"target":1063},{"edgeType":"contains","source":3775,"target":1167},{"edgeType":"contains","source":28,"target":3162},{"edgeType":"calls","source":505,"target":629},{"edgeType":"contains","source":3594,"target":3607},{"edgeType":"contains","source":4221,"target":4254},{"edgeType":"calls","source":2792,"target":554},{"edgeType":"contains","source":4816,"target":4835},{"edgeType":"calls","source":4844,"target":365},{"edgeType":"contains","source":3120,"target":330},{"edgeType":"calls","source":4701,"target":570},{"edgeType":"calls","source":4594,"target":716},{"edgeType":"calls","source":2295,"target":106},{"edgeType":"calls","source":2286,"target":385},{"edgeType":"calls","source":3095,"target":675},{"edgeType":"extends","source":4166,"target":4153},{"edgeType":"calls","source":3265,"target":690},{"edgeType":"imports","source":3571,"target":1227},{"edgeType":"calls","source":4111,"target":4061},{"edgeType":"calls","source":4594,"target":715},{"edgeType":"contains","source":4816,"target":4834},{"edgeType":"contains","source":1160,"target":1894},{"edgeType":"calls","source":4701,"target":569},{"edgeType":"calls","source":848,"target":568},{"edgeType":"calls","source":4469,"target":1417},{"edgeType":"contains","source":2481,"target":3225},{"edgeType":"calls","source":2286,"target":382},{"edgeType":"calls","source":3528,"target":991},{"edgeType":"calls","source":1498,"target":502},{"edgeType":"contains","source":4086,"target":4208},{"edgeType":"calls","source":3371,"target":572},{"edgeType":"calls","source":4268,"target":248},{"edgeType":"calls","source":3299,"target":690},{"edgeType":"contains","source":4816,"target":4833},{"edgeType":"contains","source":621,"target":637},{"edgeType":"calls","source":4609,"target":249},{"edgeType":"calls","source":4594,"target":714},{"edgeType":"calls","source":4446,"target":4245},{"edgeType":"contains","source":3120,"target":328},{"edgeType":"calls","source":4538,"target":336},{"edgeType":"calls","source":4701,"target":568},{"edgeType":"calls","source":374,"target":464},{"edgeType":"contains","source":1249,"target":1250},{"edgeType":"calls","source":848,"target":567},{"edgeType":"calls","source":4428,"target":573},{"edgeType":"calls","source":2286,"target":383},{"edgeType":"imports","source":2230,"target":511},{"edgeType":"calls","source":1725,"target":863},{"edgeType":"calls","source":1508,"target":191},{"edgeType":"contains","source":4086,"target":4207},{"edgeType":"calls","source":1528,"target":628},{"edgeType":"contains","source":4221,"target":4250},{"edgeType":"calls","source":1235,"target":1254},{"edgeType":"calls","source":4268,"target":249},{"edgeType":"contains","source":4816,"target":4832},{"edgeType":"calls","source":4609,"target":248},{"edgeType":"calls","source":4594,"target":713},{"edgeType":"calls","source":4701,"target":567},{"edgeType":"calls","source":4878,"target":365},{"edgeType":"calls","source":2656,"target":2655},{"edgeType":"calls","source":4576,"target":1269},{"edgeType":"calls","source":4572,"target":336},{"edgeType":"calls","source":1498,"target":496},{"edgeType":"calls","source":3677,"target":1655},{"edgeType":"contains","source":3594,"target":3611},{"edgeType":"calls","source":2729,"target":389},{"edgeType":"contains","source":2075,"target":2076},{"edgeType":"calls","source":3371,"target":570},{"edgeType":"calls","source":1498,"target":495},{"edgeType":"calls","source":4701,"target":566},{"edgeType":"calls","source":4594,"target":712},{"edgeType":"calls","source":4821,"target":4245},{"edgeType":"calls","source":4809,"target":389},{"edgeType":"contains","source":4816,"target":4839},{"edgeType":"calls","source":3789,"target":298},{"edgeType":"contains","source":3099,"target":3101},{"edgeType":"contains","source":3066,"target":3067},{"edgeType":"calls","source":3850,"target":3692},{"edgeType":"calls","source":3546,"target":1489},{"edgeType":"imports","source":396,"target":285},{"edgeType":"contains","source":4189,"target":4192},{"edgeType":"calls","source":624,"target":106},{"edgeType":"calls","source":1498,"target":494},{"edgeType":"calls","source":3371,"target":571},{"edgeType":"imports","source":3002,"target":3003},{"edgeType":"calls","source":2887,"target":777},{"edgeType":"calls","source":4597,"target":1675},{"edgeType":"calls","source":4727,"target":1873},{"edgeType":"calls","source":4809,"target":388},{"edgeType":"contains","source":4816,"target":4838},{"edgeType":"calls","source":4242,"target":4222},{"edgeType":"calls","source":1698,"target":640},{"edgeType":"calls","source":1759,"target":863},{"edgeType":"contains","source":6,"target":680},{"edgeType":"contains","source":4189,"target":4191},{"edgeType":"calls","source":2656,"target":2650},{"edgeType":"calls","source":2729,"target":387},{"edgeType":"contains","source":3413,"target":3935},{"edgeType":"calls","source":3445,"target":388},{"edgeType":"calls","source":1235,"target":1251},{"edgeType":"calls","source":3371,"target":568},{"edgeType":"calls","source":4809,"target":387},{"edgeType":"contains","source":4816,"target":4837},{"edgeType":"calls","source":4631,"target":1675},{"edgeType":"calls","source":4637,"target":1489},{"edgeType":"contains","source":1160,"target":1901},{"edgeType":"calls","source":1873,"target":499},{"edgeType":"contains","source":2174,"target":2177},{"edgeType":"contains","source":4189,"target":4190},{"edgeType":"calls","source":2729,"target":388},{"edgeType":"calls","source":3371,"target":569},{"edgeType":"contains","source":2269,"target":2403},{"edgeType":"calls","source":3445,"target":389},{"edgeType":"calls","source":4713,"target":191},{"edgeType":"contains","source":621,"target":640},{"edgeType":"calls","source":4803,"target":572},{"edgeType":"calls","source":4809,"target":386},{"edgeType":"contains","source":4816,"target":4836},{"edgeType":"calls","source":2493,"target":301},{"edgeType":"calls","source":2322,"target":317},{"edgeType":"calls","source":4330,"target":435},{"edgeType":"calls","source":4336,"target":249},{"edgeType":"calls","source":4136,"target":106},{"edgeType":"calls","source":4227,"target":456},{"edgeType":"calls","source":4875,"target":3624},{"edgeType":"calls","source":1498,"target":491},{"edgeType":"calls","source":2729,"target":385},{"edgeType":"calls","source":658,"target":106},{"edgeType":"calls","source":3371,"target":566},{"edgeType":"contains","source":43,"target":3763},{"edgeType":"calls","source":1269,"target":191},{"edgeType":"contains","source":798,"target":1498},{"edgeType":"calls","source":4803,"target":571},{"edgeType":"calls","source":4809,"target":385},{"edgeType":"calls","source":3439,"target":572},{"edgeType":"calls","source":3445,"target":386},{"edgeType":"calls","source":3231,"target":1735},{"edgeType":"calls","source":1133,"target":179},{"edgeType":"calls","source":4591,"target":1856},{"edgeType":"calls","source":1657,"target":847},{"edgeType":"contains","source":1160,"target":1903},{"edgeType":"calls","source":587,"target":191},{"edgeType":"calls","source":4412,"target":1063},{"edgeType":"calls","source":4065,"target":194},{"edgeType":"calls","source":4330,"target":434},{"edgeType":"contains","source":1535,"target":4022},{"edgeType":"calls","source":4336,"target":248},{"edgeType":"contains","source":3413,"target":3940},{"edgeType":"calls","source":3445,"target":387},{"edgeType":"calls","source":2729,"target":386},{"edgeType":"calls","source":784,"target":427},{"edgeType":"calls","source":2633,"target":191},{"edgeType":"contains","source":2174,"target":2183},{"edgeType":"calls","source":4803,"target":570},{"edgeType":"calls","source":4809,"target":384},{"edgeType":"calls","source":3371,"target":567},{"edgeType":"contains","source":621,"target":642},{"edgeType":"calls","source":1169,"target":1176},{"edgeType":"contains","source":2269,"target":2409},{"edgeType":"imports","source":3571,"target":1219},{"edgeType":"contains","source":3099,"target":3102},{"edgeType":"calls","source":1735,"target":546},{"edgeType":"calls","source":4602,"target":457},{"edgeType":"contains","source":886,"target":887},{"edgeType":"calls","source":411,"target":365},{"edgeType":"calls","source":4671,"target":1489},{"edgeType":"calls","source":4803,"target":568},{"edgeType":"calls","source":4809,"target":382},{"edgeType":"calls","source":2729,"target":382},{"edgeType":"calls","source":4453,"target":1905},{"edgeType":"contains","source":3594,"target":3613},{"edgeType":"calls","source":2322,"target":315},{"edgeType":"calls","source":2326,"target":191},{"edgeType":"calls","source":4250,"target":1856},{"edgeType":"contains","source":3428,"target":3474},{"edgeType":"calls","source":4844,"target":3526},{"edgeType":"calls","source":1498,"target":493},{"edgeType":"contains","source":4221,"target":4260},{"edgeType":"calls","source":2729,"target":383},{"edgeType":"contains","source":4284,"target":4421},{"edgeType":"calls","source":4803,"target":569},{"edgeType":"calls","source":4809,"target":383},{"edgeType":"calls","source":3439,"target":570},{"edgeType":"calls","source":3445,"target":384},{"edgeType":"calls","source":3371,"target":564},{"edgeType":"calls","source":374,"target":454},{"edgeType":"calls","source":4602,"target":456},{"edgeType":"contains","source":919,"target":920},{"edgeType":"calls","source":3838,"target":887},{"edgeType":"calls","source":4803,"target":567},{"edgeType":"calls","source":2322,"target":316},{"edgeType":"calls","source":2671,"target":1124},{"edgeType":"calls","source":1989,"target":1127},{"edgeType":"calls","source":4299,"target":336},{"edgeType":"contains","source":3413,"target":3938},{"edgeType":"calls","source":1498,"target":492},{"edgeType":"contains","source":4149,"target":4377},{"edgeType":"contains","source":2075,"target":2079},{"edgeType":"calls","source":2729,"target":384},{"edgeType":"calls","source":905,"target":906},{"edgeType":"calls","source":3439,"target":571},{"edgeType":"calls","source":3445,"target":385},{"edgeType":"contains","source":919,"target":923},{"edgeType":"calls","source":4639,"target":365},{"edgeType":"calls","source":4642,"target":4500},{"edgeType":"contains","source":3594,"target":3619},{"edgeType":"calls","source":4803,"target":566},{"edgeType":"calls","source":2656,"target":2643},{"edgeType":"calls","source":4576,"target":1261},{"edgeType":"calls","source":3630,"target":2046},{"edgeType":"calls","source":2985,"target":901},{"edgeType":"contains","source":1811,"target":1812},{"edgeType":"calls","source":1499,"target":456},{"edgeType":"calls","source":3439,"target":568},{"edgeType":"calls","source":3445,"target":382},{"edgeType":"calls","source":1877,"target":365},{"edgeType":"calls","source":1810,"target":1385},{"edgeType":"calls","source":3875,"target":1852},{"edgeType":"calls","source":3912,"target":705},{"edgeType":"contains","source":919,"target":922},{"edgeType":"calls","source":4487,"target":1905},{"edgeType":"calls","source":4530,"target":572},{"edgeType":"calls","source":4850,"target":2279},{"edgeType":"calls","source":4878,"target":354},{"edgeType":"calls","source":4570,"target":389},{"edgeType":"calls","source":2985,"target":902},{"edgeType":"calls","source":2998,"target":499},{"edgeType":"calls","source":2772,"target":106},{"edgeType":"calls","source":3439,"target":569},{"edgeType":"calls","source":3445,"target":383},{"edgeType":"calls","source":3124,"target":1878},{"edgeType":"calls","source":3330,"target":777},{"edgeType":"contains","source":2292,"target":2757},{"edgeType":"calls","source":3296,"target":774},{"edgeType":"contains","source":919,"target":925},{"edgeType":"calls","source":4771,"target":499},{"edgeType":"calls","source":4781,"target":189},{"edgeType":"contains","source":3099,"target":3106},{"edgeType":"calls","source":4229,"target":388},{"edgeType":"calls","source":4875,"target":446},{"edgeType":"calls","source":4878,"target":353},{"edgeType":"imports","source":97,"target":45},{"edgeType":"calls","source":4396,"target":2611},{"edgeType":"calls","source":4570,"target":388},{"edgeType":"calls","source":4530,"target":571},{"edgeType":"calls","source":2278,"target":1675},{"edgeType":"calls","source":784,"target":426},{"edgeType":"contains","source":2264,"target":451},{"edgeType":"calls","source":3888,"target":388},{"edgeType":"calls","source":3439,"target":566},{"edgeType":"contains","source":886,"target":890},{"edgeType":"calls","source":4815,"target":191},{"edgeType":"calls","source":1167,"target":179},{"edgeType":"calls","source":4570,"target":387},{"edgeType":"calls","source":4892,"target":2032},{"edgeType":"calls","source":4152,"target":1719},{"edgeType":"calls","source":4229,"target":389},{"edgeType":"calls","source":4875,"target":445},{"edgeType":"calls","source":4673,"target":365},{"edgeType":"calls","source":2360,"target":191},{"edgeType":"calls","source":4530,"target":570},{"edgeType":"calls","source":4659,"target":1856},{"edgeType":"imports","source":97,"target":46},{"edgeType":"calls","source":784,"target":425},{"edgeType":"calls","source":2242,"target":1735},{"edgeType":"calls","source":692,"target":106},{"edgeType":"calls","source":2985,"target":900},{"edgeType":"contains","source":422,"target":475},{"edgeType":"calls","source":1738,"target":447},{"edgeType":"contains","source":2174,"target":2185},{"edgeType":"calls","source":3888,"target":389},{"edgeType":"contains","source":4149,"target":4381},{"edgeType":"calls","source":3792,"target":194},{"edgeType":"contains","source":43,"target":3768},{"edgeType":"calls","source":3439,"target":567},{"edgeType":"calls","source":1261,"target":464},{"edgeType":"calls","source":4782,"target":189},{"edgeType":"contains","source":819,"target":823},{"edgeType":"contains","source":4221,"target":4237},{"edgeType":"calls","source":3417,"target":222},{"edgeType":"calls","source":4230,"target":388},{"edgeType":"calls","source":4571,"target":388},{"edgeType":"contains","source":2735,"target":2736},{"edgeType":"calls","source":311,"target":317},{"edgeType":"calls","source":411,"target":388},{"edgeType":"calls","source":2868,"target":1385},{"edgeType":"contains","source":4750,"target":4751},{"edgeType":"calls","source":4679,"target":211},{"edgeType":"calls","source":4537,"target":385},{"edgeType":"calls","source":4714,"target":183},{"edgeType":"contains","source":482,"target":699},{"edgeType":"calls","source":4435,"target":376},{"edgeType":"contains","source":2699,"target":2794},{"edgeType":"calls","source":1159,"target":454},{"edgeType":"calls","source":4134,"target":194},{"edgeType":"contains","source":3527,"target":3552},{"edgeType":"contains","source":819,"target":822},{"edgeType":"calls","source":3204,"target":484},{"edgeType":"calls","source":4230,"target":389},{"edgeType":"calls","source":4571,"target":387},{"edgeType":"calls","source":411,"target":387},{"edgeType":"contains","source":4816,"target":4818},{"edgeType":"calls","source":2500,"target":1167},{"edgeType":"calls","source":4537,"target":384},{"edgeType":"calls","source":4660,"target":1856},{"edgeType":"calls","source":2243,"target":1735},{"edgeType":"calls","source":311,"target":316},{"edgeType":"calls","source":2978,"target":2205},{"edgeType":"calls","source":1497,"target":546},{"edgeType":"calls","source":1912,"target":365},{"edgeType":"calls","source":4230,"target":386},{"edgeType":"contains","source":4816,"target":4817},{"edgeType":"calls","source":644,"target":566},{"edgeType":"calls","source":4591,"target":1880},{"edgeType":"calls","source":4571,"target":386},{"edgeType":"calls","source":4522,"target":1905},{"edgeType":"calls","source":4537,"target":383},{"edgeType":"calls","source":2395,"target":191},{"edgeType":"contains","source":2730,"target":2888},{"edgeType":"imports","source":2209,"target":90},{"edgeType":"calls","source":3943,"target":826},{"edgeType":"calls","source":3353,"target":2205},{"edgeType":"contains","source":1643,"target":1704},{"edgeType":"calls","source":3271,"target":519},{"edgeType":"calls","source":4230,"target":387},{"edgeType":"calls","source":4571,"target":385},{"edgeType":"calls","source":411,"target":389},{"edgeType":"calls","source":2740,"target":1124},{"edgeType":"calls","source":4771,"target":527},{"edgeType":"calls","source":4838,"target":564},{"edgeType":"contains","source":482,"target":700},{"edgeType":"calls","source":4399,"target":1489},{"edgeType":"calls","source":4505,"target":317},{"edgeType":"calls","source":4537,"target":382},{"edgeType":"contains","source":2730,"target":2889},{"edgeType":"contains","source":2292,"target":2726},{"edgeType":"extends","source":4404,"target":3099},{"edgeType":"contains","source":16,"target":2462},{"edgeType":"calls","source":4850,"target":191},{"edgeType":"imports","source":3643,"target":1095},{"edgeType":"calls","source":674,"target":687},{"edgeType":"calls","source":4070,"target":3230},{"edgeType":"calls","source":4230,"target":384},{"edgeType":"calls","source":1261,"target":460},{"edgeType":"calls","source":2527,"target":325},{"edgeType":"calls","source":2788,"target":690},{"edgeType":"calls","source":4505,"target":316},{"edgeType":"calls","source":4571,"target":384},{"edgeType":"calls","source":411,"target":384},{"edgeType":"contains","source":3594,"target":3595},{"edgeType":"calls","source":3452,"target":191},{"edgeType":"calls","source":4230,"target":385},{"edgeType":"calls","source":2527,"target":326},{"edgeType":"calls","source":2500,"target":106},{"edgeType":"calls","source":4768,"target":1675},{"edgeType":"calls","source":4774,"target":1489},{"edgeType":"contains","source":2730,"target":2896},{"edgeType":"calls","source":4505,"target":315},{"edgeType":"calls","source":377,"target":380},{"edgeType":"calls","source":4571,"target":383},{"edgeType":"calls","source":411,"target":383},{"edgeType":"contains","source":482,"target":702},{"edgeType":"calls","source":4353,"target":1856},{"edgeType":"calls","source":1837,"target":572},{"edgeType":"calls","source":4230,"target":382},{"edgeType":"calls","source":411,"target":386},{"edgeType":"contains","source":2735,"target":2738},{"edgeType":"calls","source":311,"target":315},{"edgeType":"calls","source":4571,"target":382},{"edgeType":"calls","source":4230,"target":383},{"edgeType":"calls","source":1302,"target":1304},{"edgeType":"calls","source":1372,"target":191},{"edgeType":"calls","source":1336,"target":1307},{"edgeType":"calls","source":796,"target":77},{"edgeType":"calls","source":411,"target":385},{"edgeType":"contains","source":2699,"target":2798},{"edgeType":"calls","source":2476,"target":848},{"edgeType":"calls","source":4641,"target":325},{"edgeType":"calls","source":2429,"target":191},{"edgeType":"calls","source":3624,"target":2256},{"edgeType":"calls","source":3541,"target":1655},{"edgeType":"calls","source":4719,"target":1077},{"edgeType":"calls","source":1837,"target":569},{"edgeType":"calls","source":4543,"target":191},{"edgeType":"contains","source":17,"target":323},{"edgeType":"imports","source":29,"target":30},{"edgeType":"calls","source":3370,"target":1672},{"edgeType":"calls","source":4594,"target":723},{"edgeType":"calls","source":3697,"target":2105},{"edgeType":"calls","source":3740,"target":772},{"edgeType":"calls","source":1837,"target":568},{"edgeType":"calls","source":1705,"target":1489},{"edgeType":"imports","source":1918,"target":664},{"edgeType":"calls","source":4171,"target":1152},{"edgeType":"calls","source":4202,"target":191},{"edgeType":"contains","source":3527,"target":3561},{"edgeType":"calls","source":2794,"target":498},{"edgeType":"calls","source":3417,"target":212},{"edgeType":"imports","source":2975,"target":664},{"edgeType":"contains","source":2735,"target":2742},{"edgeType":"calls","source":4594,"target":722},{"edgeType":"contains","source":3066,"target":3051},{"edgeType":"calls","source":411,"target":382},{"edgeType":"calls","source":377,"target":379},{"edgeType":"extends","source":3714,"target":2301},{"edgeType":"calls","source":1837,"target":571},{"edgeType":"calls","source":3947,"target":3865},{"edgeType":"calls","source":1400,"target":376},{"edgeType":"calls","source":724,"target":191},{"edgeType":"contains","source":3527,"target":3558},{"edgeType":"contains","source":11,"target":3682},{"edgeType":"contains","source":4221,"target":4242},{"edgeType":"calls","source":1837,"target":570},{"edgeType":"calls","source":3751,"target":3600},{"edgeType":"calls","source":2382,"target":587},{"edgeType":"calls","source":848,"target":570},{"edgeType":"contains","source":4816,"target":4831},{"edgeType":"calls","source":4861,"target":899},{"edgeType":"calls","source":991,"target":365},{"edgeType":"calls","source":1332,"target":365},{"edgeType":"contains","source":4086,"target":4206},{"edgeType":"calls","source":1235,"target":1258},{"edgeType":"calls","source":3554,"target":191},{"edgeType":"calls","source":3449,"target":3446},{"edgeType":"contains","source":2226,"target":3728},{"edgeType":"contains","source":4221,"target":4249},{"edgeType":"calls","source":4660,"target":1845},{"edgeType":"calls","source":4588,"target":906},{"edgeType":"calls","source":4594,"target":720},{"edgeType":"contains","source":3594,"target":3603},{"edgeType":"calls","source":4062,"target":298},{"edgeType":"extends","source":1523,"target":1520},{"edgeType":"calls","source":4495,"target":1675},{"edgeType":"calls","source":4501,"target":1489},{"edgeType":"calls","source":2286,"target":389},{"edgeType":"calls","source":848,"target":569},{"edgeType":"contains","source":4086,"target":4205},{"edgeType":"calls","source":2757,"target":587},{"edgeType":"calls","source":3417,"target":211},{"edgeType":"calls","source":1498,"target":503},{"edgeType":"imports","source":1918,"target":660},{"edgeType":"calls","source":3929,"target":194},{"edgeType":"contains","source":3527,"target":3565},{"edgeType":"calls","source":4594,"target":719},{"edgeType":"calls","source":505,"target":632},{"edgeType":"imports","source":2975,"target":660},{"edgeType":"calls","source":3552,"target":3422},{"edgeType":"calls","source":2286,"target":386},{"edgeType":"calls","source":848,"target":572},{"edgeType":"contains","source":2269,"target":2393},{"edgeType":"calls","source":1261,"target":454},{"edgeType":"contains","source":3120,"target":324},{"edgeType":"calls","source":4701,"target":572},{"edgeType":"contains","source":2292,"target":2737},{"edgeType":"calls","source":1837,"target":567},{"edgeType":"contains","source":1160,"target":1893},{"edgeType":"calls","source":4594,"target":718},{"edgeType":"calls","source":3552,"target":3423},{"edgeType":"calls","source":2286,"target":387},{"edgeType":"calls","source":4437,"target":298},{"edgeType":"contains","source":2730,"target":2902},{"edgeType":"calls","source":848,"target":571},{"edgeType":"contains","source":2269,"target":2394},{"edgeType":"contains","source":395,"target":2353},{"edgeType":"contains","source":4451,"target":4516},{"edgeType":"calls","source":1837,"target":566},{"edgeType":"calls","source":4701,"target":571},{"edgeType":"calls","source":3265,"target":692},{"edgeType":"calls","source":4027,"target":325},{"edgeType":"calls","source":2286,"target":388},{"edgeType":"calls","source":4594,"target":717},{"edgeType":"calls","source":921,"target":384},{"edgeType":"calls","source":2319,"target":385},{"edgeType":"contains","source":4648,"target":4725},{"edgeType":"calls","source":2961,"target":567},{"edgeType":"calls","source":4374,"target":4331},{"edgeType":"contains","source":1776,"target":1794},{"edgeType":"contains","source":29,"target":984},{"edgeType":"calls","source":1498,"target":467},{"edgeType":"calls","source":1738,"target":426},{"edgeType":"calls","source":4750,"target":1132},{"edgeType":"calls","source":3298,"target":690},{"edgeType":"contains","source":3643,"target":4169},{"edgeType":"calls","source":3280,"target":191},{"edgeType":"calls","source":4608,"target":249},{"edgeType":"calls","source":448,"target":249},{"edgeType":"calls","source":2555,"target":469},{"edgeType":"calls","source":4532,"target":491},{"edgeType":"calls","source":705,"target":738},{"edgeType":"calls","source":3010,"target":106},{"edgeType":"calls","source":921,"target":383},{"edgeType":"calls","source":4427,"target":573},{"edgeType":"calls","source":2319,"target":386},{"edgeType":"calls","source":2961,"target":568},{"edgeType":"calls","source":4532,"target":489},{"edgeType":"contains","source":1776,"target":1795},{"edgeType":"calls","source":374,"target":427},{"edgeType":"contains","source":2404,"target":2411},{"edgeType":"calls","source":1498,"target":466},{"edgeType":"calls","source":1738,"target":425},{"edgeType":"calls","source":1763,"target":1764},{"edgeType":"calls","source":3286,"target":3177},{"edgeType":"calls","source":1429,"target":490},{"edgeType":"calls","source":4584,"target":992},{"edgeType":"calls","source":4608,"target":248},{"edgeType":"calls","source":448,"target":248},{"edgeType":"calls","source":2564,"target":191},{"edgeType":"calls","source":2550,"target":625},{"edgeType":"calls","source":2555,"target":470},{"edgeType":"calls","source":4532,"target":490},{"edgeType":"extends","source":1295,"target":1227},{"edgeType":"calls","source":4877,"target":365},{"edgeType":"calls","source":921,"target":386},{"edgeType":"calls","source":4532,"target":488},{"edgeType":"imports","source":1918,"target":704},{"edgeType":"calls","source":2319,"target":383},{"edgeType":"contains","source":1776,"target":1792},{"edgeType":"contains","source":3936,"target":369},{"edgeType":"calls","source":1498,"target":469},{"edgeType":"calls","source":4030,"target":194},{"edgeType":"calls","source":1885,"target":99},{"edgeType":"calls","source":2555,"target":467},{"edgeType":"calls","source":4522,"target":1856},{"edgeType":"calls","source":4687,"target":969},{"edgeType":"calls","source":4820,"target":4245},{"edgeType":"calls","source":2760,"target":454},{"edgeType":"contains","source":1215,"target":1216},{"edgeType":"calls","source":4532,"target":487},{"edgeType":"calls","source":847,"target":565},{"edgeType":"calls","source":921,"target":385},{"edgeType":"contains","source":1776,"target":1793},{"edgeType":"calls","source":2319,"target":384},{"edgeType":"imports","source":396,"target":320},{"edgeType":"calls","source":1498,"target":468},{"edgeType":"calls","source":1885,"target":98},{"edgeType":"calls","source":1738,"target":427},{"edgeType":"calls","source":1740,"target":365},{"edgeType":"contains","source":3643,"target":4166},{"edgeType":"calls","source":2555,"target":468},{"edgeType":"calls","source":2961,"target":566},{"edgeType":"calls","source":4532,"target":486},{"edgeType":"contains","source":1776,"target":1798},{"edgeType":"contains","source":2404,"target":2414},{"edgeType":"calls","source":4551,"target":954},{"edgeType":"calls","source":1880,"target":248},{"edgeType":"contains","source":3643,"target":4173},{"edgeType":"calls","source":1429,"target":487},{"edgeType":"calls","source":1168,"target":1179},{"edgeType":"calls","source":1159,"target":401},{"edgeType":"calls","source":2555,"target":465},{"edgeType":"contains","source":3230,"target":3235},{"edgeType":"calls","source":2319,"target":382},{"edgeType":"calls","source":4630,"target":1675},{"edgeType":"calls","source":4636,"target":1489},{"edgeType":"calls","source":4613,"target":88},{"edgeType":"calls","source":4532,"target":485},{"edgeType":"contains","source":4221,"target":4224},{"edgeType":"calls","source":1429,"target":486},{"edgeType":"calls","source":4842,"target":389},{"edgeType":"contains","source":3428,"target":3438},{"edgeType":"calls","source":512,"target":374},{"edgeType":"calls","source":2555,"target":466},{"edgeType":"imports","source":1090,"target":1001},{"edgeType":"contains","source":4648,"target":4728},{"edgeType":"calls","source":374,"target":426},{"edgeType":"calls","source":411,"target":336},{"edgeType":"calls","source":1498,"target":465},{"edgeType":"calls","source":4135,"target":106},{"edgeType":"calls","source":4226,"target":456},{"edgeType":"calls","source":4842,"target":388},{"edgeType":"calls","source":1429,"target":489},{"edgeType":"imports","source":4451,"target":411},{"edgeType":"calls","source":3295,"target":777},{"edgeType":"calls","source":673,"target":671},{"edgeType":"calls","source":3271,"target":464},{"edgeType":"calls","source":4874,"target":3624},{"edgeType":"calls","source":921,"target":382},{"edgeType":"contains","source":1776,"target":1797},{"edgeType":"contains","source":4648,"target":4726},{"edgeType":"calls","source":374,"target":425},{"edgeType":"calls","source":1880,"target":249},{"edgeType":"calls","source":3626,"target":1088},{"edgeType":"calls","source":4411,"target":1063},{"edgeType":"calls","source":2291,"target":191},{"edgeType":"contains","source":4221,"target":4222},{"edgeType":"calls","source":1429,"target":488},{"edgeType":"calls","source":4842,"target":387},{"edgeType":"calls","source":512,"target":376},{"edgeType":"calls","source":1159,"target":402},{"edgeType":"calls","source":1234,"target":191},{"edgeType":"calls","source":4601,"target":457},{"edgeType":"contains","source":984,"target":985},{"edgeType":"calls","source":4664,"target":1675},{"edgeType":"contains","source":1160,"target":1871},{"edgeType":"calls","source":1942,"target":436},{"edgeType":"calls","source":4452,"target":1905},{"edgeType":"calls","source":109,"target":179},{"edgeType":"calls","source":4249,"target":1856},{"edgeType":"calls","source":1528,"target":585},{"edgeType":"calls","source":4843,"target":3526},{"edgeType":"calls","source":824,"target":212},{"edgeType":"calls","source":4836,"target":572},{"edgeType":"calls","source":4842,"target":386},{"edgeType":"calls","source":4703,"target":4695},{"edgeType":"contains","source":4648,"target":4733},{"edgeType":"contains","source":2269,"target":2375},{"edgeType":"calls","source":2925,"target":1675},{"edgeType":"calls","source":2476,"target":796},{"edgeType":"calls","source":4505,"target":4489},{"edgeType":"calls","source":4601,"target":456},{"edgeType":"calls","source":4456,"target":723},{"edgeType":"calls","source":2666,"target":191},{"edgeType":"imports","source":1257,"target":65},{"edgeType":"calls","source":4020,"target":499},{"edgeType":"calls","source":4298,"target":336},{"edgeType":"calls","source":4280,"target":894},{"edgeType":"contains","source":4209,"target":4600},{"edgeType":"calls","source":4849,"target":2282},{"edgeType":"calls","source":4836,"target":571},{"edgeType":"calls","source":4842,"target":385},{"edgeType":"calls","source":824,"target":211},{"edgeType":"contains","source":4648,"target":4732},{"edgeType":"calls","source":1302,"target":191},{"edgeType":"extends","source":601,"target":548},{"edgeType":"calls","source":1367,"target":1347},{"edgeType":"calls","source":2494,"target":2349},{"edgeType":"calls","source":2564,"target":179},{"edgeType":"calls","source":1657,"target":817},{"edgeType":"calls","source":4641,"target":4500},{"edgeType":"calls","source":1942,"target":438},{"edgeType":"calls","source":4836,"target":569},{"edgeType":"calls","source":4842,"target":383},{"edgeType":"calls","source":4456,"target":722},{"edgeType":"contains","source":3643,"target":4175},{"edgeType":"calls","source":1429,"target":485},{"edgeType":"calls","source":3629,"target":2046},{"edgeType":"calls","source":3655,"target":183},{"edgeType":"calls","source":1498,"target":460},{"edgeType":"calls","source":638,"target":695},{"edgeType":"calls","source":4836,"target":570},{"edgeType":"calls","source":4842,"target":384},{"edgeType":"calls","source":1133,"target":1205},{"edgeType":"calls","source":3874,"target":1852},{"edgeType":"imports","source":1257,"target":63},{"edgeType":"contains","source":3643,"target":4174},{"edgeType":"calls","source":4836,"target":568},{"edgeType":"calls","source":4842,"target":382},{"edgeType":"calls","source":1942,"target":437},{"edgeType":"calls","source":4051,"target":1650},{"edgeType":"contains","source":3428,"target":3440},{"edgeType":"calls","source":1528,"target":586},{"edgeType":"calls","source":638,"target":694},{"edgeType":"imports","source":2259,"target":1768},{"edgeType":"calls","source":1161,"target":336},{"edgeType":"calls","source":3329,"target":777},{"edgeType":"calls","source":3260,"target":1856},{"edgeType":"calls","source":4652,"target":986},{"edgeType":"calls","source":4780,"target":189},{"edgeType":"calls","source":3945,"target":705},{"edgeType":"imports","source":396,"target":325},{"edgeType":"calls","source":4788,"target":3112},{"edgeType":"calls","source":4228,"target":388},{"edgeType":"calls","source":4836,"target":567},{"edgeType":"calls","source":2283,"target":1489},{"edgeType":"calls","source":4456,"target":720},{"edgeType":"calls","source":4280,"target":891},{"edgeType":"calls","source":1701,"target":503},{"edgeType":"extends","source":2884,"target":2716},{"edgeType":"calls","source":1702,"target":472},{"edgeType":"calls","source":1336,"target":191},{"edgeType":"calls","source":3307,"target":2513},{"edgeType":"calls","source":3416,"target":191},{"edgeType":"calls","source":1177,"target":891},{"edgeType":"contains","source":1643,"target":1702},{"edgeType":"contains","source":2933,"target":2937},{"edgeType":"calls","source":1974,"target":496},{"edgeType":"calls","source":4891,"target":2032},{"edgeType":"calls","source":4788,"target":3111},{"edgeType":"calls","source":4228,"target":389},{"edgeType":"calls","source":4836,"target":566},{"edgeType":"calls","source":4151,"target":1719},{"edgeType":"calls","source":784,"target":389},{"edgeType":"calls","source":4456,"target":719},{"edgeType":"calls","source":3356,"target":995},{"edgeType":"calls","source":3372,"target":499},{"edgeType":"calls","source":1701,"target":502},{"edgeType":"calls","source":1177,"target":894},{"edgeType":"contains","source":819,"target":821},{"edgeType":"contains","source":2933,"target":2934},{"edgeType":"calls","source":4228,"target":386},{"edgeType":"calls","source":4788,"target":3110},{"edgeType":"imports","source":4209,"target":505},{"edgeType":"calls","source":2523,"target":389},{"edgeType":"calls","source":4456,"target":718},{"edgeType":"imports","source":97,"target":78},{"edgeType":"calls","source":4589,"target":1880},{"edgeType":"contains","source":2699,"target":2788},{"edgeType":"calls","source":4396,"target":464},{"edgeType":"contains","source":395,"target":4451},{"edgeType":"calls","source":1702,"target":474},{"edgeType":"contains","source":2269,"target":2377},{"edgeType":"calls","source":1876,"target":365},{"edgeType":"calls","source":4804,"target":499},{"edgeType":"calls","source":1234,"target":183},{"edgeType":"contains","source":819,"target":820},{"edgeType":"calls","source":4228,"target":387},{"edgeType":"calls","source":4230,"target":325},{"edgeType":"calls","source":4788,"target":3109},{"edgeType":"contains","source":3527,"target":3546},{"edgeType":"calls","source":2250,"target":397},{"edgeType":"calls","source":4456,"target":717},{"edgeType":"calls","source":3095,"target":628},{"edgeType":"calls","source":2985,"target":2981},{"edgeType":"calls","source":1701,"target":504},{"edgeType":"calls","source":1702,"target":473},{"edgeType":"contains","source":4451,"target":4499},{"edgeType":"calls","source":544,"target":460},{"edgeType":"calls","source":1975,"target":495},{"edgeType":"calls","source":4167,"target":194},{"edgeType":"calls","source":1234,"target":211},{"edgeType":"calls","source":4229,"target":386},{"edgeType":"calls","source":374,"target":445},{"edgeType":"calls","source":4570,"target":386},{"edgeType":"calls","source":4521,"target":1905},{"edgeType":"calls","source":4530,"target":569},{"edgeType":"contains","source":3228,"target":3275},{"edgeType":"calls","source":4616,"target":4245},{"edgeType":"imports","source":1257,"target":39},{"edgeType":"contains","source":1776,"target":1778},{"edgeType":"contains","source":4516,"target":4572},{"edgeType":"contains","source":4583,"target":4609},{"edgeType":"calls","source":3888,"target":386},{"edgeType":"calls","source":3301,"target":1672},{"edgeType":"calls","source":1975,"target":494},{"edgeType":"calls","source":4229,"target":387},{"edgeType":"calls","source":4570,"target":385},{"edgeType":"calls","source":4530,"target":568},{"edgeType":"calls","source":2739,"target":1124},{"edgeType":"contains","source":3094,"target":1088},{"edgeType":"calls","source":2691,"target":498},{"edgeType":"imports","source":1257,"target":40},{"edgeType":"calls","source":4438,"target":249},{"edgeType":"calls","source":986,"target":499},{"edgeType":"contains","source":1776,"target":1779},{"edgeType":"calls","source":2178,"target":546},{"edgeType":"contains","source":4583,"target":4608},{"edgeType":"imports","source":1749,"target":1700},{"edgeType":"calls","source":3888,"target":387},{"edgeType":"calls","source":1738,"target":441},{"edgeType":"contains","source":6,"target":3794},{"edgeType":"calls","source":1871,"target":546},{"edgeType":"calls","source":4042,"target":4067},{"edgeType":"calls","source":4069,"target":3230},{"edgeType":"calls","source":4229,"target":384},{"edgeType":"calls","source":377,"target":354},{"edgeType":"calls","source":4570,"target":384},{"edgeType":"imports","source":1516,"target":1522},{"edgeType":"calls","source":2769,"target":191},{"edgeType":"calls","source":4772,"target":464},{"edgeType":"calls","source":4849,"target":191},{"edgeType":"contains","source":1940,"target":1977},{"edgeType":"calls","source":4438,"target":248},{"edgeType":"contains","source":3956,"target":3961},{"edgeType":"contains","source":3923,"target":3927},{"edgeType":"calls","source":4530,"target":567},{"edgeType":"calls","source":3819,"target":3580},{"edgeType":"calls","source":3888,"target":384},{"edgeType":"calls","source":1234,"target":212},{"edgeType":"calls","source":1975,"target":496},{"edgeType":"calls","source":4229,"target":385},{"edgeType":"calls","source":374,"target":446},{"edgeType":"calls","source":4598,"target":572},{"edgeType":"calls","source":377,"target":353},{"edgeType":"contains","source":3413,"target":3880},{"edgeType":"calls","source":4773,"target":1489},{"edgeType":"calls","source":2313,"target":587},{"edgeType":"calls","source":4530,"target":566},{"edgeType":"contains","source":3923,"target":3926},{"edgeType":"calls","source":4570,"target":383},{"edgeType":"contains","source":4648,"target":4705},{"edgeType":"contains","source":1776,"target":1777},{"edgeType":"contains","source":6,"target":3796},{"edgeType":"calls","source":3888,"target":385},{"edgeType":"calls","source":4229,"target":382},{"edgeType":"calls","source":549,"target":301},{"edgeType":"calls","source":3367,"target":1735},{"edgeType":"calls","source":4704,"target":456},{"edgeType":"imports","source":1257,"target":35},{"edgeType":"calls","source":4709,"target":301},{"edgeType":"extends","source":3033,"target":2301},{"edgeType":"contains","source":1776,"target":1782},{"edgeType":"contains","source":3228,"target":3279},{"edgeType":"calls","source":4598,"target":571},{"edgeType":"calls","source":4570,"target":382},{"edgeType":"calls","source":453,"target":106},{"edgeType":"calls","source":3888,"target":382},{"edgeType":"calls","source":4883,"target":191},{"edgeType":"calls","source":2688,"target":587},{"edgeType":"calls","source":587,"target":179},{"edgeType":"calls","source":4229,"target":383},{"edgeType":"imports","source":4284,"target":285},{"edgeType":"extends","source":2951,"target":2730},{"edgeType":"imports","source":1483,"target":1485},{"edgeType":"contains","source":1776,"target":1783},{"edgeType":"calls","source":4598,"target":570},{"edgeType":"imports","source":2565,"target":1768},{"edgeType":"calls","source":3888,"target":383},{"edgeType":"contains","source":4253,"target":4271},{"edgeType":"calls","source":1975,"target":493},{"edgeType":"calls","source":4170,"target":1152},{"edgeType":"calls","source":4201,"target":191},{"edgeType":"calls","source":4807,"target":1489},{"edgeType":"calls","source":1301,"target":1303},{"edgeType":"calls","source":772,"target":789},{"edgeType":"contains","source":2699,"target":2764},{"edgeType":"calls","source":4718,"target":1077},{"edgeType":"imports","source":1648,"target":1654},{"edgeType":"calls","source":2453,"target":470},{"edgeType":"contains","source":4648,"target":4710},{"edgeType":"contains","source":1776,"target":1780},{"edgeType":"contains","source":4516,"target":4574},{"edgeType":"calls","source":4598,"target":569},{"edgeType":"calls","source":4542,"target":191},{"edgeType":"calls","source":1735,"target":533},{"edgeType":"calls","source":1975,"target":492},{"edgeType":"calls","source":4025,"target":2475},{"edgeType":"calls","source":3369,"target":1672},{"edgeType":"contains","source":3643,"target":4153},{"edgeType":"calls","source":705,"target":751},{"edgeType":"contains","source":1776,"target":1781},{"edgeType":"contains","source":3228,"target":3278},{"edgeType":"calls","source":4657,"target":1910},{"edgeType":"calls","source":4598,"target":568},{"edgeType":"imports","source":4079,"target":300},{"edgeType":"contains","source":1940,"target":1982},{"edgeType":"calls","source":1975,"target":491},{"edgeType":"contains","source":3413,"target":3891},{"edgeType":"contains","source":2229,"target":3598},{"edgeType":"contains","source":2488,"target":2969},{"edgeType":"contains","source":4516,"target":4581},{"edgeType":"contains","source":612,"target":2987},{"edgeType":"calls","source":4598,"target":567},{"edgeType":"calls","source":2453,"target":468},{"edgeType":"calls","source":3837,"target":902},{"edgeType":"calls","source":1677,"target":211},{"edgeType":"calls","source":1738,"target":434},{"edgeType":"calls","source":591,"target":52},{"edgeType":"calls","source":512,"target":387},{"edgeType":"contains","source":1776,"target":1786},{"edgeType":"contains","source":3643,"target":4161},{"edgeType":"contains","source":3527,"target":3529},{"edgeType":"contains","source":3413,"target":3890},{"edgeType":"contains","source":28,"target":3120},{"edgeType":"contains","source":4253,"target":4276},{"edgeType":"calls","source":4881,"target":249},{"edgeType":"calls","source":817,"target":444},{"edgeType":"calls","source":1672,"target":365},{"edgeType":"calls","source":2935,"target":325},{"edgeType":"contains","source":2488,"target":2970},{"edgeType":"contains","source":4516,"target":4580},{"edgeType":"calls","source":2453,"target":469},{"edgeType":"contains","source":4516,"target":4579},{"edgeType":"calls","source":4598,"target":566},{"edgeType":"calls","source":4576,"target":191},{"edgeType":"calls","source":1814,"target":191},{"edgeType":"calls","source":591,"target":51},{"edgeType":"calls","source":512,"target":386},{"edgeType":"contains","source":1776,"target":1787},{"edgeType":"calls","source":705,"target":748},{"edgeType":"calls","source":3448,"target":3446},{"edgeType":"contains","source":4253,"target":4275},{"edgeType":"calls","source":775,"target":692},{"edgeType":"calls","source":4881,"target":248},{"edgeType":"calls","source":591,"target":54},{"edgeType":"extends","source":4633,"target":4499},{"edgeType":"calls","source":970,"target":989},{"edgeType":"calls","source":1169,"target":106},{"edgeType":"contains","source":4516,"target":4578},{"edgeType":"calls","source":4659,"target":1845},{"edgeType":"calls","source":3837,"target":900},{"edgeType":"calls","source":512,"target":389},{"edgeType":"contains","source":1940,"target":1985},{"edgeType":"calls","source":2728,"target":397},{"edgeType":"calls","source":4494,"target":1675},{"edgeType":"contains","source":3936,"target":2475},{"edgeType":"calls","source":2453,"target":466},{"edgeType":"contains","source":1776,"target":1784},{"edgeType":"calls","source":591,"target":53},{"edgeType":"extends","source":548,"target":63},{"edgeType":"contains","source":2488,"target":2968},{"edgeType":"contains","source":4583,"target":4615},{"edgeType":"calls","source":2453,"target":467},{"edgeType":"contains","source":4516,"target":4577},{"edgeType":"calls","source":3837,"target":901},{"edgeType":"calls","source":1718,"target":1055},{"edgeType":"calls","source":1738,"target":435},{"edgeType":"calls","source":1677,"target":212},{"edgeType":"calls","source":4795,"target":1856},{"edgeType":"calls","source":512,"target":388},{"edgeType":"extends","source":207,"target":63},{"edgeType":"calls","source":4532,"target":496},{"edgeType":"contains","source":1776,"target":1785},{"edgeType":"calls","source":921,"target":388},{"edgeType":"calls","source":2961,"target":571},{"edgeType":"contains","source":2404,"target":2406},{"edgeType":"calls","source":2494,"target":2364},{"edgeType":"calls","source":1885,"target":101},{"edgeType":"calls","source":4454,"target":1856},{"edgeType":"contains","source":1776,"target":1790},{"edgeType":"calls","source":4532,"target":495},{"edgeType":"calls","source":2755,"target":1672},{"edgeType":"calls","source":591,"target":48},{"edgeType":"contains","source":3413,"target":3896},{"edgeType":"calls","source":512,"target":383},{"edgeType":"contains","source":1933,"target":2209},{"edgeType":"contains","source":2730,"target":2871},{"edgeType":"imports","source":2276,"target":2279},{"edgeType":"calls","source":921,"target":387},{"edgeType":"calls","source":2961,"target":572},{"edgeType":"calls","source":1371,"target":179},{"edgeType":"calls","source":1724,"target":863},{"edgeType":"calls","source":1498,"target":470},{"edgeType":"calls","source":1885,"target":100},{"edgeType":"calls","source":4811,"target":301},{"edgeType":"calls","source":3980,"target":3865},{"edgeType":"calls","source":1166,"target":191},{"edgeType":"calls","source":4026,"target":325},{"edgeType":"contains","source":1776,"target":1791},{"edgeType":"calls","source":4042,"target":4057},{"edgeType":"calls","source":4532,"target":494},{"edgeType":"calls","source":591,"target":47},{"edgeType":"calls","source":2453,"target":465},{"edgeType":"contains","source":3413,"target":3895},{"edgeType":"calls","source":4528,"target":1675},{"edgeType":"calls","source":512,"target":382},{"edgeType":"calls","source":2961,"target":569},{"edgeType":"calls","source":2319,"target":387},{"edgeType":"calls","source":4309,"target":1063},{"edgeType":"calls","source":705,"target":744},{"edgeType":"calls","source":817,"target":443},{"edgeType":"calls","source":996,"target":179},{"edgeType":"calls","source":1336,"target":1267},{"edgeType":"imports","source":1257,"target":41},{"edgeType":"contains","source":3643,"target":4163},{"edgeType":"calls","source":1697,"target":1703},{"edgeType":"calls","source":1953,"target":1166},{"edgeType":"calls","source":4014,"target":3865},{"edgeType":"calls","source":2365,"target":1076},{"edgeType":"calls","source":591,"target":50},{"edgeType":"contains","source":1776,"target":1788},{"edgeType":"calls","source":4843,"target":365},{"edgeType":"calls","source":512,"target":385},{"edgeType":"calls","source":4436,"target":298},{"edgeType":"calls","source":4374,"target":4334},{"edgeType":"calls","source":4532,"target":493},{"edgeType":"calls","source":2961,"target":570},{"edgeType":"calls","source":2319,"target":388},{"edgeType":"calls","source":921,"target":389},{"edgeType":"contains","source":4516,"target":4582},{"edgeType":"contains","source":2404,"target":2405},{"edgeType":"calls","source":1885,"target":102},{"edgeType":"calls","source":2625,"target":416},{"edgeType":"calls","source":4095,"target":298},{"edgeType":"calls","source":4110,"target":4061},{"edgeType":"contains","source":1776,"target":1789},{"edgeType":"calls","source":591,"target":49},{"edgeType":"calls","source":4653,"target":969},{"edgeType":"calls","source":2319,"target":389},{"edgeType":"calls","source":512,"target":384},{"edgeType":"calls","source":4532,"target":492},{"edgeType":"calls","source":4488,"target":1856},{"edgeType":"calls","source":2980,"target":77},{"edgeType":"calls","source":2254,"target":385},{"edgeType":"contains","source":3936,"target":338},{"edgeType":"calls","source":1334,"target":365},{"edgeType":"imports","source":1749,"target":1750},{"edgeType":"calls","source":3451,"target":3446},{"edgeType":"calls","source":4662,"target":1845},{"edgeType":"calls","source":1231,"target":386},{"edgeType":"contains","source":3404,"target":4146},{"edgeType":"calls","source":724,"target":248},{"edgeType":"calls","source":2320,"target":454},{"edgeType":"calls","source":4590,"target":906},{"edgeType":"calls","source":456,"target":100},{"edgeType":"calls","source":4405,"target":299},{"edgeType":"contains","source":3226,"target":3320},{"edgeType":"imports","source":1160,"target":983},{"edgeType":"contains","source":3226,"target":3322},{"edgeType":"imports","source":1257,"target":90},{"edgeType":"calls","source":2254,"target":386},{"edgeType":"contains","source":4583,"target":4592},{"edgeType":"calls","source":1231,"target":385},{"edgeType":"calls","source":3301,"target":1754},{"edgeType":"calls","source":4085,"target":705},{"edgeType":"calls","source":2759,"target":587},{"edgeType":"contains","source":3493,"target":3500},{"edgeType":"calls","source":456,"target":99},{"edgeType":"contains","source":1247,"target":1249},{"edgeType":"calls","source":2922,"target":2930},{"edgeType":"calls","source":776,"target":752},{"edgeType":"contains","source":1940,"target":1960},{"edgeType":"calls","source":2254,"target":383},{"edgeType":"contains","source":4451,"target":4455},{"edgeType":"calls","source":1231,"target":389},{"edgeType":"contains","source":28,"target":3098},{"edgeType":"contains","source":2292,"target":2676},{"edgeType":"calls","source":456,"target":102},{"edgeType":"contains","source":850,"target":871},{"edgeType":"calls","source":1231,"target":388},{"edgeType":"calls","source":643,"target":647},{"edgeType":"calls","source":4703,"target":572},{"edgeType":"calls","source":4536,"target":464},{"edgeType":"calls","source":2254,"target":384},{"edgeType":"calls","source":2213,"target":1655},{"edgeType":"contains","source":4583,"target":4590},{"edgeType":"calls","source":1373,"target":1271},{"edgeType":"calls","source":3452,"target":3414},{"edgeType":"contains","source":2269,"target":2332},{"edgeType":"calls","source":1231,"target":387},{"edgeType":"calls","source":3354,"target":1166},{"edgeType":"calls","source":1817,"target":191},{"edgeType":"calls","source":3267,"target":692},{"edgeType":"calls","source":4113,"target":4063},{"edgeType":"calls","source":724,"target":249},{"edgeType":"calls","source":2830,"target":498},{"edgeType":"calls","source":456,"target":101},{"edgeType":"calls","source":4703,"target":571},{"edgeType":"calls","source":905,"target":975},{"edgeType":"calls","source":2998,"target":572},{"edgeType":"contains","source":3163,"target":3164},{"edgeType":"calls","source":4491,"target":1856},{"edgeType":"calls","source":4312,"target":1063},{"edgeType":"calls","source":1231,"target":382},{"edgeType":"imports","source":4234,"target":1884},{"edgeType":"calls","source":411,"target":434},{"edgeType":"calls","source":4638,"target":471},{"edgeType":"calls","source":412,"target":403},{"edgeType":"calls","source":865,"target":101},{"edgeType":"contains","source":4648,"target":4696},{"edgeType":"calls","source":4703,"target":570},{"edgeType":"calls","source":4846,"target":365},{"edgeType":"calls","source":772,"target":870},{"edgeType":"contains","source":3163,"target":3165},{"edgeType":"contains","source":4583,"target":4596},{"edgeType":"calls","source":2254,"target":382},{"edgeType":"calls","source":1508,"target":1308},{"edgeType":"calls","source":3563,"target":2085},{"edgeType":"contains","source":4253,"target":4256},{"edgeType":"contains","source":850,"target":872},{"edgeType":"contains","source":2264,"target":2494},{"edgeType":"calls","source":3267,"target":690},{"edgeType":"calls","source":1157,"target":561},{"edgeType":"calls","source":4737,"target":572},{"edgeType":"calls","source":4703,"target":569},{"edgeType":"calls","source":933,"target":106},{"edgeType":"calls","source":865,"target":100},{"edgeType":"calls","source":3028,"target":1754},{"edgeType":"contains","source":4583,"target":4595},{"edgeType":"contains","source":1148,"target":1151},{"edgeType":"imports","source":97,"target":103},{"edgeType":"calls","source":3624,"target":191},{"edgeType":"contains","source":190,"target":195},{"edgeType":"calls","source":1851,"target":191},{"edgeType":"contains","source":4253,"target":4255},{"edgeType":"contains","source":38,"target":679},{"edgeType":"calls","source":4706,"target":4703},{"edgeType":"contains","source":16,"target":3475},{"edgeType":"calls","source":1231,"target":384},{"edgeType":"imports","source":1257,"target":82},{"edgeType":"calls","source":4703,"target":568},{"edgeType":"calls","source":456,"target":98},{"edgeType":"calls","source":2998,"target":570},{"edgeType":"calls","source":4737,"target":571},{"edgeType":"contains","source":1115,"target":1116},{"edgeType":"contains","source":3226,"target":3324},{"edgeType":"calls","source":4430,"target":573},{"edgeType":"calls","source":4438,"target":325},{"edgeType":"calls","source":4505,"target":3533},{"edgeType":"calls","source":3999,"target":194},{"edgeType":"calls","source":3645,"target":1655},{"edgeType":"calls","source":1676,"target":330},{"edgeType":"calls","source":4880,"target":365},{"edgeType":"contains","source":38,"target":678},{"edgeType":"calls","source":479,"target":441},{"edgeType":"calls","source":4224,"target":1675},{"edgeType":"calls","source":1231,"target":383},{"edgeType":"calls","source":2523,"target":498},{"edgeType":"contains","source":2699,"target":2748},{"edgeType":"calls","source":411,"target":435},{"edgeType":"calls","source":4737,"target":570},{"edgeType":"calls","source":4703,"target":567},{"edgeType":"calls","source":865,"target":102},{"edgeType":"calls","source":2998,"target":571},{"edgeType":"calls","source":784,"target":499},{"edgeType":"calls","source":2790,"target":2791},{"edgeType":"calls","source":411,"target":429},{"edgeType":"calls","source":4645,"target":249},{"edgeType":"calls","source":1676,"target":325},{"edgeType":"contains","source":3226,"target":3329},{"edgeType":"calls","source":4505,"target":3532},{"edgeType":"calls","source":4574,"target":336},{"edgeType":"contains","source":190,"target":197},{"edgeType":"calls","source":4033,"target":194},{"edgeType":"contains","source":3775,"target":1109},{"edgeType":"contains","source":3493,"target":3509},{"edgeType":"calls","source":3423,"target":77},{"edgeType":"calls","source":2652,"target":724},{"edgeType":"contains","source":16,"target":2420},{"edgeType":"calls","source":3658,"target":191},{"edgeType":"calls","source":4703,"target":566},{"edgeType":"calls","source":1261,"target":505},{"edgeType":"calls","source":826,"target":249},{"edgeType":"calls","source":4737,"target":569},{"edgeType":"calls","source":1157,"target":558},{"edgeType":"calls","source":2998,"target":568},{"edgeType":"calls","source":3007,"target":289},{"edgeType":"imports","source":1749,"target":1757},{"edgeType":"contains","source":2292,"target":2687},{"edgeType":"calls","source":4645,"target":248},{"edgeType":"contains","source":3226,"target":3330},{"edgeType":"contains","source":3493,"target":3508},{"edgeType":"calls","source":3388,"target":106},{"edgeType":"calls","source":4737,"target":568},{"edgeType":"calls","source":826,"target":248},{"edgeType":"calls","source":4729,"target":1873},{"edgeType":"calls","source":1157,"target":557},{"edgeType":"calls","source":2998,"target":569},{"edgeType":"contains","source":3226,"target":3327},{"edgeType":"calls","source":3806,"target":887},{"edgeType":"calls","source":2635,"target":191},{"edgeType":"contains","source":1148,"target":1155},{"edgeType":"contains","source":190,"target":199},{"edgeType":"calls","source":4737,"target":566},{"edgeType":"calls","source":4464,"target":573},{"edgeType":"contains","source":850,"target":879},{"edgeType":"calls","source":2998,"target":566},{"edgeType":"calls","source":4737,"target":567},{"edgeType":"contains","source":396,"target":2269},{"edgeType":"contains","source":4583,"target":4599},{"edgeType":"calls","source":865,"target":99},{"edgeType":"contains","source":4648,"target":4698},{"edgeType":"calls","source":4608,"target":336},{"edgeType":"calls","source":4616,"target":88},{"edgeType":"contains","source":1080,"target":1148},{"edgeType":"contains","source":1148,"target":1154},{"edgeType":"contains","source":1160,"target":1839},{"edgeType":"contains","source":190,"target":198},{"edgeType":"calls","source":3692,"target":194},{"edgeType":"contains","source":16,"target":1364},{"edgeType":"calls","source":865,"target":98},{"edgeType":"calls","source":2998,"target":567},{"edgeType":"calls","source":411,"target":425},{"edgeType":"calls","source":456,"target":87},{"edgeType":"calls","source":4570,"target":456},{"edgeType":"contains","source":190,"target":201},{"edgeType":"contains","source":2899,"target":2900},{"edgeType":"calls","source":4138,"target":106},{"edgeType":"extends","source":1398,"target":1249},{"edgeType":"calls","source":4229,"target":456},{"edgeType":"imports","source":4284,"target":325},{"edgeType":"contains","source":3956,"target":3959},{"edgeType":"contains","source":3923,"target":3925},{"edgeType":"contains","source":43,"target":3701},{"edgeType":"contains","source":4516,"target":4568},{"edgeType":"calls","source":3415,"target":2435},{"edgeType":"calls","source":3298,"target":777},{"edgeType":"calls","source":453,"target":179},{"edgeType":"calls","source":4593,"target":1856},{"edgeType":"contains","source":190,"target":200},{"edgeType":"calls","source":1808,"target":456},{"edgeType":"calls","source":2294,"target":191},{"edgeType":"contains","source":3413,"target":3878},{"edgeType":"calls","source":930,"target":191},{"edgeType":"contains","source":3923,"target":3924},{"edgeType":"contains","source":2072,"target":2112},{"edgeType":"contains","source":4516,"target":4567},{"edgeType":"contains","source":190,"target":203},{"edgeType":"calls","source":411,"target":427},{"edgeType":"contains","source":2292,"target":2688},{"edgeType":"calls","source":1672,"target":447},{"edgeType":"contains","source":3226,"target":3331},{"edgeType":"calls","source":4498,"target":572},{"edgeType":"contains","source":1175,"target":1379},{"edgeType":"calls","source":4604,"target":457},{"edgeType":"contains","source":3493,"target":3511},{"edgeType":"contains","source":2699,"target":2755},{"edgeType":"calls","source":1497,"target":586},{"edgeType":"calls","source":4846,"target":3526},{"edgeType":"contains","source":3956,"target":3957},{"edgeType":"contains","source":6,"target":3793},{"edgeType":"calls","source":1003,"target":45},{"edgeType":"calls","source":411,"target":426},{"edgeType":"calls","source":3257,"target":990},{"edgeType":"calls","source":2503,"target":1109},{"edgeType":"calls","source":3231,"target":1796},{"edgeType":"contains","source":190,"target":202},{"edgeType":"calls","source":4726,"target":902},{"edgeType":"calls","source":4771,"target":564},{"edgeType":"calls","source":1869,"target":1738},{"edgeType":"contains","source":1175,"target":1378},{"edgeType":"calls","source":2669,"target":191},{"edgeType":"contains","source":3493,"target":3510},{"edgeType":"calls","source":483,"target":308},{"edgeType":"calls","source":4604,"target":456},{"edgeType":"calls","source":4498,"target":571},{"edgeType":"calls","source":3545,"target":2632},{"edgeType":"calls","source":1497,"target":585},{"edgeType":"calls","source":1660,"target":817},{"edgeType":"contains","source":4648,"target":4701},{"edgeType":"contains","source":4209,"target":4569},{"edgeType":"calls","source":3417,"target":3429},{"edgeType":"calls","source":1393,"target":638},{"edgeType":"calls","source":479,"target":460},{"edgeType":"calls","source":4668,"target":1675},{"edgeType":"calls","source":4674,"target":1489},{"edgeType":"contains","source":4285,"target":4301},{"edgeType":"calls","source":4102,"target":194},{"edgeType":"calls","source":4806,"target":568},{"edgeType":"calls","source":308,"target":476},{"edgeType":"calls","source":2078,"target":572},{"edgeType":"calls","source":4539,"target":389},{"edgeType":"calls","source":695,"target":106},{"edgeType":"calls","source":4605,"target":457},{"edgeType":"contains","source":3162,"target":3174},{"edgeType":"calls","source":4409,"target":191},{"edgeType":"contains","source":3226,"target":3304},{"edgeType":"contains","source":2631,"target":2722},{"edgeType":"contains","source":1874,"target":1878},{"edgeType":"contains","source":650,"target":710},{"edgeType":"calls","source":82,"target":83},{"edgeType":"contains","source":2735,"target":555},{"edgeType":"contains","source":4648,"target":4675},{"edgeType":"calls","source":4847,"target":3526},{"edgeType":"contains","source":4234,"target":4825},{"edgeType":"calls","source":3423,"target":102},{"edgeType":"calls","source":4750,"target":189},{"edgeType":"calls","source":3270,"target":1675},{"edgeType":"calls","source":1885,"target":212},{"edgeType":"calls","source":4806,"target":567},{"edgeType":"calls","source":2078,"target":571},{"edgeType":"calls","source":4882,"target":325},{"edgeType":"calls","source":546,"target":496},{"edgeType":"calls","source":544,"target":558},{"edgeType":"calls","source":2504,"target":1109},{"edgeType":"contains","source":3226,"target":3305},{"edgeType":"calls","source":4605,"target":456},{"edgeType":"calls","source":4539,"target":388},{"edgeType":"calls","source":3603,"target":865},{"edgeType":"contains","source":650,"target":709},{"edgeType":"contains","source":2631,"target":2723},{"edgeType":"contains","source":4516,"target":4538},{"edgeType":"contains","source":4285,"target":4300},{"edgeType":"contains","source":850,"target":855},{"edgeType":"calls","source":453,"target":211},{"edgeType":"calls","source":3310,"target":1489},{"edgeType":"calls","source":4806,"target":566},{"edgeType":"calls","source":3423,"target":100},{"edgeType":"calls","source":4015,"target":3946},{"edgeType":"contains","source":1807,"target":1838},{"edgeType":"calls","source":578,"target":564},{"edgeType":"contains","source":3226,"target":3302},{"edgeType":"calls","source":308,"target":478},{"edgeType":"calls","source":4539,"target":387},{"edgeType":"calls","source":2660,"target":498},{"edgeType":"calls","source":2349,"target":626},{"edgeType":"contains","source":396,"target":2244},{"edgeType":"contains","source":4648,"target":4673},{"edgeType":"contains","source":4120,"target":4129},{"edgeType":"imports","source":4045,"target":325},{"edgeType":"contains","source":4285,"target":4299},{"edgeType":"contains","source":4234,"target":4823},{"edgeType":"calls","source":1944,"target":499},{"edgeType":"calls","source":644,"target":631},{"edgeType":"calls","source":308,"target":477},{"edgeType":"calls","source":4573,"target":389},{"edgeType":"extends","source":3441,"target":3421},{"edgeType":"calls","source":4539,"target":386},{"edgeType":"calls","source":4708,"target":1489},{"edgeType":"calls","source":4585,"target":4245},{"edgeType":"contains","source":2631,"target":2721},{"edgeType":"calls","source":2253,"target":1489},{"edgeType":"contains","source":650,"target":711},{"edgeType":"calls","source":2982,"target":1088},{"edgeType":"imports","source":4045,"target":1383},{"edgeType":"contains","source":4285,"target":4298},{"edgeType":"contains","source":4120,"target":4128},{"edgeType":"calls","source":3423,"target":101},{"edgeType":"contains","source":4234,"target":4829},{"edgeType":"calls","source":3423,"target":98},{"edgeType":"calls","source":546,"target":493},{"edgeType":"calls","source":2078,"target":568},{"edgeType":"calls","source":1263,"target":464},{"edgeType":"calls","source":2453,"target":571},{"edgeType":"calls","source":4573,"target":388},{"edgeType":"calls","source":4539,"target":385},{"edgeType":"calls","source":4686,"target":1113},{"edgeType":"calls","source":2755,"target":722},{"edgeType":"calls","source":4784,"target":189},{"edgeType":"calls","source":208,"target":401},{"edgeType":"calls","source":905,"target":992},{"edgeType":"contains","source":1643,"target":1644},{"edgeType":"contains","source":3936,"target":326},{"edgeType":"contains","source":38,"target":660},{"edgeType":"contains","source":4234,"target":4828},{"edgeType":"calls","source":546,"target":492},{"edgeType":"calls","source":3423,"target":99},{"edgeType":"contains","source":850,"target":856},{"edgeType":"calls","source":2078,"target":567},{"edgeType":"contains","source":2269,"target":2322},{"edgeType":"calls","source":4136,"target":194},{"edgeType":"calls","source":2453,"target":572},{"edgeType":"calls","source":4573,"target":387},{"edgeType":"contains","source":3175,"target":662},{"edgeType":"calls","source":2755,"target":723},{"edgeType":"calls","source":4818,"target":191},{"edgeType":"calls","source":1679,"target":1308},{"edgeType":"contains","source":3226,"target":3309},{"edgeType":"contains","source":395,"target":2276},{"edgeType":"calls","source":4539,"target":384},{"edgeType":"contains","source":4516,"target":4542},{"edgeType":"calls","source":2207,"target":1856},{"edgeType":"calls","source":344,"target":412},{"edgeType":"calls","source":308,"target":471},{"edgeType":"contains","source":1643,"target":1645},{"edgeType":"contains","source":2072,"target":2087},{"edgeType":"calls","source":1905,"target":1705},{"edgeType":"calls","source":546,"target":495},{"edgeType":"extends","source":798,"target":799},{"edgeType":"calls","source":544,"target":557},{"edgeType":"calls","source":2755,"target":720},{"edgeType":"calls","source":1885,"target":211},{"edgeType":"calls","source":2657,"target":587},{"edgeType":"calls","source":4170,"target":194},{"edgeType":"contains","source":4234,"target":4827},{"edgeType":"calls","source":2078,"target":570},{"edgeType":"calls","source":4593,"target":1880},{"edgeType":"calls","source":2998,"target":586},{"edgeType":"calls","source":4742,"target":1489},{"edgeType":"calls","source":4782,"target":249},{"edgeType":"calls","source":2868,"target":388},{"edgeType":"contains","source":3920,"target":3991},{"edgeType":"contains","source":4648,"target":4677},{"edgeType":"calls","source":3829,"target":194},{"edgeType":"calls","source":4539,"target":383},{"edgeType":"calls","source":2453,"target":569},{"edgeType":"calls","source":4573,"target":386},{"edgeType":"contains","source":4516,"target":4541},{"edgeType":"calls","source":546,"target":494},{"edgeType":"calls","source":2694,"target":498},{"edgeType":"contains","source":4234,"target":4826},{"edgeType":"calls","source":1938,"target":1738},{"edgeType":"calls","source":2078,"target":569},{"edgeType":"calls","source":1344,"target":68},{"edgeType":"contains","source":3643,"target":4120},{"edgeType":"calls","source":3338,"target":1675},{"edgeType":"calls","source":411,"target":451},{"edgeType":"calls","source":4782,"target":248},{"edgeType":"calls","source":2868,"target":389},{"edgeType":"calls","source":4539,"target":382},{"edgeType":"calls","source":2453,"target":570},{"edgeType":"calls","source":4573,"target":385},{"edgeType":"calls","source":208,"target":402},{"edgeType":"calls","source":2261,"target":1237},{"edgeType":"calls","source":692,"target":191},{"edgeType":"calls","source":4072,"target":3230},{"edgeType":"contains","source":38,"target":664},{"edgeType":"calls","source":2755,"target":718},{"edgeType":"calls","source":4710,"target":365},{"edgeType":"calls","source":2870,"target":324},{"edgeType":"calls","source":2868,"target":386},{"edgeType":"calls","source":1738,"target":533},{"edgeType":"calls","source":3113,"target":191},{"edgeType":"contains","source":4516,"target":4547},{"edgeType":"calls","source":2456,"target":474},{"edgeType":"calls","source":2453,"target":567},{"edgeType":"calls","source":4573,"target":384},{"edgeType":"calls","source":2529,"target":325},{"edgeType":"imports","source":1257,"target":80},{"edgeType":"extends","source":3540,"target":3535},{"edgeType":"calls","source":4170,"target":191},{"edgeType":"calls","source":2755,"target":719},{"edgeType":"calls","source":3301,"target":1763},{"edgeType":"calls","source":4776,"target":1489},{"edgeType":"contains","source":4583,"target":4584},{"edgeType":"calls","source":2868,"target":387},{"edgeType":"calls","source":2998,"target":585},{"edgeType":"contains","source":4516,"target":4546},{"edgeType":"calls","source":313,"target":312},{"edgeType":"calls","source":344,"target":408},{"edgeType":"contains","source":3226,"target":3313},{"edgeType":"calls","source":2453,"target":568},{"edgeType":"calls","source":4573,"target":383},{"edgeType":"imports","source":1257,"target":81},{"edgeType":"calls","source":2078,"target":566},{"edgeType":"calls","source":2868,"target":384},{"edgeType":"calls","source":546,"target":491},{"edgeType":"calls","source":2755,"target":716},{"edgeType":"contains","source":6,"target":3772},{"edgeType":"contains","source":482,"target":644},{"edgeType":"calls","source":2456,"target":472},{"edgeType":"calls","source":4573,"target":382},{"edgeType":"contains","source":4516,"target":4545},{"edgeType":"calls","source":4707,"target":456},{"edgeType":"calls","source":1271,"target":1270},{"edgeType":"calls","source":2755,"target":717},{"edgeType":"calls","source":1311,"target":30},{"edgeType":"calls","source":2868,"target":385},{"edgeType":"contains","source":16,"target":2404},{"edgeType":"contains","source":4234,"target":4830},{"edgeType":"calls","source":1155,"target":638},{"edgeType":"calls","source":2456,"target":473},{"edgeType":"calls","source":2453,"target":566},{"edgeType":"contains","source":4516,"target":4544},{"edgeType":"contains","source":3226,"target":3311},{"edgeType":"calls","source":411,"target":447},{"edgeType":"imports","source":1257,"target":79},{"edgeType":"imports","source":2000,"target":300},{"edgeType":"calls","source":2868,"target":382},{"edgeType":"calls","source":849,"target":605},{"edgeType":"calls","source":2755,"target":714},{"edgeType":"contains","source":97,"target":953},{"edgeType":"calls","source":3407,"target":586},{"edgeType":"calls","source":1372,"target":248},{"edgeType":"calls","source":1400,"target":437},{"edgeType":"calls","source":3271,"target":574},{"edgeType":"extends","source":1700,"target":1384},{"edgeType":"imports","source":1257,"target":76},{"edgeType":"calls","source":4545,"target":191},{"edgeType":"calls","source":4661,"target":1880},{"edgeType":"calls","source":2323,"target":365},{"edgeType":"contains","source":3493,"target":3497},{"edgeType":"calls","source":2309,"target":1856},{"edgeType":"calls","source":776,"target":753},{"edgeType":"calls","source":2868,"target":383},{"edgeType":"calls","source":2904,"target":324},{"edgeType":"calls","source":2755,"target":715},{"edgeType":"contains","source":2033,"target":2247},{"edgeType":"contains","source":4583,"target":4588},{"edgeType":"contains","source":4648,"target":4687},{"edgeType":"calls","source":1400,"target":436},{"edgeType":"calls","source":411,"target":441},{"edgeType":"imports","source":4045,"target":320},{"edgeType":"calls","source":2453,"target":564},{"edgeType":"calls","source":4746,"target":301},{"edgeType":"calls","source":1721,"target":1055},{"edgeType":"calls","source":2254,"target":387},{"edgeType":"contains","source":28,"target":3094},{"edgeType":"calls","source":4640,"target":1472},{"edgeType":"calls","source":4638,"target":477},{"edgeType":"contains","source":850,"target":867},{"edgeType":"calls","source":448,"target":354},{"edgeType":"calls","source":2755,"target":712},{"edgeType":"contains","source":3643,"target":4130},{"edgeType":"calls","source":2254,"target":388},{"edgeType":"calls","source":2207,"target":1845},{"edgeType":"calls","source":2429,"target":248},{"edgeType":"calls","source":1400,"target":438},{"edgeType":"calls","source":849,"target":606},{"edgeType":"calls","source":2755,"target":713},{"edgeType":"calls","source":3369,"target":1763},{"edgeType":"calls","source":3407,"target":585},{"edgeType":"contains","source":4648,"target":4685},{"edgeType":"calls","source":1372,"target":249},{"edgeType":"contains","source":4583,"target":4586},{"edgeType":"calls","source":4638,"target":476},{"edgeType":"calls","source":448,"target":353},{"edgeType":"contains","source":3936,"target":331},{"edgeType":"contains","source":850,"target":866},{"edgeType":"contains","source":3226,"target":3315},{"edgeType":"contains","source":3493,"target":3494},{"edgeType":"calls","source":2254,"target":389},{"edgeType":"calls","source":313,"target":310},{"edgeType":"calls","source":2429,"target":249},{"edgeType":"calls","source":2247,"target":569},{"edgeType":"calls","source":3705,"target":824},{"edgeType":"calls","source":849,"target":568},{"edgeType":"contains","source":2303,"target":2304},{"edgeType":"calls","source":4214,"target":1957},{"edgeType":"calls","source":4875,"target":494},{"edgeType":"calls","source":774,"target":779},{"edgeType":"contains","source":3226,"target":3287},{"edgeType":"calls","source":2247,"target":570},{"edgeType":"calls","source":849,"target":567},{"edgeType":"contains","source":4648,"target":4658},{"edgeType":"contains","source":2699,"target":2713},{"edgeType":"imports","source":4209,"target":574},{"edgeType":"calls","source":1509,"target":191},{"edgeType":"contains","source":2303,"target":2305},{"edgeType":"calls","source":1726,"target":863},{"edgeType":"calls","source":3319,"target":106},{"edgeType":"calls","source":1330,"target":454},{"edgeType":"extends","source":4840,"target":4499},{"edgeType":"calls","source":4530,"target":1675},{"edgeType":"calls","source":416,"target":249},{"edgeType":"calls","source":4875,"target":493},{"edgeType":"calls","source":4881,"target":307},{"edgeType":"calls","source":2319,"target":453},{"edgeType":"calls","source":747,"target":558},{"edgeType":"calls","source":849,"target":570},{"edgeType":"calls","source":796,"target":99},{"edgeType":"calls","source":2247,"target":567},{"edgeType":"imports","source":32,"target":41},{"edgeType":"calls","source":3507,"target":1675},{"edgeType":"calls","source":1672,"target":426},{"edgeType":"calls","source":4016,"target":3865},{"edgeType":"imports","source":3643,"target":1209},{"edgeType":"calls","source":2820,"target":774},{"edgeType":"calls","source":4875,"target":492},{"edgeType":"calls","source":4881,"target":306},{"edgeType":"calls","source":2765,"target":365},{"edgeType":"calls","source":4845,"target":365},{"edgeType":"contains","source":3413,"target":3832},{"edgeType":"calls","source":2793,"target":554},{"edgeType":"calls","source":849,"target":569},{"edgeType":"calls","source":4435,"target":389},{"edgeType":"calls","source":796,"target":98},{"edgeType":"calls","source":2247,"target":568},{"edgeType":"extends","source":2026,"target":1884},{"edgeType":"calls","source":1672,"target":425},{"edgeType":"calls","source":3603,"target":1871},{"edgeType":"calls","source":4762,"target":1880},{"edgeType":"calls","source":4035,"target":106},{"edgeType":"calls","source":4875,"target":491},{"edgeType":"calls","source":4881,"target":305},{"edgeType":"calls","source":4470,"target":1417},{"edgeType":"calls","source":4405,"target":4489},{"edgeType":"calls","source":4435,"target":388},{"edgeType":"calls","source":3854,"target":3600},{"edgeType":"imports","source":32,"target":39},{"edgeType":"contains","source":4209,"target":4531},{"edgeType":"calls","source":2656,"target":571},{"edgeType":"calls","source":591,"target":106},{"edgeType":"calls","source":2530,"target":249},{"edgeType":"imports","source":3228,"target":325},{"edgeType":"calls","source":4447,"target":4245},{"edgeType":"calls","source":675,"target":673},{"edgeType":"contains","source":1213,"target":1214},{"edgeType":"calls","source":3012,"target":106},{"edgeType":"calls","source":2247,"target":566},{"edgeType":"calls","source":344,"target":362},{"edgeType":"calls","source":4429,"target":573},{"edgeType":"calls","source":4435,"target":387},{"edgeType":"imports","source":32,"target":40},{"edgeType":"contains","source":28,"target":3066},{"edgeType":"calls","source":2656,"target":572},{"edgeType":"calls","source":675,"target":672},{"edgeType":"calls","source":3337,"target":1658},{"edgeType":"calls","source":4586,"target":992},{"edgeType":"calls","source":4879,"target":365},{"edgeType":"calls","source":2793,"target":553},{"edgeType":"imports","source":32,"target":37},{"edgeType":"calls","source":4435,"target":386},{"edgeType":"calls","source":4598,"target":1675},{"edgeType":"contains","source":2303,"target":2306},{"edgeType":"imports","source":3643,"target":1213},{"edgeType":"calls","source":4032,"target":194},{"edgeType":"calls","source":3998,"target":191},{"edgeType":"calls","source":2656,"target":569},{"edgeType":"calls","source":3613,"target":498},{"edgeType":"calls","source":416,"target":248},{"edgeType":"calls","source":849,"target":566},{"edgeType":"calls","source":2905,"target":249},{"edgeType":"calls","source":747,"target":557},{"edgeType":"calls","source":4822,"target":4245},{"edgeType":"contains","source":3226,"target":3291},{"edgeType":"calls","source":4435,"target":385},{"edgeType":"calls","source":4487,"target":887},{"edgeType":"contains","source":2204,"target":2205},{"edgeType":"contains","source":4285,"target":4286},{"edgeType":"calls","source":2656,"target":570},{"edgeType":"imports","source":4001,"target":1744},{"edgeType":"calls","source":2530,"target":248},{"edgeType":"calls","source":344,"target":359},{"edgeType":"extends","source":1757,"target":1776},{"edgeType":"contains","source":396,"target":2234},{"edgeType":"contains","source":2303,"target":2312},{"edgeType":"calls","source":4714,"target":191},{"edgeType":"calls","source":2625,"target":470},{"edgeType":"calls","source":512,"target":436},{"edgeType":"calls","source":2249,"target":499},{"edgeType":"calls","source":4435,"target":384},{"edgeType":"calls","source":2008,"target":570},{"edgeType":"calls","source":2656,"target":567},{"edgeType":"imports","source":1934,"target":285},{"edgeType":"contains","source":4153,"target":4157},{"edgeType":"calls","source":1002,"target":45},{"edgeType":"calls","source":344,"target":358},{"edgeType":"calls","source":1875,"target":464},{"edgeType":"contains","source":3226,"target":3297},{"edgeType":"calls","source":4632,"target":1675},{"edgeType":"calls","source":4638,"target":1489},{"edgeType":"calls","source":2008,"target":569},{"edgeType":"calls","source":4435,"target":383},{"edgeType":"contains","source":4153,"target":4156},{"edgeType":"calls","source":2656,"target":568},{"edgeType":"contains","source":4285,"target":4292},{"edgeType":"calls","source":644,"target":572},{"edgeType":"calls","source":2905,"target":248},{"edgeType":"calls","source":3879,"target":705},{"edgeType":"calls","source":344,"target":361},{"edgeType":"contains","source":4516,"target":4529},{"edgeType":"calls","source":4714,"target":189},{"edgeType":"calls","source":2625,"target":468},{"edgeType":"contains","source":3226,"target":3294},{"edgeType":"contains","source":1160,"target":1807},{"edgeType":"contains","source":2303,"target":2310},{"edgeType":"calls","source":4435,"target":382},{"edgeType":"calls","source":4228,"target":456},{"edgeType":"calls","source":2008,"target":572},{"edgeType":"contains","source":4153,"target":4155},{"edgeType":"contains","source":4120,"target":4121},{"edgeType":"contains","source":3413,"target":3840},{"edgeType":"calls","source":4762,"target":1873},{"edgeType":"contains","source":2631,"target":2712},{"edgeType":"calls","source":3297,"target":777},{"edgeType":"contains","source":4648,"target":4665},{"edgeType":"calls","source":966,"target":106},{"edgeType":"contains","source":3226,"target":3295},{"edgeType":"calls","source":3789,"target":325},{"edgeType":"calls","source":2625,"target":469},{"edgeType":"contains","source":2292,"target":2652},{"edgeType":"calls","source":512,"target":437},{"edgeType":"calls","source":2008,"target":571},{"edgeType":"calls","source":2175,"target":1735},{"edgeType":"contains","source":4153,"target":4154},{"edgeType":"contains","source":2072,"target":2073},{"edgeType":"calls","source":512,"target":438},{"edgeType":"calls","source":2656,"target":566},{"edgeType":"contains","source":2292,"target":2657},{"edgeType":"imports","source":1065,"target":793},{"edgeType":"calls","source":4666,"target":1675},{"edgeType":"calls","source":4672,"target":1489},{"edgeType":"calls","source":2625,"target":466},{"edgeType":"calls","source":4603,"target":457},{"edgeType":"contains","source":3643,"target":4115},{"edgeType":"calls","source":2773,"target":106},{"edgeType":"calls","source":2008,"target":566},{"edgeType":"contains","source":1807,"target":1836},{"edgeType":"calls","source":4537,"target":389},{"edgeType":"calls","source":644,"target":568},{"edgeType":"calls","source":344,"target":355},{"edgeType":"contains","source":2735,"target":551},{"edgeType":"contains","source":4120,"target":4127},{"edgeType":"calls","source":4845,"target":3526},{"edgeType":"contains","source":4285,"target":4297},{"edgeType":"calls","source":1168,"target":179},{"edgeType":"imports","source":4045,"target":2483},{"edgeType":"calls","source":4725,"target":902},{"edgeType":"calls","source":2625,"target":467},{"edgeType":"calls","source":1996,"target":1994},{"edgeType":"calls","source":644,"target":567},{"edgeType":"calls","source":4537,"target":388},{"edgeType":"calls","source":2672,"target":1124},{"edgeType":"calls","source":4603,"target":456},{"edgeType":"calls","source":2813,"target":2039},{"edgeType":"calls","source":3597,"target":2046},{"edgeType":"contains","source":4120,"target":4126},{"edgeType":"contains","source":2735,"target":552},{"edgeType":"contains","source":4153,"target":4160},{"edgeType":"contains","source":1874,"target":1875},{"edgeType":"contains","source":4285,"target":4296},{"edgeType":"contains","source":4648,"target":4670},{"edgeType":"calls","source":3308,"target":1489},{"edgeType":"calls","source":4643,"target":4500},{"edgeType":"calls","source":4725,"target":901},{"edgeType":"contains","source":850,"target":851},{"edgeType":"contains","source":2303,"target":2314},{"edgeType":"calls","source":3892,"target":298},{"edgeType":"contains","source":1114,"target":1123},{"edgeType":"calls","source":4537,"target":387},{"edgeType":"contains","source":3228,"target":3236},{"edgeType":"contains","source":3226,"target":3298},{"edgeType":"calls","source":2008,"target":568},{"edgeType":"contains","source":1807,"target":1834},{"edgeType":"calls","source":2658,"target":498},{"edgeType":"calls","source":344,"target":357},{"edgeType":"calls","source":4210,"target":4182},{"edgeType":"contains","source":650,"target":708},{"edgeType":"calls","source":644,"target":571},{"edgeType":"contains","source":4153,"target":4159},{"edgeType":"contains","source":4285,"target":4295},{"edgeType":"imports","source":1080,"target":325},{"edgeType":"calls","source":3231,"target":1763},{"edgeType":"calls","source":4725,"target":900},{"edgeType":"calls","source":4706,"target":1489},{"edgeType":"calls","source":2625,"target":465},{"edgeType":"contains","source":2303,"target":2315},{"edgeType":"calls","source":2008,"target":567},{"edgeType":"contains","source":3226,"target":3299},{"edgeType":"calls","source":4851,"target":2279},{"edgeType":"calls","source":638,"target":755},{"edgeType":"calls","source":644,"target":569},{"edgeType":"contains","source":1807,"target":1835},{"edgeType":"calls","source":4679,"target":212},{"edgeType":"calls","source":344,"target":356},{"edgeType":"calls","source":4537,"target":386},{"edgeType":"calls","source":4571,"target":389},{"edgeType":"calls","source":4488,"target":1905},{"edgeType":"contains","source":4120,"target":4124},{"edgeType":"contains","source":1940,"target":1941},{"edgeType":"contains","source":3,"target":681},{"edgeType":"calls","source":644,"target":570},{"edgeType":"contains","source":4153,"target":4158},{"edgeType":"contains","source":2735,"target":550},{"edgeType":"calls","source":4726,"target":901},{"edgeType":"calls","source":4783,"target":191},{"edgeType":"calls","source":4019,"target":1677},{"edgeType":"calls","source":2729,"target":1499},{"edgeType":"calls","source":2494,"target":1385},{"edgeType":"contains","source":1204,"target":1473},{"edgeType":"calls","source":2659,"target":498},{"edgeType":"calls","source":4498,"target":570},{"edgeType":"calls","source":4339,"target":1271},{"edgeType":"calls","source":4211,"target":4182},{"edgeType":"contains","source":1807,"target":1808},{"edgeType":"calls","source":3658,"target":183},{"edgeType":"calls","source":4726,"target":900},{"edgeType":"calls","source":1937,"target":1738},{"edgeType":"calls","source":1885,"target":179},{"edgeType":"calls","source":3229,"target":1856},{"edgeType":"calls","source":4498,"target":569},{"edgeType":"contains","source":1939,"target":1945},{"edgeType":"contains","source":4234,"target":4791},{"edgeType":"calls","source":2661,"target":434},{"edgeType":"calls","source":3419,"target":191},{"edgeType":"calls","source":2492,"target":388},{"edgeType":"calls","source":4498,"target":568},{"edgeType":"contains","source":1939,"target":1942},{"edgeType":"calls","source":1427,"target":638},{"edgeType":"calls","source":3359,"target":995},{"edgeType":"calls","source":3205,"target":484},{"edgeType":"imports","source":1749,"target":1763},{"edgeType":"calls","source":4135,"target":194},{"edgeType":"calls","source":2492,"target":389},{"edgeType":"calls","source":4527,"target":725},{"edgeType":"calls","source":4661,"target":1856},{"edgeType":"calls","source":2501,"target":1167},{"edgeType":"contains","source":1204,"target":1474},{"edgeType":"calls","source":2661,"target":435},{"edgeType":"calls","source":4498,"target":567},{"edgeType":"contains","source":3921,"target":3922},{"edgeType":"contains","source":6,"target":3730},{"edgeType":"calls","source":1672,"target":441},{"edgeType":"calls","source":546,"target":460},{"edgeType":"calls","source":1429,"target":570},{"edgeType":"contains","source":3413,"target":3821},{"edgeType":"calls","source":1128,"target":388},{"edgeType":"calls","source":2492,"target":386},{"edgeType":"contains","source":2730,"target":2796},{"edgeType":"calls","source":4523,"target":1905},{"edgeType":"calls","source":4618,"target":4245},{"edgeType":"calls","source":4741,"target":1489},{"edgeType":"calls","source":4498,"target":566},{"edgeType":"calls","source":1728,"target":814},{"edgeType":"calls","source":3828,"target":194},{"edgeType":"contains","source":6,"target":3733},{"edgeType":"contains","source":4284,"target":4302},{"edgeType":"calls","source":1231,"target":365},{"edgeType":"calls","source":1429,"target":569},{"edgeType":"contains","source":3413,"target":3820},{"edgeType":"contains","source":2730,"target":2797},{"edgeType":"calls","source":1128,"target":387},{"edgeType":"calls","source":1154,"target":638},{"edgeType":"contains","source":2699,"target":2701},{"edgeType":"calls","source":2492,"target":387},{"edgeType":"calls","source":2755,"target":690},{"edgeType":"calls","source":2741,"target":1124},{"edgeType":"calls","source":1672,"target":435},{"edgeType":"calls","source":4373,"target":212},{"edgeType":"imports","source":2209,"target":186},{"edgeType":"contains","source":2292,"target":2633},{"edgeType":"contains","source":3226,"target":3273},{"edgeType":"contains","source":1090,"target":1842},{"edgeType":"calls","source":4405,"target":4504},{"edgeType":"contains","source":1807,"target":1810},{"edgeType":"calls","source":2492,"target":384},{"edgeType":"calls","source":4373,"target":211},{"edgeType":"calls","source":1429,"target":572},{"edgeType":"imports","source":4209,"target":564},{"edgeType":"contains","source":2730,"target":2795},{"edgeType":"contains","source":4813,"target":4814},{"edgeType":"calls","source":1128,"target":389},{"edgeType":"contains","source":3413,"target":3818},{"edgeType":"calls","source":4769,"target":1675},{"edgeType":"calls","source":4775,"target":1489},{"edgeType":"calls","source":4405,"target":4503},{"edgeType":"contains","source":3226,"target":3274},{"edgeType":"calls","source":2492,"target":385},{"edgeType":"calls","source":1429,"target":571},{"edgeType":"imports","source":2230,"target":590},{"edgeType":"calls","source":3417,"target":3418},{"edgeType":"contains","source":6,"target":1623},{"edgeType":"calls","source":1429,"target":566},{"edgeType":"contains","source":3413,"target":3825},{"edgeType":"imports","source":32,"target":35},{"edgeType":"contains","source":2631,"target":2698},{"edgeType":"calls","source":1128,"target":384},{"edgeType":"calls","source":991,"target":402},{"edgeType":"contains","source":2730,"target":2800},{"edgeType":"calls","source":2492,"target":382},{"edgeType":"contains","source":2292,"target":2636},{"edgeType":"calls","source":2524,"target":2561},{"edgeType":"calls","source":4405,"target":4502},{"edgeType":"calls","source":4885,"target":191},{"edgeType":"calls","source":2672,"target":88},{"edgeType":"contains","source":3413,"target":3824},{"edgeType":"calls","source":3603,"target":824},{"edgeType":"imports","source":32,"target":36},{"edgeType":"calls","source":991,"target":401},{"edgeType":"contains","source":4648,"target":4650},{"edgeType":"calls","source":1128,"target":383},{"edgeType":"calls","source":4639,"target":1475},{"edgeType":"contains","source":2292,"target":2637},{"edgeType":"calls","source":2492,"target":383},{"edgeType":"imports","source":32,"target":33},{"edgeType":"calls","source":691,"target":191},{"edgeType":"calls","source":549,"target":365},{"edgeType":"calls","source":1429,"target":568},{"edgeType":"contains","source":2303,"target":179},{"edgeType":"contains","source":3420,"target":3606},{"edgeType":"contains","source":3413,"target":3823},{"edgeType":"calls","source":1128,"target":386},{"edgeType":"contains","source":2631,"target":2696},{"edgeType":"calls","source":921,"target":460},{"edgeType":"contains","source":4648,"target":4649},{"edgeType":"calls","source":996,"target":249},{"edgeType":"calls","source":1672,"target":434},{"edgeType":"calls","source":2464,"target":191},{"edgeType":"calls","source":378,"target":381},{"edgeType":"calls","source":3862,"target":191},{"edgeType":"calls","source":456,"target":77},{"edgeType":"calls","source":4660,"target":1880},{"edgeType":"contains","source":1939,"target":1950},{"edgeType":"calls","source":1429,"target":567},{"edgeType":"contains","source":3413,"target":3822},{"edgeType":"contains","source":2631,"target":2697},{"edgeType":"calls","source":3371,"target":1672},{"edgeType":"contains","source":2730,"target":2799},{"edgeType":"calls","source":1128,"target":385},{"edgeType":"calls","source":996,"target":248},{"edgeType":"calls","source":4536,"target":438},{"edgeType":"calls","source":3698,"target":2105},{"edgeType":"calls","source":3741,"target":772},{"edgeType":"contains","source":2292,"target":2635},{"edgeType":"calls","source":4468,"target":1489},{"edgeType":"calls","source":4250,"target":1905},{"edgeType":"calls","source":796,"target":101},{"edgeType":"calls","source":849,"target":572},{"edgeType":"contains","source":2255,"target":2730},{"edgeType":"calls","source":2494,"target":316},{"edgeType":"calls","source":2492,"target":378},{"edgeType":"contains","source":3226,"target":3283},{"edgeType":"calls","source":2365,"target":87},{"edgeType":"calls","source":4536,"target":437},{"edgeType":"calls","source":2228,"target":106},{"edgeType":"calls","source":796,"target":100},{"edgeType":"calls","source":849,"target":571},{"edgeType":"calls","source":4883,"target":249},{"edgeType":"calls","source":1672,"target":427},{"edgeType":"calls","source":1439,"target":1308},{"edgeType":"calls","source":2494,"target":317},{"edgeType":"calls","source":2365,"target":88},{"edgeType":"calls","source":4536,"target":436},{"edgeType":"calls","source":2247,"target":571},{"edgeType":"imports","source":3066,"target":1109},{"edgeType":"contains","source":4648,"target":4653},{"edgeType":"calls","source":3450,"target":3446},{"edgeType":"calls","source":1128,"target":382},{"edgeType":"contains","source":4516,"target":4517},{"edgeType":"calls","source":4661,"target":1845},{"edgeType":"calls","source":4875,"target":496},{"edgeType":"calls","source":4883,"target":248},{"edgeType":"calls","source":4496,"target":1675},{"edgeType":"calls","source":3519,"target":3422},{"edgeType":"calls","source":2247,"target":572},{"edgeType":"calls","source":865,"target":77},{"edgeType":"extends","source":4169,"target":4153},{"edgeType":"calls","source":796,"target":102},{"edgeType":"contains","source":16,"target":3432},{"edgeType":"contains","source":4648,"target":4652},{"edgeType":"calls","source":4710,"target":325},{"edgeType":"calls","source":4875,"target":495},{"edgeType":"calls","source":2494,"target":315},{"edgeType":"contains","source":2565,"target":2605},{"edgeType":"calls","source":3664,"target":2194},{"edgeType":"contains","source":4176,"target":4459},{"edgeType":"calls","source":986,"target":648},{"edgeType":"calls","source":4663,"target":1880},{"edgeType":"calls","source":2561,"target":2562},{"edgeType":"calls","source":4831,"target":900},{"edgeType":"calls","source":4806,"target":1675},{"edgeType":"calls","source":4505,"target":436},{"edgeType":"calls","source":4547,"target":191},{"edgeType":"calls","source":546,"target":547},{"edgeType":"contains","source":3226,"target":3254},{"edgeType":"calls","source":378,"target":470},{"edgeType":"calls","source":4280,"target":3183},{"edgeType":"calls","source":2311,"target":1856},{"edgeType":"calls","source":2906,"target":324},{"edgeType":"contains","source":2565,"target":2606},{"edgeType":"calls","source":2755,"target":777},{"edgeType":"calls","source":2764,"target":498},{"edgeType":"contains","source":4176,"target":4458},{"edgeType":"contains","source":2280,"target":2985},{"edgeType":"calls","source":4743,"target":456},{"edgeType":"calls","source":2561,"target":2563},{"edgeType":"calls","source":208,"target":454},{"edgeType":"imports","source":3571,"target":1095},{"edgeType":"calls","source":378,"target":469},{"edgeType":"contains","source":3050,"target":3426},{"edgeType":"calls","source":4598,"target":723},{"edgeType":"calls","source":4348,"target":4245},{"edgeType":"calls","source":1472,"target":383},{"edgeType":"calls","source":2846,"target":1124},{"edgeType":"calls","source":3442,"target":1675},{"edgeType":"calls","source":933,"target":179},{"edgeType":"contains","source":4176,"target":4457},{"edgeType":"contains","source":2565,"target":2603},{"edgeType":"contains","source":2401,"target":2402},{"edgeType":"contains","source":2280,"target":2981},{"edgeType":"calls","source":4642,"target":1472},{"edgeType":"calls","source":4125,"target":585},{"edgeType":"calls","source":1856,"target":106},{"edgeType":"calls","source":2798,"target":498},{"edgeType":"contains","source":3226,"target":3252},{"edgeType":"calls","source":4598,"target":722},{"edgeType":"contains","source":1204,"target":1458},{"edgeType":"calls","source":1472,"target":382},{"edgeType":"contains","source":2565,"target":2604},{"edgeType":"calls","source":3368,"target":1856},{"edgeType":"contains","source":287,"target":288},{"edgeType":"calls","source":4697,"target":1880},{"edgeType":"calls","source":2494,"target":2524},{"edgeType":"calls","source":4125,"target":586},{"edgeType":"calls","source":2386,"target":587},{"edgeType":"calls","source":2008,"target":1735},{"edgeType":"calls","source":4886,"target":249},{"edgeType":"imports","source":1934,"target":42},{"edgeType":"contains","source":1204,"target":1461},{"edgeType":"calls","source":2974,"target":325},{"edgeType":"calls","source":2265,"target":106},{"edgeType":"calls","source":185,"target":106},{"edgeType":"contains","source":2565,"target":2609},{"edgeType":"contains","source":287,"target":291},{"edgeType":"contains","source":4176,"target":4463},{"edgeType":"calls","source":1267,"target":389},{"edgeType":"imports","source":1247,"target":196},{"edgeType":"calls","source":2834,"target":437},{"edgeType":"imports","source":1934,"target":41},{"edgeType":"calls","source":378,"target":466},{"edgeType":"calls","source":4886,"target":248},{"edgeType":"calls","source":451,"target":317},{"edgeType":"calls","source":4532,"target":652},{"edgeType":"calls","source":4664,"target":1845},{"edgeType":"calls","source":4592,"target":906},{"edgeType":"calls","source":4598,"target":720},{"edgeType":"calls","source":2207,"target":1905},{"edgeType":"calls","source":4280,"target":3177},{"edgeType":"contains","source":2565,"target":2610},{"edgeType":"calls","source":3933,"target":194},{"edgeType":"contains","source":287,"target":290},{"edgeType":"contains","source":4176,"target":4462},{"edgeType":"calls","source":1159,"target":565},{"edgeType":"calls","source":1267,"target":388},{"edgeType":"calls","source":378,"target":465},{"edgeType":"calls","source":4598,"target":719},{"edgeType":"calls","source":2457,"target":498},{"edgeType":"calls","source":2761,"target":587},{"edgeType":"calls","source":451,"target":316},{"edgeType":"calls","source":2834,"target":438},{"edgeType":"calls","source":4800,"target":1856},{"edgeType":"imports","source":1934,"target":40},{"edgeType":"contains","source":2565,"target":2607},{"edgeType":"contains","source":3326,"target":3328},{"edgeType":"contains","source":1204,"target":1463},{"edgeType":"contains","source":287,"target":293},{"edgeType":"imports","source":621,"target":574},{"edgeType":"contains","source":4234,"target":4777},{"edgeType":"contains","source":4176,"target":4461},{"edgeType":"contains","source":4284,"target":4285},{"edgeType":"contains","source":31,"target":4001},{"edgeType":"calls","source":4615,"target":191},{"edgeType":"calls","source":4598,"target":718},{"edgeType":"imports","source":1934,"target":39},{"edgeType":"calls","source":378,"target":468},{"edgeType":"contains","source":3226,"target":3256},{"edgeType":"calls","source":4685,"target":3306},{"edgeType":"calls","source":2953,"target":3089},{"edgeType":"contains","source":2565,"target":2608},{"edgeType":"contains","source":3226,"target":3258},{"edgeType":"contains","source":1204,"target":1462},{"edgeType":"calls","source":2215,"target":1655},{"edgeType":"contains","source":287,"target":292},{"edgeType":"calls","source":1629,"target":1853},{"edgeType":"contains","source":4176,"target":4460},{"edgeType":"calls","source":3356,"target":1166},{"edgeType":"calls","source":1956,"target":1229},{"edgeType":"contains","source":2269,"target":2271},{"edgeType":"calls","source":3468,"target":865},{"edgeType":"calls","source":2876,"target":191},{"edgeType":"calls","source":2834,"target":436},{"edgeType":"calls","source":378,"target":467},{"edgeType":"calls","source":4598,"target":717},{"edgeType":"calls","source":4663,"target":1873},{"edgeType":"calls","source":4493,"target":1856},{"edgeType":"contains","source":3226,"target":3263},{"edgeType":"calls","source":4598,"target":715},{"edgeType":"contains","source":1204,"target":1465},{"edgeType":"contains","source":287,"target":295},{"edgeType":"calls","source":4314,"target":1063},{"edgeType":"calls","source":1267,"target":385},{"edgeType":"contains","source":4086,"target":4087},{"edgeType":"calls","source":3502,"target":865},{"edgeType":"contains","source":4382,"target":1253},{"edgeType":"contains","source":2255,"target":2710},{"edgeType":"contains","source":650,"target":669},{"edgeType":"calls","source":4598,"target":716},{"edgeType":"calls","source":4725,"target":3121},{"edgeType":"calls","source":4542,"target":336},{"edgeType":"imports","source":1918,"target":548},{"edgeType":"contains","source":1204,"target":1464},{"edgeType":"calls","source":4438,"target":389},{"edgeType":"calls","source":4598,"target":714},{"edgeType":"calls","source":1510,"target":1308},{"edgeType":"contains","source":287,"target":294},{"edgeType":"calls","source":3548,"target":498},{"edgeType":"calls","source":4308,"target":191},{"edgeType":"contains","source":2038,"target":2039},{"edgeType":"contains","source":650,"target":668},{"edgeType":"calls","source":1267,"target":384},{"edgeType":"calls","source":4658,"target":969},{"edgeType":"calls","source":4779,"target":389},{"edgeType":"calls","source":2792,"target":2793},{"edgeType":"contains","source":287,"target":297},{"edgeType":"calls","source":4438,"target":388},{"edgeType":"calls","source":4598,"target":713},{"edgeType":"contains","source":1204,"target":1467},{"edgeType":"calls","source":3523,"target":212},{"edgeType":"imports","source":2975,"target":548},{"edgeType":"calls","source":4708,"target":4703},{"edgeType":"contains","source":4382,"target":1251},{"edgeType":"contains","source":16,"target":2356},{"edgeType":"calls","source":1267,"target":387},{"edgeType":"calls","source":754,"target":435},{"edgeType":"calls","source":451,"target":315},{"edgeType":"calls","source":4754,"target":106},{"edgeType":"calls","source":4779,"target":388},{"edgeType":"calls","source":3030,"target":1754},{"edgeType":"contains","source":1204,"target":1466},{"edgeType":"calls","source":4598,"target":712},{"edgeType":"calls","source":4438,"target":387},{"edgeType":"calls","source":4432,"target":573},{"edgeType":"calls","source":1729,"target":863},{"edgeType":"imports","source":3936,"target":344},{"edgeType":"calls","source":1267,"target":386},{"edgeType":"calls","source":754,"target":434},{"edgeType":"calls","source":4779,"target":387},{"edgeType":"calls","source":4607,"target":1489},{"edgeType":"contains","source":3226,"target":3267},{"edgeType":"contains","source":1204,"target":1469},{"edgeType":"calls","source":4035,"target":194},{"edgeType":"calls","source":4438,"target":386},{"edgeType":"calls","source":2051,"target":389},{"edgeType":"contains","source":3326,"target":3338},{"edgeType":"calls","source":2032,"target":2035},{"edgeType":"calls","source":777,"target":773},{"edgeType":"calls","source":2765,"target":454},{"edgeType":"calls","source":2656,"target":662},{"edgeType":"calls","source":4779,"target":386},{"edgeType":"calls","source":2895,"target":2766},{"edgeType":"calls","source":1229,"target":502},{"edgeType":"calls","source":4779,"target":384},{"edgeType":"calls","source":4438,"target":385},{"edgeType":"contains","source":1204,"target":1468},{"edgeType":"calls","source":1951,"target":317},{"edgeType":"calls","source":2051,"target":388},{"edgeType":"calls","source":479,"target":496},{"edgeType":"calls","source":4260,"target":1675},{"edgeType":"calls","source":3523,"target":211},{"edgeType":"calls","source":4779,"target":385},{"edgeType":"calls","source":4731,"target":1873},{"edgeType":"calls","source":3209,"target":1489},{"edgeType":"calls","source":4726,"target":969},{"edgeType":"contains","source":3226,"target":3265},{"edgeType":"calls","source":4779,"target":383},{"edgeType":"calls","source":4807,"target":572},{"edgeType":"calls","source":4438,"target":384},{"edgeType":"contains","source":1204,"target":1471},{"edgeType":"calls","source":1851,"target":249},{"edgeType":"contains","source":2038,"target":2040},{"edgeType":"calls","source":3792,"target":325},{"edgeType":"calls","source":1205,"target":191},{"edgeType":"calls","source":3715,"target":1655},{"edgeType":"calls","source":1267,"target":383},{"edgeType":"calls","source":777,"target":775},{"edgeType":"calls","source":4518,"target":4245},{"edgeType":"calls","source":4618,"target":88},{"edgeType":"calls","source":1851,"target":248},{"edgeType":"calls","source":4779,"target":382},{"edgeType":"calls","source":4765,"target":1873},{"edgeType":"calls","source":4807,"target":571},{"edgeType":"calls","source":1651,"target":106},{"edgeType":"calls","source":2652,"target":784},{"edgeType":"contains","source":1204,"target":1470},{"edgeType":"calls","source":1858,"target":1088},{"edgeType":"calls","source":4438,"target":383},{"edgeType":"calls","source":4873,"target":4868},{"edgeType":"calls","source":1229,"target":503},{"edgeType":"calls","source":1267,"target":382},{"edgeType":"calls","source":864,"target":191},{"edgeType":"calls","source":1128,"target":491},{"edgeType":"contains","source":3710,"target":4090},{"edgeType":"calls","source":4098,"target":384},{"edgeType":"calls","source":2395,"target":325},{"edgeType":"calls","source":2892,"target":774},{"edgeType":"contains","source":637,"target":1047},{"edgeType":"contains","source":3920,"target":3923},{"edgeType":"calls","source":2979,"target":191},{"edgeType":"calls","source":921,"target":566},{"edgeType":"imports","source":4376,"target":434},{"edgeType":"imports","source":2255,"target":648},{"edgeType":"contains","source":2565,"target":2588},{"edgeType":"contains","source":4382,"target":4398},{"edgeType":"calls","source":1128,"target":490},{"edgeType":"calls","source":4519,"target":4245},{"edgeType":"contains","source":1516,"target":2340},{"edgeType":"calls","source":4636,"target":1675},{"edgeType":"calls","source":3843,"target":891},{"edgeType":"calls","source":4493,"target":1880},{"edgeType":"imports","source":1247,"target":185},{"edgeType":"calls","source":4098,"target":385},{"edgeType":"contains","source":681,"target":739},{"edgeType":"extends","source":1288,"target":1262},{"edgeType":"contains","source":2565,"target":2589},{"edgeType":"imports","source":44,"target":482},{"edgeType":"imports","source":4376,"target":435},{"edgeType":"calls","source":2602,"target":248},{"edgeType":"calls","source":1128,"target":493},{"edgeType":"calls","source":1055,"target":642},{"edgeType":"calls","source":4098,"target":382},{"edgeType":"calls","source":1880,"target":436},{"edgeType":"contains","source":3066,"target":797},{"edgeType":"calls","source":4573,"target":456},{"edgeType":"contains","source":1516,"target":2337},{"edgeType":"calls","source":4341,"target":249},{"edgeType":"contains","source":637,"target":1049},{"edgeType":"contains","source":3920,"target":3921},{"edgeType":"calls","source":921,"target":568},{"edgeType":"calls","source":3414,"target":445},{"edgeType":"contains","source":2565,"target":2586},{"edgeType":"contains","source":4382,"target":4397},{"edgeType":"calls","source":1128,"target":492},{"edgeType":"calls","source":2602,"target":249},{"edgeType":"calls","source":4098,"target":383},{"edgeType":"calls","source":4849,"target":3526},{"edgeType":"contains","source":3520,"target":3635},{"edgeType":"calls","source":4341,"target":248},{"edgeType":"contains","source":637,"target":1048},{"edgeType":"calls","source":2935,"target":497},{"edgeType":"calls","source":921,"target":567},{"edgeType":"contains","source":2565,"target":2587},{"edgeType":"calls","source":3414,"target":446},{"edgeType":"contains","source":1516,"target":2343},{"edgeType":"calls","source":556,"target":249},{"edgeType":"calls","source":4104,"target":194},{"edgeType":"calls","source":1128,"target":487},{"edgeType":"calls","source":4676,"target":1489},{"edgeType":"calls","source":697,"target":106},{"edgeType":"calls","source":2231,"target":2234},{"edgeType":"contains","source":2565,"target":2592},{"edgeType":"contains","source":637,"target":1051},{"edgeType":"calls","source":3917,"target":705},{"edgeType":"calls","source":556,"target":248},{"edgeType":"calls","source":1157,"target":644},{"edgeType":"calls","source":1128,"target":486},{"edgeType":"contains","source":681,"target":2858},{"edgeType":"contains","source":1516,"target":2344},{"edgeType":"calls","source":2429,"target":325},{"edgeType":"calls","source":2436,"target":108},{"edgeType":"calls","source":887,"target":558},{"edgeType":"contains","source":2565,"target":2593},{"edgeType":"contains","source":3710,"target":4094},{"edgeType":"calls","source":3601,"target":2046},{"edgeType":"calls","source":2662,"target":498},{"edgeType":"contains","source":1516,"target":2341},{"edgeType":"contains","source":4382,"target":4401},{"edgeType":"contains","source":3710,"target":4092},{"edgeType":"calls","source":1128,"target":489},{"edgeType":"contains","source":650,"target":651},{"edgeType":"calls","source":4630,"target":1856},{"edgeType":"calls","source":2323,"target":437},{"edgeType":"contains","source":2565,"target":2590},{"edgeType":"calls","source":921,"target":564},{"edgeType":"calls","source":4214,"target":4182},{"edgeType":"calls","source":1370,"target":1443},{"edgeType":"calls","source":3661,"target":183},{"edgeType":"calls","source":1873,"target":1705},{"edgeType":"contains","source":1516,"target":2342},{"edgeType":"contains","source":4382,"target":4400},{"edgeType":"calls","source":1128,"target":488},{"edgeType":"contains","source":3710,"target":4091},{"edgeType":"contains","source":637,"target":1053},{"edgeType":"calls","source":4575,"target":389},{"edgeType":"calls","source":4587,"target":4245},{"edgeType":"calls","source":2323,"target":438},{"edgeType":"contains","source":2565,"target":2591},{"edgeType":"calls","source":4492,"target":1905},{"edgeType":"calls","source":4279,"target":4280},{"edgeType":"contains","source":637,"target":1052},{"edgeType":"calls","source":1517,"target":1113},{"edgeType":"calls","source":2035,"target":906},{"edgeType":"calls","source":1472,"target":389},{"edgeType":"contains","source":2565,"target":2597},{"edgeType":"calls","source":4786,"target":189},{"edgeType":"calls","source":4824,"target":68},{"edgeType":"calls","source":2925,"target":1856},{"edgeType":"calls","source":4575,"target":388},{"edgeType":"contains","source":2565,"target":2596},{"edgeType":"calls","source":4369,"target":1489},{"edgeType":"calls","source":2283,"target":1675},{"edgeType":"contains","source":3920,"target":3931},{"edgeType":"calls","source":4138,"target":194},{"edgeType":"calls","source":1336,"target":376},{"edgeType":"calls","source":1472,"target":388},{"edgeType":"contains","source":650,"target":652},{"edgeType":"contains","source":2565,"target":2598},{"edgeType":"calls","source":1231,"target":460},{"edgeType":"calls","source":2524,"target":2661},{"edgeType":"calls","source":2365,"target":191},{"edgeType":"calls","source":2971,"target":1489},{"edgeType":"calls","source":4575,"target":387},{"edgeType":"calls","source":4577,"target":325},{"edgeType":"calls","source":2323,"target":436},{"edgeType":"contains","source":3623,"target":3624},{"edgeType":"contains","source":3920,"target":3930},{"edgeType":"calls","source":1907,"target":1705},{"edgeType":"calls","source":2763,"target":534},{"edgeType":"contains","source":1516,"target":2345},{"edgeType":"calls","source":1128,"target":485},{"edgeType":"calls","source":4784,"target":249},{"edgeType":"imports","source":4045,"target":1175},{"edgeType":"calls","source":2872,"target":326},{"edgeType":"imports","source":1934,"target":35},{"edgeType":"calls","source":1672,"target":533},{"edgeType":"calls","source":887,"target":557},{"edgeType":"imports","source":4209,"target":320},{"edgeType":"calls","source":4575,"target":386},{"edgeType":"contains","source":2565,"target":2594},{"edgeType":"contains","source":3710,"target":4097},{"edgeType":"contains","source":3643,"target":4060},{"edgeType":"imports","source":2000,"target":103},{"edgeType":"calls","source":4831,"target":905},{"edgeType":"calls","source":2740,"target":191},{"edgeType":"contains","source":2280,"target":1917},{"edgeType":"contains","source":1516,"target":2346},{"edgeType":"calls","source":3437,"target":1839},{"edgeType":"calls","source":4784,"target":248},{"edgeType":"calls","source":4810,"target":499},{"edgeType":"calls","source":2964,"target":1703},{"edgeType":"calls","source":208,"target":464},{"edgeType":"contains","source":2565,"target":2595},{"edgeType":"calls","source":4575,"target":385},{"edgeType":"contains","source":3710,"target":4096},{"edgeType":"contains","source":2292,"target":2602},{"edgeType":"calls","source":1472,"target":385},{"edgeType":"calls","source":2872,"target":324},{"edgeType":"calls","source":4854,"target":191},{"edgeType":"calls","source":789,"target":417},{"edgeType":"calls","source":694,"target":191},{"edgeType":"calls","source":4779,"target":402},{"edgeType":"contains","source":2565,"target":2601},{"edgeType":"calls","source":2458,"target":474},{"edgeType":"calls","source":4575,"target":384},{"edgeType":"calls","source":416,"target":353},{"edgeType":"calls","source":459,"target":77},{"edgeType":"calls","source":4410,"target":1271},{"edgeType":"calls","source":83,"target":106},{"edgeType":"contains","source":38,"target":601},{"edgeType":"calls","source":1472,"target":384},{"edgeType":"calls","source":2872,"target":325},{"edgeType":"calls","source":4779,"target":401},{"edgeType":"calls","source":4772,"target":1675},{"edgeType":"calls","source":4778,"target":1489},{"edgeType":"calls","source":3280,"target":2476},{"edgeType":"calls","source":4575,"target":383},{"edgeType":"contains","source":2280,"target":2980},{"edgeType":"calls","source":1728,"target":904},{"edgeType":"calls","source":4074,"target":3230},{"edgeType":"calls","source":1472,"target":387},{"edgeType":"calls","source":4831,"target":902},{"edgeType":"calls","source":2764,"target":499},{"edgeType":"contains","source":2565,"target":2599},{"edgeType":"calls","source":3390,"target":2234},{"edgeType":"calls","source":2458,"target":472},{"edgeType":"calls","source":4575,"target":382},{"edgeType":"calls","source":2561,"target":2564},{"edgeType":"calls","source":4437,"target":1489},{"edgeType":"calls","source":4505,"target":438},{"edgeType":"contains","source":650,"target":658},{"edgeType":"contains","source":38,"target":603},{"edgeType":"calls","source":1472,"target":386},{"edgeType":"calls","source":4831,"target":901},{"edgeType":"contains","source":2565,"target":2600},{"edgeType":"contains","source":2280,"target":1921},{"edgeType":"extends","source":2803,"target":1874},{"edgeType":"imports","source":4209,"target":325},{"edgeType":"calls","source":2458,"target":473},{"edgeType":"calls","source":416,"target":354},{"edgeType":"calls","source":4505,"target":437},{"edgeType":"extends","source":1621,"target":1520},{"edgeType":"calls","source":4025,"target":519},{"edgeType":"calls","source":817,"target":569},{"edgeType":"calls","source":985,"target":646},{"edgeType":"calls","source":1629,"target":1823},{"edgeType":"calls","source":3407,"target":1672},{"edgeType":"contains","source":4382,"target":4383},{"edgeType":"calls","source":4641,"target":1472},{"edgeType":"calls","source":3272,"target":571},{"edgeType":"contains","source":3710,"target":4074},{"edgeType":"calls","source":625,"target":179},{"edgeType":"calls","source":2788,"target":777},{"edgeType":"calls","source":378,"target":437},{"edgeType":"contains","source":1538,"target":1641},{"edgeType":"calls","source":4396,"target":1668},{"edgeType":"contains","source":2631,"target":2641},{"edgeType":"calls","source":817,"target":568},{"edgeType":"imports","source":4001,"target":482},{"edgeType":"calls","source":3100,"target":2733},{"edgeType":"calls","source":1818,"target":191},{"edgeType":"calls","source":1629,"target":1822},{"edgeType":"calls","source":4710,"target":389},{"edgeType":"calls","source":3272,"target":572},{"edgeType":"contains","source":3710,"target":4073},{"edgeType":"calls","source":725,"target":249},{"edgeType":"calls","source":4396,"target":1667},{"edgeType":"calls","source":378,"target":436},{"edgeType":"calls","source":411,"target":470},{"edgeType":"calls","source":4576,"target":1372},{"edgeType":"calls","source":4628,"target":817},{"edgeType":"extends","source":2777,"target":2716},{"edgeType":"calls","source":4396,"target":1665},{"edgeType":"calls","source":824,"target":354},{"edgeType":"calls","source":817,"target":571},{"edgeType":"contains","source":2259,"target":1485},{"edgeType":"contains","source":2631,"target":2638},{"edgeType":"contains","source":4376,"target":4566},{"edgeType":"calls","source":1367,"target":434},{"edgeType":"calls","source":3280,"target":2435},{"edgeType":"contains","source":3710,"target":4072},{"edgeType":"calls","source":4065,"target":298},{"edgeType":"calls","source":4710,"target":388},{"edgeType":"calls","source":4663,"target":1845},{"edgeType":"calls","source":3272,"target":569},{"edgeType":"calls","source":4396,"target":1666},{"edgeType":"calls","source":2435,"target":2205},{"edgeType":"contains","source":3424,"target":3425},{"edgeType":"calls","source":817,"target":570},{"edgeType":"calls","source":824,"target":353},{"edgeType":"contains","source":637,"target":1032},{"edgeType":"calls","source":4396,"target":1664},{"edgeType":"contains","source":4376,"target":4565},{"edgeType":"calls","source":3272,"target":570},{"edgeType":"calls","source":4092,"target":519},{"edgeType":"calls","source":2456,"target":498},{"edgeType":"calls","source":4710,"target":387},{"edgeType":"calls","source":378,"target":438},{"edgeType":"calls","source":4396,"target":1663},{"edgeType":"contains","source":3259,"target":3260},{"edgeType":"calls","source":4396,"target":606},{"edgeType":"calls","source":2965,"target":571},{"edgeType":"calls","source":1852,"target":191},{"edgeType":"calls","source":1958,"target":1133},{"edgeType":"calls","source":1367,"target":427},{"edgeType":"calls","source":4237,"target":249},{"edgeType":"calls","source":3272,"target":567},{"edgeType":"calls","source":2490,"target":498},{"edgeType":"calls","source":411,"target":467},{"edgeType":"calls","source":4710,"target":386},{"edgeType":"contains","source":3226,"target":3227},{"edgeType":"calls","source":4396,"target":1662},{"edgeType":"calls","source":2965,"target":572},{"edgeType":"calls","source":4396,"target":605},{"edgeType":"calls","source":2214,"target":1655},{"edgeType":"calls","source":1869,"target":720},{"edgeType":"calls","source":3272,"target":568},{"edgeType":"contains","source":4382,"target":4386},{"edgeType":"imports","source":3098,"target":3099},{"edgeType":"calls","source":1367,"target":426},{"edgeType":"calls","source":411,"target":466},{"edgeType":"calls","source":4710,"target":385},{"edgeType":"calls","source":4883,"target":307},{"edgeType":"calls","source":817,"target":567},{"edgeType":"calls","source":3039,"target":389},{"edgeType":"calls","source":4492,"target":1856},{"edgeType":"calls","source":3451,"target":301},{"edgeType":"calls","source":1869,"target":723},{"edgeType":"contains","source":4382,"target":4385},{"edgeType":"contains","source":3710,"target":4076},{"edgeType":"calls","source":1271,"target":1291},{"edgeType":"calls","source":1150,"target":814},{"edgeType":"calls","source":725,"target":248},{"edgeType":"calls","source":344,"target":432},{"edgeType":"calls","source":411,"target":469},{"edgeType":"calls","source":2965,"target":569},{"edgeType":"calls","source":4710,"target":384},{"edgeType":"calls","source":4740,"target":4739},{"edgeType":"calls","source":4883,"target":306},{"edgeType":"calls","source":4847,"target":365},{"edgeType":"calls","source":2791,"target":2792},{"edgeType":"calls","source":890,"target":417},{"edgeType":"calls","source":4541,"target":336},{"edgeType":"calls","source":846,"target":724},{"edgeType":"calls","source":2298,"target":106},{"edgeType":"calls","source":3564,"target":2085},{"edgeType":"calls","source":1869,"target":722},{"edgeType":"calls","source":4037,"target":106},{"edgeType":"calls","source":3417,"target":299},{"edgeType":"contains","source":4382,"target":4384},{"edgeType":"calls","source":4237,"target":248},{"edgeType":"calls","source":3272,"target":566},{"edgeType":"calls","source":3264,"target":1871},{"edgeType":"calls","source":344,"target":431},{"edgeType":"calls","source":2453,"target":587},{"edgeType":"calls","source":4710,"target":383},{"edgeType":"calls","source":411,"target":468},{"edgeType":"calls","source":2965,"target":570},{"edgeType":"calls","source":817,"target":566},{"edgeType":"calls","source":4883,"target":305},{"edgeType":"calls","source":3841,"target":894},{"edgeType":"calls","source":1762,"target":863},{"edgeType":"contains","source":2565,"target":2580},{"edgeType":"calls","source":4588,"target":992},{"edgeType":"contains","source":482,"target":559},{"edgeType":"calls","source":1869,"target":717},{"edgeType":"calls","source":1877,"target":469},{"edgeType":"calls","source":4071,"target":106},{"edgeType":"calls","source":1271,"target":1285},{"edgeType":"calls","source":3302,"target":690},{"edgeType":"calls","source":4710,"target":382},{"edgeType":"calls","source":3039,"target":387},{"edgeType":"calls","source":3029,"target":1754},{"edgeType":"calls","source":2980,"target":102},{"edgeType":"calls","source":2965,"target":567},{"edgeType":"calls","source":344,"target":424},{"edgeType":"calls","source":4431,"target":573},{"edgeType":"calls","source":1877,"target":468},{"edgeType":"calls","source":1869,"target":716},{"edgeType":"imports","source":3936,"target":375},{"edgeType":"calls","source":3339,"target":1658},{"edgeType":"imports","source":621,"target":622},{"edgeType":"contains","source":2565,"target":2581},{"edgeType":"calls","source":3039,"target":388},{"edgeType":"calls","source":2965,"target":568},{"edgeType":"calls","source":1168,"target":249},{"edgeType":"contains","source":482,"target":561},{"edgeType":"calls","source":3680,"target":1655},{"edgeType":"calls","source":4034,"target":194},{"edgeType":"calls","source":1869,"target":719},{"edgeType":"calls","source":4740,"target":4735},{"edgeType":"calls","source":2868,"target":401},{"edgeType":"contains","source":3,"target":612},{"edgeType":"calls","source":1367,"target":425},{"edgeType":"calls","source":411,"target":465},{"edgeType":"calls","source":2980,"target":100},{"edgeType":"calls","source":2894,"target":2766},{"edgeType":"contains","source":637,"target":1041},{"edgeType":"calls","source":3039,"target":385},{"edgeType":"calls","source":3792,"target":298},{"edgeType":"contains","source":482,"target":560},{"edgeType":"calls","source":4537,"target":456},{"edgeType":"contains","source":2565,"target":2579},{"edgeType":"calls","source":2602,"target":191},{"edgeType":"calls","source":1869,"target":718},{"edgeType":"calls","source":1877,"target":470},{"edgeType":"calls","source":1509,"target":1308},{"edgeType":"extends","source":4163,"target":4153},{"edgeType":"calls","source":1326,"target":638},{"edgeType":"contains","source":681,"target":3904},{"edgeType":"contains","source":6,"target":3689},{"edgeType":"calls","source":2965,"target":566},{"edgeType":"calls","source":2980,"target":101},{"edgeType":"calls","source":4730,"target":1873},{"edgeType":"calls","source":2868,"target":402},{"edgeType":"imports","source":3768,"target":300},{"edgeType":"calls","source":3039,"target":386},{"edgeType":"calls","source":2470,"target":1109},{"edgeType":"calls","source":2527,"target":2513},{"edgeType":"calls","source":1877,"target":465},{"edgeType":"calls","source":1869,"target":713},{"edgeType":"calls","source":1738,"target":546},{"edgeType":"calls","source":4725,"target":969},{"edgeType":"calls","source":4465,"target":573},{"edgeType":"calls","source":308,"target":480},{"edgeType":"calls","source":2251,"target":499},{"edgeType":"contains","source":3520,"target":3634},{"edgeType":"calls","source":1498,"target":586},{"edgeType":"calls","source":3039,"target":383},{"edgeType":"contains","source":2565,"target":2584},{"edgeType":"calls","source":2980,"target":98},{"edgeType":"contains","source":4382,"target":4395},{"edgeType":"contains","source":637,"target":1043},{"edgeType":"calls","source":453,"target":212},{"edgeType":"calls","source":4609,"target":336},{"edgeType":"calls","source":3841,"target":891},{"edgeType":"calls","source":1719,"target":77},{"edgeType":"calls","source":1869,"target":712},{"edgeType":"calls","source":4806,"target":571},{"edgeType":"contains","source":3520,"target":3633},{"edgeType":"calls","source":1498,"target":585},{"edgeType":"calls","source":3485,"target":299},{"edgeType":"calls","source":4872,"target":4868},{"edgeType":"calls","source":3583,"target":1489},{"edgeType":"calls","source":1271,"target":1280},{"edgeType":"calls","source":4806,"target":572},{"edgeType":"calls","source":3039,"target":384},{"edgeType":"calls","source":2980,"target":99},{"edgeType":"calls","source":1002,"target":106},{"edgeType":"contains","source":798,"target":1336},{"edgeType":"contains","source":637,"target":1042},{"edgeType":"contains","source":2565,"target":2585},{"edgeType":"contains","source":3094,"target":3096},{"edgeType":"calls","source":1677,"target":325},{"edgeType":"calls","source":4806,"target":570},{"edgeType":"contains","source":1516,"target":2333},{"edgeType":"calls","source":1869,"target":715},{"edgeType":"calls","source":1877,"target":467},{"edgeType":"calls","source":4230,"target":456},{"edgeType":"calls","source":4571,"target":456},{"edgeType":"contains","source":3520,"target":3632},{"edgeType":"calls","source":2317,"target":565},{"edgeType":"calls","source":4364,"target":531},{"edgeType":"contains","source":637,"target":1045},{"edgeType":"calls","source":4878,"target":3624},{"edgeType":"extends","source":1324,"target":1262},{"edgeType":"contains","source":2565,"target":2582},{"edgeType":"contains","source":4382,"target":4393},{"edgeType":"calls","source":3299,"target":777},{"edgeType":"calls","source":1168,"target":248},{"edgeType":"contains","source":3094,"target":3097},{"edgeType":"calls","source":4594,"target":1856},{"edgeType":"calls","source":1877,"target":466},{"edgeType":"calls","source":1869,"target":714},{"edgeType":"calls","source":1839,"target":587},{"edgeType":"calls","source":4806,"target":569},{"edgeType":"calls","source":2741,"target":106},{"edgeType":"calls","source":4068,"target":194},{"edgeType":"calls","source":308,"target":481},{"edgeType":"calls","source":4364,"target":530},{"edgeType":"contains","source":3710,"target":4083},{"edgeType":"contains","source":3520,"target":3631},{"edgeType":"contains","source":2565,"target":2583},{"edgeType":"contains","source":4382,"target":4392},{"edgeType":"calls","source":3039,"target":382},{"edgeType":"contains","source":637,"target":1044},{"edgeType":"calls","source":4807,"target":570},{"edgeType":"calls","source":2051,"target":385},{"edgeType":"calls","source":4849,"target":325},{"edgeType":"calls","source":208,"target":438},{"edgeType":"calls","source":587,"target":316},{"edgeType":"calls","source":512,"target":527},{"edgeType":"calls","source":479,"target":493},{"edgeType":"calls","source":4438,"target":382},{"edgeType":"calls","source":4340,"target":249},{"edgeType":"calls","source":817,"target":586},{"edgeType":"imports","source":1934,"target":1119},{"edgeType":"calls","source":1719,"target":106},{"edgeType":"calls","source":1661,"target":847},{"edgeType":"calls","source":479,"target":492},{"edgeType":"calls","source":4807,"target":569},{"edgeType":"contains","source":2928,"target":2931},{"edgeType":"calls","source":2051,"target":384},{"edgeType":"calls","source":587,"target":315},{"edgeType":"contains","source":1516,"target":2307},{"edgeType":"calls","source":817,"target":585},{"edgeType":"calls","source":4340,"target":248},{"edgeType":"calls","source":208,"target":437},{"edgeType":"imports","source":1934,"target":1118},{"edgeType":"contains","source":6,"target":3662},{"edgeType":"contains","source":798,"target":1307},{"edgeType":"calls","source":4669,"target":1675},{"edgeType":"calls","source":4807,"target":568},{"edgeType":"calls","source":4024,"target":3700},{"edgeType":"calls","source":1951,"target":316},{"edgeType":"calls","source":2051,"target":387},{"edgeType":"calls","source":2833,"target":453},{"edgeType":"calls","source":479,"target":495},{"edgeType":"calls","source":4606,"target":457},{"edgeType":"calls","source":4410,"target":191},{"edgeType":"calls","source":4254,"target":1856},{"edgeType":"imports","source":1934,"target":1117},{"edgeType":"extends","source":373,"target":63},{"edgeType":"contains","source":285,"target":301},{"edgeType":"calls","source":1344,"target":106},{"edgeType":"calls","source":3277,"target":1489},{"edgeType":"calls","source":4807,"target":567},{"edgeType":"calls","source":1951,"target":315},{"edgeType":"contains","source":2928,"target":2929},{"edgeType":"calls","source":2051,"target":386},{"edgeType":"imports","source":1160,"target":799},{"edgeType":"calls","source":587,"target":317},{"edgeType":"calls","source":479,"target":494},{"edgeType":"calls","source":4606,"target":456},{"edgeType":"calls","source":2286,"target":499},{"edgeType":"calls","source":4311,"target":88},{"edgeType":"contains","source":4234,"target":4723},{"edgeType":"calls","source":1229,"target":499},{"edgeType":"calls","source":1261,"target":564},{"edgeType":"calls","source":1395,"target":638},{"edgeType":"calls","source":4785,"target":191},{"edgeType":"contains","source":2196,"target":3428},{"edgeType":"calls","source":4807,"target":566},{"edgeType":"calls","source":1906,"target":1705},{"edgeType":"calls","source":479,"target":489},{"edgeType":"contains","source":681,"target":3883},{"edgeType":"contains","source":3571,"target":4142},{"edgeType":"calls","source":4742,"target":4695},{"edgeType":"calls","source":4629,"target":1856},{"edgeType":"calls","source":2959,"target":774},{"edgeType":"calls","source":1719,"target":102},{"edgeType":"calls","source":3660,"target":183},{"edgeType":"calls","source":1646,"target":1308},{"edgeType":"calls","source":479,"target":488},{"edgeType":"contains","source":3571,"target":4141},{"edgeType":"contains","source":681,"target":3882},{"edgeType":"contains","source":2730,"target":2731},{"edgeType":"calls","source":4606,"target":454},{"edgeType":"calls","source":4491,"target":1905},{"edgeType":"calls","source":4709,"target":1489},{"edgeType":"contains","source":1833,"target":1998},{"edgeType":"contains","source":2735,"target":461},{"edgeType":"contains","source":6,"target":3666},{"edgeType":"calls","source":1719,"target":101},{"edgeType":"calls","source":1837,"target":1728},{"edgeType":"calls","source":479,"target":491},{"edgeType":"contains","source":2928,"target":2932},{"edgeType":"contains","source":1516,"target":2308},{"edgeType":"calls","source":1989,"target":191},{"edgeType":"contains","source":3571,"target":4140},{"edgeType":"calls","source":2051,"target":383},{"edgeType":"calls","source":208,"target":436},{"edgeType":"calls","source":4368,"target":1489},{"edgeType":"calls","source":83,"target":83},{"edgeType":"calls","source":1701,"target":662},{"edgeType":"calls","source":3929,"target":298},{"edgeType":"calls","source":3415,"target":378},{"edgeType":"calls","source":4137,"target":194},{"edgeType":"calls","source":479,"target":490},{"edgeType":"calls","source":2051,"target":382},{"edgeType":"calls","source":1307,"target":191},{"edgeType":"imports","source":3428,"target":3436},{"edgeType":"calls","source":2364,"target":191},{"edgeType":"calls","source":849,"target":648},{"edgeType":"imports","source":2255,"target":674},{"edgeType":"calls","source":2246,"target":1735},{"edgeType":"calls","source":4294,"target":1668},{"edgeType":"calls","source":1338,"target":1344},{"edgeType":"contains","source":3,"target":1647},{"edgeType":"calls","source":4171,"target":194},{"edgeType":"contains","source":3,"target":3764},{"edgeType":"calls","source":1271,"target":1302},{"edgeType":"calls","source":2754,"target":1839},{"edgeType":"calls","source":479,"target":485},{"edgeType":"contains","source":2631,"target":2632},{"edgeType":"contains","source":2928,"target":2938},{"edgeType":"calls","source":4737,"target":1675},{"edgeType":"calls","source":2869,"target":388},{"edgeType":"calls","source":2900,"target":484},{"edgeType":"calls","source":1719,"target":98},{"edgeType":"calls","source":3830,"target":194},{"edgeType":"calls","source":4568,"target":572},{"edgeType":"calls","source":2247,"target":1701},{"edgeType":"calls","source":344,"target":442},{"edgeType":"calls","source":4294,"target":1667},{"edgeType":"contains","source":2292,"target":2570},{"edgeType":"contains","source":6,"target":3670},{"edgeType":"contains","source":28,"target":4045},{"edgeType":"calls","source":3301,"target":1796},{"edgeType":"contains","source":637,"target":1022},{"edgeType":"contains","source":2928,"target":2939},{"edgeType":"calls","source":906,"target":988},{"edgeType":"calls","source":2869,"target":389},{"edgeType":"calls","source":4568,"target":571},{"edgeType":"contains","source":2292,"target":2571},{"edgeType":"calls","source":4294,"target":1666},{"edgeType":"imports","source":1749,"target":519},{"edgeType":"calls","source":1272,"target":1273},{"edgeType":"calls","source":2869,"target":386},{"edgeType":"calls","source":479,"target":487},{"edgeType":"contains","source":1337,"target":1519},{"edgeType":"calls","source":3229,"target":1911},{"edgeType":"contains","source":2735,"target":463},{"edgeType":"contains","source":2730,"target":2732},{"edgeType":"calls","source":3032,"target":1675},{"edgeType":"contains","source":2928,"target":2936},{"edgeType":"calls","source":864,"target":179},{"edgeType":"contains","source":1833,"target":1999},{"edgeType":"imports","source":3571,"target":1104},{"edgeType":"calls","source":2457,"target":474},{"edgeType":"calls","source":1719,"target":100},{"edgeType":"calls","source":2530,"target":325},{"edgeType":"contains","source":482,"target":544},{"edgeType":"calls","source":4409,"target":1271},{"edgeType":"contains","source":2735,"target":462},{"edgeType":"calls","source":4568,"target":570},{"edgeType":"calls","source":3709,"target":772},{"edgeType":"calls","source":4294,"target":1665},{"edgeType":"calls","source":479,"target":486},{"edgeType":"contains","source":2730,"target":2733},{"edgeType":"calls","source":2869,"target":387},{"edgeType":"calls","source":4568,"target":569},{"edgeType":"calls","source":1719,"target":99},{"edgeType":"calls","source":2316,"target":1675},{"edgeType":"calls","source":2494,"target":2499},{"edgeType":"calls","source":4356,"target":1856},{"edgeType":"calls","source":1517,"target":1076},{"edgeType":"calls","source":4294,"target":1664},{"edgeType":"calls","source":1915,"target":365},{"edgeType":"calls","source":2869,"target":384},{"edgeType":"calls","source":3485,"target":3486},{"edgeType":"calls","source":1273,"target":179},{"edgeType":"contains","source":2565,"target":2568},{"edgeType":"contains","source":4376,"target":4564},{"edgeType":"calls","source":1367,"target":436},{"edgeType":"calls","source":1271,"target":1298},{"edgeType":"contains","source":637,"target":1027},{"edgeType":"calls","source":4617,"target":106},{"edgeType":"calls","source":4568,"target":568},{"edgeType":"contains","source":3710,"target":4070},{"edgeType":"calls","source":2457,"target":472},{"edgeType":"contains","source":1516,"target":2319},{"edgeType":"imports","source":29,"target":983},{"edgeType":"calls","source":4436,"target":1489},{"edgeType":"calls","source":4294,"target":1663},{"edgeType":"calls","source":2869,"target":385},{"edgeType":"calls","source":817,"target":572},{"edgeType":"calls","source":774,"target":848},{"edgeType":"contains","source":4376,"target":4563},{"edgeType":"calls","source":1367,"target":435},{"edgeType":"contains","source":2565,"target":2569},{"edgeType":"calls","source":2457,"target":473},{"edgeType":"calls","source":4568,"target":567},{"edgeType":"contains","source":1833,"target":2006},{"edgeType":"calls","source":484,"target":325},{"edgeType":"contains","source":3710,"target":4069},{"edgeType":"calls","source":4294,"target":1662},{"edgeType":"calls","source":3639,"target":824},{"edgeType":"calls","source":1367,"target":438},{"edgeType":"calls","source":2869,"target":382},{"edgeType":"calls","source":4811,"target":1489},{"edgeType":"contains","source":2631,"target":2634},{"edgeType":"contains","source":2565,"target":2566},{"edgeType":"calls","source":344,"target":440},{"edgeType":"calls","source":4568,"target":566},{"edgeType":"calls","source":4708,"target":454},{"edgeType":"contains","source":3400,"target":992},{"edgeType":"calls","source":2726,"target":587},{"edgeType":"calls","source":2869,"target":383},{"edgeType":"calls","source":1367,"target":437},{"edgeType":"imports","source":1483,"target":302},{"edgeType":"contains","source":2565,"target":2567},{"edgeType":"contains","source":637,"target":1028},{"edgeType":"calls","source":344,"target":439},{"edgeType":"calls","source":4594,"target":1873},{"edgeType":"calls","source":4651,"target":106},{"edgeType":"calls","source":185,"target":83},{"edgeType":"calls","source":4347,"target":4245},{"edgeType":"calls","source":2403,"target":1088},{"edgeType":"imports","source":2276,"target":1088},{"edgeType":"extends","source":664,"target":603},{"edgeType":"calls","source":647,"target":653},{"edgeType":"contains","source":4777,"target":4789},{"edgeType":"calls","source":2813,"target":101},{"edgeType":"imports","source":2209,"target":42},{"edgeType":"calls","source":3041,"target":1489},{"edgeType":"calls","source":1372,"target":376},{"edgeType":"calls","source":1336,"target":435},{"edgeType":"contains","source":4376,"target":4535},{"edgeType":"contains","source":3710,"target":4041},{"edgeType":"calls","source":3826,"target":3580},{"edgeType":"contains","source":1080,"target":2063},{"edgeType":"calls","source":4412,"target":1271},{"edgeType":"imports","source":3221,"target":2495},{"edgeType":"calls","source":2429,"target":378},{"edgeType":"calls","source":4230,"target":569},{"edgeType":"contains","source":637,"target":997},{"edgeType":"contains","source":6,"target":1531},{"edgeType":"calls","source":2813,"target":102},{"edgeType":"imports","source":2209,"target":41},{"edgeType":"calls","source":1336,"target":434},{"edgeType":"imports","source":3701,"target":302},{"edgeType":"contains","source":1080,"target":2062},{"edgeType":"calls","source":4780,"target":1489},{"edgeType":"contains","source":3885,"target":3900},{"edgeType":"contains","source":1204,"target":1389},{"edgeType":"calls","source":4230,"target":570},{"edgeType":"contains","source":4777,"target":4787},{"edgeType":"calls","source":826,"target":391},{"edgeType":"calls","source":2813,"target":99},{"edgeType":"imports","source":2209,"target":40},{"edgeType":"calls","source":954,"target":651},{"edgeType":"calls","source":1108,"target":106},{"edgeType":"calls","source":2528,"target":478},{"edgeType":"calls","source":4711,"target":456},{"edgeType":"contains","source":3710,"target":4039},{"edgeType":"calls","source":1719,"target":191},{"edgeType":"contains","source":1080,"target":2065},{"edgeType":"calls","source":4833,"target":902},{"edgeType":"contains","source":3885,"target":3899},{"edgeType":"calls","source":4439,"target":1489},{"edgeType":"calls","source":4230,"target":567},{"edgeType":"contains","source":4777,"target":4786},{"edgeType":"calls","source":2813,"target":100},{"edgeType":"imports","source":2209,"target":39},{"edgeType":"contains","source":1700,"target":1870},{"edgeType":"contains","source":2292,"target":2544},{"edgeType":"contains","source":1080,"target":2064},{"edgeType":"calls","source":4833,"target":901},{"edgeType":"contains","source":3885,"target":3898},{"edgeType":"contains","source":1204,"target":1391},{"edgeType":"calls","source":4230,"target":568},{"edgeType":"contains","source":3520,"target":3586},{"edgeType":"calls","source":1280,"target":1109},{"edgeType":"imports","source":1918,"target":603},{"edgeType":"calls","source":4833,"target":900},{"edgeType":"calls","source":563,"target":82},{"edgeType":"calls","source":2528,"target":476},{"edgeType":"contains","source":1833,"target":1981},{"edgeType":"calls","source":2216,"target":1692},{"edgeType":"calls","source":969,"target":179},{"edgeType":"imports","source":2975,"target":603},{"edgeType":"calls","source":3746,"target":772},{"edgeType":"calls","source":1676,"target":460},{"edgeType":"calls","source":4745,"target":456},{"edgeType":"calls","source":2813,"target":98},{"edgeType":"calls","source":4230,"target":566},{"edgeType":"contains","source":1160,"target":1700},{"edgeType":"calls","source":4350,"target":4245},{"edgeType":"calls","source":4597,"target":1873},{"edgeType":"calls","source":4654,"target":106},{"edgeType":"calls","source":2528,"target":477},{"edgeType":"contains","source":548,"target":592},{"edgeType":"calls","source":1672,"target":587},{"edgeType":"extends","source":2084,"target":2038},{"edgeType":"calls","source":3780,"target":772},{"edgeType":"contains","source":2196,"target":3409},{"edgeType":"contains","source":2292,"target":2548},{"edgeType":"calls","source":3999,"target":325},{"edgeType":"calls","source":1071,"target":191},{"edgeType":"imports","source":1918,"target":601},{"edgeType":"calls","source":4644,"target":1472},{"edgeType":"imports","source":2209,"target":35},{"edgeType":"calls","source":3526,"target":191},{"edgeType":"calls","source":1307,"target":1331},{"edgeType":"imports","source":2975,"target":601},{"edgeType":"calls","source":3773,"target":990},{"edgeType":"contains","source":2264,"target":2360},{"edgeType":"contains","source":3710,"target":4042},{"edgeType":"calls","source":2010,"target":1735},{"edgeType":"calls","source":4230,"target":564},{"edgeType":"calls","source":4270,"target":381},{"edgeType":"calls","source":4699,"target":1880},{"edgeType":"calls","source":4438,"target":456},{"edgeType":"contains","source":548,"target":594},{"edgeType":"calls","source":1498,"target":690},{"edgeType":"calls","source":1528,"target":817},{"edgeType":"contains","source":38,"target":548},{"edgeType":"imports","source":2201,"target":299},{"edgeType":"contains","source":2201,"target":2204},{"edgeType":"calls","source":4068,"target":298},{"edgeType":"contains","source":4277,"target":4442},{"edgeType":"contains","source":2264,"target":2365},{"edgeType":"calls","source":1336,"target":426},{"edgeType":"calls","source":4501,"target":1675},{"edgeType":"calls","source":4631,"target":1873},{"edgeType":"contains","source":548,"target":593},{"edgeType":"calls","source":4304,"target":381},{"edgeType":"contains","source":186,"target":188},{"edgeType":"contains","source":3936,"target":1270},{"edgeType":"calls","source":1871,"target":1810},{"edgeType":"calls","source":1336,"target":425},{"edgeType":"calls","source":4089,"target":705},{"edgeType":"contains","source":4277,"target":4441},{"edgeType":"calls","source":4658,"target":1035},{"edgeType":"calls","source":2459,"target":498},{"edgeType":"extends","source":2803,"target":1954},{"edgeType":"contains","source":1090,"target":1760},{"edgeType":"calls","source":4805,"target":1763},{"edgeType":"calls","source":4518,"target":88},{"edgeType":"calls","source":3558,"target":3422},{"edgeType":"calls","source":2078,"target":1735},{"edgeType":"calls","source":4025,"target":572},{"edgeType":"calls","source":1719,"target":183},{"edgeType":"contains","source":32,"target":737},{"edgeType":"contains","source":3,"target":1636},{"edgeType":"contains","source":4277,"target":4440},{"edgeType":"contains","source":28,"target":1918},{"edgeType":"contains","source":1516,"target":2296},{"edgeType":"contains","source":548,"target":596},{"edgeType":"calls","source":628,"target":179},{"edgeType":"calls","source":817,"target":662},{"edgeType":"calls","source":3143,"target":1489},{"edgeType":"contains","source":548,"target":595},{"edgeType":"calls","source":2493,"target":498},{"edgeType":"calls","source":2217,"target":1655},{"edgeType":"calls","source":3558,"target":3423},{"edgeType":"calls","source":4033,"target":325},{"edgeType":"contains","source":32,"target":735},{"edgeType":"contains","source":2168,"target":2169},{"edgeType":"contains","source":32,"target":736},{"edgeType":"calls","source":2742,"target":179},{"edgeType":"contains","source":2264,"target":2364},{"edgeType":"calls","source":1336,"target":427},{"edgeType":"calls","source":1344,"target":179},{"edgeType":"contains","source":1516,"target":2297},{"edgeType":"calls","source":2528,"target":471},{"edgeType":"calls","source":2834,"target":498},{"edgeType":"calls","source":2365,"target":2349},{"edgeType":"calls","source":349,"target":365},{"edgeType":"calls","source":1676,"target":453},{"edgeType":"calls","source":2494,"target":464},{"edgeType":"calls","source":4495,"target":1856},{"edgeType":"calls","source":2247,"target":722},{"edgeType":"calls","source":4025,"target":570},{"edgeType":"extends","source":1987,"target":1884},{"edgeType":"extends","source":3669,"target":3652},{"edgeType":"calls","source":587,"target":387},{"edgeType":"calls","source":1512,"target":1308},{"edgeType":"calls","source":552,"target":415},{"edgeType":"contains","source":548,"target":598},{"edgeType":"contains","source":395,"target":4284},{"edgeType":"calls","source":4452,"target":4245},{"edgeType":"calls","source":4544,"target":336},{"edgeType":"imports","source":1749,"target":564},{"edgeType":"contains","source":1833,"target":1989},{"edgeType":"calls","source":1869,"target":1868},{"edgeType":"calls","source":2247,"target":723},{"edgeType":"calls","source":4102,"target":298},{"edgeType":"calls","source":4025,"target":571},{"edgeType":"calls","source":4793,"target":4245},{"edgeType":"calls","source":665,"target":82},{"edgeType":"extends","source":4203,"target":4010},{"edgeType":"calls","source":587,"target":386},{"edgeType":"contains","source":4277,"target":4445},{"edgeType":"contains","source":548,"target":597},{"edgeType":"calls","source":1329,"target":638},{"edgeType":"calls","source":1719,"target":179},{"edgeType":"contains","source":1090,"target":1768},{"edgeType":"calls","source":4025,"target":568},{"edgeType":"calls","source":2247,"target":720},{"edgeType":"calls","source":3546,"target":1675},{"edgeType":"calls","source":3552,"target":1489},{"edgeType":"calls","source":587,"target":389},{"edgeType":"calls","source":695,"target":212},{"edgeType":"contains","source":4277,"target":4444},{"edgeType":"calls","source":784,"target":624},{"edgeType":"calls","source":3287,"target":191},{"edgeType":"calls","source":3305,"target":690},{"edgeType":"contains","source":548,"target":600},{"edgeType":"imports","source":4045,"target":206},{"edgeType":"calls","source":4434,"target":573},{"edgeType":"calls","source":1871,"target":1808},{"edgeType":"calls","source":4025,"target":569},{"edgeType":"calls","source":4280,"target":4290},{"edgeType":"calls","source":695,"target":211},{"edgeType":"calls","source":587,"target":388},{"edgeType":"contains","source":3420,"target":3527},{"edgeType":"contains","source":4277,"target":4443},{"edgeType":"contains","source":548,"target":599},{"edgeType":"contains","source":395,"target":3228},{"edgeType":"calls","source":3342,"target":1658},{"edgeType":"calls","source":4592,"target":992},{"edgeType":"calls","source":4703,"target":722},{"edgeType":"calls","source":3845,"target":894},{"edgeType":"calls","source":1766,"target":863},{"edgeType":"calls","source":4742,"target":570},{"edgeType":"imports","source":3443,"target":1940},{"edgeType":"contains","source":621,"target":1477},{"edgeType":"contains","source":2735,"target":423},{"edgeType":"calls","source":3691,"target":382},{"edgeType":"extends","source":1952,"target":1884},{"edgeType":"calls","source":755,"target":493},{"edgeType":"contains","source":1700,"target":1855},{"edgeType":"calls","source":4530,"target":1856},{"edgeType":"calls","source":4742,"target":569},{"edgeType":"calls","source":4435,"target":573},{"edgeType":"calls","source":2231,"target":191},{"edgeType":"calls","source":185,"target":192},{"edgeType":"calls","source":755,"target":492},{"edgeType":"calls","source":2734,"target":454},{"edgeType":"calls","source":3691,"target":383},{"edgeType":"imports","source":1918,"target":590},{"edgeType":"calls","source":3343,"target":1658},{"edgeType":"calls","source":3386,"target":325},{"edgeType":"contains","source":621,"target":1476},{"edgeType":"calls","source":2531,"target":401},{"edgeType":"calls","source":3990,"target":625},{"edgeType":"calls","source":4703,"target":720},{"edgeType":"calls","source":4487,"target":4245},{"edgeType":"calls","source":4610,"target":1489},{"edgeType":"calls","source":4038,"target":194},{"edgeType":"calls","source":4742,"target":568},{"edgeType":"calls","source":4579,"target":336},{"edgeType":"contains","source":1636,"target":1722},{"edgeType":"contains","source":3520,"target":3570},{"edgeType":"calls","source":776,"target":901},{"edgeType":"calls","source":1513,"target":1308},{"edgeType":"calls","source":755,"target":495},{"edgeType":"calls","source":758,"target":402},{"edgeType":"contains","source":11,"target":1363},{"edgeType":"contains","source":2735,"target":421},{"edgeType":"calls","source":3507,"target":1856},{"edgeType":"calls","source":2531,"target":402},{"edgeType":"calls","source":411,"target":587},{"edgeType":"calls","source":4742,"target":567},{"edgeType":"calls","source":4703,"target":719},{"edgeType":"calls","source":1754,"target":179},{"edgeType":"calls","source":2657,"target":724},{"edgeType":"contains","source":1833,"target":1958},{"edgeType":"contains","source":3701,"target":2186},{"edgeType":"contains","source":621,"target":1478},{"edgeType":"calls","source":4269,"target":1489},{"edgeType":"calls","source":776,"target":900},{"edgeType":"calls","source":758,"target":401},{"edgeType":"calls","source":755,"target":494},{"edgeType":"contains","source":2266,"target":2277},{"edgeType":"contains","source":2735,"target":422},{"edgeType":"calls","source":4703,"target":718},{"edgeType":"contains","source":4278,"target":4390},{"edgeType":"calls","source":4742,"target":566},{"edgeType":"calls","source":2046,"target":1692},{"edgeType":"calls","source":2474,"target":1109},{"edgeType":"calls","source":4249,"target":4222},{"edgeType":"calls","source":185,"target":189},{"edgeType":"imports","source":2230,"target":1485},{"edgeType":"calls","source":1347,"target":106},{"edgeType":"calls","source":3998,"target":376},{"edgeType":"calls","source":3322,"target":191},{"edgeType":"calls","source":4703,"target":717},{"edgeType":"calls","source":4768,"target":1873},{"edgeType":"calls","source":2035,"target":975},{"edgeType":"calls","source":3845,"target":891},{"edgeType":"imports","source":1090,"target":886},{"edgeType":"calls","source":1077,"target":1076},{"edgeType":"contains","source":1700,"target":1859},{"edgeType":"calls","source":4818,"target":3494},{"edgeType":"contains","source":1080,"target":2050},{"edgeType":"calls","source":4521,"target":4245},{"edgeType":"calls","source":4495,"target":1880},{"edgeType":"contains","source":1749,"target":3512},{"edgeType":"contains","source":1700,"target":1860},{"edgeType":"contains","source":4278,"target":4389},{"edgeType":"calls","source":1077,"target":1079},{"edgeType":"contains","source":3050,"target":3345},{"edgeType":"calls","source":4575,"target":456},{"edgeType":"calls","source":2500,"target":301},{"edgeType":"contains","source":3175,"target":527},{"edgeType":"calls","source":185,"target":191},{"edgeType":"contains","source":1090,"target":1743},{"edgeType":"contains","source":1080,"target":2053},{"edgeType":"calls","source":4703,"target":716},{"edgeType":"contains","source":1204,"target":1380},{"edgeType":"calls","source":755,"target":491},{"edgeType":"calls","source":3019,"target":68},{"edgeType":"imports","source":621,"target":623},{"edgeType":"contains","source":4278,"target":4388},{"edgeType":"contains","source":4234,"target":4695},{"edgeType":"calls","source":4687,"target":3325},{"edgeType":"contains","source":3710,"target":4025},{"edgeType":"imports","source":3534,"target":183},{"edgeType":"calls","source":647,"target":666},{"edgeType":"calls","source":290,"target":106},{"edgeType":"calls","source":4844,"target":572},{"edgeType":"calls","source":4754,"target":191},{"edgeType":"calls","source":4598,"target":1856},{"edgeType":"calls","source":4703,"target":715},{"edgeType":"calls","source":3731,"target":194},{"edgeType":"contains","source":3885,"target":3886},{"edgeType":"contains","source":4278,"target":4387},{"edgeType":"imports","source":621,"target":624},{"edgeType":"calls","source":3462,"target":77},{"edgeType":"contains","source":2232,"target":2278},{"edgeType":"calls","source":4106,"target":194},{"edgeType":"calls","source":4027,"target":3700},{"edgeType":"contains","source":2232,"target":2283},{"edgeType":"contains","source":2264,"target":2348},{"edgeType":"calls","source":1267,"target":468},{"edgeType":"calls","source":4543,"target":389},{"edgeType":"calls","source":4672,"target":1675},{"edgeType":"calls","source":4678,"target":1489},{"edgeType":"calls","source":4703,"target":714},{"edgeType":"calls","source":4536,"target":606},{"edgeType":"contains","source":1090,"target":1745},{"edgeType":"contains","source":1080,"target":2055},{"edgeType":"calls","source":2836,"target":453},{"edgeType":"calls","source":4844,"target":571},{"edgeType":"contains","source":4777,"target":4781},{"edgeType":"calls","source":2813,"target":109},{"edgeType":"contains","source":1700,"target":1863},{"edgeType":"contains","source":3885,"target":3893},{"edgeType":"extends","source":2186,"target":2038},{"edgeType":"calls","source":3461,"target":106},{"edgeType":"calls","source":1417,"target":45},{"edgeType":"contains","source":2264,"target":2349},{"edgeType":"imports","source":2259,"target":1654},{"edgeType":"contains","source":4346,"target":4399},{"edgeType":"calls","source":1267,"target":467},{"edgeType":"contains","source":681,"target":682},{"edgeType":"contains","source":4777,"target":4780},{"edgeType":"calls","source":2768,"target":448},{"edgeType":"calls","source":4703,"target":713},{"edgeType":"contains","source":1090,"target":1744},{"edgeType":"contains","source":1080,"target":2054},{"edgeType":"calls","source":4844,"target":570},{"edgeType":"calls","source":2678,"target":1124},{"edgeType":"contains","source":1204,"target":1381},{"edgeType":"calls","source":4543,"target":388},{"edgeType":"calls","source":4536,"target":605},{"edgeType":"contains","source":2292,"target":2538},{"edgeType":"calls","source":4844,"target":569},{"edgeType":"calls","source":1267,"target":470},{"edgeType":"calls","source":1310,"target":1251},{"edgeType":"calls","source":3308,"target":1675},{"edgeType":"calls","source":4632,"target":1856},{"edgeType":"calls","source":4703,"target":712},{"edgeType":"calls","source":2973,"target":1489},{"edgeType":"contains","source":1080,"target":2057},{"edgeType":"contains","source":1090,"target":1747},{"edgeType":"calls","source":183,"target":249},{"edgeType":"calls","source":4494,"target":1906},{"edgeType":"calls","source":4543,"target":387},{"edgeType":"contains","source":1749,"target":3513},{"edgeType":"contains","source":1700,"target":1861},{"edgeType":"calls","source":1443,"target":299},{"edgeType":"contains","source":3710,"target":4031},{"edgeType":"calls","source":1517,"target":1176},{"edgeType":"calls","source":1267,"target":469},{"edgeType":"contains","source":4278,"target":4391},{"edgeType":"calls","source":4844,"target":568},{"edgeType":"imports","source":3936,"target":393},{"edgeType":"contains","source":2264,"target":2347},{"edgeType":"calls","source":359,"target":77},{"edgeType":"calls","source":4589,"target":4245},{"edgeType":"contains","source":4777,"target":4778},{"edgeType":"calls","source":2813,"target":108},{"edgeType":"calls","source":2836,"target":452},{"edgeType":"contains","source":1080,"target":2056},{"edgeType":"calls","source":4543,"target":386},{"edgeType":"contains","source":1749,"target":3514},{"edgeType":"extends","source":3208,"target":3122},{"edgeType":"calls","source":183,"target":248},{"edgeType":"calls","source":2257,"target":1489},{"edgeType":"contains","source":1700,"target":1862},{"edgeType":"calls","source":4024,"target":1677},{"edgeType":"calls","source":3735,"target":66},{"edgeType":"calls","source":1856,"target":179},{"edgeType":"calls","source":1344,"target":191},{"edgeType":"calls","source":4844,"target":567},{"edgeType":"calls","source":2734,"target":1497},{"edgeType":"calls","source":3519,"target":417},{"edgeType":"calls","source":1109,"target":77},{"edgeType":"calls","source":4810,"target":564},{"edgeType":"calls","source":3039,"target":498},{"edgeType":"calls","source":4543,"target":385},{"edgeType":"calls","source":4552,"target":106},{"edgeType":"contains","source":1080,"target":2059},{"edgeType":"calls","source":2291,"target":1489},{"edgeType":"calls","source":1679,"target":376},{"edgeType":"contains","source":1204,"target":1386},{"edgeType":"calls","source":4371,"target":1489},{"edgeType":"contains","source":1516,"target":2286},{"edgeType":"calls","source":4348,"target":88},{"edgeType":"imports","source":4451,"target":285},{"edgeType":"contains","source":3885,"target":3897},{"edgeType":"contains","source":3520,"target":3585},{"edgeType":"contains","source":1700,"target":1867},{"edgeType":"calls","source":2813,"target":106},{"edgeType":"calls","source":4844,"target":566},{"edgeType":"calls","source":4201,"target":417},{"edgeType":"calls","source":3364,"target":995},{"edgeType":"calls","source":1517,"target":1169},{"edgeType":"contains","source":637,"target":993},{"edgeType":"contains","source":4777,"target":4784},{"edgeType":"contains","source":1090,"target":1748},{"edgeType":"contains","source":1080,"target":2058},{"edgeType":"calls","source":2318,"target":653},{"edgeType":"contains","source":2292,"target":2542},{"edgeType":"calls","source":4543,"target":384},{"edgeType":"contains","source":3520,"target":3584},{"edgeType":"calls","source":4230,"target":572},{"edgeType":"contains","source":6,"target":1530},{"edgeType":"calls","source":1267,"target":466},{"edgeType":"contains","source":2264,"target":2350},{"edgeType":"calls","source":2667,"target":401},{"edgeType":"contains","source":548,"target":584},{"edgeType":"calls","source":969,"target":191},{"edgeType":"calls","source":2365,"target":2364},{"edgeType":"calls","source":1701,"target":753},{"edgeType":"contains","source":1090,"target":1751},{"edgeType":"contains","source":1080,"target":2061},{"edgeType":"calls","source":4543,"target":383},{"edgeType":"calls","source":4230,"target":571},{"edgeType":"calls","source":2746,"target":1124},{"edgeType":"calls","source":4875,"target":3831},{"edgeType":"calls","source":1261,"target":651},{"edgeType":"calls","source":1267,"target":465},{"edgeType":"calls","source":4833,"target":905},{"edgeType":"calls","source":2667,"target":402},{"edgeType":"calls","source":1055,"target":695},{"edgeType":"contains","source":4777,"target":4782},{"edgeType":"calls","source":1701,"target":752},{"edgeType":"calls","source":2395,"target":378},{"edgeType":"contains","source":1080,"target":2060},{"edgeType":"calls","source":4543,"target":382},{"edgeType":"contains","source":3621,"target":3622},{"edgeType":"contains","source":3885,"target":3894},{"edgeType":"contains","source":1700,"target":1866},{"edgeType":"calls","source":2905,"target":387},{"edgeType":"contains","source":2735,"target":407},{"edgeType":"calls","source":725,"target":316},{"edgeType":"calls","source":4832,"target":902},{"edgeType":"calls","source":3414,"target":464},{"edgeType":"calls","source":459,"target":106},{"edgeType":"calls","source":4576,"target":382},{"edgeType":"calls","source":3888,"target":568},{"edgeType":"calls","source":2739,"target":248},{"edgeType":"contains","source":3520,"target":3556},{"edgeType":"calls","source":4090,"target":648},{"edgeType":"calls","source":2459,"target":472},{"edgeType":"calls","source":378,"target":503},{"edgeType":"calls","source":2905,"target":388},{"edgeType":"calls","source":3607,"target":824},{"edgeType":"calls","source":725,"target":315},{"edgeType":"contains","source":6,"target":3612},{"edgeType":"calls","source":2739,"target":249},{"edgeType":"calls","source":3439,"target":747},{"edgeType":"calls","source":2459,"target":473},{"edgeType":"calls","source":2496,"target":2497},{"edgeType":"calls","source":3888,"target":569},{"edgeType":"calls","source":2009,"target":1735},{"edgeType":"calls","source":4832,"target":901},{"edgeType":"calls","source":2671,"target":1300},{"edgeType":"calls","source":2278,"target":1856},{"edgeType":"contains","source":1833,"target":1944},{"edgeType":"calls","source":378,"target":502},{"edgeType":"calls","source":618,"target":464},{"edgeType":"imports","source":2000,"target":210},{"edgeType":"calls","source":2905,"target":385},{"edgeType":"calls","source":933,"target":212},{"edgeType":"calls","source":3489,"target":3422},{"edgeType":"calls","source":448,"target":449},{"edgeType":"calls","source":4031,"target":2475},{"edgeType":"calls","source":3888,"target":566},{"edgeType":"calls","source":4054,"target":705},{"edgeType":"calls","source":4832,"target":900},{"edgeType":"calls","source":4807,"target":1675},{"edgeType":"extends","source":1062,"target":984},{"edgeType":"calls","source":2051,"target":436},{"edgeType":"contains","source":637,"target":966},{"edgeType":"calls","source":1417,"target":1063},{"edgeType":"calls","source":3489,"target":3423},{"edgeType":"calls","source":2809,"target":191},{"edgeType":"calls","source":725,"target":317},{"edgeType":"calls","source":2907,"target":324},{"edgeType":"calls","source":2905,"target":386},{"edgeType":"contains","source":6,"target":3614},{"edgeType":"calls","source":933,"target":211},{"edgeType":"contains","source":2232,"target":2257},{"edgeType":"contains","source":4346,"target":4372},{"edgeType":"contains","source":2735,"target":406},{"edgeType":"calls","source":378,"target":504},{"edgeType":"calls","source":4744,"target":456},{"edgeType":"calls","source":1752,"target":191},{"edgeType":"calls","source":3888,"target":567},{"edgeType":"calls","source":4438,"target":427},{"edgeType":"calls","source":2905,"target":383},{"edgeType":"contains","source":4278,"target":4373},{"edgeType":"contains","source":4278,"target":4374},{"edgeType":"calls","source":1916,"target":387},{"edgeType":"contains","source":3520,"target":3560},{"edgeType":"imports","source":1114,"target":190},{"edgeType":"calls","source":459,"target":102},{"edgeType":"calls","source":4643,"target":1472},{"edgeType":"calls","source":4438,"target":426},{"edgeType":"contains","source":1934,"target":1988},{"edgeType":"calls","source":2905,"target":384},{"edgeType":"contains","source":6,"target":3616},{"edgeType":"calls","source":1400,"target":527},{"edgeType":"calls","source":4033,"target":298},{"edgeType":"contains","source":2266,"target":2267},{"edgeType":"calls","source":1916,"target":386},{"edgeType":"calls","source":459,"target":101},{"edgeType":"calls","source":4629,"target":1905},{"edgeType":"calls","source":4438,"target":425},{"edgeType":"imports","source":3795,"target":1654},{"edgeType":"calls","source":1916,"target":389},{"edgeType":"calls","source":1810,"target":504},{"edgeType":"imports","source":2000,"target":206},{"edgeType":"calls","source":2562,"target":444},{"edgeType":"contains","source":1934,"target":1986},{"edgeType":"calls","source":1916,"target":388},{"edgeType":"calls","source":4088,"target":705},{"edgeType":"contains","source":3701,"target":2174},{"edgeType":"calls","source":2458,"target":498},{"edgeType":"calls","source":2905,"target":382},{"edgeType":"calls","source":2762,"target":587},{"edgeType":"contains","source":1209,"target":1211},{"edgeType":"contains","source":1700,"target":1846},{"edgeType":"calls","source":1916,"target":383},{"edgeType":"contains","source":798,"target":1267},{"edgeType":"contains","source":2230,"target":2329},{"edgeType":"contains","source":2266,"target":2270},{"edgeType":"calls","source":4226,"target":652},{"edgeType":"contains","source":4278,"target":4378},{"edgeType":"contains","source":647,"target":663},{"edgeType":"calls","source":459,"target":98},{"edgeType":"contains","source":1209,"target":1210},{"edgeType":"calls","source":1730,"target":863},{"edgeType":"calls","source":2216,"target":1655},{"edgeType":"calls","source":1513,"target":191},{"edgeType":"contains","source":3710,"target":4015},{"edgeType":"contains","source":1700,"target":1847},{"edgeType":"calls","source":1916,"target":382},{"edgeType":"contains","source":97,"target":799},{"edgeType":"contains","source":798,"target":1266},{"edgeType":"calls","source":2562,"target":443},{"edgeType":"calls","source":4638,"target":565},{"edgeType":"calls","source":4494,"target":1856},{"edgeType":"contains","source":1833,"target":1949},{"edgeType":"calls","source":1002,"target":179},{"edgeType":"contains","source":548,"target":563},{"edgeType":"calls","source":4650,"target":191},{"edgeType":"contains","source":2481,"target":3002},{"edgeType":"calls","source":4279,"target":4293},{"edgeType":"calls","source":4315,"target":1063},{"edgeType":"calls","source":1916,"target":385},{"edgeType":"calls","source":1758,"target":1055},{"edgeType":"calls","source":4849,"target":365},{"edgeType":"contains","source":2266,"target":2268},{"edgeType":"contains","source":3520,"target":3562},{"edgeType":"contains","source":612,"target":693},{"edgeType":"calls","source":459,"target":100},{"edgeType":"calls","source":4726,"target":3121},{"edgeType":"contains","source":3050,"target":3332},{"edgeType":"contains","source":1204,"target":1367},{"edgeType":"contains","source":1209,"target":1212},{"edgeType":"contains","source":548,"target":562},{"edgeType":"calls","source":1443,"target":249},{"edgeType":"calls","source":1916,"target":384},{"edgeType":"contains","source":1933,"target":2021},{"edgeType":"contains","source":4278,"target":4375},{"edgeType":"calls","source":1942,"target":1692},{"edgeType":"contains","source":2230,"target":2328},{"edgeType":"calls","source":1443,"target":248},{"edgeType":"extends","source":1522,"target":1529},{"edgeType":"calls","source":3266,"target":1871},{"edgeType":"calls","source":459,"target":99},{"edgeType":"contains","source":395,"target":1080},{"edgeType":"calls","source":3817,"target":3814},{"edgeType":"calls","source":3843,"target":894},{"edgeType":"calls","source":1852,"target":249},{"edgeType":"calls","source":4590,"target":992},{"edgeType":"calls","source":2279,"target":754},{"edgeType":"calls","source":4279,"target":4291},{"edgeType":"calls","source":1880,"target":438},{"edgeType":"contains","source":3710,"target":4020},{"edgeType":"calls","source":4098,"target":388},{"edgeType":"contains","source":16,"target":3316},{"edgeType":"calls","source":587,"target":354},{"edgeType":"calls","source":3553,"target":3541},{"edgeType":"contains","source":2266,"target":2274},{"edgeType":"calls","source":3304,"target":690},{"edgeType":"calls","source":921,"target":570},{"edgeType":"contains","source":2735,"target":419},{"edgeType":"calls","source":1128,"target":495},{"edgeType":"calls","source":4528,"target":1856},{"edgeType":"calls","source":1880,"target":437},{"edgeType":"calls","source":1852,"target":248},{"edgeType":"extends","source":3174,"target":3175},{"edgeType":"calls","source":3553,"target":3543},{"edgeType":"calls","source":4349,"target":1063},{"edgeType":"calls","source":4433,"target":573},{"edgeType":"imports","source":2201,"target":1383},{"edgeType":"calls","source":3817,"target":3815},{"edgeType":"contains","source":1833,"target":1956},{"edgeType":"calls","source":4098,"target":389},{"edgeType":"contains","source":4234,"target":4688},{"edgeType":"imports","source":3685,"target":1884},{"edgeType":"calls","source":587,"target":353},{"edgeType":"calls","source":3553,"target":3542},{"edgeType":"calls","source":4790,"target":77},{"edgeType":"contains","source":2266,"target":2275},{"edgeType":"calls","source":3341,"target":1658},{"edgeType":"calls","source":921,"target":569},{"edgeType":"extends","source":1001,"target":770},{"edgeType":"calls","source":1128,"target":494},{"edgeType":"contains","source":2735,"target":420},{"edgeType":"calls","source":3817,"target":3812},{"edgeType":"calls","source":4577,"target":336},{"edgeType":"calls","source":4098,"target":386},{"edgeType":"calls","source":1844,"target":499},{"edgeType":"calls","source":4036,"target":194},{"edgeType":"contains","source":1700,"target":1848},{"edgeType":"contains","source":3571,"target":4099},{"edgeType":"contains","source":1934,"target":1993},{"edgeType":"imports","source":2201,"target":325},{"edgeType":"calls","source":2846,"target":88},{"edgeType":"calls","source":551,"target":415},{"edgeType":"calls","source":3661,"target":191},{"edgeType":"calls","source":3695,"target":194},{"edgeType":"contains","source":2266,"target":2272},{"edgeType":"calls","source":1511,"target":1308},{"edgeType":"contains","source":4278,"target":4380},{"edgeType":"calls","source":921,"target":572},{"edgeType":"calls","source":3855,"target":3692},{"edgeType":"calls","source":4098,"target":387},{"edgeType":"calls","source":4539,"target":456},{"edgeType":"calls","source":4267,"target":1489},{"edgeType":"contains","source":4149,"target":4150},{"edgeType":"calls","source":1305,"target":1351},{"edgeType":"contains","source":4278,"target":4379},{"edgeType":"contains","source":2266,"target":2273},{"edgeType":"calls","source":556,"target":259},{"edgeType":"contains","source":2229,"target":3420},{"edgeType":"contains","source":2735,"target":418},{"edgeType":"calls","source":1128,"target":496},{"edgeType":"calls","source":921,"target":571},{"edgeType":"calls","source":416,"target":398},{"edgeType":"calls","source":4578,"target":336},{"edgeType":"calls","source":4025,"target":566},{"edgeType":"calls","source":4037,"target":194},{"edgeType":"contains","source":1175,"target":1183},{"edgeType":"calls","source":4091,"target":1691},{"edgeType":"calls","source":2051,"target":451},{"edgeType":"calls","source":587,"target":382},{"edgeType":"calls","source":2247,"target":718},{"edgeType":"calls","source":4280,"target":4289},{"edgeType":"calls","source":378,"target":519},{"edgeType":"contains","source":19,"target":23},{"edgeType":"calls","source":824,"target":435},{"edgeType":"contains","source":396,"target":2077},{"edgeType":"contains","source":2417,"target":3906},{"edgeType":"calls","source":1075,"target":1109},{"edgeType":"contains","source":3710,"target":3990},{"edgeType":"calls","source":3856,"target":3692},{"edgeType":"contains","source":1175,"target":1182},{"edgeType":"calls","source":4025,"target":567},{"edgeType":"calls","source":4280,"target":4288},{"edgeType":"calls","source":2247,"target":719},{"edgeType":"calls","source":4268,"target":1489},{"edgeType":"contains","source":19,"target":22},{"edgeType":"calls","source":2813,"target":3257},{"edgeType":"calls","source":824,"target":434},{"edgeType":"contains","source":798,"target":1241},{"edgeType":"calls","source":1371,"target":389},{"edgeType":"calls","source":2562,"target":464},{"edgeType":"calls","source":4031,"target":378},{"edgeType":"calls","source":587,"target":384},{"edgeType":"calls","source":2473,"target":1109},{"edgeType":"calls","source":4280,"target":4287},{"edgeType":"contains","source":4115,"target":4119},{"edgeType":"calls","source":2247,"target":716},{"edgeType":"calls","source":2813,"target":83},{"edgeType":"contains","source":2001,"target":2002},{"edgeType":"calls","source":587,"target":385},{"edgeType":"contains","source":2232,"target":2240},{"edgeType":"calls","source":1653,"target":106},{"edgeType":"imports","source":4451,"target":325},{"edgeType":"calls","source":4637,"target":1675},{"edgeType":"imports","source":1749,"target":574},{"edgeType":"calls","source":587,"target":383},{"edgeType":"calls","source":4494,"target":1880},{"edgeType":"calls","source":2247,"target":717},{"edgeType":"calls","source":4520,"target":4245},{"edgeType":"extends","source":1398,"target":63},{"edgeType":"contains","source":2001,"target":2003},{"edgeType":"calls","source":4875,"target":4868},{"edgeType":"contains","source":4115,"target":4118},{"edgeType":"contains","source":2232,"target":2241},{"edgeType":"contains","source":4376,"target":1312},{"edgeType":"contains","source":4346,"target":4356},{"edgeType":"calls","source":4696,"target":902},{"edgeType":"calls","source":3268,"target":774},{"edgeType":"calls","source":4790,"target":102},{"edgeType":"calls","source":3302,"target":777},{"edgeType":"calls","source":2051,"target":447},{"edgeType":"imports","source":3221,"target":2508},{"edgeType":"calls","source":2733,"target":446},{"edgeType":"calls","source":2247,"target":714},{"edgeType":"calls","source":1371,"target":386},{"edgeType":"contains","source":4278,"target":4357},{"edgeType":"calls","source":4790,"target":101},{"edgeType":"contains","source":3710,"target":3994},{"edgeType":"extends","source":3099,"target":190},{"edgeType":"calls","source":4843,"target":572},{"edgeType":"calls","source":4696,"target":901},{"edgeType":"calls","source":4597,"target":1856},{"edgeType":"calls","source":2247,"target":715},{"edgeType":"contains","source":1833,"target":1932},{"edgeType":"imports","source":2021,"target":1654},{"edgeType":"calls","source":3437,"target":1878},{"edgeType":"contains","source":3851,"target":3852},{"edgeType":"calls","source":1371,"target":385},{"edgeType":"calls","source":1517,"target":87},{"edgeType":"calls","source":4790,"target":100},{"edgeType":"contains","source":3710,"target":3993},{"edgeType":"calls","source":4105,"target":194},{"edgeType":"calls","source":3996,"target":402},{"edgeType":"calls","source":4026,"target":3700},{"edgeType":"calls","source":2494,"target":454},{"edgeType":"contains","source":1833,"target":1928},{"edgeType":"calls","source":2835,"target":453},{"edgeType":"calls","source":4843,"target":571},{"edgeType":"calls","source":4728,"target":965},{"edgeType":"contains","source":1204,"target":1347},{"edgeType":"calls","source":4696,"target":900},{"edgeType":"calls","source":4671,"target":1675},{"edgeType":"calls","source":4280,"target":4283},{"edgeType":"calls","source":2247,"target":712},{"edgeType":"calls","source":1371,"target":388},{"edgeType":"calls","source":3996,"target":401},{"edgeType":"contains","source":4278,"target":4355},{"edgeType":"calls","source":2733,"target":445},{"edgeType":"calls","source":2531,"target":365},{"edgeType":"calls","source":4843,"target":570},{"edgeType":"calls","source":4790,"target":99},{"edgeType":"calls","source":2247,"target":713},{"edgeType":"calls","source":4336,"target":1489},{"edgeType":"calls","source":4313,"target":88},{"edgeType":"calls","source":1371,"target":387},{"edgeType":"contains","source":4278,"target":4354},{"edgeType":"contains","source":2232,"target":2245},{"edgeType":"calls","source":2663,"target":498},{"edgeType":"contains","source":4278,"target":4361},{"edgeType":"calls","source":4023,"target":1677},{"edgeType":"calls","source":1371,"target":382},{"edgeType":"calls","source":3353,"target":249},{"edgeType":"calls","source":4631,"target":1856},{"edgeType":"contains","source":3175,"target":2614},{"edgeType":"calls","source":824,"target":426},{"edgeType":"calls","source":4790,"target":98},{"edgeType":"calls","source":4843,"target":569},{"edgeType":"calls","source":4280,"target":4281},{"edgeType":"calls","source":4843,"target":568},{"edgeType":"contains","source":4278,"target":4360},{"edgeType":"contains","source":2232,"target":2251},{"edgeType":"calls","source":824,"target":425},{"edgeType":"contains","source":2735,"target":400},{"edgeType":"calls","source":2961,"target":774},{"edgeType":"calls","source":2813,"target":77},{"edgeType":"calls","source":4576,"target":389},{"edgeType":"contains","source":4278,"target":4359},{"edgeType":"calls","source":4843,"target":567},{"edgeType":"calls","source":1371,"target":384},{"edgeType":"calls","source":1305,"target":1373},{"edgeType":"calls","source":3437,"target":1871},{"edgeType":"contains","source":647,"target":649},{"edgeType":"calls","source":4787,"target":189},{"edgeType":"calls","source":4576,"target":388},{"edgeType":"calls","source":2527,"target":484},{"edgeType":"calls","source":4370,"target":1489},{"edgeType":"contains","source":4278,"target":4358},{"edgeType":"contains","source":2232,"target":2249},{"edgeType":"calls","source":4843,"target":566},{"edgeType":"calls","source":4139,"target":194},{"edgeType":"calls","source":1371,"target":383},{"edgeType":"calls","source":3353,"target":248},{"edgeType":"contains","source":3710,"target":3996},{"edgeType":"calls","source":824,"target":427},{"edgeType":"calls","source":2248,"target":1735},{"edgeType":"calls","source":4576,"target":387},{"edgeType":"calls","source":4578,"target":325},{"edgeType":"calls","source":1908,"target":1705},{"edgeType":"calls","source":1472,"target":1475},{"edgeType":"contains","source":4278,"target":4365},{"edgeType":"contains","source":4277,"target":4396},{"edgeType":"calls","source":587,"target":370},{"edgeType":"calls","source":4622,"target":4245},{"edgeType":"contains","source":4346,"target":4371},{"edgeType":"calls","source":921,"target":586},{"edgeType":"contains","source":548,"target":549},{"edgeType":"calls","source":1301,"target":434},{"edgeType":"calls","source":992,"target":499},{"edgeType":"calls","source":2460,"target":445},{"edgeType":"calls","source":3888,"target":572},{"edgeType":"extends","source":1262,"target":63},{"edgeType":"calls","source":4576,"target":386},{"edgeType":"calls","source":4405,"target":402},{"edgeType":"calls","source":2323,"target":464},{"edgeType":"calls","source":2051,"target":438},{"edgeType":"calls","source":4832,"target":905},{"edgeType":"contains","source":4278,"target":4364},{"edgeType":"contains","source":4346,"target":4370},{"edgeType":"calls","source":921,"target":585},{"edgeType":"calls","source":4576,"target":385},{"edgeType":"imports","source":4234,"target":704},{"edgeType":"calls","source":2460,"target":446},{"edgeType":"calls","source":4405,"target":401},{"edgeType":"calls","source":2051,"target":437},{"edgeType":"calls","source":2051,"target":441},{"edgeType":"contains","source":3520,"target":3549},{"edgeType":"calls","source":2905,"target":389},{"edgeType":"contains","source":4278,"target":4363},{"edgeType":"contains","source":4277,"target":4394},{"edgeType":"calls","source":3711,"target":772},{"edgeType":"contains","source":4346,"target":4369},{"edgeType":"contains","source":482,"target":483},{"edgeType":"calls","source":4576,"target":384},{"edgeType":"calls","source":3888,"target":570},{"edgeType":"calls","source":3842,"target":1996},{"edgeType":"calls","source":2459,"target":474},{"edgeType":"calls","source":4615,"target":3403},{"edgeType":"calls","source":2767,"target":1497},{"edgeType":"calls","source":1301,"target":435},{"edgeType":"calls","source":587,"target":371},{"edgeType":"contains","source":6,"target":3610},{"edgeType":"calls","source":3457,"target":191},{"edgeType":"contains","source":4278,"target":4362},{"edgeType":"contains","source":2232,"target":2253},{"edgeType":"contains","source":4346,"target":4368},{"edgeType":"calls","source":4773,"target":1675},{"edgeType":"calls","source":3116,"target":191},{"edgeType":"calls","source":3888,"target":571},{"edgeType":"calls","source":4576,"target":383},{"edgeType":"calls","source":4071,"target":183},{"edgeType":"contains","source":2280,"target":3380},{"edgeType":"calls","source":4846,"target":567},{"edgeType":"contains","source":2975,"target":2976},{"edgeType":"calls","source":2781,"target":102},{"edgeType":"calls","source":1231,"target":585},{"edgeType":"calls","source":2998,"target":774},{"edgeType":"calls","source":3270,"target":1856},{"edgeType":"contains","source":3501,"target":412},{"edgeType":"calls","source":418,"target":419},{"edgeType":"calls","source":4539,"target":571},{"edgeType":"contains","source":16,"target":3799},{"edgeType":"calls","source":183,"target":305},{"edgeType":"extends","source":1947,"target":1857},{"edgeType":"contains","source":2280,"target":2323},{"edgeType":"calls","source":4350,"target":88},{"edgeType":"contains","source":4524,"target":4638},{"edgeType":"contains","source":3727,"target":3975},{"edgeType":"calls","source":4270,"target":454},{"edgeType":"calls","source":4846,"target":566},{"edgeType":"calls","source":3366,"target":995},{"edgeType":"calls","source":3041,"target":499},{"edgeType":"calls","source":3801,"target":194},{"edgeType":"calls","source":4539,"target":570},{"edgeType":"calls","source":4668,"target":1856},{"edgeType":"contains","source":4524,"target":4637},{"edgeType":"calls","source":692,"target":383},{"edgeType":"imports","source":4209,"target":1269},{"edgeType":"imports","source":4240,"target":308},{"edgeType":"contains","source":2280,"target":3378},{"edgeType":"calls","source":2738,"target":376},{"edgeType":"calls","source":2781,"target":100},{"edgeType":"contains","source":3727,"target":3974},{"edgeType":"contains","source":3501,"target":3581},{"edgeType":"contains","source":4791,"target":4815},{"edgeType":"calls","source":4539,"target":569},{"edgeType":"contains","source":6,"target":1997},{"edgeType":"calls","source":4742,"target":1675},{"edgeType":"calls","source":2321,"target":619},{"edgeType":"contains","source":2269,"target":2662},{"edgeType":"calls","source":183,"target":307},{"edgeType":"contains","source":4524,"target":4636},{"edgeType":"calls","source":692,"target":382},{"edgeType":"contains","source":4524,"target":4635},{"edgeType":"imports","source":2201,"target":2203},{"edgeType":"contains","source":2280,"target":3379},{"edgeType":"calls","source":2781,"target":101},{"edgeType":"calls","source":1231,"target":586},{"edgeType":"contains","source":3727,"target":3973},{"edgeType":"calls","source":4578,"target":416},{"edgeType":"calls","source":1853,"target":330},{"edgeType":"calls","source":418,"target":420},{"edgeType":"contains","source":11,"target":3955},{"edgeType":"calls","source":183,"target":306},{"edgeType":"contains","source":2269,"target":2663},{"edgeType":"calls","source":4539,"target":568},{"edgeType":"calls","source":4304,"target":454},{"edgeType":"calls","source":2782,"target":1124},{"edgeType":"calls","source":1169,"target":388},{"edgeType":"calls","source":453,"target":387},{"edgeType":"calls","source":1853,"target":325},{"edgeType":"calls","source":3161,"target":3116},{"edgeType":"contains","source":4791,"target":4821},{"edgeType":"calls","source":4783,"target":402},{"edgeType":"calls","source":4679,"target":4683},{"edgeType":"calls","source":3933,"target":325},{"edgeType":"contains","source":2115,"target":2157},{"edgeType":"calls","source":4858,"target":191},{"edgeType":"calls","source":2781,"target":98},{"edgeType":"calls","source":4539,"target":567},{"edgeType":"calls","source":2657,"target":771},{"edgeType":"calls","source":550,"target":551},{"edgeType":"contains","source":2280,"target":3384},{"edgeType":"contains","source":2269,"target":2668},{"edgeType":"contains","source":2269,"target":2669},{"edgeType":"calls","source":2781,"target":99},{"edgeType":"contains","source":3727,"target":3979},{"edgeType":"calls","source":1336,"target":496},{"edgeType":"calls","source":3119,"target":191},{"edgeType":"imports","source":1090,"target":704},{"edgeType":"calls","source":3161,"target":3117},{"edgeType":"calls","source":1169,"target":387},{"edgeType":"imports","source":1247,"target":65},{"edgeType":"calls","source":4783,"target":401},{"edgeType":"calls","source":4659,"target":4245},{"edgeType":"calls","source":4679,"target":4682},{"edgeType":"calls","source":4776,"target":1675},{"edgeType":"calls","source":4782,"target":1489},{"edgeType":"contains","source":4791,"target":4820},{"edgeType":"calls","source":4869,"target":906},{"edgeType":"contains","source":2115,"target":2158},{"edgeType":"calls","source":4539,"target":566},{"edgeType":"calls","source":692,"target":376},{"edgeType":"calls","source":3987,"target":3937},{"edgeType":"calls","source":4607,"target":572},{"edgeType":"contains","source":2280,"target":3385},{"edgeType":"calls","source":453,"target":386},{"edgeType":"contains","source":2280,"target":3382},{"edgeType":"contains","source":3727,"target":3978},{"edgeType":"calls","source":3494,"target":191},{"edgeType":"calls","source":1646,"target":402},{"edgeType":"calls","source":3338,"target":1856},{"edgeType":"calls","source":4713,"target":456},{"edgeType":"calls","source":453,"target":389},{"edgeType":"contains","source":4791,"target":4819},{"edgeType":"calls","source":561,"target":212},{"edgeType":"calls","source":4607,"target":571},{"edgeType":"contains","source":2280,"target":3383},{"edgeType":"contains","source":3727,"target":3977},{"edgeType":"calls","source":2830,"target":692},{"edgeType":"contains","source":1749,"target":1874},{"edgeType":"calls","source":3869,"target":194},{"edgeType":"calls","source":1646,"target":401},{"edgeType":"imports","source":1247,"target":63},{"edgeType":"calls","source":453,"target":388},{"edgeType":"calls","source":1169,"target":389},{"edgeType":"calls","source":2393,"target":498},{"edgeType":"calls","source":561,"target":211},{"edgeType":"calls","source":4892,"target":191},{"edgeType":"contains","source":2115,"target":2156},{"edgeType":"calls","source":2679,"target":88},{"edgeType":"calls","source":4607,"target":570},{"edgeType":"contains","source":2204,"target":2573},{"edgeType":"calls","source":4452,"target":88},{"edgeType":"contains","source":1636,"target":2211},{"edgeType":"calls","source":3143,"target":499},{"edgeType":"contains","source":3467,"target":3588},{"edgeType":"contains","source":696,"target":697},{"edgeType":"contains","source":2777,"target":2780},{"edgeType":"calls","source":1653,"target":179},{"edgeType":"calls","source":4781,"target":460},{"edgeType":"calls","source":1169,"target":384},{"edgeType":"calls","source":3999,"target":389},{"edgeType":"calls","source":1336,"target":492},{"edgeType":"contains","source":3727,"target":3985},{"edgeType":"contains","source":2115,"target":2161},{"edgeType":"calls","source":453,"target":383},{"edgeType":"calls","source":4681,"target":389},{"edgeType":"imports","source":1247,"target":76},{"edgeType":"calls","source":4551,"target":191},{"edgeType":"calls","source":4607,"target":569},{"edgeType":"calls","source":2296,"target":331},{"edgeType":"calls","source":4396,"target":1823},{"edgeType":"calls","source":2218,"target":1692},{"edgeType":"contains","source":2204,"target":2574},{"edgeType":"contains","source":3120,"target":2718},{"edgeType":"calls","source":1727,"target":1055},{"edgeType":"calls","source":1169,"target":383},{"edgeType":"calls","source":1336,"target":491},{"edgeType":"contains","source":1654,"target":1655},{"edgeType":"imports","source":4209,"target":1260},{"edgeType":"calls","source":4607,"target":568},{"edgeType":"contains","source":320,"target":724},{"edgeType":"calls","source":4570,"target":658},{"edgeType":"contains","source":3797,"target":3928},{"edgeType":"calls","source":453,"target":382},{"edgeType":"contains","source":3768,"target":3770},{"edgeType":"calls","source":2830,"target":690},{"edgeType":"contains","source":3727,"target":3984},{"edgeType":"calls","source":4882,"target":499},{"edgeType":"calls","source":4835,"target":899},{"edgeType":"calls","source":4747,"target":456},{"edgeType":"calls","source":748,"target":750},{"edgeType":"calls","source":4681,"target":388},{"edgeType":"contains","source":2269,"target":2670},{"edgeType":"calls","source":4396,"target":1822},{"edgeType":"contains","source":3768,"target":1654},{"edgeType":"calls","source":2461,"target":498},{"edgeType":"contains","source":3727,"target":3982},{"edgeType":"contains","source":2777,"target":2778},{"edgeType":"calls","source":1336,"target":495},{"edgeType":"calls","source":3999,"target":387},{"edgeType":"calls","source":1311,"target":212},{"edgeType":"calls","source":1169,"target":386},{"edgeType":"calls","source":4607,"target":567},{"edgeType":"contains","source":3727,"target":3983},{"edgeType":"contains","source":2115,"target":2159},{"edgeType":"calls","source":453,"target":385},{"edgeType":"contains","source":44,"target":827},{"edgeType":"calls","source":4681,"target":387},{"edgeType":"calls","source":4646,"target":1472},{"edgeType":"contains","source":2204,"target":2572},{"edgeType":"contains","source":3727,"target":3981},{"edgeType":"imports","source":396,"target":1088},{"edgeType":"calls","source":3528,"target":191},{"edgeType":"calls","source":1336,"target":494},{"edgeType":"calls","source":3999,"target":388},{"edgeType":"calls","source":1657,"target":1113},{"edgeType":"calls","source":4123,"target":772},{"edgeType":"calls","source":4036,"target":298},{"edgeType":"calls","source":1336,"target":493},{"edgeType":"contains","source":4791,"target":4822},{"edgeType":"calls","source":1311,"target":211},{"edgeType":"calls","source":1169,"target":385},{"edgeType":"calls","source":3207,"target":628},{"edgeType":"calls","source":4681,"target":386},{"edgeType":"calls","source":4607,"target":566},{"edgeType":"calls","source":453,"target":384},{"edgeType":"contains","source":44,"target":829},{"edgeType":"contains","source":3467,"target":3592},{"edgeType":"contains","source":2204,"target":2577},{"edgeType":"contains","source":3501,"target":424},{"edgeType":"calls","source":1839,"target":1808},{"edgeType":"calls","source":3999,"target":385},{"edgeType":"calls","source":1845,"target":565},{"edgeType":"calls","source":2254,"target":571},{"edgeType":"contains","source":3099,"target":1258},{"edgeType":"calls","source":1336,"target":488},{"edgeType":"extends","source":770,"target":302},{"edgeType":"calls","source":3333,"target":3061},{"edgeType":"calls","source":4681,"target":385},{"edgeType":"calls","source":817,"target":722},{"edgeType":"calls","source":1231,"target":572},{"edgeType":"calls","source":4596,"target":906},{"edgeType":"calls","source":724,"target":434},{"edgeType":"calls","source":2869,"target":533},{"edgeType":"calls","source":2986,"target":77},{"edgeType":"calls","source":921,"target":669},{"edgeType":"contains","source":44,"target":828},{"edgeType":"contains","source":2115,"target":2166},{"edgeType":"contains","source":3467,"target":3591},{"edgeType":"calls","source":2254,"target":572},{"edgeType":"calls","source":459,"target":191},{"edgeType":"contains","source":2204,"target":2578},{"edgeType":"calls","source":3999,"target":386},{"edgeType":"calls","source":3736,"target":83},{"edgeType":"calls","source":2747,"target":88},{"edgeType":"calls","source":1336,"target":487},{"edgeType":"calls","source":3457,"target":3446},{"edgeType":"calls","source":1231,"target":571},{"edgeType":"calls","source":4681,"target":384},{"edgeType":"calls","source":4818,"target":365},{"edgeType":"contains","source":3797,"target":3932},{"edgeType":"calls","source":1672,"target":645},{"edgeType":"contains","source":2204,"target":2575},{"edgeType":"contains","source":2115,"target":2163},{"edgeType":"contains","source":2255,"target":2051},{"edgeType":"contains","source":3467,"target":3590},{"edgeType":"calls","source":4681,"target":382},{"edgeType":"calls","source":4570,"target":652},{"edgeType":"calls","source":2254,"target":569},{"edgeType":"calls","source":3999,"target":383},{"edgeType":"contains","source":696,"target":703},{"edgeType":"calls","source":1839,"target":753},{"edgeType":"contains","source":2481,"target":3501},{"edgeType":"calls","source":4242,"target":249},{"edgeType":"calls","source":1336,"target":490},{"edgeType":"calls","source":1109,"target":1185},{"edgeType":"calls","source":748,"target":749},{"edgeType":"contains","source":3669,"target":3671},{"edgeType":"calls","source":4681,"target":383},{"edgeType":"calls","source":4667,"target":817},{"edgeType":"calls","source":1169,"target":382},{"edgeType":"calls","source":1071,"target":249},{"edgeType":"contains","source":1621,"target":1622},{"edgeType":"contains","source":1654,"target":1656},{"edgeType":"contains","source":3467,"target":3589},{"edgeType":"contains","source":2204,"target":2576},{"edgeType":"calls","source":1839,"target":752},{"edgeType":"calls","source":2254,"target":570},{"edgeType":"calls","source":2219,"target":1655},{"edgeType":"contains","source":681,"target":3281},{"edgeType":"calls","source":3999,"target":384},{"edgeType":"calls","source":1336,"target":489},{"edgeType":"calls","source":1340,"target":365},{"edgeType":"calls","source":2729,"target":1701},{"edgeType":"contains","source":3727,"target":3986},{"edgeType":"calls","source":3273,"target":692},{"edgeType":"calls","source":1071,"target":248},{"edgeType":"calls","source":724,"target":435},{"edgeType":"calls","source":817,"target":723},{"edgeType":"calls","source":2895,"target":2897},{"edgeType":"calls","source":1746,"target":492},{"edgeType":"contains","source":4130,"target":4151},{"edgeType":"contains","source":16,"target":3782},{"edgeType":"calls","source":4710,"target":571},{"edgeType":"contains","source":2259,"target":843},{"edgeType":"contains","source":4524,"target":4622},{"edgeType":"contains","source":2511,"target":2545},{"edgeType":"calls","source":4241,"target":311},{"edgeType":"contains","source":1054,"target":1201},{"edgeType":"contains","source":3864,"target":3941},{"edgeType":"contains","source":3162,"target":2447},{"edgeType":"calls","source":4710,"target":572},{"edgeType":"calls","source":824,"target":534},{"edgeType":"contains","source":1849,"target":1926},{"edgeType":"calls","source":906,"target":106},{"edgeType":"contains","source":1454,"target":1487},{"edgeType":"contains","source":43,"target":830},{"edgeType":"contains","source":4791,"target":4800},{"edgeType":"contains","source":2806,"target":2914},{"edgeType":"calls","source":1746,"target":491},{"edgeType":"calls","source":2496,"target":498},{"edgeType":"calls","source":4752,"target":325},{"edgeType":"calls","source":4710,"target":570},{"edgeType":"calls","source":4036,"target":325},{"edgeType":"contains","source":2511,"target":2546},{"edgeType":"contains","source":1054,"target":1200},{"edgeType":"calls","source":3618,"target":1655},{"edgeType":"calls","source":3561,"target":3422},{"edgeType":"contains","source":1884,"target":1899},{"edgeType":"calls","source":3373,"target":794},{"edgeType":"calls","source":3274,"target":692},{"edgeType":"contains","source":1455,"target":1457},{"edgeType":"contains","source":1454,"target":1488},{"edgeType":"contains","source":1454,"target":1484},{"edgeType":"calls","source":1746,"target":494},{"edgeType":"calls","source":4710,"target":569},{"edgeType":"contains","source":2255,"target":965},{"edgeType":"contains","source":44,"target":802},{"edgeType":"contains","source":2226,"target":2921},{"edgeType":"contains","source":3051,"target":1658},{"edgeType":"contains","source":2511,"target":2543},{"edgeType":"calls","source":2365,"target":1385},{"edgeType":"calls","source":725,"target":434},{"edgeType":"contains","source":3864,"target":3939},{"edgeType":"contains","source":1054,"target":1203},{"edgeType":"calls","source":1746,"target":493},{"edgeType":"contains","source":3,"target":2072},{"edgeType":"calls","source":4710,"target":568},{"edgeType":"imports","source":4001,"target":302},{"edgeType":"contains","source":4130,"target":4148},{"edgeType":"calls","source":4105,"target":298},{"edgeType":"calls","source":4547,"target":336},{"edgeType":"contains","source":4524,"target":4618},{"edgeType":"contains","source":1054,"target":1202},{"edgeType":"calls","source":3001,"target":1754},{"edgeType":"contains","source":1849,"target":1925},{"edgeType":"contains","source":1454,"target":1486},{"edgeType":"calls","source":3104,"target":675},{"edgeType":"calls","source":3274,"target":690},{"edgeType":"calls","source":4710,"target":567},{"edgeType":"calls","source":1746,"target":488},{"edgeType":"calls","source":3847,"target":894},{"edgeType":"calls","source":2051,"target":546},{"edgeType":"contains","source":3864,"target":3945},{"edgeType":"contains","source":2511,"target":2549},{"edgeType":"contains","source":2077,"target":2261},{"edgeType":"contains","source":2269,"target":2651},{"edgeType":"calls","source":2986,"target":102},{"edgeType":"contains","source":1455,"target":1460},{"edgeType":"calls","source":1746,"target":487},{"edgeType":"calls","source":4710,"target":566},{"edgeType":"contains","source":2077,"target":2262},{"edgeType":"imports","source":3701,"target":91},{"edgeType":"contains","source":2511,"target":2550},{"edgeType":"calls","source":4237,"target":1489},{"edgeType":"contains","source":2269,"target":2653},{"edgeType":"calls","source":1746,"target":486},{"edgeType":"calls","source":1059,"target":646},{"edgeType":"calls","source":4793,"target":106},{"edgeType":"contains","source":2806,"target":2915},{"edgeType":"calls","source":4136,"target":389},{"edgeType":"contains","source":1884,"target":1900},{"edgeType":"calls","source":1746,"target":490},{"edgeType":"calls","source":4040,"target":194},{"edgeType":"contains","source":2511,"target":2547},{"edgeType":"calls","source":4889,"target":301},{"edgeType":"imports","source":3534,"target":2098},{"edgeType":"calls","source":4612,"target":1489},{"edgeType":"calls","source":4581,"target":336},{"edgeType":"calls","source":2986,"target":100},{"edgeType":"calls","source":1657,"target":77},{"edgeType":"calls","source":3847,"target":891},{"edgeType":"contains","source":3404,"target":3405},{"edgeType":"contains","source":4130,"target":4152},{"edgeType":"calls","source":1746,"target":489},{"edgeType":"imports","source":3701,"target":93},{"edgeType":"calls","source":4579,"target":397},{"edgeType":"calls","source":2986,"target":101},{"edgeType":"contains","source":1455,"target":1459},{"edgeType":"calls","source":1296,"target":697},{"edgeType":"calls","source":1332,"target":638},{"edgeType":"contains","source":1224,"target":1225},{"edgeType":"contains","source":4524,"target":4630},{"edgeType":"calls","source":4136,"target":387},{"edgeType":"calls","source":4722,"target":191},{"edgeType":"calls","source":692,"target":389},{"edgeType":"calls","source":2657,"target":783},{"edgeType":"calls","source":2986,"target":98},{"edgeType":"calls","source":2257,"target":499},{"edgeType":"calls","source":903,"target":191},{"edgeType":"contains","source":3501,"target":3575},{"edgeType":"imports","source":3534,"target":2084},{"edgeType":"calls","source":1372,"target":1507},{"edgeType":"calls","source":555,"target":407},{"edgeType":"calls","source":4770,"target":1873},{"edgeType":"calls","source":1998,"target":1127},{"edgeType":"calls","source":3324,"target":191},{"edgeType":"calls","source":4136,"target":388},{"edgeType":"contains","source":4524,"target":4629},{"edgeType":"calls","source":4615,"target":336},{"edgeType":"contains","source":2280,"target":3373},{"edgeType":"calls","source":459,"target":212},{"edgeType":"contains","source":6,"target":3042},{"edgeType":"calls","source":692,"target":388},{"edgeType":"calls","source":2986,"target":99},{"edgeType":"contains","source":3501,"target":3574},{"edgeType":"calls","source":3061,"target":3059},{"edgeType":"calls","source":1372,"target":1506},{"edgeType":"calls","source":3583,"target":1675},{"edgeType":"calls","source":484,"target":497},{"edgeType":"calls","source":4136,"target":385},{"edgeType":"calls","source":3452,"target":448},{"edgeType":"contains","source":2511,"target":2551},{"edgeType":"calls","source":3305,"target":777},{"edgeType":"imports","source":1090,"target":697},{"edgeType":"contains","source":6,"target":3046},{"edgeType":"contains","source":2269,"target":2654},{"edgeType":"calls","source":4403,"target":565},{"edgeType":"calls","source":1746,"target":485},{"edgeType":"imports","source":830,"target":300},{"edgeType":"contains","source":4791,"target":4807},{"edgeType":"contains","source":3099,"target":1235},{"edgeType":"calls","source":1443,"target":365},{"edgeType":"contains","source":3162,"target":339},{"edgeType":"calls","source":2657,"target":782},{"edgeType":"contains","source":1224,"target":1226},{"edgeType":"calls","source":1297,"target":662},{"edgeType":"contains","source":2511,"target":2552},{"edgeType":"contains","source":4791,"target":4806},{"edgeType":"calls","source":4136,"target":386},{"edgeType":"calls","source":292,"target":106},{"edgeType":"calls","source":4846,"target":572},{"edgeType":"contains","source":2255,"target":2032},{"edgeType":"calls","source":1310,"target":1311},{"edgeType":"calls","source":4846,"target":571},{"edgeType":"calls","source":692,"target":385},{"edgeType":"calls","source":4136,"target":383},{"edgeType":"calls","source":1372,"target":1503},{"edgeType":"contains","source":2280,"target":3376},{"edgeType":"calls","source":4674,"target":1675},{"edgeType":"calls","source":1701,"target":817},{"edgeType":"contains","source":3501,"target":3579},{"edgeType":"calls","source":2431,"target":1443},{"edgeType":"contains","source":3501,"target":408},{"edgeType":"imports","source":1918,"target":1454},{"edgeType":"contains","source":2269,"target":2660},{"edgeType":"calls","source":4136,"target":384},{"edgeType":"calls","source":4846,"target":570},{"edgeType":"calls","source":692,"target":384},{"edgeType":"calls","source":1372,"target":1502},{"edgeType":"contains","source":2280,"target":3377},{"edgeType":"calls","source":1077,"target":77},{"edgeType":"calls","source":418,"target":422},{"edgeType":"contains","source":2259,"target":857},{"edgeType":"calls","source":451,"target":456},{"edgeType":"calls","source":2291,"target":499},{"edgeType":"imports","source":2255,"target":519},{"edgeType":"calls","source":3605,"target":2046},{"edgeType":"calls","source":183,"target":308},{"edgeType":"calls","source":1911,"target":1705},{"edgeType":"contains","source":2511,"target":2555},{"edgeType":"calls","source":4846,"target":569},{"edgeType":"contains","source":4524,"target":4632},{"edgeType":"calls","source":2761,"target":724},{"edgeType":"calls","source":1372,"target":1505},{"edgeType":"calls","source":459,"target":211},{"edgeType":"calls","source":3310,"target":1675},{"edgeType":"calls","source":4790,"target":191},{"edgeType":"calls","source":3121,"target":3306},{"edgeType":"calls","source":692,"target":387},{"edgeType":"calls","source":3061,"target":3052},{"edgeType":"calls","source":893,"target":499},{"edgeType":"contains","source":3501,"target":3577},{"edgeType":"contains","source":2269,"target":2658},{"edgeType":"contains","source":1257,"target":1262},{"edgeType":"contains","source":4791,"target":4811},{"edgeType":"calls","source":4136,"target":382},{"edgeType":"calls","source":4846,"target":568},{"edgeType":"calls","source":3392,"target":191},{"edgeType":"calls","source":1372,"target":1504},{"edgeType":"contains","source":4524,"target":4631},{"edgeType":"calls","source":1310,"target":1312},{"edgeType":"calls","source":4714,"target":1489},{"edgeType":"calls","source":4591,"target":4245},{"edgeType":"calls","source":692,"target":386},{"edgeType":"extends","source":1221,"target":1104},{"edgeType":"calls","source":2253,"target":1675},{"edgeType":"contains","source":2280,"target":2318},{"edgeType":"contains","source":2269,"target":2659},{"edgeType":"contains","source":3501,"target":3576},{"edgeType":"calls","source":4539,"target":572},{"edgeType":"calls","source":4026,"target":1677},{"edgeType":"calls","source":4741,"target":1675},{"edgeType":"calls","source":4787,"target":249},{"edgeType":"calls","source":3462,"target":99},{"edgeType":"contains","source":3467,"target":3547},{"edgeType":"calls","source":2492,"target":572},{"edgeType":"contains","source":4130,"target":4135},{"edgeType":"calls","source":359,"target":101},{"edgeType":"calls","source":1063,"target":474},{"edgeType":"calls","source":2453,"target":724},{"edgeType":"contains","source":721,"target":937},{"edgeType":"contains","source":3936,"target":1691},{"edgeType":"calls","source":3462,"target":100},{"edgeType":"contains","source":1123,"target":1159},{"edgeType":"calls","source":2747,"target":1124},{"edgeType":"calls","source":4834,"target":905},{"edgeType":"imports","source":2255,"target":564},{"edgeType":"calls","source":1128,"target":572},{"edgeType":"contains","source":4130,"target":4134},{"edgeType":"calls","source":3810,"target":1996},{"edgeType":"calls","source":1063,"target":473},{"edgeType":"contains","source":2115,"target":2121},{"edgeType":"contains","source":2077,"target":2242},{"edgeType":"calls","source":4787,"target":248},{"edgeType":"calls","source":2228,"target":301},{"edgeType":"contains","source":2511,"target":2529},{"edgeType":"calls","source":359,"target":100},{"edgeType":"contains","source":1054,"target":1187},{"edgeType":"calls","source":619,"target":499},{"edgeType":"calls","source":587,"target":434},{"edgeType":"calls","source":824,"target":486},{"edgeType":"imports","source":621,"target":479},{"edgeType":"imports","source":4451,"target":2256},{"edgeType":"contains","source":3467,"target":3545},{"edgeType":"contains","source":2077,"target":2239},{"edgeType":"calls","source":2492,"target":570},{"edgeType":"calls","source":3827,"target":3580},{"edgeType":"contains","source":4130,"target":4133},{"edgeType":"calls","source":3844,"target":1996},{"edgeType":"calls","source":526,"target":211},{"edgeType":"contains","source":721,"target":939},{"edgeType":"calls","source":2051,"target":502},{"edgeType":"contains","source":4723,"target":4776},{"edgeType":"calls","source":824,"target":485},{"edgeType":"contains","source":1054,"target":1186},{"edgeType":"calls","source":3372,"target":774},{"edgeType":"calls","source":3462,"target":98},{"edgeType":"calls","source":359,"target":102},{"edgeType":"calls","source":1109,"target":106},{"edgeType":"contains","source":3467,"target":3544},{"edgeType":"calls","source":2492,"target":571},{"edgeType":"contains","source":2204,"target":2531},{"edgeType":"contains","source":4130,"target":4132},{"edgeType":"calls","source":4775,"target":1675},{"edgeType":"calls","source":4781,"target":1489},{"edgeType":"calls","source":2321,"target":587},{"edgeType":"calls","source":4456,"target":2051},{"edgeType":"calls","source":2326,"target":1489},{"edgeType":"contains","source":2511,"target":2527},{"edgeType":"contains","source":721,"target":938},{"edgeType":"contains","source":4723,"target":4775},{"edgeType":"contains","source":3623,"target":4000},{"edgeType":"calls","source":2225,"target":388},{"edgeType":"contains","source":1054,"target":1189},{"edgeType":"contains","source":627,"target":684},{"edgeType":"calls","source":4712,"target":456},{"edgeType":"calls","source":1109,"target":101},{"edgeType":"calls","source":1128,"target":569},{"edgeType":"calls","source":4123,"target":744},{"edgeType":"calls","source":4834,"target":902},{"edgeType":"contains","source":3864,"target":3929},{"edgeType":"contains","source":681,"target":2181},{"edgeType":"calls","source":2492,"target":568},{"edgeType":"contains","source":4130,"target":4139},{"edgeType":"calls","source":2225,"target":389},{"edgeType":"contains","source":1054,"target":1188},{"edgeType":"calls","source":2498,"target":2497},{"edgeType":"contains","source":627,"target":683},{"edgeType":"calls","source":1128,"target":568},{"edgeType":"imports","source":2646,"target":1123},{"edgeType":"calls","source":3868,"target":194},{"edgeType":"calls","source":1109,"target":100},{"edgeType":"calls","source":4891,"target":191},{"edgeType":"contains","source":2077,"target":2246},{"edgeType":"calls","source":4834,"target":901},{"edgeType":"calls","source":2678,"target":88},{"edgeType":"contains","source":721,"target":940},{"edgeType":"contains","source":681,"target":2180},{"edgeType":"calls","source":2492,"target":569},{"edgeType":"contains","source":3162,"target":319},{"edgeType":"calls","source":4373,"target":392},{"edgeType":"calls","source":2225,"target":386},{"edgeType":"contains","source":1054,"target":1191},{"edgeType":"calls","source":3902,"target":194},{"edgeType":"calls","source":4056,"target":705},{"edgeType":"contains","source":627,"target":686},{"edgeType":"calls","source":4780,"target":460},{"edgeType":"calls","source":1128,"target":571},{"edgeType":"calls","source":1063,"target":472},{"edgeType":"contains","source":2115,"target":2122},{"edgeType":"contains","source":2077,"target":2243},{"edgeType":"imports","source":3571,"target":1001},{"edgeType":"contains","source":2208,"target":296},{"edgeType":"calls","source":561,"target":179},{"edgeType":"calls","source":4834,"target":900},{"edgeType":"calls","source":4815,"target":1489},{"edgeType":"calls","source":4680,"target":389},{"edgeType":"contains","source":4524,"target":4607},{"edgeType":"calls","source":2492,"target":566},{"edgeType":"contains","source":2511,"target":2530},{"edgeType":"calls","source":359,"target":99},{"edgeType":"calls","source":2217,"target":1692},{"edgeType":"calls","source":2225,"target":387},{"edgeType":"contains","source":1054,"target":1190},{"edgeType":"contains","source":3467,"target":3548},{"edgeType":"calls","source":1128,"target":570},{"edgeType":"contains","source":4130,"target":4136},{"edgeType":"contains","source":627,"target":685},{"edgeType":"calls","source":1109,"target":102},{"edgeType":"contains","source":1884,"target":1885},{"edgeType":"contains","source":721,"target":942},{"edgeType":"contains","source":681,"target":2182},{"edgeType":"contains","source":97,"target":1260},{"edgeType":"calls","source":2811,"target":191},{"edgeType":"calls","source":4680,"target":388},{"edgeType":"calls","source":359,"target":98},{"edgeType":"imports","source":2201,"target":1175},{"edgeType":"calls","source":4468,"target":1675},{"edgeType":"calls","source":2492,"target":567},{"edgeType":"calls","source":4598,"target":1873},{"edgeType":"calls","source":4373,"target":390},{"edgeType":"contains","source":721,"target":946},{"edgeType":"calls","source":2225,"target":384},{"edgeType":"contains","source":4791,"target":4793},{"edgeType":"contains","source":1054,"target":1193},{"edgeType":"calls","source":1497,"target":754},{"edgeType":"contains","source":3162,"target":3496},{"edgeType":"calls","source":3624,"target":354},{"edgeType":"calls","source":1878,"target":570},{"edgeType":"contains","source":3162,"target":325},{"edgeType":"calls","source":1752,"target":248},{"edgeType":"contains","source":627,"target":688},{"edgeType":"contains","source":4524,"target":4613},{"edgeType":"contains","source":6,"target":913},{"edgeType":"contains","source":4130,"target":4143},{"edgeType":"calls","source":1064,"target":435},{"edgeType":"calls","source":2935,"target":572},{"edgeType":"contains","source":44,"target":792},{"edgeType":"contains","source":3864,"target":3933},{"edgeType":"calls","source":4540,"target":499},{"edgeType":"calls","source":4680,"target":387},{"edgeType":"calls","source":4645,"target":1472},{"edgeType":"contains","source":799,"target":641},{"edgeType":"calls","source":2234,"target":106},{"edgeType":"calls","source":2225,"target":385},{"edgeType":"contains","source":3727,"target":3950},{"edgeType":"contains","source":3501,"target":3557},{"edgeType":"contains","source":721,"target":945},{"edgeType":"contains","source":1054,"target":1192},{"edgeType":"contains","source":2710,"target":2711},{"edgeType":"contains","source":3467,"target":3554},{"edgeType":"calls","source":83,"target":191},{"edgeType":"contains","source":4791,"target":4792},{"edgeType":"calls","source":1928,"target":1133},{"edgeType":"calls","source":1878,"target":569},{"edgeType":"calls","source":4122,"target":772},{"edgeType":"contains","source":4524,"target":4612},{"edgeType":"calls","source":1339,"target":365},{"edgeType":"contains","source":681,"target":2184},{"edgeType":"contains","source":44,"target":791},{"edgeType":"contains","source":3833,"target":3836},{"edgeType":"calls","source":1064,"target":434},{"edgeType":"calls","source":2736,"target":400},{"edgeType":"contains","source":2077,"target":2250},{"edgeType":"calls","source":4680,"target":386},{"edgeType":"calls","source":83,"target":194},{"edgeType":"contains","source":3727,"target":3949},{"edgeType":"calls","source":2225,"target":382},{"edgeType":"calls","source":3691,"target":389},{"edgeType":"contains","source":1054,"target":1195},{"edgeType":"calls","source":1878,"target":572},{"edgeType":"calls","source":4123,"target":738},{"edgeType":"calls","source":1109,"target":99},{"edgeType":"calls","source":1128,"target":567},{"edgeType":"calls","source":4680,"target":385},{"edgeType":"contains","source":4524,"target":4611},{"edgeType":"contains","source":3833,"target":3835},{"edgeType":"calls","source":4595,"target":906},{"edgeType":"calls","source":2985,"target":77},{"edgeType":"calls","source":2935,"target":570},{"edgeType":"imports","source":4079,"target":39},{"edgeType":"contains","source":2201,"target":2631},{"edgeType":"calls","source":2225,"target":383},{"edgeType":"contains","source":3727,"target":3948},{"edgeType":"calls","source":3624,"target":353},{"edgeType":"contains","source":3501,"target":3555},{"edgeType":"calls","source":1878,"target":571},{"edgeType":"contains","source":1054,"target":1194},{"edgeType":"calls","source":1752,"target":249},{"edgeType":"calls","source":1128,"target":566},{"edgeType":"contains","source":2077,"target":2248},{"edgeType":"calls","source":4680,"target":384},{"edgeType":"contains","source":4524,"target":4610},{"edgeType":"calls","source":1109,"target":98},{"edgeType":"contains","source":3833,"target":3834},{"edgeType":"calls","source":2935,"target":571},{"edgeType":"imports","source":4079,"target":40},{"edgeType":"calls","source":2746,"target":88},{"edgeType":"contains","source":1454,"target":1482},{"edgeType":"contains","source":721,"target":950},{"edgeType":"contains","source":3534,"target":3596},{"edgeType":"calls","source":422,"target":249},{"edgeType":"calls","source":1878,"target":566},{"edgeType":"calls","source":1856,"target":191},{"edgeType":"calls","source":3691,"target":387},{"edgeType":"contains","source":1054,"target":1197},{"edgeType":"contains","source":3936,"target":648},{"edgeType":"calls","source":620,"target":454},{"edgeType":"contains","source":2511,"target":2540},{"edgeType":"calls","source":724,"target":401},{"edgeType":"calls","source":3595,"target":191},{"edgeType":"calls","source":3568,"target":2085},{"edgeType":"calls","source":2935,"target":568},{"edgeType":"calls","source":4680,"target":383},{"edgeType":"imports","source":4079,"target":41},{"edgeType":"calls","source":1732,"target":863},{"edgeType":"contains","source":16,"target":3777},{"edgeType":"contains","source":2077,"target":2254},{"edgeType":"calls","source":422,"target":248},{"edgeType":"calls","source":2218,"target":1655},{"edgeType":"calls","source":3691,"target":388},{"edgeType":"contains","source":1054,"target":1196},{"edgeType":"contains","source":2511,"target":2541},{"edgeType":"contains","source":4524,"target":4616},{"edgeType":"calls","source":755,"target":496},{"edgeType":"calls","source":3359,"target":1166},{"edgeType":"contains","source":3701,"target":3704},{"edgeType":"calls","source":4680,"target":382},{"edgeType":"calls","source":776,"target":902},{"edgeType":"calls","source":2935,"target":569},{"edgeType":"contains","source":721,"target":952},{"edgeType":"calls","source":1719,"target":212},{"edgeType":"calls","source":3888,"target":1677},{"edgeType":"contains","source":97,"target":1269},{"edgeType":"calls","source":2528,"target":498},{"edgeType":"contains","source":1454,"target":1480},{"edgeType":"calls","source":4496,"target":1856},{"edgeType":"calls","source":4652,"target":191},{"edgeType":"calls","source":3691,"target":385},{"edgeType":"calls","source":4317,"target":1063},{"edgeType":"contains","source":4791,"target":4795},{"edgeType":"calls","source":1878,"target":568},{"edgeType":"contains","source":1054,"target":1199},{"edgeType":"calls","source":2869,"target":498},{"edgeType":"calls","source":3691,"target":384},{"edgeType":"contains","source":3701,"target":3703},{"edgeType":"calls","source":4758,"target":77},{"edgeType":"calls","source":2935,"target":566},{"edgeType":"contains","source":4130,"target":4145},{"edgeType":"calls","source":4453,"target":4245},{"edgeType":"contains","source":6,"target":918},{"edgeType":"calls","source":1657,"target":1076},{"edgeType":"calls","source":1719,"target":211},{"edgeType":"calls","source":4545,"target":336},{"edgeType":"calls","source":4742,"target":571},{"edgeType":"contains","source":1454,"target":1481},{"edgeType":"calls","source":4703,"target":723},{"edgeType":"calls","source":1878,"target":567},{"edgeType":"calls","source":4041,"target":106},{"edgeType":"calls","source":1528,"target":847},{"edgeType":"calls","source":3691,"target":386},{"edgeType":"contains","source":4791,"target":4794},{"edgeType":"calls","source":2302,"target":106},{"edgeType":"calls","source":4137,"target":301},{"edgeType":"contains","source":1054,"target":1198},{"edgeType":"calls","source":4794,"target":4245},{"edgeType":"calls","source":2802,"target":462},{"edgeType":"calls","source":556,"target":325},{"edgeType":"calls","source":3519,"target":1489},{"edgeType":"calls","source":2643,"target":106},{"edgeType":"calls","source":2935,"target":567},{"edgeType":"calls","source":4742,"target":572},{"edgeType":"contains","source":4130,"target":4144},{"edgeType":"calls","source":724,"target":402},{"edgeType":"contains","source":2077,"target":2252},{"edgeType":"contains","source":3936,"target":645},{"edgeType":"contains","source":16,"target":3749},{"edgeType":"contains","source":1288,"target":1314},{"edgeType":"contains","source":953,"target":1128},{"edgeType":"contains","source":4723,"target":4762},{"edgeType":"contains","source":2511,"target":2512},{"edgeType":"calls","source":2254,"target":567},{"edgeType":"contains","source":681,"target":3218},{"edgeType":"contains","source":721,"target":921},{"edgeType":"contains","source":4524,"target":4589},{"edgeType":"calls","source":1514,"target":1308},{"edgeType":"calls","source":817,"target":718},{"edgeType":"calls","source":760,"target":371},{"edgeType":"calls","source":747,"target":774},{"edgeType":"contains","source":3162,"target":3471},{"edgeType":"calls","source":1231,"target":568},{"edgeType":"contains","source":3535,"target":3537},{"edgeType":"calls","source":4454,"target":4245},{"edgeType":"contains","source":1288,"target":1315},{"edgeType":"calls","source":4546,"target":336},{"edgeType":"calls","source":2510,"target":1088},{"edgeType":"calls","source":2254,"target":568},{"edgeType":"calls","source":3999,"target":382},{"edgeType":"calls","source":4104,"target":298},{"edgeType":"calls","source":4242,"target":248},{"edgeType":"contains","source":4524,"target":4587},{"edgeType":"calls","source":4795,"target":4245},{"edgeType":"contains","source":3162,"target":3472},{"edgeType":"calls","source":817,"target":717},{"edgeType":"calls","source":3600,"target":66},{"edgeType":"calls","source":931,"target":354},{"edgeType":"calls","source":2876,"target":1370},{"edgeType":"contains","source":3535,"target":3536},{"edgeType":"calls","source":3273,"target":690},{"edgeType":"calls","source":1231,"target":567},{"edgeType":"calls","source":3000,"target":1754},{"edgeType":"contains","source":3467,"target":3528},{"edgeType":"calls","source":4585,"target":183},{"edgeType":"contains","source":63,"target":180},{"edgeType":"contains","source":3400,"target":3491},{"edgeType":"contains","source":44,"target":769},{"edgeType":"calls","source":4785,"target":325},{"edgeType":"contains","source":3162,"target":3469},{"edgeType":"calls","source":1336,"target":486},{"edgeType":"calls","source":2985,"target":102},{"edgeType":"contains","source":1148,"target":1427},{"edgeType":"calls","source":1231,"target":570},{"edgeType":"contains","source":1933,"target":3515},{"edgeType":"calls","source":817,"target":720},{"edgeType":"calls","source":4687,"target":191},{"edgeType":"contains","source":4856,"target":4864},{"edgeType":"calls","source":1733,"target":863},{"edgeType":"calls","source":4696,"target":969},{"edgeType":"calls","source":2492,"target":587},{"edgeType":"contains","source":44,"target":768},{"edgeType":"contains","source":3501,"target":359},{"edgeType":"contains","source":1288,"target":1313},{"edgeType":"calls","source":556,"target":353},{"edgeType":"calls","source":2254,"target":566},{"edgeType":"contains","source":4524,"target":4585},{"edgeType":"contains","source":4451,"target":4734},{"edgeType":"imports","source":2255,"target":546},{"edgeType":"contains","source":3162,"target":3470},{"edgeType":"calls","source":556,"target":354},{"edgeType":"calls","source":1231,"target":569},{"edgeType":"calls","source":3344,"target":1658},{"edgeType":"calls","source":817,"target":719},{"edgeType":"contains","source":1520,"target":1521},{"edgeType":"calls","source":1336,"target":485},{"edgeType":"contains","source":1288,"target":1318},{"edgeType":"calls","source":4611,"target":1489},{"edgeType":"calls","source":1231,"target":564},{"edgeType":"imports","source":1247,"target":81},{"edgeType":"contains","source":2077,"target":2228},{"edgeType":"calls","source":1917,"target":439},{"edgeType":"contains","source":3864,"target":3912},{"edgeType":"calls","source":724,"target":425},{"edgeType":"calls","source":2737,"target":388},{"edgeType":"contains","source":4524,"target":4593},{"edgeType":"calls","source":4488,"target":4245},{"edgeType":"calls","source":4580,"target":336},{"edgeType":"calls","source":817,"target":714},{"edgeType":"calls","source":724,"target":426},{"edgeType":"calls","source":2978,"target":2431},{"edgeType":"calls","source":2985,"target":100},{"edgeType":"contains","source":3936,"target":623},{"edgeType":"calls","source":1672,"target":1691},{"edgeType":"contains","source":1114,"target":1426},{"edgeType":"contains","source":1288,"target":1319},{"edgeType":"contains","source":4723,"target":4765},{"edgeType":"calls","source":4758,"target":102},{"edgeType":"imports","source":1247,"target":82},{"edgeType":"calls","source":1818,"target":336},{"edgeType":"contains","source":63,"target":181},{"edgeType":"contains","source":44,"target":770},{"edgeType":"calls","source":2737,"target":389},{"edgeType":"calls","source":291,"target":106},{"edgeType":"calls","source":2656,"target":786},{"edgeType":"calls","source":817,"target":713},{"edgeType":"calls","source":4270,"target":1489},{"edgeType":"calls","source":2985,"target":101},{"edgeType":"contains","source":3936,"target":622},{"edgeType":"contains","source":1114,"target":1425},{"edgeType":"calls","source":1350,"target":45},{"edgeType":"contains","source":1288,"target":1320},{"edgeType":"calls","source":4758,"target":101},{"edgeType":"imports","source":1247,"target":79},{"edgeType":"calls","source":4721,"target":191},{"edgeType":"contains","source":627,"target":670},{"edgeType":"contains","source":1288,"target":1316},{"edgeType":"calls","source":1996,"target":106},{"edgeType":"calls","source":4224,"target":1856},{"edgeType":"calls","source":587,"target":446},{"edgeType":"contains","source":2417,"target":3314},{"edgeType":"calls","source":2737,"target":386},{"edgeType":"contains","source":4524,"target":4591},{"edgeType":"calls","source":2563,"target":495},{"edgeType":"contains","source":2511,"target":2514},{"edgeType":"calls","source":2985,"target":98},{"edgeType":"calls","source":4250,"target":4222},{"edgeType":"calls","source":1514,"target":249},{"edgeType":"calls","source":4396,"target":753},{"edgeType":"imports","source":4079,"target":35},{"edgeType":"calls","source":817,"target":716},{"edgeType":"contains","source":3123,"target":454},{"edgeType":"calls","source":931,"target":353},{"edgeType":"contains","source":3535,"target":3539},{"edgeType":"calls","source":1655,"target":106},{"edgeType":"calls","source":3353,"target":2431},{"edgeType":"calls","source":1231,"target":566},{"edgeType":"contains","source":1454,"target":1456},{"edgeType":"calls","source":4758,"target":100},{"edgeType":"contains","source":1288,"target":1317},{"edgeType":"imports","source":1247,"target":80},{"edgeType":"calls","source":4769,"target":1873},{"edgeType":"calls","source":587,"target":445},{"edgeType":"calls","source":2737,"target":387},{"edgeType":"calls","source":2563,"target":496},{"edgeType":"calls","source":4522,"target":4245},{"edgeType":"calls","source":4622,"target":88},{"edgeType":"calls","source":1514,"target":248},{"edgeType":"contains","source":4451,"target":4738},{"edgeType":"calls","source":4396,"target":752},{"edgeType":"calls","source":724,"target":427},{"edgeType":"contains","source":3864,"target":3909},{"edgeType":"calls","source":817,"target":715},{"edgeType":"calls","source":824,"target":498},{"edgeType":"contains","source":3066,"target":1165},{"edgeType":"calls","source":2985,"target":99},{"edgeType":"contains","source":3535,"target":3538},{"edgeType":"calls","source":4815,"target":446},{"edgeType":"contains","source":627,"target":672},{"edgeType":"contains","source":4723,"target":4770},{"edgeType":"calls","source":3304,"target":777},{"edgeType":"contains","source":4524,"target":4597},{"edgeType":"calls","source":2501,"target":301},{"edgeType":"calls","source":4576,"target":456},{"edgeType":"calls","source":2781,"target":77},{"edgeType":"calls","source":2563,"target":493},{"edgeType":"calls","source":4758,"target":99},{"edgeType":"calls","source":2737,"target":384},{"edgeType":"calls","source":4304,"target":1489},{"edgeType":"calls","source":325,"target":106},{"edgeType":"calls","source":1444,"target":299},{"edgeType":"contains","source":1288,"target":1323},{"edgeType":"contains","source":3066,"target":1170},{"edgeType":"calls","source":1856,"target":211},{"edgeType":"calls","source":4815,"target":445},{"edgeType":"calls","source":1949,"target":499},{"edgeType":"contains","source":627,"target":671},{"edgeType":"contains","source":4723,"target":4769},{"edgeType":"contains","source":721,"target":928},{"edgeType":"calls","source":2494,"target":519},{"edgeType":"calls","source":459,"target":179},{"edgeType":"calls","source":2563,"target":494},{"edgeType":"calls","source":2737,"target":385},{"edgeType":"calls","source":4845,"target":572},{"edgeType":"calls","source":4758,"target":98},{"edgeType":"calls","source":4028,"target":3700},{"edgeType":"calls","source":2737,"target":382},{"edgeType":"calls","source":4107,"target":194},{"edgeType":"calls","source":3353,"target":1370},{"edgeType":"contains","source":4723,"target":4768},{"edgeType":"calls","source":2531,"target":426},{"edgeType":"contains","source":3936,"target":625},{"edgeType":"calls","source":2563,"target":491},{"edgeType":"calls","source":2636,"target":342},{"edgeType":"calls","source":4679,"target":1489},{"edgeType":"calls","source":2837,"target":453},{"edgeType":"calls","source":4845,"target":571},{"edgeType":"calls","source":3766,"target":194},{"edgeType":"calls","source":817,"target":712},{"edgeType":"calls","source":3657,"target":402},{"edgeType":"calls","source":4845,"target":570},{"edgeType":"calls","source":2679,"target":1124},{"edgeType":"calls","source":549,"target":562},{"edgeType":"contains","source":627,"target":673},{"edgeType":"contains","source":3936,"target":624},{"edgeType":"contains","source":4524,"target":4594},{"edgeType":"contains","source":2077,"target":2231},{"edgeType":"calls","source":2563,"target":492},{"edgeType":"calls","source":2531,"target":427},{"edgeType":"calls","source":2737,"target":383},{"edgeType":"calls","source":2769,"target":448},{"edgeType":"contains","source":2280,"target":2281},{"edgeType":"calls","source":2271,"target":1088},{"edgeType":"contains","source":1288,"target":1322},{"edgeType":"calls","source":1856,"target":212},{"edgeType":"calls","source":4845,"target":569},{"edgeType":"contains","source":2276,"target":3467},{"edgeType":"calls","source":824,"target":488},{"edgeType":"calls","source":1109,"target":1167},{"edgeType":"calls","source":4586,"target":2256},{"edgeType":"contains","source":4163,"target":4165},{"edgeType":"calls","source":4495,"target":1906},{"edgeType":"contains","source":4130,"target":4131},{"edgeType":"contains","source":627,"target":676},{"edgeType":"contains","source":4723,"target":4774},{"edgeType":"calls","source":3638,"target":2046},{"edgeType":"calls","source":1943,"target":1738},{"edgeType":"contains","source":2806,"target":2892},{"edgeType":"calls","source":4845,"target":568},{"edgeType":"calls","source":587,"target":435},{"edgeType":"calls","source":526,"target":212},{"edgeType":"calls","source":2531,"target":425},{"edgeType":"calls","source":824,"target":487},{"edgeType":"calls","source":2837,"target":452},{"edgeType":"contains","source":2115,"target":2117},{"edgeType":"contains","source":2077,"target":2238},{"edgeType":"contains","source":4163,"target":4164},{"edgeType":"contains","source":627,"target":675},{"edgeType":"contains","source":4723,"target":4773},{"edgeType":"calls","source":4286,"target":985},{"edgeType":"calls","source":3657,"target":401},{"edgeType":"calls","source":2051,"target":503},{"edgeType":"calls","source":4845,"target":567},{"edgeType":"calls","source":3462,"target":101},{"edgeType":"calls","source":1267,"target":499},{"edgeType":"calls","source":796,"target":301},{"edgeType":"calls","source":4779,"target":499},{"edgeType":"calls","source":4789,"target":189},{"edgeType":"calls","source":824,"target":490},{"edgeType":"calls","source":3104,"target":628},{"edgeType":"calls","source":3933,"target":298},{"edgeType":"imports","source":1918,"target":1485},{"edgeType":"calls","source":4496,"target":1873},{"edgeType":"calls","source":4372,"target":1489},{"edgeType":"imports","source":2975,"target":1485},{"edgeType":"contains","source":4723,"target":4772},{"edgeType":"calls","source":3446,"target":1655},{"edgeType":"calls","source":4202,"target":417},{"edgeType":"contains","source":1148,"target":1439},{"edgeType":"calls","source":4845,"target":566},{"edgeType":"contains","source":4524,"target":4598},{"edgeType":"calls","source":3462,"target":102},{"edgeType":"calls","source":3526,"target":3403},{"edgeType":"calls","source":824,"target":489},{"edgeType":"calls","source":4746,"target":464},{"edgeType":"contains","source":1535,"target":4239},{"edgeType":"contains","source":3864,"target":3917},{"edgeType":"calls","source":4580,"target":325},{"edgeType":"calls","source":3613,"target":1763},{"edgeType":"calls","source":2250,"target":1735},{"edgeType":"contains","source":627,"target":677},{"edgeType":"calls","source":1910,"target":1705},{"edgeType":"calls","source":1370,"target":570},{"edgeType":"calls","source":703,"target":106},{"edgeType":"calls","source":4848,"target":571},{"edgeType":"contains","source":3123,"target":436},{"edgeType":"calls","source":3416,"target":567},{"edgeType":"calls","source":4701,"target":900},{"edgeType":"calls","source":4676,"target":1675},{"edgeType":"calls","source":4722,"target":249},{"edgeType":"calls","source":1234,"target":558},{"edgeType":"contains","source":1516,"target":1629},{"edgeType":"contains","source":1947,"target":2009},{"edgeType":"calls","source":4752,"target":376},{"edgeType":"contains","source":1750,"target":717},{"edgeType":"calls","source":2433,"target":386},{"edgeType":"contains","source":3400,"target":3477},{"edgeType":"calls","source":2337,"target":191},{"edgeType":"calls","source":2362,"target":473},{"edgeType":"calls","source":4384,"target":4385},{"edgeType":"calls","source":1385,"target":1161},{"edgeType":"contains","source":1750,"target":718},{"edgeType":"calls","source":2772,"target":448},{"edgeType":"contains","source":3797,"target":3853},{"edgeType":"calls","source":1370,"target":569},{"edgeType":"calls","source":4848,"target":570},{"edgeType":"contains","source":3123,"target":437},{"edgeType":"calls","source":3416,"target":568},{"edgeType":"calls","source":4758,"target":189},{"edgeType":"contains","source":3269,"target":3310},{"edgeType":"calls","source":1234,"target":557},{"edgeType":"calls","source":4722,"target":248},{"edgeType":"contains","source":1947,"target":2010},{"edgeType":"contains","source":2204,"target":1443},{"edgeType":"calls","source":2362,"target":474},{"edgeType":"calls","source":2433,"target":387},{"edgeType":"calls","source":4341,"target":1489},{"edgeType":"calls","source":3554,"target":2632},{"edgeType":"calls","source":1958,"target":1367},{"edgeType":"calls","source":4098,"target":566},{"edgeType":"calls","source":3996,"target":557},{"edgeType":"contains","source":3864,"target":3889},{"edgeType":"calls","source":1234,"target":560},{"edgeType":"calls","source":4848,"target":569},{"edgeType":"contains","source":958,"target":959},{"edgeType":"calls","source":1370,"target":572},{"edgeType":"contains","source":1090,"target":1095},{"edgeType":"calls","source":2668,"target":498},{"edgeType":"calls","source":3641,"target":2046},{"edgeType":"calls","source":2971,"target":1675},{"edgeType":"calls","source":2977,"target":1489},{"edgeType":"contains","source":1750,"target":715},{"edgeType":"calls","source":288,"target":289},{"edgeType":"calls","source":2433,"target":384},{"edgeType":"contains","source":3501,"target":344},{"edgeType":"imports","source":3936,"target":285},{"edgeType":"calls","source":2319,"target":747},{"edgeType":"calls","source":4144,"target":194},{"edgeType":"calls","source":1385,"target":106},{"edgeType":"calls","source":1370,"target":571},{"edgeType":"calls","source":705,"target":45},{"edgeType":"calls","source":1279,"target":1278},{"edgeType":"calls","source":4861,"target":2279},{"edgeType":"calls","source":3416,"target":566},{"edgeType":"imports","source":4045,"target":78},{"edgeType":"calls","source":4848,"target":568},{"edgeType":"calls","source":1385,"target":1163},{"edgeType":"contains","source":3269,"target":3308},{"edgeType":"contains","source":1947,"target":2008},{"edgeType":"calls","source":3307,"target":774},{"edgeType":"contains","source":1750,"target":716},{"edgeType":"calls","source":2433,"target":385},{"edgeType":"calls","source":3902,"target":298},{"edgeType":"calls","source":2362,"target":472},{"edgeType":"calls","source":4593,"target":4245},{"edgeType":"calls","source":4028,"target":1677},{"edgeType":"contains","source":4723,"target":4742},{"edgeType":"calls","source":1996,"target":191},{"edgeType":"contains","source":3797,"target":3858},{"edgeType":"calls","source":4848,"target":567},{"edgeType":"calls","source":3773,"target":66},{"edgeType":"calls","source":991,"target":687},{"edgeType":"calls","source":1385,"target":101},{"edgeType":"calls","source":1370,"target":566},{"edgeType":"contains","source":65,"target":104},{"edgeType":"calls","source":2362,"target":469},{"edgeType":"calls","source":2433,"target":382},{"edgeType":"contains","source":2280,"target":3319},{"edgeType":"contains","source":1750,"target":722},{"edgeType":"calls","source":2817,"target":106},{"edgeType":"calls","source":4848,"target":566},{"edgeType":"calls","source":2985,"target":183},{"edgeType":"calls","source":1385,"target":100},{"edgeType":"calls","source":2433,"target":383},{"edgeType":"calls","source":3769,"target":191},{"edgeType":"calls","source":2048,"target":687},{"edgeType":"calls","source":2362,"target":470},{"edgeType":"calls","source":552,"target":554},{"edgeType":"contains","source":1750,"target":719},{"edgeType":"calls","source":1444,"target":1445},{"edgeType":"calls","source":1370,"target":568},{"edgeType":"calls","source":2798,"target":692},{"edgeType":"contains","source":3123,"target":438},{"edgeType":"contains","source":1816,"target":1844},{"edgeType":"contains","source":3467,"target":3516},{"edgeType":"calls","source":3257,"target":2318},{"edgeType":"calls","source":420,"target":421},{"edgeType":"calls","source":4790,"target":249},{"edgeType":"calls","source":4709,"target":1703},{"edgeType":"contains","source":2204,"target":1444},{"edgeType":"calls","source":83,"target":298},{"edgeType":"calls","source":2362,"target":467},{"edgeType":"contains","source":958,"target":962},{"edgeType":"contains","source":1750,"target":720},{"edgeType":"contains","source":3864,"target":3892},{"edgeType":"calls","source":2764,"target":690},{"edgeType":"calls","source":3011,"target":1489},{"edgeType":"calls","source":1370,"target":567},{"edgeType":"calls","source":1385,"target":102},{"edgeType":"calls","source":3352,"target":1489},{"edgeType":"contains","source":1518,"target":1570},{"edgeType":"contains","source":3400,"target":3478},{"edgeType":"calls","source":4681,"target":456},{"edgeType":"contains","source":2806,"target":2866},{"edgeType":"calls","source":4790,"target":248},{"edgeType":"contains","source":2204,"target":1445},{"edgeType":"calls","source":2362,"target":468},{"edgeType":"contains","source":16,"target":3738},{"edgeType":"calls","source":2283,"target":1856},{"edgeType":"extends","source":660,"target":603},{"edgeType":"calls","source":1693,"target":1119},{"edgeType":"contains","source":3467,"target":3522},{"edgeType":"contains","source":4856,"target":4859},{"edgeType":"calls","source":1677,"target":558},{"edgeType":"calls","source":3452,"target":2614},{"edgeType":"calls","source":1250,"target":53},{"edgeType":"contains","source":1816,"target":1851},{"edgeType":"calls","source":2798,"target":690},{"edgeType":"calls","source":2362,"target":465},{"edgeType":"calls","source":622,"target":495},{"edgeType":"calls","source":3559,"target":3526},{"edgeType":"contains","source":958,"target":964},{"edgeType":"contains","source":3599,"target":3657},{"edgeType":"contains","source":4823,"target":4824},{"edgeType":"contains","source":4856,"target":4858},{"edgeType":"calls","source":1677,"target":557},{"edgeType":"calls","source":1675,"target":1676},{"edgeType":"calls","source":1693,"target":1118},{"edgeType":"calls","source":1250,"target":52},{"edgeType":"imports","source":2259,"target":482},{"edgeType":"calls","source":4757,"target":1269},{"edgeType":"calls","source":4661,"target":4245},{"edgeType":"calls","source":4778,"target":1675},{"edgeType":"calls","source":4784,"target":1489},{"edgeType":"calls","source":4070,"target":369},{"edgeType":"contains","source":3799,"target":3800},{"edgeType":"contains","source":3797,"target":3862},{"edgeType":"calls","source":4229,"target":725},{"edgeType":"calls","source":2435,"target":2431},{"edgeType":"calls","source":4649,"target":389},{"edgeType":"calls","source":4635,"target":1880},{"edgeType":"calls","source":2362,"target":466},{"edgeType":"calls","source":4609,"target":572},{"edgeType":"calls","source":622,"target":494},{"edgeType":"calls","source":2979,"target":2476},{"edgeType":"contains","source":1750,"target":723},{"edgeType":"calls","source":3100,"target":2953},{"edgeType":"contains","source":4856,"target":4857},{"edgeType":"calls","source":1385,"target":99},{"edgeType":"calls","source":4110,"target":183},{"edgeType":"imports","source":1114,"target":35},{"edgeType":"calls","source":4437,"target":1675},{"edgeType":"calls","source":552,"target":553},{"edgeType":"calls","source":325,"target":191},{"edgeType":"calls","source":4715,"target":456},{"edgeType":"calls","source":4609,"target":571},{"edgeType":"calls","source":4649,"target":388},{"edgeType":"imports","source":3420,"target":1485},{"edgeType":"imports","source":3598,"target":185},{"edgeType":"calls","source":1675,"target":1678},{"edgeType":"calls","source":1385,"target":98},{"edgeType":"calls","source":3837,"target":191},{"edgeType":"calls","source":3871,"target":194},{"edgeType":"calls","source":3769,"target":185},{"edgeType":"calls","source":3452,"target":499},{"edgeType":"calls","source":4031,"target":519},{"edgeType":"calls","source":1250,"target":54},{"edgeType":"calls","source":4609,"target":570},{"edgeType":"calls","source":622,"target":496},{"edgeType":"calls","source":4649,"target":387},{"edgeType":"calls","source":1655,"target":179},{"edgeType":"calls","source":4454,"target":88},{"edgeType":"contains","source":4723,"target":4758},{"edgeType":"calls","source":3871,"target":191},{"edgeType":"calls","source":1728,"target":30},{"edgeType":"contains","source":2806,"target":2876},{"edgeType":"contains","source":4856,"target":4863},{"edgeType":"calls","source":622,"target":491},{"edgeType":"calls","source":4059,"target":705},{"edgeType":"calls","source":1250,"target":49},{"edgeType":"calls","source":4609,"target":569},{"edgeType":"calls","source":4649,"target":386},{"edgeType":"contains","source":3799,"target":3805},{"edgeType":"imports","source":621,"target":519},{"edgeType":"calls","source":3039,"target":1672},{"edgeType":"calls","source":4543,"target":499},{"edgeType":"contains","source":3467,"target":3525},{"edgeType":"extends","source":4535,"target":3099},{"edgeType":"calls","source":1498,"target":817},{"edgeType":"contains","source":1090,"target":1104},{"edgeType":"contains","source":4856,"target":4862},{"edgeType":"calls","source":1250,"target":48},{"edgeType":"calls","source":4649,"target":385},{"edgeType":"calls","source":1109,"target":191},{"edgeType":"calls","source":4609,"target":568},{"edgeType":"imports","source":1080,"target":1088},{"edgeType":"contains","source":3799,"target":3804},{"edgeType":"calls","source":4749,"target":456},{"edgeType":"calls","source":4837,"target":899},{"edgeType":"calls","source":4609,"target":566},{"edgeType":"contains","source":3467,"target":3524},{"edgeType":"contains","source":4723,"target":4756},{"edgeType":"contains","source":4856,"target":4861},{"edgeType":"calls","source":1693,"target":1117},{"edgeType":"calls","source":1250,"target":51},{"edgeType":"calls","source":4609,"target":567},{"edgeType":"calls","source":4649,"target":384},{"edgeType":"calls","source":622,"target":493},{"edgeType":"extends","source":704,"target":302},{"edgeType":"contains","source":3799,"target":3803},{"edgeType":"contains","source":3864,"target":3902},{"edgeType":"calls","source":4772,"target":1856},{"edgeType":"calls","source":4551,"target":249},{"edgeType":"calls","source":4649,"target":382},{"edgeType":"contains","source":4723,"target":4755},{"edgeType":"contains","source":4856,"target":4860},{"edgeType":"calls","source":4038,"target":298},{"edgeType":"contains","source":1849,"target":1888},{"edgeType":"calls","source":4125,"target":772},{"edgeType":"extends","source":1631,"target":103},{"edgeType":"calls","source":1250,"target":50},{"edgeType":"calls","source":4649,"target":383},{"edgeType":"calls","source":622,"target":492},{"edgeType":"imports","source":3534,"target":2174},{"edgeType":"calls","source":4644,"target":569},{"edgeType":"calls","source":2464,"target":498},{"edgeType":"calls","source":2570,"target":383},{"edgeType":"calls","source":3529,"target":3423},{"edgeType":"contains","source":4723,"target":4729},{"edgeType":"calls","source":4072,"target":331},{"edgeType":"calls","source":3958,"target":3865},{"edgeType":"contains","source":2730,"target":975},{"edgeType":"calls","source":2764,"target":712},{"edgeType":"calls","source":3529,"target":3422},{"edgeType":"calls","source":865,"target":386},{"edgeType":"calls","source":2570,"target":384},{"edgeType":"calls","source":4644,"target":570},{"edgeType":"calls","source":3280,"target":571},{"edgeType":"calls","source":4684,"target":387},{"edgeType":"contains","source":3534,"target":3535},{"edgeType":"calls","source":4773,"target":1856},{"edgeType":"calls","source":4644,"target":568},{"edgeType":"calls","source":4684,"target":385},{"edgeType":"calls","source":4599,"target":906},{"edgeType":"calls","source":2464,"target":499},{"edgeType":"calls","source":4314,"target":1285},{"edgeType":"contains","source":627,"target":630},{"edgeType":"contains","source":798,"target":1671},{"edgeType":"contains","source":395,"target":1479},{"edgeType":"calls","source":652,"target":646},{"edgeType":"calls","source":2779,"target":248},{"edgeType":"calls","source":2764,"target":713},{"edgeType":"calls","source":1489,"target":1124},{"edgeType":"calls","source":865,"target":385},{"edgeType":"calls","source":2570,"target":385},{"edgeType":"calls","source":3280,"target":572},{"edgeType":"contains","source":3269,"target":3293},{"edgeType":"calls","source":4684,"target":386},{"edgeType":"calls","source":1132,"target":564},{"edgeType":"calls","source":2947,"target":325},{"edgeType":"calls","source":2498,"target":499},{"edgeType":"contains","source":3467,"target":3495},{"edgeType":"calls","source":4684,"target":384},{"edgeType":"contains","source":2255,"target":899},{"edgeType":"calls","source":4644,"target":567},{"edgeType":"calls","source":1852,"target":445},{"edgeType":"calls","source":2297,"target":388},{"edgeType":"contains","source":4690,"target":4693},{"edgeType":"calls","source":1514,"target":353},{"edgeType":"contains","source":395,"target":1483},{"edgeType":"contains","source":2840,"target":2848},{"edgeType":"calls","source":1898,"target":1133},{"edgeType":"contains","source":4723,"target":4727},{"edgeType":"calls","source":1336,"target":585},{"edgeType":"calls","source":4237,"target":499},{"edgeType":"calls","source":1285,"target":1109},{"edgeType":"calls","source":1309,"target":365},{"edgeType":"calls","source":3489,"target":1489},{"edgeType":"calls","source":1231,"target":669},{"edgeType":"contains","source":3269,"target":3290},{"edgeType":"calls","source":3280,"target":569},{"edgeType":"contains","source":1750,"target":1756},{"edgeType":"calls","source":2964,"target":2966},{"edgeType":"calls","source":865,"target":388},{"edgeType":"calls","source":4644,"target":566},{"edgeType":"calls","source":2570,"target":382},{"edgeType":"calls","source":4684,"target":383},{"edgeType":"contains","source":4690,"target":4692},{"edgeType":"calls","source":2297,"target":389},{"edgeType":"contains","source":2840,"target":2849},{"edgeType":"contains","source":1148,"target":1393},{"edgeType":"calls","source":4807,"target":1856},{"edgeType":"calls","source":1498,"target":847},{"edgeType":"contains","source":3699,"target":3702},{"edgeType":"calls","source":3280,"target":570},{"edgeType":"calls","source":865,"target":387},{"edgeType":"imports","source":696,"target":285},{"edgeType":"contains","source":1636,"target":4234},{"edgeType":"calls","source":2964,"target":2967},{"edgeType":"contains","source":627,"target":635},{"edgeType":"calls","source":4586,"target":249},{"edgeType":"calls","source":1718,"target":365},{"edgeType":"contains","source":1881,"target":1929},{"edgeType":"calls","source":4684,"target":382},{"edgeType":"calls","source":4746,"target":574},{"edgeType":"contains","source":2840,"target":2854},{"edgeType":"calls","source":2297,"target":386},{"edgeType":"calls","source":1444,"target":402},{"edgeType":"calls","source":3572,"target":2085},{"edgeType":"contains","source":3797,"target":3842},{"edgeType":"contains","source":3098,"target":3312},{"edgeType":"calls","source":865,"target":382},{"edgeType":"calls","source":3729,"target":389},{"edgeType":"calls","source":758,"target":528},{"edgeType":"contains","source":3864,"target":3879},{"edgeType":"contains","source":3467,"target":3502},{"edgeType":"calls","source":1241,"target":353},{"edgeType":"calls","source":1234,"target":570},{"edgeType":"calls","source":3280,"target":567},{"edgeType":"calls","source":2498,"target":498},{"edgeType":"calls","source":1075,"target":1270},{"edgeType":"calls","source":4586,"target":248},{"edgeType":"calls","source":4762,"target":77},{"edgeType":"contains","source":2840,"target":2855},{"edgeType":"calls","source":2297,"target":387},{"edgeType":"calls","source":4038,"target":325},{"edgeType":"calls","source":2830,"target":777},{"edgeType":"imports","source":2259,"target":453},{"edgeType":"contains","source":1636,"target":4240},{"edgeType":"contains","source":1148,"target":1395},{"edgeType":"calls","source":3280,"target":568},{"edgeType":"calls","source":1234,"target":569},{"edgeType":"calls","source":1444,"target":401},{"edgeType":"contains","source":3501,"target":3504},{"edgeType":"contains","source":590,"target":727},{"edgeType":"calls","source":4665,"target":969},{"edgeType":"contains","source":4723,"target":4731},{"edgeType":"contains","source":1947,"target":1995},{"edgeType":"contains","source":2840,"target":2852},{"edgeType":"calls","source":2297,"target":384},{"edgeType":"calls","source":4314,"target":1280},{"edgeType":"calls","source":2178,"target":902},{"edgeType":"calls","source":4858,"target":4500},{"edgeType":"calls","source":3729,"target":387},{"edgeType":"contains","source":1881,"target":1927},{"edgeType":"calls","source":1234,"target":572},{"edgeType":"calls","source":865,"target":384},{"edgeType":"contains","source":3501,"target":3503},{"edgeType":"calls","source":3258,"target":191},{"edgeType":"contains","source":627,"target":636},{"edgeType":"contains","source":590,"target":726},{"edgeType":"contains","source":2840,"target":2853},{"edgeType":"calls","source":4107,"target":298},{"edgeType":"contains","source":4723,"target":4730},{"edgeType":"calls","source":2297,"target":385},{"edgeType":"calls","source":3729,"target":388},{"edgeType":"calls","source":3766,"target":298},{"edgeType":"calls","source":865,"target":383},{"edgeType":"calls","source":3280,"target":566},{"edgeType":"calls","source":1241,"target":354},{"edgeType":"calls","source":1234,"target":571},{"edgeType":"extends","source":3687,"target":1884},{"edgeType":"calls","source":1234,"target":566},{"edgeType":"contains","source":590,"target":729},{"edgeType":"calls","source":4788,"target":325},{"edgeType":"contains","source":4723,"target":4737},{"edgeType":"contains","source":3797,"target":3846},{"edgeType":"calls","source":2323,"target":633},{"edgeType":"calls","source":4596,"target":992},{"edgeType":"calls","source":2178,"target":900},{"edgeType":"calls","source":3729,"target":385},{"edgeType":"calls","source":2297,"target":382},{"edgeType":"contains","source":3123,"target":427},{"edgeType":"calls","source":1888,"target":375},{"edgeType":"contains","source":590,"target":728},{"edgeType":"calls","source":4243,"target":308},{"edgeType":"calls","source":2323,"target":634},{"edgeType":"calls","source":2297,"target":383},{"edgeType":"imports","source":3643,"target":886},{"edgeType":"calls","source":2178,"target":901},{"edgeType":"calls","source":3729,"target":386},{"edgeType":"calls","source":3022,"target":106},{"edgeType":"calls","source":978,"target":45},{"edgeType":"imports","source":4451,"target":2264},{"edgeType":"calls","source":4795,"target":106},{"edgeType":"contains","source":590,"target":731},{"edgeType":"calls","source":4098,"target":572},{"edgeType":"calls","source":2846,"target":1330},{"edgeType":"imports","source":3768,"target":183},{"edgeType":"calls","source":4491,"target":4245},{"edgeType":"calls","source":3729,"target":383},{"edgeType":"contains","source":3123,"target":425},{"edgeType":"contains","source":3797,"target":3844},{"edgeType":"calls","source":1234,"target":568},{"edgeType":"calls","source":1234,"target":567},{"edgeType":"contains","source":590,"target":730},{"edgeType":"calls","source":1517,"target":1307},{"edgeType":"calls","source":3729,"target":384},{"edgeType":"contains","source":850,"target":1126},{"edgeType":"contains","source":3123,"target":426},{"edgeType":"calls","source":1334,"target":638},{"edgeType":"calls","source":1770,"target":863},{"edgeType":"contains","source":3534,"target":3540},{"edgeType":"contains","source":1288,"target":1289},{"edgeType":"calls","source":4098,"target":570},{"edgeType":"calls","source":3416,"target":571},{"edgeType":"calls","source":1235,"target":531},{"edgeType":"contains","source":590,"target":733},{"edgeType":"contains","source":1750,"target":713},{"edgeType":"calls","source":4724,"target":191},{"edgeType":"contains","source":65,"target":95},{"edgeType":"calls","source":921,"target":752},{"edgeType":"imports","source":2000,"target":35},{"edgeType":"calls","source":2985,"target":191},{"edgeType":"calls","source":4489,"target":77},{"edgeType":"calls","source":3580,"target":772},{"edgeType":"contains","source":4723,"target":4741},{"edgeType":"calls","source":4098,"target":571},{"edgeType":"calls","source":3416,"target":572},{"edgeType":"calls","source":1235,"target":530},{"edgeType":"calls","source":1234,"target":561},{"edgeType":"contains","source":590,"target":732},{"edgeType":"imports","source":3768,"target":186},{"edgeType":"contains","source":1750,"target":714},{"edgeType":"contains","source":65,"target":94},{"edgeType":"contains","source":3797,"target":3849},{"edgeType":"calls","source":4772,"target":1873},{"edgeType":"contains","source":2730,"target":988},{"edgeType":"calls","source":3729,"target":382},{"edgeType":"calls","source":4098,"target":568},{"edgeType":"calls","source":1279,"target":1283},{"edgeType":"calls","source":4280,"target":211},{"edgeType":"calls","source":1180,"target":1181},{"edgeType":"calls","source":3416,"target":569},{"edgeType":"calls","source":4701,"target":902},{"edgeType":"imports","source":3571,"target":1009},{"edgeType":"calls","source":2433,"target":388},{"edgeType":"calls","source":3996,"target":558},{"edgeType":"calls","source":1445,"target":365},{"edgeType":"calls","source":4098,"target":567},{"edgeType":"calls","source":3868,"target":298},{"edgeType":"calls","source":3416,"target":570},{"edgeType":"contains","source":1123,"target":1124},{"edgeType":"calls","source":4848,"target":572},{"edgeType":"calls","source":4098,"target":569},{"edgeType":"calls","source":4280,"target":212},{"edgeType":"contains","source":1750,"target":712},{"edgeType":"calls","source":4701,"target":901},{"edgeType":"calls","source":4754,"target":1372},{"edgeType":"contains","source":65,"target":96},{"edgeType":"calls","source":4869,"target":2035},{"edgeType":"calls","source":921,"target":753},{"edgeType":"calls","source":294,"target":106},{"edgeType":"calls","source":2433,"target":389},{"edgeType":"contains","source":590,"target":734},{"edgeType":"calls","source":3548,"target":1763},{"edgeType":"calls","source":3554,"target":2634},{"edgeType":"calls","source":1845,"target":1705},{"edgeType":"calls","source":3889,"target":705},{"edgeType":"calls","source":563,"target":185},{"edgeType":"calls","source":591,"target":374},{"edgeType":"calls","source":1307,"target":376},{"edgeType":"contains","source":1713,"target":1831},{"edgeType":"calls","source":1077,"target":106},{"edgeType":"contains","source":2077,"target":2175},{"edgeType":"contains","source":65,"target":67},{"edgeType":"imports","source":1114,"target":1119},{"edgeType":"calls","source":4649,"target":365},{"edgeType":"calls","source":4635,"target":1856},{"edgeType":"calls","source":2494,"target":2690},{"edgeType":"calls","source":1645,"target":468},{"edgeType":"calls","source":3640,"target":2046},{"edgeType":"calls","source":4143,"target":194},{"edgeType":"calls","source":1443,"target":1444},{"edgeType":"contains","source":3038,"target":3039},{"edgeType":"calls","source":755,"target":574},{"edgeType":"contains","source":3071,"target":3073},{"edgeType":"calls","source":2965,"target":774},{"edgeType":"calls","source":2876,"target":2476},{"edgeType":"calls","source":4785,"target":376},{"edgeType":"calls","source":4709,"target":1675},{"edgeType":"contains","source":3269,"target":3277},{"edgeType":"contains","source":1713,"target":1832},{"edgeType":"contains","source":65,"target":66},{"edgeType":"contains","source":2806,"target":2831},{"edgeType":"imports","source":1114,"target":1120},{"edgeType":"calls","source":1645,"target":467},{"edgeType":"calls","source":4373,"target":464},{"edgeType":"calls","source":4027,"target":1677},{"edgeType":"calls","source":2701,"target":499},{"edgeType":"calls","source":3452,"target":473},{"edgeType":"contains","source":1713,"target":1829},{"edgeType":"calls","source":3121,"target":3334},{"edgeType":"calls","source":2475,"target":106},{"edgeType":"calls","source":1657,"target":98},{"edgeType":"calls","source":1645,"target":470},{"edgeType":"imports","source":1114,"target":1117},{"edgeType":"imports","source":3162,"target":3166},{"edgeType":"calls","source":1517,"target":1267},{"edgeType":"contains","source":3098,"target":1175},{"edgeType":"calls","source":2294,"target":1489},{"edgeType":"calls","source":4368,"target":1675},{"edgeType":"contains","source":798,"target":1657},{"edgeType":"calls","source":3452,"target":474},{"edgeType":"contains","source":320,"target":619},{"edgeType":"contains","source":1713,"target":1830},{"edgeType":"calls","source":3121,"target":3336},{"edgeType":"calls","source":1701,"target":847},{"edgeType":"contains","source":4161,"target":4162},{"edgeType":"calls","source":1645,"target":469},{"edgeType":"calls","source":4669,"target":1856},{"edgeType":"calls","source":1677,"target":534},{"edgeType":"imports","source":1114,"target":1118},{"edgeType":"calls","source":2252,"target":1735},{"edgeType":"contains","source":2806,"target":2829},{"edgeType":"imports","source":4103,"target":1485},{"edgeType":"contains","source":3005,"target":3008},{"edgeType":"calls","source":1345,"target":1308},{"edgeType":"imports","source":1114,"target":1115},{"edgeType":"calls","source":4614,"target":389},{"edgeType":"calls","source":4574,"target":572},{"edgeType":"calls","source":1077,"target":102},{"edgeType":"contains","source":3963,"target":3965},{"edgeType":"calls","source":4714,"target":460},{"edgeType":"calls","source":1812,"target":572},{"edgeType":"calls","source":4789,"target":249},{"edgeType":"contains","source":4524,"target":4543},{"edgeType":"contains","source":3005,"target":3009},{"edgeType":"imports","source":2255,"target":626},{"edgeType":"calls","source":2749,"target":1124},{"edgeType":"calls","source":3362,"target":2205},{"edgeType":"calls","source":3452,"target":472},{"edgeType":"calls","source":3237,"target":1852},{"edgeType":"calls","source":4680,"target":456},{"edgeType":"imports","source":3162,"target":3163},{"edgeType":"calls","source":4614,"target":388},{"edgeType":"calls","source":1077,"target":101},{"edgeType":"calls","source":1812,"target":571},{"edgeType":"calls","source":4789,"target":248},{"edgeType":"contains","source":3963,"target":3964},{"edgeType":"calls","source":2701,"target":498},{"edgeType":"calls","source":4836,"target":905},{"edgeType":"calls","source":4574,"target":571},{"edgeType":"calls","source":4408,"target":1489},{"edgeType":"contains","source":3005,"target":3006},{"edgeType":"calls","source":2877,"target":324},{"edgeType":"imports","source":4209,"target":1372},{"edgeType":"calls","source":1645,"target":466},{"edgeType":"calls","source":3452,"target":469},{"edgeType":"calls","source":2494,"target":2684},{"edgeType":"imports","source":3228,"target":3230},{"edgeType":"calls","source":452,"target":453},{"edgeType":"contains","source":4194,"target":4201},{"edgeType":"calls","source":3846,"target":1996},{"edgeType":"calls","source":2774,"target":346},{"edgeType":"contains","source":798,"target":1661},{"edgeType":"calls","source":2783,"target":1124},{"edgeType":"calls","source":4614,"target":387},{"edgeType":"calls","source":4574,"target":570},{"edgeType":"calls","source":772,"target":45},{"edgeType":"contains","source":2972,"target":2973},{"edgeType":"calls","source":665,"target":191},{"edgeType":"calls","source":2907,"target":452},{"edgeType":"contains","source":3005,"target":3007},{"edgeType":"calls","source":1645,"target":465},{"edgeType":"calls","source":3452,"target":470},{"edgeType":"calls","source":4660,"target":4245},{"edgeType":"calls","source":4069,"target":369},{"edgeType":"contains","source":4194,"target":4200},{"edgeType":"contains","source":798,"target":1660},{"edgeType":"calls","source":4614,"target":386},{"edgeType":"calls","source":4608,"target":572},{"edgeType":"calls","source":4574,"target":569},{"edgeType":"contains","source":4524,"target":4540},{"edgeType":"contains","source":3005,"target":3012},{"edgeType":"contains","source":3098,"target":3300},{"edgeType":"calls","source":1812,"target":568},{"edgeType":"calls","source":3452,"target":467},{"edgeType":"calls","source":1674,"target":1675},{"edgeType":"calls","source":1720,"target":249},{"edgeType":"calls","source":1653,"target":212},{"edgeType":"contains","source":2001,"target":311},{"edgeType":"contains","source":1849,"target":1852},{"edgeType":"calls","source":1074,"target":191},{"edgeType":"calls","source":1077,"target":98},{"edgeType":"calls","source":4836,"target":902},{"edgeType":"calls","source":4849,"target":499},{"edgeType":"contains","source":3864,"target":3867},{"edgeType":"calls","source":4436,"target":1675},{"edgeType":"calls","source":419,"target":413},{"edgeType":"calls","source":4614,"target":385},{"edgeType":"calls","source":4608,"target":571},{"edgeType":"calls","source":4529,"target":906},{"edgeType":"calls","source":4574,"target":568},{"edgeType":"calls","source":3870,"target":194},{"edgeType":"calls","source":1812,"target":567},{"edgeType":"contains","source":3467,"target":3488},{"edgeType":"extends","source":2204,"target":340},{"edgeType":"calls","source":3611,"target":824},{"edgeType":"calls","source":1653,"target":211},{"edgeType":"calls","source":1657,"target":87},{"edgeType":"calls","source":3452,"target":468},{"edgeType":"calls","source":1720,"target":248},{"edgeType":"contains","source":2631,"target":865},{"edgeType":"contains","source":3963,"target":3968},{"edgeType":"calls","source":1989,"target":365},{"edgeType":"calls","source":1278,"target":1265},{"edgeType":"calls","source":4574,"target":567},{"edgeType":"calls","source":2394,"target":498},{"edgeType":"contains","source":3864,"target":3866},{"edgeType":"calls","source":4836,"target":901},{"edgeType":"contains","source":396,"target":2497},{"edgeType":"calls","source":665,"target":185},{"edgeType":"calls","source":4614,"target":384},{"edgeType":"calls","source":4608,"target":570},{"edgeType":"contains","source":850,"target":1111},{"edgeType":"calls","source":4453,"target":88},{"edgeType":"contains","source":3005,"target":3010},{"edgeType":"calls","source":4353,"target":4245},{"edgeType":"contains","source":3467,"target":3487},{"edgeType":"calls","source":3870,"target":191},{"edgeType":"calls","source":4782,"target":460},{"edgeType":"calls","source":3353,"target":2476},{"edgeType":"contains","source":3963,"target":3967},{"edgeType":"calls","source":3452,"target":464},{"edgeType":"calls","source":1812,"target":570},{"edgeType":"calls","source":1077,"target":100},{"edgeType":"calls","source":4230,"target":658},{"edgeType":"calls","source":4614,"target":383},{"edgeType":"calls","source":4608,"target":569},{"edgeType":"calls","source":624,"target":402},{"edgeType":"calls","source":4574,"target":566},{"edgeType":"calls","source":4836,"target":900},{"edgeType":"calls","source":4811,"target":1675},{"edgeType":"calls","source":4746,"target":519},{"edgeType":"contains","source":850,"target":1110},{"edgeType":"calls","source":2297,"target":331},{"edgeType":"calls","source":2316,"target":1856},{"edgeType":"contains","source":2840,"target":2841},{"edgeType":"calls","source":2219,"target":1692},{"edgeType":"calls","source":83,"target":259},{"edgeType":"contains","source":2806,"target":2838},{"edgeType":"calls","source":1812,"target":569},{"edgeType":"calls","source":3452,"target":466},{"edgeType":"calls","source":3452,"target":465},{"edgeType":"contains","source":1881,"target":1916},{"edgeType":"contains","source":1816,"target":1817},{"edgeType":"calls","source":1077,"target":99},{"edgeType":"calls","source":4614,"target":382},{"edgeType":"calls","source":4608,"target":568},{"edgeType":"calls","source":419,"target":414},{"edgeType":"calls","source":624,"target":401},{"edgeType":"calls","source":4748,"target":456},{"edgeType":"calls","source":4586,"target":191},{"edgeType":"contains","source":660,"target":661},{"edgeType":"contains","source":4690,"target":4691},{"edgeType":"contains","source":1247,"target":1491},{"edgeType":"calls","source":1746,"target":496},{"edgeType":"contains","source":3005,"target":3016},{"edgeType":"calls","source":4608,"target":567},{"edgeType":"imports","source":1160,"target":754},{"edgeType":"calls","source":2851,"target":1124},{"edgeType":"calls","source":1746,"target":495},{"edgeType":"calls","source":3052,"target":179},{"edgeType":"contains","source":850,"target":1112},{"edgeType":"calls","source":3032,"target":1856},{"edgeType":"imports","source":1918,"target":511},{"edgeType":"contains","source":3467,"target":3492},{"edgeType":"calls","source":4312,"target":1285},{"edgeType":"contains","source":4723,"target":4724},{"edgeType":"contains","source":2972,"target":2983},{"edgeType":"calls","source":1341,"target":365},{"edgeType":"calls","source":1347,"target":179},{"edgeType":"calls","source":3121,"target":3325},{"edgeType":"calls","source":4608,"target":566},{"edgeType":"contains","source":3699,"target":3700},{"edgeType":"calls","source":725,"target":435},{"edgeType":"contains","source":1750,"target":1755},{"edgeType":"calls","source":4702,"target":1880},{"edgeType":"contains","source":1881,"target":1922},{"edgeType":"contains","source":2204,"target":2476},{"edgeType":"calls","source":1812,"target":566},{"edgeType":"extends","source":1688,"target":482},{"edgeType":"contains","source":3005,"target":3014},{"edgeType":"contains","source":798,"target":1670},{"edgeType":"contains","source":3071,"target":3082},{"edgeType":"calls","source":4028,"target":574},{"edgeType":"calls","source":1372,"target":464},{"edgeType":"imports","source":1114,"target":1121},{"edgeType":"contains","source":798,"target":1669},{"edgeType":"contains","source":627,"target":628},{"edgeType":"contains","source":3071,"target":3083},{"edgeType":"contains","source":3467,"target":3490},{"edgeType":"contains","source":1247,"target":1490},{"edgeType":"extends","source":4161,"target":4153},{"edgeType":"contains","source":3098,"target":3303},{"edgeType":"contains","source":3005,"target":3015},{"edgeType":"contains","source":3963,"target":3970},{"edgeType":"calls","source":497,"target":106},{"edgeType":"calls","source":3458,"target":3446},{"edgeType":"calls","source":1282,"target":82},{"edgeType":"calls","source":419,"target":410},{"edgeType":"imports","source":1114,"target":1122},{"edgeType":"contains","source":3864,"target":3868},{"edgeType":"calls","source":3869,"target":249},{"edgeType":"calls","source":3798,"target":336},{"edgeType":"contains","source":4060,"target":4108},{"edgeType":"contains","source":2264,"target":2703},{"edgeType":"calls","source":4551,"target":248},{"edgeType":"contains","source":3123,"target":386},{"edgeType":"contains","source":689,"target":790},{"edgeType":"contains","source":3099,"target":3244},{"edgeType":"contains","source":6,"target":3992},{"edgeType":"calls","source":325,"target":179},{"edgeType":"calls","source":1657,"target":1169},{"edgeType":"calls","source":1660,"target":1076},{"edgeType":"contains","source":2264,"target":2704},{"edgeType":"calls","source":3624,"target":446},{"edgeType":"calls","source":3939,"target":194},{"edgeType":"calls","source":4093,"target":705},{"edgeType":"contains","source":3099,"target":3245},{"edgeType":"calls","source":1372,"target":490},{"edgeType":"calls","source":4806,"target":1856},{"edgeType":"contains","source":3123,"target":387},{"edgeType":"calls","source":3624,"target":445},{"edgeType":"contains","source":1649,"target":1686},{"edgeType":"contains","source":3599,"target":3600},{"edgeType":"contains","source":3123,"target":384},{"edgeType":"contains","source":4688,"target":4722},{"edgeType":"contains","source":3002,"target":3078},{"edgeType":"contains","source":3099,"target":3242},{"edgeType":"extends","source":4865,"target":4499},{"edgeType":"calls","source":3442,"target":1856},{"edgeType":"calls","source":2783,"target":88},{"edgeType":"calls","source":2963,"target":2964},{"edgeType":"calls","source":1250,"target":47},{"edgeType":"contains","source":28,"target":2255},{"edgeType":"calls","source":3869,"target":248},{"edgeType":"contains","source":2264,"target":2702},{"edgeType":"calls","source":2221,"target":1655},{"edgeType":"calls","source":3731,"target":298},{"edgeType":"contains","source":3123,"target":385},{"edgeType":"contains","source":4688,"target":4721},{"edgeType":"contains","source":696,"target":574},{"edgeType":"calls","source":4280,"target":191},{"edgeType":"contains","source":3099,"target":3243},{"edgeType":"calls","source":4785,"target":389},{"edgeType":"contains","source":2211,"target":2236},{"edgeType":"contains","source":2264,"target":2707},{"edgeType":"calls","source":4320,"target":1063},{"edgeType":"contains","source":1713,"target":1819},{"edgeType":"calls","source":2829,"target":774},{"edgeType":"contains","source":3099,"target":3248},{"edgeType":"calls","source":1282,"target":106},{"edgeType":"calls","source":1372,"target":487},{"edgeType":"calls","source":459,"target":249},{"edgeType":"calls","source":2531,"target":499},{"edgeType":"contains","source":44,"target":704},{"edgeType":"calls","source":4752,"target":354},{"edgeType":"calls","source":4785,"target":388},{"edgeType":"contains","source":4060,"target":4111},{"edgeType":"calls","source":4106,"target":298},{"edgeType":"contains","source":2211,"target":2237},{"edgeType":"calls","source":4044,"target":106},{"edgeType":"contains","source":2264,"target":2708},{"edgeType":"contains","source":4524,"target":4526},{"edgeType":"imports","source":1749,"target":1497},{"edgeType":"contains","source":3120,"target":484},{"edgeType":"contains","source":3797,"target":3808},{"edgeType":"contains","source":1713,"target":1820},{"edgeType":"contains","source":3099,"target":3249},{"edgeType":"contains","source":1485,"target":1489},{"edgeType":"calls","source":1297,"target":697},{"edgeType":"calls","source":3271,"target":1871},{"edgeType":"calls","source":1372,"target":486},{"edgeType":"contains","source":3467,"target":3468},{"edgeType":"calls","source":3309,"target":690},{"edgeType":"calls","source":4752,"target":353},{"edgeType":"calls","source":4785,"target":387},{"edgeType":"extends","source":3115,"target":2730},{"edgeType":"contains","source":4060,"target":4110},{"edgeType":"contains","source":2264,"target":2705},{"edgeType":"calls","source":4595,"target":992},{"edgeType":"calls","source":2339,"target":106},{"edgeType":"calls","source":4587,"target":183},{"edgeType":"calls","source":4438,"target":574},{"edgeType":"contains","source":4524,"target":4525},{"edgeType":"contains","source":3099,"target":3246},{"edgeType":"contains","source":3123,"target":388},{"edgeType":"calls","source":1372,"target":489},{"edgeType":"contains","source":1649,"target":1687},{"edgeType":"calls","source":4698,"target":969},{"edgeType":"contains","source":689,"target":795},{"edgeType":"contains","source":2806,"target":2817},{"edgeType":"calls","source":4785,"target":386},{"edgeType":"calls","source":1674,"target":1697},{"edgeType":"contains","source":4060,"target":4109},{"edgeType":"contains","source":2211,"target":2235},{"edgeType":"contains","source":2264,"target":2706},{"edgeType":"contains","source":395,"target":396},{"edgeType":"extends","source":3699,"target":3652},{"edgeType":"calls","source":625,"target":391},{"edgeType":"contains","source":3123,"target":389},{"edgeType":"contains","source":3099,"target":3247},{"edgeType":"calls","source":1372,"target":488},{"edgeType":"calls","source":4785,"target":385},{"edgeType":"calls","source":4737,"target":1873},{"edgeType":"calls","source":4794,"target":106},{"edgeType":"calls","source":1128,"target":648},{"edgeType":"calls","source":3993,"target":625},{"edgeType":"contains","source":16,"target":520},{"edgeType":"contains","source":6,"target":2944},{"edgeType":"calls","source":4607,"target":1675},{"edgeType":"calls","source":4613,"target":1489},{"edgeType":"calls","source":2714,"target":106},{"edgeType":"calls","source":4438,"target":572},{"edgeType":"calls","source":4582,"target":336},{"edgeType":"contains","source":1518,"target":1526},{"edgeType":"contains","source":3002,"target":3088},{"edgeType":"calls","source":975,"target":106},{"edgeType":"calls","source":1444,"target":365},{"edgeType":"calls","source":3817,"target":1852},{"edgeType":"calls","source":4785,"target":384},{"edgeType":"calls","source":3209,"target":1675},{"edgeType":"calls","source":1109,"target":179},{"edgeType":"contains","source":4524,"target":4530},{"edgeType":"calls","source":2851,"target":88},{"edgeType":"calls","source":4679,"target":499},{"edgeType":"extends","source":1224,"target":1104},{"edgeType":"contains","source":1518,"target":1527},{"edgeType":"calls","source":4438,"target":571},{"edgeType":"contains","source":1485,"target":1493},{"edgeType":"calls","source":293,"target":106},{"edgeType":"contains","source":1713,"target":1824},{"edgeType":"contains","source":3099,"target":3253},{"edgeType":"calls","source":3580,"target":744},{"edgeType":"calls","source":4785,"target":383},{"edgeType":"contains","source":4060,"target":4114},{"edgeType":"calls","source":1769,"target":863},{"edgeType":"calls","source":1917,"target":503},{"edgeType":"contains","source":2806,"target":2820},{"edgeType":"calls","source":2477,"target":1109},{"edgeType":"contains","source":2264,"target":2709},{"edgeType":"calls","source":459,"target":248},{"edgeType":"calls","source":826,"target":499},{"edgeType":"contains","source":3002,"target":3086},{"edgeType":"calls","source":4438,"target":570},{"edgeType":"contains","source":3099,"target":3250},{"edgeType":"contains","source":1713,"target":1821},{"edgeType":"calls","source":1372,"target":485},{"edgeType":"contains","source":3432,"target":3499},{"edgeType":"contains","source":4060,"target":4113},{"edgeType":"calls","source":1917,"target":502},{"edgeType":"contains","source":4524,"target":4528},{"edgeType":"calls","source":4785,"target":382},{"edgeType":"calls","source":4438,"target":569},{"edgeType":"contains","source":3002,"target":3087},{"edgeType":"imports","source":3534,"target":2186},{"edgeType":"contains","source":3797,"target":3810},{"edgeType":"contains","source":3099,"target":3251},{"edgeType":"contains","source":3432,"target":3498},{"edgeType":"contains","source":1518,"target":1525},{"edgeType":"calls","source":1976,"target":1839},{"edgeType":"contains","source":1221,"target":1223},{"edgeType":"calls","source":1279,"target":191},{"edgeType":"calls","source":3272,"target":774},{"edgeType":"calls","source":3207,"target":675},{"edgeType":"calls","source":1164,"target":585},{"edgeType":"contains","source":1713,"target":1827},{"edgeType":"calls","source":2775,"target":325},{"edgeType":"calls","source":4438,"target":568},{"edgeType":"contains","source":4194,"target":4195},{"edgeType":"calls","source":1657,"target":100},{"edgeType":"calls","source":1645,"target":472},{"edgeType":"calls","source":1932,"target":1088},{"edgeType":"calls","source":4031,"target":499},{"edgeType":"extends","source":1881,"target":1884},{"edgeType":"contains","source":3002,"target":3092},{"edgeType":"contains","source":1221,"target":1222},{"edgeType":"calls","source":1301,"target":565},{"edgeType":"calls","source":4075,"target":194},{"edgeType":"contains","source":1713,"target":1828},{"edgeType":"calls","source":4757,"target":191},{"edgeType":"calls","source":1657,"target":99},{"edgeType":"calls","source":4438,"target":567},{"edgeType":"calls","source":4312,"target":1302},{"edgeType":"calls","source":2225,"target":464},{"edgeType":"calls","source":3734,"target":194},{"edgeType":"calls","source":1913,"target":1676},{"edgeType":"contains","source":3269,"target":3270},{"edgeType":"calls","source":3494,"target":3403},{"edgeType":"contains","source":1713,"target":1825},{"edgeType":"calls","source":3323,"target":248},{"edgeType":"calls","source":3257,"target":180},{"edgeType":"calls","source":4732,"target":965},{"edgeType":"calls","source":4721,"target":249},{"edgeType":"calls","source":904,"target":191},{"edgeType":"calls","source":1657,"target":102},{"edgeType":"calls","source":1645,"target":474},{"edgeType":"calls","source":987,"target":789},{"edgeType":"calls","source":4438,"target":566},{"edgeType":"calls","source":4260,"target":1856},{"edgeType":"contains","source":3002,"target":3090},{"edgeType":"contains","source":3236,"target":3237},{"edgeType":"calls","source":2771,"target":448},{"edgeType":"calls","source":1999,"target":1127},{"edgeType":"calls","source":1385,"target":77},{"edgeType":"calls","source":1164,"target":586},{"edgeType":"calls","source":3323,"target":249},{"edgeType":"calls","source":3277,"target":1675},{"edgeType":"calls","source":4721,"target":248},{"edgeType":"contains","source":1713,"target":1826},{"edgeType":"calls","source":3121,"target":3340},{"edgeType":"contains","source":16,"target":2639},{"edgeType":"calls","source":2942,"target":1489},{"edgeType":"contains","source":4146,"target":2508},{"edgeType":"calls","source":1645,"target":473},{"edgeType":"calls","source":1657,"target":101},{"edgeType":"contains","source":3,"target":3043},{"edgeType":"calls","source":3998,"target":464},{"edgeType":"calls","source":4340,"target":1489},{"edgeType":"calls","source":3580,"target":738},{"edgeType":"contains","source":3002,"target":3091},{"edgeType":"calls","source":1913,"target":1678},{"edgeType":"contains","source":395,"target":2488},{"edgeType":"calls","source":451,"target":585},{"edgeType":"calls","source":4726,"target":191},{"edgeType":"calls","source":3801,"target":325},{"edgeType":"contains","source":2211,"target":2216},{"edgeType":"calls","source":2322,"target":722},{"edgeType":"calls","source":2403,"target":325},{"edgeType":"contains","source":689,"target":773},{"edgeType":"calls","source":4078,"target":194},{"edgeType":"calls","source":1964,"target":191},{"edgeType":"calls","source":399,"target":82},{"edgeType":"calls","source":4385,"target":191},{"edgeType":"calls","source":2282,"target":906},{"edgeType":"calls","source":2322,"target":723},{"edgeType":"contains","source":2211,"target":2217},{"edgeType":"calls","source":4000,"target":499},{"edgeType":"contains","source":4688,"target":4706},{"edgeType":"contains","source":1148,"target":1345},{"edgeType":"contains","source":320,"target":587},{"edgeType":"calls","source":3452,"target":572},{"edgeType":"calls","source":3309,"target":777},{"edgeType":"calls","source":2395,"target":571},{"edgeType":"contains","source":2204,"target":2431},{"edgeType":"calls","source":978,"target":106},{"edgeType":"contains","source":2211,"target":2214},{"edgeType":"calls","source":2322,"target":720},{"edgeType":"imports","source":2488,"target":574},{"edgeType":"contains","source":689,"target":775},{"edgeType":"calls","source":2035,"target":106},{"edgeType":"calls","source":451,"target":586},{"edgeType":"calls","source":2395,"target":572},{"edgeType":"contains","source":31,"target":32},{"edgeType":"calls","source":4456,"target":102},{"edgeType":"contains","source":2211,"target":2215},{"edgeType":"imports","source":4045,"target":3051},{"edgeType":"contains","source":3002,"target":3062},{"edgeType":"calls","source":4315,"target":1302},{"edgeType":"calls","source":3737,"target":194},{"edgeType":"calls","source":4094,"target":754},{"edgeType":"imports","source":2255,"target":397},{"edgeType":"calls","source":1372,"target":570},{"edgeType":"calls","source":3452,"target":570},{"edgeType":"calls","source":824,"target":645},{"edgeType":"imports","source":4376,"target":190},{"edgeType":"calls","source":3352,"target":499},{"edgeType":"calls","source":1344,"target":381},{"edgeType":"contains","source":689,"target":777},{"edgeType":"calls","source":2435,"target":1443},{"edgeType":"calls","source":2429,"target":572},{"edgeType":"calls","source":2395,"target":569},{"edgeType":"calls","source":422,"target":423},{"edgeType":"contains","source":1947,"target":1948},{"edgeType":"contains","source":3995,"target":3997},{"edgeType":"calls","source":1812,"target":1728},{"edgeType":"calls","source":1657,"target":191},{"edgeType":"calls","source":4549,"target":389},{"edgeType":"calls","source":4678,"target":1675},{"edgeType":"calls","source":2239,"target":2234},{"edgeType":"calls","source":564,"target":249},{"edgeType":"calls","source":2322,"target":718},{"edgeType":"calls","source":4456,"target":101},{"edgeType":"contains","source":1643,"target":2916},{"edgeType":"contains","source":3099,"target":3233},{"edgeType":"calls","source":3452,"target":571},{"edgeType":"calls","source":3613,"target":865},{"edgeType":"calls","source":2945,"target":1489},{"edgeType":"calls","source":975,"target":191},{"edgeType":"calls","source":1372,"target":569},{"edgeType":"contains","source":31,"target":34},{"edgeType":"calls","source":2395,"target":570},{"edgeType":"calls","source":4549,"target":388},{"edgeType":"calls","source":564,"target":248},{"edgeType":"imports","source":3710,"target":754},{"edgeType":"calls","source":2322,"target":719},{"edgeType":"calls","source":4456,"target":100},{"edgeType":"contains","source":2211,"target":2221},{"edgeType":"calls","source":4112,"target":194},{"edgeType":"calls","source":1372,"target":572},{"edgeType":"calls","source":2980,"target":401},{"edgeType":"calls","source":4884,"target":572},{"edgeType":"contains","source":1148,"target":1349},{"edgeType":"calls","source":1182,"target":1177},{"edgeType":"calls","source":1205,"target":464},{"edgeType":"calls","source":2973,"target":1675},{"edgeType":"calls","source":3452,"target":568},{"edgeType":"imports","source":3811,"target":1852},{"edgeType":"calls","source":330,"target":106},{"edgeType":"calls","source":4549,"target":387},{"edgeType":"calls","source":3869,"target":325},{"edgeType":"contains","source":2204,"target":2435},{"edgeType":"contains","source":2211,"target":2218},{"edgeType":"calls","source":4794,"target":191},{"edgeType":"calls","source":2322,"target":716},{"edgeType":"calls","source":4456,"target":99},{"edgeType":"calls","source":2670,"target":498},{"edgeType":"contains","source":2951,"target":1475},{"edgeType":"calls","source":2429,"target":570},{"edgeType":"calls","source":2395,"target":567},{"edgeType":"contains","source":4688,"target":4709},{"edgeType":"calls","source":707,"target":45},{"edgeType":"calls","source":1372,"target":571},{"edgeType":"calls","source":4884,"target":571},{"edgeType":"contains","source":1148,"target":1348},{"edgeType":"calls","source":2980,"target":402},{"edgeType":"calls","source":3452,"target":569},{"edgeType":"contains","source":681,"target":1026},{"edgeType":"contains","source":689,"target":778},{"edgeType":"calls","source":2429,"target":571},{"edgeType":"extends","source":1217,"target":1104},{"edgeType":"calls","source":4713,"target":587},{"edgeType":"calls","source":4788,"target":376},{"edgeType":"calls","source":1914,"target":1738},{"edgeType":"contains","source":16,"target":3672},{"edgeType":"calls","source":2322,"target":717},{"edgeType":"calls","source":4456,"target":98},{"edgeType":"contains","source":2211,"target":2219},{"edgeType":"calls","source":2257,"target":1675},{"edgeType":"calls","source":1998,"target":191},{"edgeType":"calls","source":4030,"target":1677},{"edgeType":"calls","source":4549,"target":386},{"edgeType":"calls","source":4543,"target":572},{"edgeType":"calls","source":2395,"target":568},{"edgeType":"calls","source":4315,"target":1298},{"edgeType":"contains","source":4688,"target":4708},{"edgeType":"contains","source":1643,"target":2919},{"edgeType":"contains","source":857,"target":859},{"edgeType":"calls","source":4884,"target":570},{"edgeType":"calls","source":3452,"target":566},{"edgeType":"imports","source":2276,"target":1871},{"edgeType":"calls","source":1372,"target":566},{"edgeType":"contains","source":1247,"target":1454},{"edgeType":"calls","source":1853,"target":453},{"edgeType":"calls","source":4549,"target":385},{"edgeType":"calls","source":4501,"target":1873},{"edgeType":"calls","source":4543,"target":571},{"edgeType":"calls","source":4371,"target":1675},{"edgeType":"calls","source":2322,"target":714},{"edgeType":"calls","source":2429,"target":568},{"edgeType":"calls","source":2291,"target":1675},{"edgeType":"calls","source":758,"target":572},{"edgeType":"contains","source":857,"target":858},{"edgeType":"contains","source":1643,"target":2920},{"edgeType":"contains","source":1649,"target":1677},{"edgeType":"calls","source":3392,"target":1370},{"edgeType":"calls","source":1344,"target":376},{"edgeType":"calls","source":3452,"target":567},{"edgeType":"contains","source":1148,"target":1350},{"edgeType":"imports","source":3643,"target":704},{"edgeType":"contains","source":4688,"target":4714},{"edgeType":"contains","source":689,"target":780},{"edgeType":"calls","source":2633,"target":587},{"edgeType":"contains","source":6,"target":813},{"edgeType":"contains","source":31,"target":38},{"edgeType":"calls","source":4031,"target":587},{"edgeType":"calls","source":4884,"target":569},{"edgeType":"calls","source":4549,"target":384},{"edgeType":"calls","source":4543,"target":570},{"edgeType":"calls","source":591,"target":464},{"edgeType":"calls","source":2429,"target":569},{"edgeType":"imports","source":3420,"target":1288},{"edgeType":"contains","source":2280,"target":3257},{"edgeType":"calls","source":2395,"target":566},{"edgeType":"calls","source":2322,"target":715},{"edgeType":"contains","source":2211,"target":2225},{"edgeType":"contains","source":857,"target":861},{"edgeType":"contains","source":1643,"target":2917},{"edgeType":"contains","source":3099,"target":3234},{"edgeType":"contains","source":721,"target":849},{"edgeType":"calls","source":3839,"target":194},{"edgeType":"calls","source":1372,"target":568},{"edgeType":"calls","source":2649,"target":88},{"edgeType":"contains","source":4060,"target":4098},{"edgeType":"calls","source":4629,"target":4245},{"edgeType":"calls","source":3308,"target":1856},{"edgeType":"contains","source":6,"target":816},{"edgeType":"calls","source":2429,"target":566},{"edgeType":"calls","source":4549,"target":383},{"edgeType":"calls","source":4543,"target":569},{"edgeType":"calls","source":4884,"target":568},{"edgeType":"extends","source":1520,"target":1227},{"edgeType":"calls","source":2322,"target":712},{"edgeType":"calls","source":4617,"target":389},{"edgeType":"contains","source":1643,"target":2918},{"edgeType":"contains","source":857,"target":860},{"edgeType":"contains","source":1749,"target":2803},{"edgeType":"calls","source":1241,"target":400},{"edgeType":"calls","source":1372,"target":567},{"edgeType":"contains","source":2000,"target":308},{"edgeType":"contains","source":1947,"target":1951},{"edgeType":"calls","source":4783,"target":527},{"edgeType":"contains","source":4209,"target":4763},{"edgeType":"calls","source":2752,"target":1124},{"edgeType":"calls","source":4884,"target":567},{"edgeType":"calls","source":2322,"target":713},{"edgeType":"contains","source":2211,"target":2223},{"edgeType":"calls","source":4617,"target":388},{"edgeType":"calls","source":2429,"target":567},{"edgeType":"calls","source":4549,"target":382},{"edgeType":"extends","source":3696,"target":3535},{"edgeType":"calls","source":4543,"target":568},{"edgeType":"calls","source":864,"target":454},{"edgeType":"calls","source":3041,"target":1675},{"edgeType":"calls","source":3849,"target":1996},{"edgeType":"contains","source":2806,"target":2810},{"edgeType":"contains","source":3099,"target":3240},{"edgeType":"contains","source":3123,"target":382},{"edgeType":"imports","source":4045,"target":1987},{"edgeType":"calls","source":2880,"target":324},{"edgeType":"calls","source":4884,"target":566},{"edgeType":"contains","source":63,"target":108},{"edgeType":"calls","source":4862,"target":191},{"edgeType":"calls","source":758,"target":569},{"edgeType":"contains","source":6,"target":818},{"edgeType":"calls","source":4543,"target":567},{"edgeType":"calls","source":4617,"target":387},{"edgeType":"calls","source":4439,"target":1675},{"edgeType":"calls","source":325,"target":249},{"edgeType":"contains","source":2264,"target":2700},{"edgeType":"contains","source":689,"target":785},{"edgeType":"contains","source":3123,"target":383},{"edgeType":"contains","source":3099,"target":3241},{"edgeType":"contains","source":2806,"target":2811},{"edgeType":"calls","source":1759,"target":191},{"edgeType":"calls","source":4780,"target":1675},{"edgeType":"calls","source":4786,"target":1489},{"edgeType":"calls","source":4617,"target":386},{"edgeType":"contains","source":63,"target":107},{"edgeType":"calls","source":620,"target":618},{"edgeType":"calls","source":4543,"target":566},{"edgeType":"calls","source":758,"target":568},{"edgeType":"contains","source":3099,"target":3238},{"edgeType":"calls","source":1348,"target":1308},{"edgeType":"calls","source":3628,"target":389},{"edgeType":"contains","source":689,"target":788},{"edgeType":"contains","source":1249,"target":1394},{"edgeType":"calls","source":3319,"target":454},{"edgeType":"calls","source":2876,"target":446},{"edgeType":"contains","source":3764,"target":3765},{"edgeType":"calls","source":4617,"target":385},{"edgeType":"calls","source":2571,"target":388},{"edgeType":"contains","source":3936,"target":547},{"edgeType":"calls","source":2531,"target":571},{"edgeType":"calls","source":758,"target":571},{"edgeType":"calls","source":4717,"target":456},{"edgeType":"calls","source":2812,"target":316},{"edgeType":"calls","source":4794,"target":183},{"edgeType":"extends","source":603,"target":63},{"edgeType":"calls","source":4399,"target":1856},{"edgeType":"contains","source":689,"target":787},{"edgeType":"contains","source":3123,"target":381},{"edgeType":"calls","source":1653,"target":308},{"edgeType":"contains","source":3099,"target":3239},{"edgeType":"calls","source":2492,"target":724},{"edgeType":"contains","source":3797,"target":3798},{"edgeType":"calls","source":2531,"target":572},{"edgeType":"contains","source":3936,"target":546},{"edgeType":"calls","source":4617,"target":384},{"edgeType":"contains","source":4209,"target":4767},{"edgeType":"calls","source":758,"target":570},{"edgeType":"calls","source":2571,"target":389},{"edgeType":"calls","source":2812,"target":317},{"edgeType":"contains","source":63,"target":109},{"edgeType":"contains","source":6,"target":3960},{"edgeType":"calls","source":2223,"target":1693},{"edgeType":"calls","source":4454,"target":183},{"edgeType":"calls","source":1853,"target":478},{"edgeType":"contains","source":2699,"target":2927},{"edgeType":"calls","source":3460,"target":342},{"edgeType":"calls","source":563,"target":301},{"edgeType":"calls","source":591,"target":490},{"edgeType":"contains","source":1148,"target":1326},{"edgeType":"calls","source":4718,"target":456},{"edgeType":"contains","source":3596,"target":3661},{"edgeType":"contains","source":3598,"target":3599},{"edgeType":"imports","source":1160,"target":504},{"edgeType":"calls","source":1853,"target":477},{"edgeType":"contains","source":4688,"target":4690},{"edgeType":"calls","source":2679,"target":1300},{"edgeType":"calls","source":3455,"target":498},{"edgeType":"calls","source":591,"target":489},{"edgeType":"contains","source":1649,"target":1653},{"edgeType":"contains","source":3936,"target":519},{"edgeType":"calls","source":2395,"target":587},{"edgeType":"contains","source":3596,"target":3658},{"edgeType":"contains","source":16,"target":1538},{"edgeType":"imports","source":4451,"target":4189},{"edgeType":"calls","source":4607,"target":723},{"edgeType":"calls","source":4567,"target":906},{"edgeType":"contains","source":886,"target":994},{"edgeType":"contains","source":4688,"target":4689},{"edgeType":"calls","source":4039,"target":2475},{"edgeType":"calls","source":4062,"target":705},{"edgeType":"contains","source":3002,"target":3045},{"edgeType":"calls","source":4815,"target":1675},{"edgeType":"calls","source":4821,"target":1489},{"edgeType":"calls","source":2813,"target":314},{"edgeType":"imports","source":3643,"target":697},{"edgeType":"calls","source":4245,"target":317},{"edgeType":"contains","source":1054,"target":1071},{"edgeType":"contains","source":1649,"target":1650},{"edgeType":"calls","source":4686,"target":389},{"edgeType":"calls","source":4686,"target":387},{"edgeType":"calls","source":4607,"target":722},{"edgeType":"calls","source":1678,"target":1676},{"edgeType":"calls","source":2764,"target":777},{"edgeType":"contains","source":1054,"target":1070},{"edgeType":"calls","source":4686,"target":388},{"edgeType":"contains","source":1649,"target":1651},{"edgeType":"calls","source":2563,"target":662},{"edgeType":"calls","source":4686,"target":386},{"edgeType":"contains","source":63,"target":83},{"edgeType":"calls","source":4035,"target":483},{"edgeType":"contains","source":2269,"target":2519},{"edgeType":"calls","source":4323,"target":1069},{"edgeType":"calls","source":2798,"target":777},{"edgeType":"calls","source":4245,"target":315},{"edgeType":"calls","source":1417,"target":1305},{"edgeType":"calls","source":2869,"target":690},{"edgeType":"calls","source":2876,"target":473},{"edgeType":"calls","source":591,"target":486},{"edgeType":"calls","source":3234,"target":3116},{"edgeType":"calls","source":1336,"target":645},{"edgeType":"calls","source":4607,"target":720},{"edgeType":"calls","source":1692,"target":179},{"edgeType":"calls","source":4686,"target":385},{"edgeType":"calls","source":4671,"target":1907},{"edgeType":"calls","source":4491,"target":88},{"edgeType":"calls","source":2297,"target":453},{"edgeType":"contains","source":4688,"target":4694},{"edgeType":"calls","source":4245,"target":316},{"edgeType":"contains","source":1148,"target":1329},{"edgeType":"calls","source":591,"target":485},{"edgeType":"calls","source":2937,"target":1754},{"edgeType":"calls","source":4706,"target":1880},{"edgeType":"calls","source":4824,"target":336},{"edgeType":"calls","source":3234,"target":3117},{"edgeType":"calls","source":2876,"target":474},{"edgeType":"calls","source":3212,"target":628},{"edgeType":"calls","source":3039,"target":1763},{"edgeType":"calls","source":4607,"target":719},{"edgeType":"calls","source":2538,"target":378},{"edgeType":"calls","source":4686,"target":384},{"edgeType":"contains","source":2255,"target":2951},{"edgeType":"calls","source":1853,"target":476},{"edgeType":"calls","source":4075,"target":298},{"edgeType":"contains","source":3002,"target":3049},{"edgeType":"calls","source":4032,"target":574},{"edgeType":"calls","source":591,"target":488},{"edgeType":"contains","source":886,"target":998},{"edgeType":"contains","source":1148,"target":1332},{"edgeType":"calls","source":4686,"target":383},{"edgeType":"calls","source":4607,"target":718},{"edgeType":"calls","source":2429,"target":587},{"edgeType":"calls","source":4714,"target":572},{"edgeType":"calls","source":4468,"target":1856},{"edgeType":"calls","source":4311,"target":381},{"edgeType":"calls","source":2876,"target":472},{"edgeType":"calls","source":591,"target":487},{"edgeType":"calls","source":1282,"target":1263},{"edgeType":"calls","source":970,"target":365},{"edgeType":"calls","source":4686,"target":382},{"edgeType":"contains","source":4688,"target":4699},{"edgeType":"calls","source":1205,"target":474},{"edgeType":"calls","source":4714,"target":571},{"edgeType":"calls","source":4607,"target":717},{"edgeType":"calls","source":4517,"target":336},{"edgeType":"calls","source":4588,"target":249},{"edgeType":"contains","source":2269,"target":2523},{"edgeType":"calls","source":2836,"target":2766},{"edgeType":"contains","source":886,"target":1000},{"edgeType":"calls","source":987,"target":890},{"edgeType":"contains","source":1148,"target":1334},{"edgeType":"contains","source":3400,"target":3403},{"edgeType":"calls","source":1385,"target":179},{"edgeType":"calls","source":1205,"target":473},{"edgeType":"calls","source":4714,"target":570},{"edgeType":"imports","source":1918,"target":1324},{"edgeType":"calls","source":703,"target":179},{"edgeType":"calls","source":4607,"target":716},{"edgeType":"calls","source":4588,"target":248},{"edgeType":"calls","source":3565,"target":3422},{"edgeType":"contains","source":886,"target":999},{"edgeType":"calls","source":4714,"target":569},{"edgeType":"contains","source":4688,"target":4697},{"edgeType":"calls","source":4774,"target":1880},{"edgeType":"calls","source":2436,"target":365},{"edgeType":"calls","source":4800,"target":4245},{"edgeType":"imports","source":1934,"target":1884},{"edgeType":"calls","source":4607,"target":715},{"edgeType":"contains","source":3120,"target":452},{"edgeType":"calls","source":4323,"target":1063},{"edgeType":"contains","source":1643,"target":2901},{"edgeType":"calls","source":1660,"target":1169},{"edgeType":"contains","source":3400,"target":3401},{"edgeType":"calls","source":4714,"target":568},{"edgeType":"calls","source":1168,"target":565},{"edgeType":"contains","source":1249,"target":1374},{"edgeType":"calls","source":4047,"target":106},{"edgeType":"calls","source":1853,"target":471},{"edgeType":"calls","source":4607,"target":714},{"edgeType":"contains","source":3120,"target":453},{"edgeType":"contains","source":1649,"target":1659},{"edgeType":"calls","source":789,"target":687},{"edgeType":"contains","source":1148,"target":1335},{"edgeType":"calls","source":3519,"target":1675},{"edgeType":"calls","source":1251,"target":106},{"edgeType":"calls","source":4790,"target":325},{"edgeType":"contains","source":4688,"target":4703},{"edgeType":"calls","source":2866,"target":774},{"edgeType":"calls","source":4714,"target":567},{"edgeType":"calls","source":4607,"target":713},{"edgeType":"contains","source":2211,"target":2212},{"edgeType":"calls","source":2915,"target":1370},{"edgeType":"contains","source":2269,"target":2528},{"edgeType":"contains","source":3123,"target":365},{"edgeType":"contains","source":4688,"target":4702},{"edgeType":"calls","source":4607,"target":712},{"edgeType":"calls","source":2801,"target":2790},{"edgeType":"calls","source":4701,"target":969},{"edgeType":"calls","source":4714,"target":566},{"edgeType":"contains","source":4209,"target":4753},{"edgeType":"calls","source":966,"target":479},{"edgeType":"contains","source":2211,"target":2213},{"edgeType":"calls","source":3459,"target":2476},{"edgeType":"contains","source":3098,"target":3255},{"edgeType":"contains","source":1148,"target":1341},{"edgeType":"calls","source":1205,"target":472},{"edgeType":"calls","source":4044,"target":194},{"edgeType":"calls","source":1108,"target":308},{"edgeType":"calls","source":3230,"target":3230},{"edgeType":"calls","source":4493,"target":4245},{"edgeType":"calls","source":4610,"target":1675},{"edgeType":"calls","source":4616,"target":1489},{"edgeType":"calls","source":4593,"target":88},{"edgeType":"contains","source":1643,"target":2905},{"edgeType":"calls","source":3996,"target":624},{"edgeType":"contains","source":1148,"target":1340},{"edgeType":"contains","source":4451,"target":4648},{"edgeType":"contains","source":2204,"target":1370},{"edgeType":"calls","source":2321,"target":756},{"edgeType":"calls","source":3545,"target":865},{"edgeType":"calls","source":1772,"target":863},{"edgeType":"contains","source":3002,"target":3058},{"edgeType":"contains","source":1148,"target":1339},{"edgeType":"calls","source":3690,"target":1655},{"edgeType":"calls","source":1371,"target":572},{"edgeType":"calls","source":2741,"target":384},{"edgeType":"calls","source":2742,"target":353},{"edgeType":"calls","source":556,"target":468},{"edgeType":"contains","source":4455,"target":4498},{"edgeType":"calls","source":587,"target":564},{"edgeType":"contains","source":3696,"target":3715},{"edgeType":"contains","source":1643,"target":2878},{"edgeType":"calls","source":4742,"target":719},{"edgeType":"calls","source":4762,"target":99},{"edgeType":"contains","source":1713,"target":1765},{"edgeType":"contains","source":3594,"target":3706},{"edgeType":"calls","source":2394,"target":571},{"edgeType":"contains","source":4225,"target":4229},{"edgeType":"calls","source":1880,"target":1705},{"edgeType":"calls","source":1371,"target":571},{"edgeType":"contains","source":1148,"target":1309},{"edgeType":"calls","source":2741,"target":385},{"edgeType":"calls","source":2742,"target":354},{"edgeType":"calls","source":706,"target":45},{"edgeType":"contains","source":2401,"target":3693},{"edgeType":"calls","source":4849,"target":572},{"edgeType":"calls","source":3323,"target":1370},{"edgeType":"contains","source":4455,"target":4497},{"edgeType":"calls","source":556,"target":467},{"edgeType":"calls","source":4742,"target":718},{"edgeType":"calls","source":4762,"target":98},{"edgeType":"contains","source":16,"target":1518},{"edgeType":"contains","source":4225,"target":4228},{"edgeType":"contains","source":3594,"target":3705},{"edgeType":"calls","source":1672,"target":753},{"edgeType":"calls","source":2394,"target":572},{"edgeType":"calls","source":3546,"target":1856},{"edgeType":"calls","source":3702,"target":191},{"edgeType":"calls","source":1280,"target":1281},{"edgeType":"calls","source":4200,"target":606},{"edgeType":"calls","source":556,"target":470},{"edgeType":"calls","source":587,"target":566},{"edgeType":"contains","source":1054,"target":1055},{"edgeType":"calls","source":4849,"target":571},{"edgeType":"calls","source":2741,"target":382},{"edgeType":"calls","source":4742,"target":717},{"edgeType":"calls","source":4810,"target":723},{"edgeType":"contains","source":4225,"target":4227},{"edgeType":"calls","source":2394,"target":569},{"edgeType":"calls","source":4614,"target":457},{"edgeType":"calls","source":4548,"target":389},{"edgeType":"calls","source":3736,"target":191},{"edgeType":"calls","source":2238,"target":2234},{"edgeType":"calls","source":1963,"target":191},{"edgeType":"calls","source":4200,"target":605},{"edgeType":"calls","source":2741,"target":383},{"edgeType":"calls","source":4849,"target":570},{"edgeType":"calls","source":556,"target":469},{"edgeType":"calls","source":4742,"target":716},{"edgeType":"calls","source":4810,"target":722},{"edgeType":"contains","source":63,"target":64},{"edgeType":"contains","source":798,"target":533},{"edgeType":"calls","source":2394,"target":570},{"edgeType":"contains","source":681,"target":3103},{"edgeType":"contains","source":3596,"target":3641},{"edgeType":"contains","source":4225,"target":4226},{"edgeType":"contains","source":2269,"target":2498},{"edgeType":"calls","source":4548,"target":388},{"edgeType":"calls","source":4614,"target":456},{"edgeType":"calls","source":1853,"target":429},{"edgeType":"calls","source":2294,"target":499},{"edgeType":"contains","source":1054,"target":1057},{"edgeType":"contains","source":3003,"target":3004},{"edgeType":"contains","source":3002,"target":3035},{"edgeType":"calls","source":4849,"target":569},{"edgeType":"calls","source":4793,"target":191},{"edgeType":"calls","source":1371,"target":568},{"edgeType":"contains","source":1643,"target":2882},{"edgeType":"calls","source":4548,"target":387},{"edgeType":"calls","source":4590,"target":2256},{"edgeType":"contains","source":4060,"target":4063},{"edgeType":"calls","source":4742,"target":715},{"edgeType":"calls","source":2669,"target":498},{"edgeType":"calls","source":4145,"target":194},{"edgeType":"calls","source":4349,"target":1271},{"edgeType":"calls","source":4489,"target":102},{"edgeType":"calls","source":497,"target":179},{"edgeType":"calls","source":2394,"target":567},{"edgeType":"contains","source":1054,"target":1056},{"edgeType":"calls","source":652,"target":658},{"edgeType":"calls","source":4849,"target":568},{"edgeType":"contains","source":3002,"target":3036},{"edgeType":"calls","source":4810,"target":720},{"edgeType":"calls","source":1371,"target":567},{"edgeType":"calls","source":2394,"target":568},{"edgeType":"calls","source":4548,"target":386},{"edgeType":"calls","source":4712,"target":587},{"edgeType":"calls","source":4594,"target":4245},{"edgeType":"contains","source":28,"target":2208},{"edgeType":"calls","source":4742,"target":714},{"edgeType":"contains","source":886,"target":978},{"edgeType":"calls","source":4029,"target":1677},{"edgeType":"calls","source":4489,"target":101},{"edgeType":"calls","source":1371,"target":570},{"edgeType":"calls","source":2808,"target":415},{"edgeType":"calls","source":556,"target":466},{"edgeType":"calls","source":2764,"target":722},{"edgeType":"calls","source":4849,"target":567},{"edgeType":"imports","source":1160,"target":546},{"edgeType":"contains","source":1713,"target":1767},{"edgeType":"calls","source":1672,"target":752},{"edgeType":"contains","source":4060,"target":4061},{"edgeType":"calls","source":4742,"target":713},{"edgeType":"calls","source":4783,"target":499},{"edgeType":"contains","source":28,"target":97},{"edgeType":"calls","source":1656,"target":191},{"edgeType":"calls","source":4810,"target":719},{"edgeType":"calls","source":4489,"target":100},{"edgeType":"calls","source":4548,"target":385},{"edgeType":"calls","source":4557,"target":106},{"edgeType":"calls","source":4353,"target":88},{"edgeType":"contains","source":3936,"target":504},{"edgeType":"calls","source":1371,"target":569},{"edgeType":"contains","source":1054,"target":1058},{"edgeType":"calls","source":2764,"target":723},{"edgeType":"contains","source":3594,"target":3707},{"edgeType":"contains","source":3596,"target":3645},{"edgeType":"calls","source":4742,"target":712},{"edgeType":"calls","source":4810,"target":718},{"edgeType":"contains","source":4225,"target":4230},{"edgeType":"calls","source":4849,"target":566},{"edgeType":"calls","source":556,"target":465},{"edgeType":"contains","source":2269,"target":2502},{"edgeType":"calls","source":4489,"target":99},{"edgeType":"calls","source":4548,"target":384},{"edgeType":"imports","source":2259,"target":302},{"edgeType":"calls","source":2394,"target":566},{"edgeType":"calls","source":2254,"target":1735},{"edgeType":"imports","source":1934,"target":1936},{"edgeType":"calls","source":1347,"target":1308},{"edgeType":"calls","source":1307,"target":434},{"edgeType":"calls","source":1439,"target":570},{"edgeType":"imports","source":3050,"target":1165},{"edgeType":"calls","source":4810,"target":717},{"edgeType":"calls","source":4020,"target":894},{"edgeType":"calls","source":2764,"target":720},{"edgeType":"calls","source":2776,"target":348},{"edgeType":"calls","source":4456,"target":2178},{"edgeType":"calls","source":4548,"target":383},{"edgeType":"contains","source":16,"target":3642},{"edgeType":"calls","source":2672,"target":401},{"edgeType":"calls","source":4576,"target":572},{"edgeType":"calls","source":4489,"target":98},{"edgeType":"calls","source":906,"target":179},{"edgeType":"contains","source":3002,"target":3040},{"edgeType":"imports","source":1934,"target":1935},{"edgeType":"contains","source":3594,"target":3713},{"edgeType":"calls","source":1439,"target":569},{"edgeType":"contains","source":4060,"target":4066},{"edgeType":"calls","source":4810,"target":716},{"edgeType":"calls","source":4548,"target":382},{"edgeType":"calls","source":2751,"target":1124},{"edgeType":"calls","source":2672,"target":402},{"edgeType":"calls","source":4576,"target":571},{"edgeType":"imports","source":2126,"target":210},{"edgeType":"contains","source":3594,"target":3712},{"edgeType":"calls","source":1439,"target":572},{"edgeType":"calls","source":1371,"target":566},{"edgeType":"calls","source":4810,"target":715},{"edgeType":"calls","source":2764,"target":718},{"edgeType":"contains","source":3,"target":1933},{"edgeType":"extends","source":3663,"target":3535},{"edgeType":"calls","source":4576,"target":570},{"edgeType":"imports","source":3768,"target":35},{"edgeType":"calls","source":1307,"target":435},{"edgeType":"imports","source":3443,"target":1654},{"edgeType":"calls","source":3381,"target":2733},{"edgeType":"calls","source":1439,"target":571},{"edgeType":"contains","source":4060,"target":4064},{"edgeType":"calls","source":4810,"target":714},{"edgeType":"calls","source":4576,"target":569},{"edgeType":"calls","source":4230,"target":725},{"edgeType":"calls","source":2764,"target":719},{"edgeType":"calls","source":2325,"target":587},{"edgeType":"calls","source":2221,"target":1693},{"edgeType":"calls","source":1439,"target":566},{"edgeType":"calls","source":3522,"target":473},{"edgeType":"calls","source":4793,"target":183},{"edgeType":"calls","source":4810,"target":713},{"edgeType":"calls","source":1250,"target":82},{"edgeType":"calls","source":1306,"target":460},{"edgeType":"calls","source":4576,"target":568},{"edgeType":"calls","source":2764,"target":716},{"edgeType":"contains","source":28,"target":1160},{"edgeType":"calls","source":2570,"target":388},{"edgeType":"calls","source":4851,"target":499},{"edgeType":"contains","source":4060,"target":4071},{"edgeType":"calls","source":4716,"target":456},{"edgeType":"contains","source":886,"target":987},{"edgeType":"calls","source":1660,"target":1113},{"edgeType":"contains","source":3696,"target":3726},{"edgeType":"contains","source":1054,"target":1064},{"edgeType":"calls","source":3522,"target":474},{"edgeType":"contains","source":2730,"target":906},{"edgeType":"calls","source":1514,"target":354},{"edgeType":"calls","source":3613,"target":824},{"edgeType":"calls","source":1852,"target":446},{"edgeType":"calls","source":4810,"target":712},{"edgeType":"calls","source":4020,"target":891},{"edgeType":"calls","source":1336,"target":586},{"edgeType":"contains","source":4451,"target":4633},{"edgeType":"calls","source":4576,"target":567},{"edgeType":"calls","source":865,"target":389},{"edgeType":"calls","source":2570,"target":389},{"edgeType":"calls","source":2764,"target":717},{"edgeType":"calls","source":2656,"target":894},{"edgeType":"contains","source":2276,"target":2292},{"edgeType":"contains","source":2803,"target":2868},{"edgeType":"calls","source":1439,"target":568},{"edgeType":"contains","source":4853,"target":4855},{"edgeType":"calls","source":1656,"target":183},{"edgeType":"calls","source":2656,"target":891},{"edgeType":"calls","source":4644,"target":572},{"edgeType":"calls","source":4684,"target":389},{"edgeType":"calls","source":2570,"target":386},{"edgeType":"calls","source":4576,"target":566},{"edgeType":"calls","source":421,"target":415},{"edgeType":"calls","source":2779,"target":249},{"edgeType":"calls","source":2764,"target":714},{"edgeType":"calls","source":4784,"target":460},{"edgeType":"calls","source":4819,"target":1489},{"edgeType":"calls","source":2801,"target":2738},{"edgeType":"calls","source":3708,"target":2105},{"edgeType":"contains","source":2269,"target":2510},{"edgeType":"contains","source":4853,"target":4854},{"edgeType":"calls","source":3522,"target":472},{"edgeType":"calls","source":1439,"target":567},{"edgeType":"calls","source":4838,"target":899},{"edgeType":"extends","source":2933,"target":1857},{"edgeType":"contains","source":612,"target":2083},{"edgeType":"calls","source":4684,"target":388},{"edgeType":"calls","source":2570,"target":387},{"edgeType":"calls","source":4644,"target":571},{"edgeType":"calls","source":4750,"target":456},{"edgeType":"calls","source":2764,"target":715},{"edgeType":"contains","source":3596,"target":3627},{"edgeType":"calls","source":4617,"target":382},{"edgeType":"calls","source":2531,"target":568},{"edgeType":"calls","source":4356,"target":4245},{"edgeType":"calls","source":1508,"target":570},{"edgeType":"calls","source":3628,"target":387},{"edgeType":"contains","source":2639,"target":2640},{"edgeType":"contains","source":4753,"target":4757},{"edgeType":"calls","source":4820,"target":1489},{"edgeType":"calls","source":1508,"target":569},{"edgeType":"calls","source":2571,"target":386},{"edgeType":"calls","source":2531,"target":569},{"edgeType":"calls","source":4617,"target":383},{"edgeType":"contains","source":1647,"target":3795},{"edgeType":"contains","source":3594,"target":3688},{"edgeType":"calls","source":3628,"target":388},{"edgeType":"imports","source":2126,"target":186},{"edgeType":"imports","source":2255,"target":416},{"edgeType":"calls","source":1508,"target":568},{"edgeType":"calls","source":2531,"target":570},{"edgeType":"contains","source":3696,"target":3698},{"edgeType":"contains","source":3663,"target":3664},{"edgeType":"calls","source":2571,"target":387},{"edgeType":"calls","source":2812,"target":315},{"edgeType":"calls","source":975,"target":179},{"edgeType":"calls","source":2876,"target":445},{"edgeType":"contains","source":2269,"target":2480},{"edgeType":"calls","source":3786,"target":772},{"edgeType":"calls","source":2531,"target":566},{"edgeType":"calls","source":325,"target":248},{"edgeType":"calls","source":2571,"target":383},{"edgeType":"calls","source":1508,"target":572},{"edgeType":"contains","source":2933,"target":3037},{"edgeType":"calls","source":4073,"target":331},{"edgeType":"calls","source":3628,"target":384},{"edgeType":"calls","source":758,"target":567},{"edgeType":"contains","source":1643,"target":2860},{"edgeType":"calls","source":411,"target":754},{"edgeType":"calls","source":3233,"target":3116},{"edgeType":"contains","source":3696,"target":3697},{"edgeType":"calls","source":692,"target":499},{"edgeType":"contains","source":3594,"target":3686},{"edgeType":"calls","source":1660,"target":87},{"edgeType":"calls","source":2571,"target":384},{"edgeType":"calls","source":2531,"target":567},{"edgeType":"calls","source":1508,"target":571},{"edgeType":"calls","source":3628,"target":386},{"edgeType":"calls","source":2296,"target":453},{"edgeType":"contains","source":4753,"target":4754},{"edgeType":"calls","source":4040,"target":298},{"edgeType":"calls","source":3628,"target":385},{"edgeType":"calls","source":758,"target":566},{"edgeType":"calls","source":2571,"target":385},{"edgeType":"calls","source":4783,"target":519},{"edgeType":"contains","source":4753,"target":4761},{"edgeType":"calls","source":451,"target":564},{"edgeType":"contains","source":2639,"target":2644},{"edgeType":"calls","source":3628,"target":382},{"edgeType":"calls","source":3337,"target":3061},{"edgeType":"calls","source":1109,"target":249},{"edgeType":"calls","source":1817,"target":499},{"edgeType":"calls","source":3941,"target":194},{"edgeType":"calls","source":2571,"target":382},{"edgeType":"calls","source":4585,"target":4540},{"edgeType":"contains","source":2639,"target":2645},{"edgeType":"contains","source":4753,"target":4760},{"edgeType":"calls","source":4095,"target":705},{"edgeType":"calls","source":3628,"target":383},{"edgeType":"calls","source":4634,"target":906},{"edgeType":"contains","source":1247,"target":1398},{"edgeType":"contains","source":2639,"target":2642},{"edgeType":"calls","source":4071,"target":389},{"edgeType":"contains","source":4753,"target":4759},{"edgeType":"calls","source":1371,"target":586},{"edgeType":"calls","source":2974,"target":571},{"edgeType":"calls","source":1508,"target":567},{"edgeType":"contains","source":3596,"target":3630},{"edgeType":"contains","source":2269,"target":2485},{"edgeType":"imports","source":2259,"target":285},{"edgeType":"contains","source":3002,"target":3017},{"edgeType":"calls","source":2223,"target":1655},{"edgeType":"calls","source":1371,"target":585},{"edgeType":"calls","source":1508,"target":566},{"edgeType":"calls","source":587,"target":578},{"edgeType":"calls","source":591,"target":454},{"edgeType":"calls","source":3364,"target":1166},{"edgeType":"calls","source":817,"target":847},{"edgeType":"calls","source":2974,"target":572},{"edgeType":"contains","source":3596,"target":3629},{"edgeType":"contains","source":3594,"target":3691},{"edgeType":"calls","source":3143,"target":1675},{"edgeType":"calls","source":3149,"target":1489},{"edgeType":"calls","source":1851,"target":499},{"edgeType":"calls","source":4071,"target":387},{"edgeType":"calls","source":4501,"target":1856},{"edgeType":"calls","source":587,"target":572},{"edgeType":"contains","source":2269,"target":2490},{"edgeType":"calls","source":4322,"target":1063},{"edgeType":"imports","source":621,"target":340},{"edgeType":"calls","source":2831,"target":774},{"edgeType":"calls","source":2974,"target":569},{"edgeType":"imports","source":1918,"target":302},{"edgeType":"contains","source":3432,"target":3435},{"edgeType":"contains","source":1249,"target":1343},{"edgeType":"calls","source":4071,"target":388},{"edgeType":"contains","source":2481,"target":4376},{"edgeType":"calls","source":587,"target":571},{"edgeType":"imports","source":4240,"target":183},{"edgeType":"contains","source":1713,"target":1758},{"edgeType":"calls","source":2974,"target":570},{"edgeType":"calls","source":1335,"target":638},{"edgeType":"calls","source":1771,"target":863},{"edgeType":"imports","source":2259,"target":300},{"edgeType":"contains","source":3432,"target":3434},{"edgeType":"calls","source":1109,"target":248},{"edgeType":"calls","source":3311,"target":690},{"edgeType":"calls","source":4071,"target":385},{"edgeType":"calls","source":4248,"target":183},{"edgeType":"calls","source":4589,"target":183},{"edgeType":"calls","source":2974,"target":567},{"edgeType":"calls","source":2882,"target":248},{"edgeType":"calls","source":3801,"target":298},{"edgeType":"calls","source":1445,"target":402},{"edgeType":"contains","source":3432,"target":3433},{"edgeType":"calls","source":3552,"target":1675},{"edgeType":"calls","source":3558,"target":1489},{"edgeType":"calls","source":4071,"target":386},{"edgeType":"calls","source":4456,"target":77},{"edgeType":"calls","source":2882,"target":249},{"edgeType":"calls","source":2850,"target":1241},{"edgeType":"calls","source":2974,"target":568},{"edgeType":"calls","source":3023,"target":106},{"edgeType":"calls","source":3850,"target":894},{"edgeType":"contains","source":1384,"target":1385},{"edgeType":"calls","source":1272,"target":479},{"edgeType":"calls","source":1445,"target":401},{"edgeType":"calls","source":587,"target":568},{"edgeType":"calls","source":4071,"target":383},{"edgeType":"calls","source":4043,"target":194},{"edgeType":"calls","source":1958,"target":349},{"edgeType":"calls","source":3257,"target":248},{"edgeType":"contains","source":1713,"target":1761},{"edgeType":"calls","source":4492,"target":4245},{"edgeType":"calls","source":4584,"target":336},{"edgeType":"calls","source":864,"target":437},{"edgeType":"calls","source":2812,"target":301},{"edgeType":"calls","source":4742,"target":723},{"edgeType":"calls","source":2741,"target":388},{"edgeType":"contains","source":3596,"target":3640},{"edgeType":"calls","source":2365,"target":417},{"edgeType":"calls","source":864,"target":438},{"edgeType":"contains","source":3663,"target":3677},{"edgeType":"contains","source":1643,"target":2874},{"edgeType":"calls","source":3850,"target":891},{"edgeType":"calls","source":3702,"target":194},{"edgeType":"calls","source":587,"target":567},{"edgeType":"calls","source":4071,"target":384},{"edgeType":"calls","source":3257,"target":249},{"edgeType":"calls","source":4107,"target":325},{"edgeType":"calls","source":2475,"target":179},{"edgeType":"contains","source":1643,"target":2875},{"edgeType":"calls","source":864,"target":436},{"edgeType":"calls","source":2741,"target":389},{"edgeType":"calls","source":906,"target":191},{"edgeType":"calls","source":4681,"target":499},{"edgeType":"calls","source":4742,"target":722},{"edgeType":"calls","source":4762,"target":102},{"edgeType":"calls","source":1693,"target":106},{"edgeType":"calls","source":2974,"target":566},{"edgeType":"contains","source":2269,"target":2496},{"edgeType":"contains","source":3663,"target":3676},{"edgeType":"calls","source":4268,"target":1675},{"edgeType":"calls","source":295,"target":106},{"edgeType":"calls","source":3544,"target":865},{"edgeType":"contains","source":3002,"target":3027},{"edgeType":"calls","source":1677,"target":1659},{"edgeType":"calls","source":3766,"target":325},{"edgeType":"calls","source":2741,"target":386},{"edgeType":"calls","source":2661,"target":752},{"edgeType":"calls","source":2649,"target":1124},{"edgeType":"calls","source":1077,"target":179},{"edgeType":"calls","source":4762,"target":101},{"edgeType":"calls","source":4725,"target":191},{"edgeType":"calls","source":587,"target":570},{"edgeType":"imports","source":4103,"target":207},{"edgeType":"contains","source":2269,"target":2493},{"edgeType":"imports","source":2126,"target":190},{"edgeType":"calls","source":4254,"target":4222},{"edgeType":"contains","source":3596,"target":3638},{"edgeType":"extends","source":721,"target":650},{"edgeType":"calls","source":4077,"target":194},{"edgeType":"calls","source":1659,"target":106},{"edgeType":"contains","source":1219,"target":1220},{"edgeType":"calls","source":2661,"target":753},{"edgeType":"calls","source":4071,"target":382},{"edgeType":"calls","source":4526,"target":4245},{"edgeType":"contains","source":28,"target":2201},{"edgeType":"calls","source":4742,"target":720},{"edgeType":"calls","source":4762,"target":100},{"edgeType":"calls","source":587,"target":569},{"edgeType":"calls","source":2741,"target":387},{"edgeType":"contains","source":3663,"target":3674},{"edgeType":"contains","source":3696,"target":3708},{"edgeType":"contains","source":1643,"target":2873},{"edgeType":"imports","source":3066,"target":645},{"edgeType":"contains","source":1249,"target":1346},{"edgeType":"calls","source":3386,"target":572},{"edgeType":"calls","source":2670,"target":570},{"edgeType":"calls","source":1269,"target":662},{"edgeType":"calls","source":3296,"target":191},{"edgeType":"contains","source":3623,"target":3831},{"edgeType":"contains","source":1643,"target":2845},{"edgeType":"calls","source":4731,"target":102},{"edgeType":"calls","source":4790,"target":387},{"edgeType":"contains","source":4284,"target":4481},{"edgeType":"calls","source":3561,"target":1489},{"edgeType":"calls","source":1493,"target":1117},{"edgeType":"calls","source":1754,"target":425},{"edgeType":"contains","source":3099,"target":3161},{"edgeType":"calls","source":3563,"target":3541},{"edgeType":"imports","source":3701,"target":1094},{"edgeType":"calls","source":2670,"target":571},{"edgeType":"imports","source":44,"target":300},{"edgeType":"contains","source":3332,"target":3339},{"edgeType":"calls","source":4237,"target":1675},{"edgeType":"calls","source":424,"target":430},{"edgeType":"calls","source":4694,"target":191},{"edgeType":"calls","source":4731,"target":101},{"edgeType":"calls","source":4790,"target":386},{"edgeType":"contains","source":681,"target":3068},{"edgeType":"contains","source":4284,"target":4480},{"edgeType":"calls","source":2261,"target":566},{"edgeType":"calls","source":3563,"target":3542},{"edgeType":"calls","source":3671,"target":194},{"edgeType":"contains","source":2735,"target":2819},{"edgeType":"imports","source":4234,"target":1485},{"edgeType":"calls","source":2670,"target":568},{"edgeType":"calls","source":1336,"target":701},{"edgeType":"calls","source":3386,"target":570},{"edgeType":"calls","source":4731,"target":100},{"edgeType":"calls","source":4495,"target":4245},{"edgeType":"calls","source":4618,"target":1489},{"edgeType":"calls","source":4790,"target":385},{"edgeType":"calls","source":4742,"target":1873},{"edgeType":"calls","source":4775,"target":1907},{"edgeType":"calls","source":2945,"target":499},{"edgeType":"contains","source":2209,"target":2210},{"edgeType":"contains","source":4284,"target":4479},{"edgeType":"contains","source":2269,"target":2464},{"edgeType":"calls","source":2241,"target":2240},{"edgeType":"contains","source":2735,"target":2816},{"edgeType":"calls","source":1493,"target":1119},{"edgeType":"calls","source":1898,"target":191},{"edgeType":"calls","source":1856,"target":436},{"edgeType":"calls","source":1754,"target":427},{"edgeType":"imports","source":1918,"target":1398},{"edgeType":"contains","source":3099,"target":3159},{"edgeType":"imports","source":3701,"target":39},{"edgeType":"calls","source":2670,"target":569},{"edgeType":"contains","source":3332,"target":3337},{"edgeType":"calls","source":3386,"target":571},{"edgeType":"calls","source":4731,"target":99},{"edgeType":"calls","source":4790,"target":384},{"edgeType":"calls","source":2856,"target":88},{"edgeType":"calls","source":4549,"target":456},{"edgeType":"extends","source":1219,"target":1104},{"edgeType":"contains","source":4284,"target":4478},{"edgeType":"imports","source":3701,"target":40},{"edgeType":"calls","source":4012,"target":191},{"edgeType":"contains","source":3428,"target":3531},{"edgeType":"calls","source":3547,"target":865},{"edgeType":"calls","source":1493,"target":1118},{"edgeType":"calls","source":4046,"target":194},{"edgeType":"extends","source":4194,"target":4010},{"edgeType":"contains","source":3099,"target":3160},{"edgeType":"calls","source":1754,"target":426},{"edgeType":"calls","source":1774,"target":863},{"edgeType":"contains","source":4421,"target":4466},{"edgeType":"calls","source":3386,"target":568},{"edgeType":"calls","source":2670,"target":566},{"edgeType":"calls","source":4731,"target":98},{"edgeType":"contains","source":3332,"target":3342},{"edgeType":"calls","source":4790,"target":383},{"edgeType":"calls","source":4818,"target":572},{"edgeType":"contains","source":1713,"target":1736},{"edgeType":"calls","source":4438,"target":725},{"edgeType":"calls","source":3726,"target":1655},{"edgeType":"calls","source":1882,"target":1738},{"edgeType":"contains","source":4284,"target":4485},{"edgeType":"imports","source":3701,"target":41},{"edgeType":"calls","source":4136,"target":572},{"edgeType":"imports","source":3598,"target":63},{"edgeType":"contains","source":2735,"target":2822},{"edgeType":"contains","source":1713,"target":1737},{"edgeType":"contains","source":4421,"target":4465},{"edgeType":"calls","source":3386,"target":569},{"edgeType":"calls","source":2670,"target":567},{"edgeType":"calls","source":1489,"target":179},{"edgeType":"calls","source":619,"target":723},{"edgeType":"calls","source":4750,"target":565},{"edgeType":"calls","source":4790,"target":382},{"edgeType":"contains","source":3332,"target":3343},{"edgeType":"calls","source":4818,"target":571},{"edgeType":"calls","source":4776,"target":1873},{"edgeType":"calls","source":2847,"target":365},{"edgeType":"contains","source":1535,"target":4084},{"edgeType":"contains","source":2735,"target":2823},{"edgeType":"calls","source":2531,"target":648},{"edgeType":"calls","source":4629,"target":88},{"edgeType":"contains","source":4284,"target":4484},{"edgeType":"imports","source":3701,"target":42},{"edgeType":"calls","source":4279,"target":366},{"edgeType":"contains","source":3120,"target":2513},{"edgeType":"contains","source":4421,"target":4464},{"edgeType":"calls","source":1371,"target":669},{"edgeType":"contains","source":3623,"target":3833},{"edgeType":"calls","source":4750,"target":564},{"edgeType":"calls","source":3311,"target":777},{"edgeType":"calls","source":4818,"target":570},{"edgeType":"calls","source":3386,"target":566},{"edgeType":"calls","source":3417,"target":662},{"edgeType":"contains","source":1713,"target":1734},{"edgeType":"calls","source":3212,"target":675},{"edgeType":"contains","source":2077,"target":2078},{"edgeType":"contains","source":4284,"target":4483},{"edgeType":"calls","source":4705,"target":902},{"edgeType":"calls","source":2265,"target":435},{"edgeType":"imports","source":3598,"target":65},{"edgeType":"calls","source":4311,"target":1489},{"edgeType":"contains","source":681,"target":3075},{"edgeType":"contains","source":681,"target":2018},{"edgeType":"calls","source":4136,"target":570},{"edgeType":"calls","source":4873,"target":2035},{"edgeType":"contains","source":3332,"target":3341},{"edgeType":"calls","source":4818,"target":569},{"edgeType":"calls","source":3386,"target":567},{"edgeType":"calls","source":2887,"target":1237},{"edgeType":"calls","source":325,"target":326},{"edgeType":"contains","source":16,"target":1492},{"edgeType":"calls","source":424,"target":428},{"edgeType":"contains","source":4284,"target":4482},{"edgeType":"calls","source":4705,"target":901},{"edgeType":"contains","source":395,"target":3484},{"edgeType":"calls","source":4317,"target":1302},{"edgeType":"calls","source":4136,"target":571},{"edgeType":"contains","source":2735,"target":2821},{"edgeType":"calls","source":3583,"target":1856},{"edgeType":"contains","source":1713,"target":1740},{"edgeType":"calls","source":4867,"target":106},{"edgeType":"contains","source":2903,"target":2904},{"edgeType":"calls","source":1659,"target":191},{"edgeType":"calls","source":4818,"target":568},{"edgeType":"calls","source":4617,"target":457},{"edgeType":"contains","source":2735,"target":2826},{"edgeType":"calls","source":4551,"target":389},{"edgeType":"calls","source":4705,"target":900},{"edgeType":"calls","source":1964,"target":249},{"edgeType":"calls","source":4136,"target":568},{"edgeType":"calls","source":619,"target":720},{"edgeType":"contains","source":681,"target":3077},{"edgeType":"calls","source":2431,"target":572},{"edgeType":"contains","source":4421,"target":4470},{"edgeType":"contains","source":3596,"target":3618},{"edgeType":"calls","source":1250,"target":185},{"edgeType":"calls","source":4638,"target":1919},{"edgeType":"calls","source":4694,"target":183},{"edgeType":"calls","source":4617,"target":456},{"edgeType":"calls","source":1133,"target":640},{"edgeType":"calls","source":1964,"target":248},{"edgeType":"calls","source":4752,"target":499},{"edgeType":"calls","source":4762,"target":189},{"edgeType":"calls","source":1764,"target":106},{"edgeType":"contains","source":2735,"target":2827},{"edgeType":"calls","source":4818,"target":567},{"edgeType":"contains","source":6,"target":3918},{"edgeType":"calls","source":4136,"target":569},{"edgeType":"calls","source":619,"target":719},{"edgeType":"calls","source":4551,"target":388},{"edgeType":"contains","source":681,"target":3076},{"edgeType":"calls","source":4345,"target":1489},{"edgeType":"calls","source":4386,"target":1275},{"edgeType":"calls","source":2265,"target":434},{"edgeType":"contains","source":4421,"target":4469},{"edgeType":"calls","source":3645,"target":2046},{"edgeType":"calls","source":619,"target":722},{"edgeType":"contains","source":2933,"target":3029},{"edgeType":"contains","source":3332,"target":3344},{"edgeType":"calls","source":3362,"target":249},{"edgeType":"contains","source":3623,"target":3837},{"edgeType":"contains","source":2735,"target":2824},{"edgeType":"calls","source":457,"target":459},{"edgeType":"calls","source":4818,"target":566},{"edgeType":"calls","source":3871,"target":325},{"edgeType":"contains","source":2933,"target":3028},{"edgeType":"calls","source":4551,"target":387},{"edgeType":"calls","source":4136,"target":566},{"edgeType":"calls","source":4148,"target":194},{"edgeType":"calls","source":4279,"target":361},{"edgeType":"calls","source":4386,"target":1274},{"edgeType":"calls","source":2431,"target":570},{"edgeType":"contains","source":4421,"target":4467},{"edgeType":"calls","source":4279,"target":3532},{"edgeType":"calls","source":4356,"target":88},{"edgeType":"contains","source":1713,"target":1739},{"edgeType":"calls","source":3743,"target":66},{"edgeType":"contains","source":3002,"target":3005},{"edgeType":"contains","source":2933,"target":3030},{"edgeType":"calls","source":4714,"target":1675},{"edgeType":"calls","source":4597,"target":4245},{"edgeType":"contains","source":2735,"target":2825},{"edgeType":"calls","source":4790,"target":376},{"edgeType":"calls","source":4032,"target":1677},{"edgeType":"calls","source":4551,"target":386},{"edgeType":"contains","source":4284,"target":4486},{"edgeType":"calls","source":4136,"target":567},{"edgeType":"imports","source":3936,"target":2260},{"edgeType":"calls","source":2431,"target":571},{"edgeType":"calls","source":4279,"target":362},{"edgeType":"calls","source":4279,"target":3533},{"edgeType":"calls","source":2241,"target":2233},{"edgeType":"contains","source":2269,"target":2478},{"edgeType":"contains","source":2903,"target":2908},{"edgeType":"calls","source":2339,"target":248},{"edgeType":"imports","source":2201,"target":30},{"edgeType":"calls","source":933,"target":495},{"edgeType":"contains","source":1643,"target":2857},{"edgeType":"calls","source":2431,"target":568},{"edgeType":"calls","source":4551,"target":385},{"edgeType":"calls","source":674,"target":68},{"edgeType":"contains","source":3795,"target":3797},{"edgeType":"calls","source":591,"target":527},{"edgeType":"calls","source":2339,"target":249},{"edgeType":"calls","source":619,"target":716},{"edgeType":"calls","source":564,"target":307},{"edgeType":"calls","source":3620,"target":1763},{"edgeType":"calls","source":933,"target":494},{"edgeType":"contains","source":2269,"target":2479},{"edgeType":"contains","source":3594,"target":3684},{"edgeType":"calls","source":1344,"target":438},{"edgeType":"calls","source":3773,"target":191},{"edgeType":"calls","source":3362,"target":248},{"edgeType":"calls","source":1528,"target":1076},{"edgeType":"calls","source":4674,"target":1856},{"edgeType":"calls","source":2635,"target":587},{"edgeType":"calls","source":1344,"target":437},{"edgeType":"contains","source":4421,"target":4473},{"edgeType":"calls","source":4857,"target":411},{"edgeType":"calls","source":564,"target":306},{"edgeType":"calls","source":2431,"target":569},{"edgeType":"calls","source":619,"target":715},{"edgeType":"calls","source":4551,"target":384},{"edgeType":"contains","source":2903,"target":2906},{"edgeType":"calls","source":3807,"target":191},{"edgeType":"calls","source":1152,"target":1107},{"edgeType":"calls","source":4631,"target":4245},{"edgeType":"calls","source":4794,"target":249},{"edgeType":"calls","source":3310,"target":1856},{"edgeType":"contains","source":2735,"target":2828},{"edgeType":"contains","source":2699,"target":2887},{"edgeType":"extends","source":3596,"target":3535},{"edgeType":"calls","source":619,"target":718},{"edgeType":"calls","source":4279,"target":357},{"edgeType":"calls","source":2736,"target":2738},{"edgeType":"calls","source":2431,"target":566},{"edgeType":"contains","source":4421,"target":4472},{"edgeType":"calls","source":4551,"target":383},{"edgeType":"calls","source":2656,"target":990},{"edgeType":"calls","source":4619,"target":389},{"edgeType":"calls","source":2253,"target":1856},{"edgeType":"contains","source":2903,"target":2907},{"edgeType":"imports","source":3701,"target":35},{"edgeType":"calls","source":933,"target":496},{"edgeType":"contains","source":3936,"target":479},{"edgeType":"calls","source":3580,"target":887},{"edgeType":"calls","source":4794,"target":248},{"edgeType":"calls","source":1152,"target":1106},{"edgeType":"calls","source":1241,"target":461},{"edgeType":"calls","source":4619,"target":388},{"edgeType":"calls","source":619,"target":717},{"edgeType":"calls","source":2431,"target":567},{"edgeType":"calls","source":4279,"target":358},{"edgeType":"calls","source":741,"target":106},{"edgeType":"contains","source":6,"target":2867},{"edgeType":"contains","source":4421,"target":4471},{"edgeType":"calls","source":4551,"target":382},{"edgeType":"calls","source":4408,"target":1675},{"edgeType":"contains","source":2269,"target":2449},{"edgeType":"calls","source":4311,"target":454},{"edgeType":"contains","source":984,"target":1059},{"edgeType":"contains","source":689,"target":691},{"edgeType":"contains","source":2735,"target":2802},{"edgeType":"imports","source":4045,"target":983},{"edgeType":"calls","source":4755,"target":1489},{"edgeType":"calls","source":4795,"target":249},{"edgeType":"calls","source":1330,"target":901},{"edgeType":"calls","source":1109,"target":353},{"edgeType":"contains","source":1647,"target":1648},{"edgeType":"calls","source":4632,"target":4245},{"edgeType":"contains","source":689,"target":690},{"edgeType":"calls","source":1754,"target":441},{"edgeType":"calls","source":1720,"target":438},{"edgeType":"contains","source":2803,"target":2809},{"edgeType":"contains","source":1811,"target":1850},{"edgeType":"imports","source":2259,"target":325},{"edgeType":"calls","source":1330,"target":900},{"edgeType":"contains","source":285,"target":529},{"edgeType":"calls","source":4686,"target":456},{"edgeType":"calls","source":4795,"target":248},{"edgeType":"calls","source":4368,"target":1856},{"edgeType":"contains","source":590,"target":591},{"edgeType":"contains","source":984,"target":1061},{"edgeType":"imports","source":2021,"target":302},{"edgeType":"contains","source":285,"target":532},{"edgeType":"contains","source":1713,"target":1714},{"edgeType":"contains","source":3710,"target":3230},{"edgeType":"calls","source":4575,"target":725},{"edgeType":"calls","source":2789,"target":1124},{"edgeType":"contains","source":2269,"target":2448},{"edgeType":"calls","source":3146,"target":628},{"edgeType":"calls","source":4448,"target":1489},{"edgeType":"contains","source":689,"target":692},{"edgeType":"contains","source":2735,"target":2801},{"edgeType":"imports","source":3768,"target":1117},{"edgeType":"imports","source":3534,"target":2029},{"edgeType":"contains","source":984,"target":1060},{"edgeType":"contains","source":3066,"target":996},{"edgeType":"calls","source":1330,"target":902},{"edgeType":"calls","source":1109,"target":354},{"edgeType":"contains","source":1713,"target":1715},{"edgeType":"calls","source":4700,"target":1077},{"edgeType":"contains","source":19,"target":321},{"edgeType":"calls","source":4789,"target":1489},{"edgeType":"calls","source":2436,"target":437},{"edgeType":"contains","source":2803,"target":2812},{"edgeType":"calls","source":1651,"target":460},{"edgeType":"calls","source":1659,"target":212},{"edgeType":"calls","source":423,"target":474},{"edgeType":"calls","source":2225,"target":1693},{"edgeType":"imports","source":3768,"target":1118},{"edgeType":"contains","source":799,"target":456},{"edgeType":"calls","source":4842,"target":902},{"edgeType":"contains","source":1515,"target":1516},{"edgeType":"calls","source":1071,"target":470},{"edgeType":"contains","source":2735,"target":2807},{"edgeType":"imports","source":3768,"target":1119},{"edgeType":"calls","source":1659,"target":211},{"edgeType":"calls","source":423,"target":473},{"edgeType":"calls","source":2322,"target":1858},{"edgeType":"calls","source":2436,"target":438},{"edgeType":"contains","source":2269,"target":2454},{"edgeType":"calls","source":2265,"target":454},{"edgeType":"contains","source":1713,"target":1721},{"edgeType":"calls","source":4842,"target":901},{"edgeType":"contains","source":1811,"target":1854},{"edgeType":"calls","source":969,"target":460},{"edgeType":"calls","source":1071,"target":469},{"edgeType":"calls","source":1720,"target":437},{"edgeType":"contains","source":2269,"target":2451},{"edgeType":"contains","source":2735,"target":2804},{"edgeType":"calls","source":563,"target":365},{"edgeType":"calls","source":4842,"target":900},{"edgeType":"contains","source":285,"target":536},{"edgeType":"calls","source":4752,"target":519},{"edgeType":"calls","source":4795,"target":1300},{"edgeType":"calls","source":705,"target":191},{"edgeType":"contains","source":1713,"target":1718},{"edgeType":"contains","source":3596,"target":3597},{"edgeType":"calls","source":2436,"target":436},{"edgeType":"imports","source":3420,"target":1324},{"edgeType":"calls","source":1762,"target":191},{"edgeType":"calls","source":1720,"target":436},{"edgeType":"calls","source":4042,"target":331},{"edgeType":"calls","source":3928,"target":3865},{"edgeType":"extends","source":2001,"target":103},{"edgeType":"imports","source":3571,"target":886},{"edgeType":"imports","source":2126,"target":213},{"edgeType":"contains","source":799,"target":457},{"edgeType":"calls","source":2742,"target":464},{"edgeType":"contains","source":285,"target":535},{"edgeType":"imports","source":1483,"target":63},{"edgeType":"calls","source":887,"target":890},{"edgeType":"calls","source":423,"target":470},{"edgeType":"calls","source":1071,"target":466},{"edgeType":"calls","source":4592,"target":191},{"edgeType":"contains","source":2699,"target":2869},{"edgeType":"calls","source":4680,"target":634},{"edgeType":"calls","source":3789,"target":772},{"edgeType":"calls","source":4708,"target":1880},{"edgeType":"calls","source":3962,"target":3865},{"edgeType":"calls","source":2035,"target":179},{"edgeType":"calls","source":4037,"target":483},{"edgeType":"calls","source":4436,"target":1856},{"edgeType":"contains","source":2269,"target":2457},{"edgeType":"calls","source":2435,"target":464},{"edgeType":"calls","source":4325,"target":1069},{"edgeType":"calls","source":1445,"target":499},{"edgeType":"contains","source":285,"target":538},{"edgeType":"calls","source":3743,"target":83},{"edgeType":"imports","source":2255,"target":458},{"edgeType":"calls","source":423,"target":469},{"edgeType":"calls","source":4680,"target":633},{"edgeType":"calls","source":1071,"target":465},{"edgeType":"calls","source":1761,"target":1273},{"edgeType":"contains","source":6,"target":3901},{"edgeType":"calls","source":4493,"target":88},{"edgeType":"calls","source":556,"target":574},{"edgeType":"contains","source":799,"target":459},{"edgeType":"contains","source":681,"target":3060},{"edgeType":"contains","source":2269,"target":2458},{"edgeType":"contains","source":4455,"target":4456},{"edgeType":"contains","source":285,"target":537},{"edgeType":"calls","source":1071,"target":468},{"edgeType":"contains","source":2735,"target":2808},{"edgeType":"calls","source":325,"target":339},{"edgeType":"contains","source":621,"target":695},{"edgeType":"calls","source":423,"target":472},{"edgeType":"calls","source":4077,"target":298},{"edgeType":"calls","source":4811,"target":1856},{"edgeType":"calls","source":2261,"target":571},{"edgeType":"contains","source":285,"target":541},{"edgeType":"calls","source":2333,"target":453},{"edgeType":"calls","source":4279,"target":3550},{"edgeType":"contains","source":285,"target":540},{"edgeType":"contains","source":3596,"target":3601},{"edgeType":"imports","source":1749,"target":285},{"edgeType":"calls","source":1071,"target":467},{"edgeType":"contains","source":19,"target":329},{"edgeType":"calls","source":4742,"target":1880},{"edgeType":"calls","source":1734,"target":1055},{"edgeType":"contains","source":6,"target":3903},{"edgeType":"contains","source":28,"target":3221},{"edgeType":"contains","source":2269,"target":2456},{"edgeType":"calls","source":2261,"target":572},{"edgeType":"contains","source":285,"target":539},{"edgeType":"calls","source":4313,"target":381},{"edgeType":"calls","source":978,"target":179},{"edgeType":"calls","source":1902,"target":1127},{"edgeType":"contains","source":2735,"target":2814},{"edgeType":"calls","source":690,"target":645},{"edgeType":"calls","source":2782,"target":1330},{"edgeType":"calls","source":423,"target":466},{"edgeType":"contains","source":2201,"target":341},{"edgeType":"calls","source":4590,"target":249},{"edgeType":"contains","source":4284,"target":4477},{"edgeType":"calls","source":2282,"target":975},{"edgeType":"calls","source":2261,"target":569},{"edgeType":"calls","source":904,"target":354},{"edgeType":"imports","source":2259,"target":330},{"edgeType":"calls","source":1856,"target":438},{"edgeType":"contains","source":6,"target":3905},{"edgeType":"calls","source":2502,"target":498},{"edgeType":"calls","source":423,"target":465},{"edgeType":"contains","source":4284,"target":4475},{"edgeType":"contains","source":285,"target":542},{"edgeType":"calls","source":4590,"target":248},{"edgeType":"contains","source":4284,"target":4476},{"edgeType":"calls","source":2261,"target":570},{"edgeType":"calls","source":904,"target":353},{"edgeType":"imports","source":3598,"target":39},{"edgeType":"contains","source":1643,"target":2842},{"edgeType":"contains","source":2735,"target":2815},{"edgeType":"calls","source":1856,"target":437},{"edgeType":"calls","source":1517,"target":376},{"edgeType":"calls","source":4790,"target":389},{"edgeType":"contains","source":285,"target":545},{"edgeType":"contains","source":4451,"target":4583},{"edgeType":"calls","source":196,"target":106},{"edgeType":"contains","source":2269,"target":2459},{"edgeType":"calls","source":2670,"target":572},{"edgeType":"contains","source":4284,"target":4474},{"edgeType":"calls","source":423,"target":468},{"edgeType":"calls","source":2261,"target":567},{"edgeType":"calls","source":2337,"target":325},{"edgeType":"calls","source":4325,"target":1063},{"edgeType":"calls","source":705,"target":183},{"edgeType":"contains","source":1643,"target":2839},{"edgeType":"contains","source":3596,"target":3605},{"edgeType":"imports","source":3598,"target":40},{"edgeType":"calls","source":1444,"target":528},{"edgeType":"calls","source":3563,"target":3543},{"edgeType":"calls","source":3658,"target":1655},{"edgeType":"calls","source":4790,"target":388},{"edgeType":"contains","source":3332,"target":3333},{"edgeType":"contains","source":2201,"target":340},{"edgeType":"calls","source":330,"target":179},{"edgeType":"contains","source":2292,"target":2805},{"edgeType":"calls","source":423,"target":467},{"edgeType":"calls","source":4707,"target":847},{"edgeType":"calls","source":2261,"target":568},{"edgeType":"contains","source":2269,"target":2461},{"edgeType":"imports","source":3598,"target":41},{"edgeType":"calls","source":196,"target":105},{"edgeType":"contains","source":1713,"target":1727},{"edgeType":"calls","source":3857,"target":772},{"edgeType":"contains","source":1148,"target":1244},{"edgeType":"calls","source":556,"target":534},{"edgeType":"calls","source":638,"target":106},{"edgeType":"calls","source":4245,"target":336},{"edgeType":"contains","source":4421,"target":4429},{"edgeType":"calls","source":2540,"target":339},{"edgeType":"calls","source":4611,"target":1675},{"edgeType":"calls","source":1179,"target":248},{"edgeType":"calls","source":4494,"target":4245},{"edgeType":"calls","source":1071,"target":425},{"edgeType":"calls","source":4586,"target":336},{"edgeType":"calls","source":4594,"target":88},{"edgeType":"calls","source":930,"target":567},{"edgeType":"calls","source":2937,"target":716},{"edgeType":"calls","source":4790,"target":354},{"edgeType":"calls","source":4741,"target":1873},{"edgeType":"calls","source":930,"target":568},{"edgeType":"calls","source":3019,"target":289},{"edgeType":"contains","source":2269,"target":2433},{"edgeType":"imports","source":1247,"target":35},{"edgeType":"calls","source":4408,"target":569},{"edgeType":"calls","source":2395,"target":606},{"edgeType":"calls","source":1856,"target":401},{"edgeType":"contains","source":2730,"target":2940},{"edgeType":"contains","source":2735,"target":2785},{"edgeType":"contains","source":1217,"target":1218},{"edgeType":"contains","source":3166,"target":3167},{"edgeType":"calls","source":3219,"target":1489},{"edgeType":"contains","source":4421,"target":4428},{"edgeType":"calls","source":2937,"target":717},{"edgeType":"calls","source":4790,"target":353},{"edgeType":"calls","source":930,"target":566},{"edgeType":"contains","source":3594,"target":3639},{"edgeType":"calls","source":4548,"target":456},{"edgeType":"calls","source":4408,"target":568},{"edgeType":"contains","source":2226,"target":3767},{"edgeType":"calls","source":2261,"target":533},{"edgeType":"contains","source":2730,"target":2941},{"edgeType":"calls","source":2737,"target":572},{"edgeType":"calls","source":1166,"target":653},{"edgeType":"extends","source":1454,"target":1249},{"edgeType":"calls","source":3419,"target":571},{"edgeType":"calls","source":2937,"target":714},{"edgeType":"calls","source":1071,"target":427},{"edgeType":"contains","source":4421,"target":4427},{"edgeType":"calls","source":463,"target":248},{"edgeType":"contains","source":16,"target":1455},{"edgeType":"calls","source":930,"target":570},{"edgeType":"calls","source":4408,"target":567},{"edgeType":"calls","source":2243,"target":1088},{"edgeType":"calls","source":1179,"target":249},{"edgeType":"calls","source":3329,"target":191},{"edgeType":"calls","source":3419,"target":572},{"edgeType":"calls","source":1071,"target":426},{"edgeType":"contains","source":4421,"target":4426},{"edgeType":"calls","source":4651,"target":1489},{"edgeType":"contains","source":2292,"target":2776},{"edgeType":"calls","source":2846,"target":365},{"edgeType":"calls","source":4775,"target":1873},{"edgeType":"calls","source":2937,"target":715},{"edgeType":"calls","source":930,"target":569},{"edgeType":"contains","source":721,"target":740},{"edgeType":"calls","source":324,"target":328},{"edgeType":"calls","source":4528,"target":4245},{"edgeType":"calls","source":4408,"target":566},{"edgeType":"calls","source":258,"target":260},{"edgeType":"calls","source":2395,"target":605},{"edgeType":"contains","source":2735,"target":2784},{"edgeType":"imports","source":1749,"target":1384},{"edgeType":"calls","source":1856,"target":402},{"edgeType":"contains","source":4421,"target":4433},{"edgeType":"calls","source":3419,"target":569},{"edgeType":"calls","source":2737,"target":570},{"edgeType":"contains","source":2284,"target":4086},{"edgeType":"contains","source":3166,"target":3170},{"edgeType":"contains","source":2292,"target":2781},{"edgeType":"calls","source":1183,"target":1177},{"edgeType":"calls","source":1283,"target":191},{"edgeType":"calls","source":2937,"target":712},{"edgeType":"calls","source":3363,"target":191},{"edgeType":"imports","source":4451,"target":78},{"edgeType":"calls","source":1754,"target":388},{"edgeType":"calls","source":2429,"target":605},{"edgeType":"contains","source":28,"target":29},{"edgeType":"calls","source":331,"target":106},{"edgeType":"calls","source":2737,"target":571},{"edgeType":"calls","source":4872,"target":2035},{"edgeType":"contains","source":4421,"target":4432},{"edgeType":"calls","source":3419,"target":570},{"edgeType":"contains","source":3166,"target":3171},{"edgeType":"calls","source":906,"target":249},{"edgeType":"calls","source":3319,"target":499},{"edgeType":"calls","source":2937,"target":713},{"edgeType":"calls","source":1305,"target":565},{"edgeType":"contains","source":1811,"target":1837},{"edgeType":"calls","source":2429,"target":606},{"edgeType":"calls","source":3892,"target":705},{"edgeType":"calls","source":4552,"target":4556},{"edgeType":"calls","source":1754,"target":387},{"edgeType":"imports","source":1749,"target":325},{"edgeType":"calls","source":526,"target":402},{"edgeType":"contains","source":2269,"target":2438},{"edgeType":"calls","source":1999,"target":191},{"edgeType":"contains","source":2735,"target":2790},{"edgeType":"contains","source":3166,"target":3168},{"edgeType":"calls","source":3620,"target":1735},{"edgeType":"contains","source":4421,"target":4431},{"edgeType":"calls","source":4866,"target":106},{"edgeType":"calls","source":2737,"target":568},{"edgeType":"calls","source":3419,"target":567},{"edgeType":"contains","source":6,"target":3884},{"edgeType":"calls","source":4679,"target":1675},{"edgeType":"calls","source":4552,"target":4555},{"edgeType":"calls","source":2265,"target":402},{"edgeType":"calls","source":1965,"target":191},{"edgeType":"contains","source":3166,"target":3169},{"edgeType":"calls","source":2737,"target":569},{"edgeType":"calls","source":2775,"target":448},{"edgeType":"contains","source":4421,"target":4430},{"edgeType":"calls","source":898,"target":499},{"edgeType":"calls","source":3419,"target":568},{"edgeType":"calls","source":1132,"target":645},{"edgeType":"calls","source":1754,"target":389},{"edgeType":"calls","source":458,"target":398},{"edgeType":"calls","source":4552,"target":4554},{"edgeType":"calls","source":4525,"target":106},{"edgeType":"contains","source":798,"target":1528},{"edgeType":"contains","source":2730,"target":2943},{"edgeType":"calls","source":4344,"target":1489},{"edgeType":"calls","source":4292,"target":985},{"edgeType":"contains","source":285,"target":522},{"edgeType":"imports","source":3701,"target":1118},{"edgeType":"calls","source":4592,"target":2256},{"edgeType":"calls","source":4653,"target":365},{"edgeType":"calls","source":3998,"target":585},{"edgeType":"calls","source":4552,"target":4553},{"edgeType":"contains","source":2735,"target":2793},{"edgeType":"calls","source":1754,"target":384},{"edgeType":"calls","source":4795,"target":191},{"edgeType":"calls","source":3870,"target":325},{"edgeType":"calls","source":2737,"target":566},{"edgeType":"calls","source":4113,"target":191},{"edgeType":"calls","source":4501,"target":1906},{"edgeType":"calls","source":2238,"target":1237},{"edgeType":"contains","source":285,"target":521},{"edgeType":"calls","source":740,"target":106},{"edgeType":"contains","source":953,"target":954},{"edgeType":"calls","source":2737,"target":567},{"edgeType":"imports","source":3701,"target":1119},{"edgeType":"calls","source":3419,"target":566},{"edgeType":"calls","source":1754,"target":383},{"edgeType":"calls","source":3998,"target":586},{"edgeType":"calls","source":532,"target":212},{"edgeType":"calls","source":2265,"target":401},{"edgeType":"contains","source":285,"target":524},{"edgeType":"contains","source":4421,"target":4435},{"edgeType":"contains","source":3166,"target":3172},{"edgeType":"calls","source":906,"target":248},{"edgeType":"imports","source":2255,"target":505},{"edgeType":"contains","source":1643,"target":2818},{"edgeType":"contains","source":2730,"target":2946},{"edgeType":"contains","source":2735,"target":2791},{"edgeType":"calls","source":456,"target":457},{"edgeType":"calls","source":4785,"target":499},{"edgeType":"calls","source":3939,"target":298},{"edgeType":"calls","source":1754,"target":386},{"edgeType":"calls","source":2762,"target":846},{"edgeType":"calls","source":526,"target":401},{"edgeType":"contains","source":2269,"target":2439},{"edgeType":"calls","source":1963,"target":249},{"edgeType":"imports","source":1247,"target":41},{"edgeType":"calls","source":2679,"target":248},{"edgeType":"calls","source":2293,"target":587},{"edgeType":"contains","source":2699,"target":2850},{"edgeType":"contains","source":285,"target":523},{"edgeType":"contains","source":4421,"target":4434},{"edgeType":"contains","source":3166,"target":3173},{"edgeType":"calls","source":2820,"target":106},{"edgeType":"contains","source":3685,"target":1881},{"edgeType":"contains","source":2735,"target":2792},{"edgeType":"calls","source":4687,"target":365},{"edgeType":"calls","source":1754,"target":385},{"edgeType":"contains","source":2201,"target":320},{"edgeType":"calls","source":1963,"target":248},{"edgeType":"contains","source":11,"target":3732},{"edgeType":"extends","source":1104,"target":482},{"edgeType":"calls","source":2679,"target":249},{"edgeType":"contains","source":2269,"target":2445},{"edgeType":"calls","source":865,"target":456},{"edgeType":"calls","source":2326,"target":1675},{"edgeType":"calls","source":1349,"target":1308},{"edgeType":"calls","source":1677,"target":653},{"edgeType":"calls","source":1234,"target":644},{"edgeType":"calls","source":3289,"target":2476},{"edgeType":"calls","source":4630,"target":4245},{"edgeType":"imports","source":1247,"target":39},{"edgeType":"calls","source":4665,"target":1046},{"edgeType":"contains","source":285,"target":526},{"edgeType":"contains","source":799,"target":447},{"edgeType":"calls","source":1385,"target":191},{"edgeType":"calls","source":3355,"target":1489},{"edgeType":"contains","source":29,"target":1062},{"edgeType":"imports","source":1247,"target":40},{"edgeType":"contains","source":6,"target":2832},{"edgeType":"calls","source":2753,"target":1124},{"edgeType":"calls","source":4684,"target":456},{"edgeType":"calls","source":4851,"target":564},{"edgeType":"contains","source":285,"target":525},{"edgeType":"calls","source":2365,"target":464},{"edgeType":"calls","source":933,"target":464},{"edgeType":"contains","source":2933,"target":3000},{"edgeType":"calls","source":1678,"target":1681},{"edgeType":"calls","source":1754,"target":382},{"edgeType":"calls","source":1656,"target":249},{"edgeType":"extends","source":769,"target":302},{"edgeType":"imports","source":1247,"target":37},{"edgeType":"calls","source":2881,"target":324},{"edgeType":"calls","source":2540,"target":325},{"edgeType":"imports","source":3420,"target":325},{"edgeType":"calls","source":399,"target":106},{"edgeType":"calls","source":4863,"target":191},{"edgeType":"calls","source":532,"target":211},{"edgeType":"contains","source":2269,"target":2443},{"edgeType":"calls","source":2787,"target":1124},{"edgeType":"calls","source":4446,"target":1489},{"edgeType":"contains","source":2933,"target":3001},{"edgeType":"contains","source":953,"target":960},{"edgeType":"calls","source":2872,"target":2718},{"edgeType":"calls","source":1656,"target":248},{"edgeType":"calls","source":4781,"target":1675},{"edgeType":"calls","source":4787,"target":1489},{"edgeType":"extends","source":3623,"target":2730},{"edgeType":"calls","source":669,"target":191},{"edgeType":"calls","source":1659,"target":183},{"edgeType":"calls","source":970,"target":401},{"edgeType":"calls","source":933,"target":491},{"edgeType":"calls","source":3939,"target":325},{"edgeType":"contains","source":919,"target":927},{"edgeType":"calls","source":1701,"target":995},{"edgeType":"calls","source":619,"target":712},{"edgeType":"extends","source":768,"target":302},{"edgeType":"calls","source":4279,"target":355},{"edgeType":"contains","source":3727,"target":3729},{"edgeType":"calls","source":2802,"target":2804},{"edgeType":"calls","source":4619,"target":387},{"edgeType":"calls","source":2541,"target":325},{"edgeType":"contains","source":28,"target":1065},{"edgeType":"calls","source":695,"target":470},{"edgeType":"contains","source":2075,"target":2088},{"edgeType":"calls","source":4447,"target":1489},{"edgeType":"contains","source":919,"target":926},{"edgeType":"calls","source":1851,"target":572},{"edgeType":"contains","source":3428,"target":3483},{"edgeType":"contains","source":3099,"target":3113},{"edgeType":"calls","source":1761,"target":191},{"edgeType":"contains","source":2933,"target":2974},{"edgeType":"imports","source":3768,"target":91},{"edgeType":"imports","source":3701,"target":2168},{"edgeType":"calls","source":4074,"target":369},{"edgeType":"calls","source":4279,"target":356},{"edgeType":"calls","source":4653,"target":389},{"edgeType":"contains","source":2292,"target":2761},{"edgeType":"calls","source":4619,"target":386},{"edgeType":"calls","source":695,"target":469},{"edgeType":"calls","source":1035,"target":499},{"edgeType":"calls","source":4782,"target":1675},{"edgeType":"calls","source":933,"target":493},{"edgeType":"contains","source":721,"target":725},{"edgeType":"calls","source":4619,"target":384},{"edgeType":"calls","source":4841,"target":902},{"edgeType":"calls","source":564,"target":305},{"edgeType":"contains","source":2000,"target":183},{"edgeType":"calls","source":4193,"target":905},{"edgeType":"calls","source":1344,"target":436},{"edgeType":"calls","source":1244,"target":365},{"edgeType":"contains","source":2075,"target":2086},{"edgeType":"calls","source":4719,"target":456},{"edgeType":"calls","source":4619,"target":385},{"edgeType":"calls","source":4653,"target":388},{"edgeType":"calls","source":619,"target":714},{"edgeType":"contains","source":4221,"target":4268},{"edgeType":"calls","source":933,"target":492},{"edgeType":"calls","source":4497,"target":2051},{"edgeType":"calls","source":3773,"target":185},{"edgeType":"calls","source":970,"target":402},{"edgeType":"contains","source":2269,"target":2415},{"edgeType":"calls","source":996,"target":653},{"edgeType":"calls","source":4619,"target":383},{"edgeType":"calls","source":4653,"target":386},{"edgeType":"contains","source":3527,"target":3583},{"edgeType":"contains","source":3594,"target":3620},{"edgeType":"calls","source":4841,"target":901},{"edgeType":"calls","source":2675,"target":398},{"edgeType":"calls","source":4653,"target":387},{"edgeType":"contains","source":2292,"target":2759},{"edgeType":"calls","source":619,"target":713},{"edgeType":"calls","source":1720,"target":402},{"edgeType":"contains","source":18,"target":322},{"edgeType":"calls","source":3909,"target":194},{"edgeType":"calls","source":1659,"target":179},{"edgeType":"calls","source":4653,"target":385},{"edgeType":"calls","source":4687,"target":388},{"edgeType":"contains","source":4086,"target":4231},{"edgeType":"calls","source":4619,"target":382},{"edgeType":"calls","source":4576,"target":658},{"edgeType":"calls","source":4568,"target":906},{"edgeType":"calls","source":1932,"target":1229},{"edgeType":"calls","source":3674,"target":2194},{"edgeType":"calls","source":1851,"target":569},{"edgeType":"calls","source":695,"target":466},{"edgeType":"calls","source":724,"target":624},{"edgeType":"contains","source":3099,"target":3116},{"edgeType":"calls","source":2737,"target":587},{"edgeType":"calls","source":4841,"target":900},{"edgeType":"calls","source":4822,"target":1489},{"edgeType":"calls","source":1510,"target":569},{"edgeType":"contains","source":285,"target":501},{"edgeType":"calls","source":3624,"target":572},{"edgeType":"calls","source":3548,"target":1871},{"edgeType":"calls","source":4687,"target":389},{"edgeType":"calls","source":4787,"target":460},{"edgeType":"calls","source":1169,"target":570},{"edgeType":"contains","source":3594,"target":3628},{"edgeType":"calls","source":2433,"target":498},{"edgeType":"calls","source":1759,"target":249},{"edgeType":"calls","source":4687,"target":387},{"edgeType":"calls","source":1851,"target":568},{"edgeType":"calls","source":1720,"target":401},{"edgeType":"calls","source":4547,"target":499},{"edgeType":"calls","source":4653,"target":384},{"edgeType":"calls","source":4041,"target":331},{"edgeType":"calls","source":695,"target":465},{"edgeType":"contains","source":3099,"target":3117},{"edgeType":"calls","source":1510,"target":568},{"edgeType":"contains","source":285,"target":500},{"edgeType":"calls","source":3039,"target":1796},{"edgeType":"calls","source":1169,"target":569},{"edgeType":"imports","source":4451,"target":2178},{"edgeType":"calls","source":2436,"target":402},{"edgeType":"contains","source":3594,"target":3625},{"edgeType":"calls","source":4653,"target":383},{"edgeType":"calls","source":4687,"target":386},{"edgeType":"calls","source":4587,"target":4543},{"edgeType":"calls","source":4672,"target":1908},{"edgeType":"calls","source":1510,"target":572},{"edgeType":"calls","source":1851,"target":571},{"edgeType":"contains","source":2699,"target":2830},{"edgeType":"calls","source":4324,"target":1069},{"edgeType":"contains","source":2730,"target":2926},{"edgeType":"contains","source":1811,"target":1818},{"edgeType":"calls","source":2856,"target":1124},{"edgeType":"calls","source":695,"target":468},{"edgeType":"calls","source":3624,"target":570},{"edgeType":"calls","source":3684,"target":824},{"edgeType":"calls","source":1510,"target":571},{"edgeType":"calls","source":1169,"target":572},{"edgeType":"contains","source":2292,"target":2762},{"edgeType":"contains","source":3594,"target":3626},{"edgeType":"calls","source":3323,"target":388},{"edgeType":"calls","source":4653,"target":382},{"edgeType":"imports","source":3701,"target":1117},{"edgeType":"calls","source":4687,"target":385},{"edgeType":"imports","source":2201,"target":35},{"edgeType":"calls","source":1851,"target":570},{"edgeType":"calls","source":4492,"target":88},{"edgeType":"calls","source":4317,"target":1285},{"edgeType":"calls","source":695,"target":467},{"edgeType":"calls","source":3624,"target":571},{"edgeType":"calls","source":1510,"target":570},{"edgeType":"contains","source":3775,"target":1185},{"edgeType":"calls","source":1169,"target":571},{"edgeType":"calls","source":3323,"target":389},{"edgeType":"calls","source":3213,"target":628},{"edgeType":"calls","source":985,"target":990},{"edgeType":"calls","source":422,"target":468},{"edgeType":"calls","source":3227,"target":191},{"edgeType":"calls","source":4687,"target":384},{"edgeType":"calls","source":1169,"target":566},{"edgeType":"calls","source":3999,"target":571},{"edgeType":"calls","source":4731,"target":77},{"edgeType":"contains","source":4253,"target":4343},{"edgeType":"calls","source":3658,"target":571},{"edgeType":"calls","source":3624,"target":568},{"edgeType":"calls","source":669,"target":211},{"edgeType":"calls","source":3339,"target":3061},{"edgeType":"calls","source":3323,"target":386},{"edgeType":"calls","source":4687,"target":383},{"edgeType":"calls","source":3999,"target":572},{"edgeType":"calls","source":639,"target":82},{"edgeType":"calls","source":2675,"target":391},{"edgeType":"contains","source":4253,"target":4342},{"edgeType":"calls","source":2436,"target":401},{"edgeType":"calls","source":422,"target":467},{"edgeType":"calls","source":3624,"target":569},{"edgeType":"calls","source":2868,"target":1808},{"edgeType":"calls","source":724,"target":619},{"edgeType":"calls","source":3658,"target":572},{"edgeType":"contains","source":2933,"target":2982},{"edgeType":"calls","source":3392,"target":2476},{"edgeType":"calls","source":1721,"target":365},{"edgeType":"calls","source":3323,"target":387},{"edgeType":"calls","source":3999,"target":569},{"edgeType":"calls","source":3323,"target":384},{"edgeType":"calls","source":422,"target":470},{"edgeType":"calls","source":4687,"target":382},{"edgeType":"calls","source":1851,"target":567},{"edgeType":"calls","source":1759,"target":248},{"edgeType":"contains","source":798,"target":1517},{"edgeType":"calls","source":4248,"target":249},{"edgeType":"calls","source":2297,"target":479},{"edgeType":"calls","source":4589,"target":249},{"edgeType":"contains","source":2699,"target":2834},{"edgeType":"contains","source":3099,"target":3118},{"edgeType":"calls","source":3658,"target":569},{"edgeType":"calls","source":3624,"target":566},{"edgeType":"calls","source":1510,"target":567},{"edgeType":"calls","source":772,"target":191},{"edgeType":"calls","source":2837,"target":2766},{"edgeType":"calls","source":2937,"target":723},{"edgeType":"calls","source":865,"target":479},{"edgeType":"calls","source":966,"target":519},{"edgeType":"calls","source":1169,"target":568},{"edgeType":"calls","source":3999,"target":570},{"edgeType":"calls","source":422,"target":469},{"edgeType":"contains","source":3413,"target":3954},{"edgeType":"calls","source":1851,"target":566},{"edgeType":"contains","source":4086,"target":4232},{"edgeType":"contains","source":18,"target":327},{"edgeType":"calls","source":3857,"target":744},{"edgeType":"calls","source":2787,"target":88},{"edgeType":"extends","source":1649,"target":482},{"edgeType":"calls","source":2225,"target":1655},{"edgeType":"calls","source":4589,"target":248},{"edgeType":"contains","source":396,"target":3408},{"edgeType":"calls","source":3624,"target":567},{"edgeType":"calls","source":1510,"target":566},{"edgeType":"calls","source":3658,"target":570},{"edgeType":"calls","source":669,"target":212},{"edgeType":"calls","source":794,"target":565},{"edgeType":"calls","source":996,"target":645},{"edgeType":"calls","source":1169,"target":567},{"edgeType":"calls","source":3232,"target":3206},{"edgeType":"calls","source":3323,"target":385},{"edgeType":"calls","source":3366,"target":1166},{"edgeType":"calls","source":3323,"target":382},{"edgeType":"calls","source":3999,"target":567},{"edgeType":"contains","source":4421,"target":4425},{"edgeType":"contains","source":396,"target":3411},{"edgeType":"calls","source":4317,"target":1280},{"edgeType":"calls","source":4324,"target":1063},{"edgeType":"calls","source":930,"target":572},{"edgeType":"calls","source":3658,"target":567},{"edgeType":"calls","source":3323,"target":383},{"edgeType":"calls","source":1897,"target":191},{"edgeType":"calls","source":1183,"target":1184},{"edgeType":"calls","source":3999,"target":568},{"edgeType":"calls","source":4248,"target":248},{"edgeType":"calls","source":2767,"target":1763},{"edgeType":"contains","source":4421,"target":4424},{"edgeType":"contains","source":4086,"target":4238},{"edgeType":"calls","source":463,"target":249},{"edgeType":"contains","source":396,"target":3410},{"edgeType":"contains","source":2292,"target":2774},{"edgeType":"calls","source":2937,"target":722},{"edgeType":"calls","source":4408,"target":572},{"edgeType":"calls","source":3658,"target":568},{"edgeType":"calls","source":930,"target":571},{"edgeType":"contains","source":2933,"target":2986},{"edgeType":"calls","source":1773,"target":863},{"edgeType":"calls","source":3295,"target":191},{"edgeType":"calls","source":3313,"target":690},{"edgeType":"contains","source":18,"target":332},{"edgeType":"calls","source":4599,"target":992},{"edgeType":"calls","source":4591,"target":183},{"edgeType":"calls","source":2937,"target":718},{"edgeType":"calls","source":422,"target":466},{"edgeType":"calls","source":4681,"target":564},{"edgeType":"calls","source":2937,"target":719},{"edgeType":"calls","source":4408,"target":571},{"edgeType":"calls","source":903,"target":354},{"edgeType":"calls","source":3857,"target":738},{"edgeType":"contains","source":3364,"target":3365},{"edgeType":"contains","source":396,"target":3412},{"edgeType":"calls","source":3999,"target":566},{"edgeType":"calls","source":4242,"target":1489},{"edgeType":"calls","source":422,"target":465},{"edgeType":"contains","source":4421,"target":4422},{"edgeType":"calls","source":826,"target":626},{"edgeType":"calls","source":3729,"target":479},{"edgeType":"calls","source":2937,"target":720},{"edgeType":"calls","source":4408,"target":570},{"edgeType":"calls","source":903,"target":353},{"edgeType":"contains","source":2933,"target":2984},{"edgeType":"calls","source":3658,"target":566},{"edgeType":"contains","source":2884,"target":2890},{"edgeType":"calls","source":3360,"target":387},{"edgeType":"contains","source":1529,"target":1556},{"edgeType":"calls","source":573,"target":106},{"edgeType":"calls","source":4709,"target":1907},{"edgeType":"calls","source":1996,"target":389},{"edgeType":"contains","source":803,"target":807},{"edgeType":"contains","source":704,"target":705},{"edgeType":"calls","source":4592,"target":249},{"edgeType":"contains","source":4734,"target":4735},{"edgeType":"contains","source":2976,"target":3209},{"edgeType":"calls","source":4639,"target":906},{"edgeType":"calls","source":2979,"target":571},{"edgeType":"calls","source":2985,"target":385},{"edgeType":"calls","source":2207,"target":191},{"edgeType":"contains","source":4535,"target":4561},{"edgeType":"contains","source":320,"target":981},{"edgeType":"contains","source":2284,"target":3520},{"edgeType":"calls","source":3661,"target":569},{"edgeType":"contains","source":862,"target":1091},{"edgeType":"contains","source":2884,"target":2891},{"edgeType":"contains","source":2803,"target":3288},{"edgeType":"calls","source":3292,"target":382},{"edgeType":"calls","source":1996,"target":388},{"edgeType":"calls","source":3360,"target":388},{"edgeType":"contains","source":770,"target":772},{"edgeType":"contains","source":803,"target":806},{"edgeType":"contains","source":3699,"target":4050},{"edgeType":"contains","source":1529,"target":1557},{"edgeType":"calls","source":3998,"target":3865},{"edgeType":"contains","source":3038,"target":3402},{"edgeType":"calls","source":4592,"target":248},{"edgeType":"calls","source":2985,"target":386},{"edgeType":"calls","source":2979,"target":572},{"edgeType":"contains","source":4535,"target":4560},{"edgeType":"contains","source":320,"target":980},{"edgeType":"contains","source":3699,"target":4051},{"edgeType":"calls","source":3661,"target":570},{"edgeType":"contains","source":803,"target":809},{"edgeType":"calls","source":1164,"target":814},{"edgeType":"contains","source":1529,"target":1554},{"edgeType":"contains","source":3002,"target":287},{"edgeType":"contains","source":704,"target":707},{"edgeType":"calls","source":3360,"target":385},{"edgeType":"calls","source":325,"target":397},{"edgeType":"calls","source":2985,"target":382},{"edgeType":"calls","source":2979,"target":568},{"edgeType":"calls","source":2633,"target":724},{"edgeType":"calls","source":4792,"target":389},{"edgeType":"calls","source":2985,"target":383},{"edgeType":"calls","source":2979,"target":569},{"edgeType":"calls","source":3161,"target":212},{"edgeType":"calls","source":4320,"target":1280},{"edgeType":"contains","source":4535,"target":4559},{"edgeType":"calls","source":2243,"target":2244},{"edgeType":"calls","source":3980,"target":191},{"edgeType":"imports","source":38,"target":285},{"edgeType":"calls","source":1347,"target":426},{"edgeType":"imports","source":2126,"target":1094},{"edgeType":"calls","source":4031,"target":724},{"edgeType":"calls","source":3661,"target":567},{"edgeType":"contains","source":43,"target":1114},{"edgeType":"calls","source":3360,"target":386},{"edgeType":"contains","source":1529,"target":1555},{"edgeType":"contains","source":803,"target":808},{"edgeType":"contains","source":2803,"target":3286},{"edgeType":"contains","source":704,"target":706},{"edgeType":"calls","source":4792,"target":388},{"edgeType":"calls","source":2985,"target":384},{"edgeType":"calls","source":2979,"target":570},{"edgeType":"calls","source":986,"target":1046},{"edgeType":"calls","source":3529,"target":1489},{"edgeType":"calls","source":1347,"target":425},{"edgeType":"contains","source":320,"target":982},{"edgeType":"imports","source":2126,"target":1093},{"edgeType":"calls","source":3661,"target":568},{"edgeType":"imports","source":2276,"target":1728},{"edgeType":"calls","source":2714,"target":325},{"edgeType":"calls","source":4110,"target":388},{"edgeType":"calls","source":3360,"target":383},{"edgeType":"contains","source":1529,"target":1560},{"edgeType":"contains","source":2884,"target":2894},{"edgeType":"calls","source":4792,"target":387},{"edgeType":"contains","source":803,"target":811},{"edgeType":"calls","source":2979,"target":566},{"edgeType":"contains","source":862,"target":1096},{"edgeType":"calls","source":933,"target":569},{"edgeType":"calls","source":975,"target":325},{"edgeType":"calls","source":3146,"target":675},{"edgeType":"imports","source":2126,"target":35},{"edgeType":"contains","source":373,"target":399},{"edgeType":"contains","source":1529,"target":1561},{"edgeType":"calls","source":3729,"target":571},{"edgeType":"contains","source":3573,"target":3734},{"edgeType":"calls","source":4112,"target":325},{"edgeType":"calls","source":4110,"target":387},{"edgeType":"calls","source":1996,"target":384},{"edgeType":"calls","source":1990,"target":570},{"edgeType":"contains","source":803,"target":810},{"edgeType":"calls","source":4110,"target":389},{"edgeType":"calls","source":3286,"target":564},{"edgeType":"calls","source":3360,"target":384},{"edgeType":"calls","source":4705,"target":969},{"edgeType":"calls","source":933,"target":568},{"edgeType":"calls","source":4792,"target":386},{"edgeType":"calls","source":1071,"target":519},{"edgeType":"contains","source":2884,"target":2895},{"edgeType":"calls","source":2979,"target":567},{"edgeType":"contains","source":2803,"target":3292},{"edgeType":"calls","source":3161,"target":211},{"edgeType":"contains","source":1529,"target":1562},{"edgeType":"calls","source":3661,"target":566},{"edgeType":"calls","source":3639,"target":191},{"edgeType":"calls","source":1996,"target":383},{"edgeType":"calls","source":1990,"target":569},{"edgeType":"calls","source":3729,"target":572},{"edgeType":"calls","source":3855,"target":894},{"edgeType":"calls","source":1996,"target":387},{"edgeType":"calls","source":2746,"target":388},{"edgeType":"contains","source":3573,"target":3731},{"edgeType":"calls","source":2778,"target":453},{"edgeType":"contains","source":1631,"target":510},{"edgeType":"contains","source":1529,"target":1558},{"edgeType":"calls","source":1289,"target":106},{"edgeType":"contains","source":482,"target":194},{"edgeType":"calls","source":4792,"target":385},{"edgeType":"calls","source":933,"target":572},{"edgeType":"calls","source":3855,"target":891},{"edgeType":"calls","source":4597,"target":88},{"edgeType":"calls","source":3729,"target":569},{"edgeType":"calls","source":1758,"target":365},{"edgeType":"calls","source":4110,"target":385},{"edgeType":"calls","source":1285,"target":1286},{"edgeType":"imports","source":3571,"target":704},{"edgeType":"calls","source":1996,"target":386},{"edgeType":"calls","source":1990,"target":572},{"edgeType":"calls","source":2746,"target":389},{"edgeType":"calls","source":3360,"target":382},{"edgeType":"contains","source":1529,"target":1559},{"edgeType":"calls","source":1340,"target":638},{"edgeType":"contains","source":4734,"target":4736},{"edgeType":"calls","source":4792,"target":384},{"edgeType":"contains","source":862,"target":1097},{"edgeType":"calls","source":933,"target":570},{"edgeType":"contains","source":803,"target":812},{"edgeType":"contains","source":2884,"target":2893},{"edgeType":"calls","source":975,"target":326},{"edgeType":"calls","source":933,"target":571},{"edgeType":"contains","source":4535,"target":4562},{"edgeType":"calls","source":2450,"target":1109},{"edgeType":"calls","source":4551,"target":456},{"edgeType":"calls","source":3729,"target":570},{"edgeType":"calls","source":3937,"target":464},{"edgeType":"calls","source":4110,"target":386},{"edgeType":"calls","source":1996,"target":385},{"edgeType":"calls","source":1990,"target":571},{"edgeType":"calls","source":2746,"target":386},{"edgeType":"calls","source":789,"target":801},{"edgeType":"contains","source":2884,"target":2898},{"edgeType":"contains","source":4569,"target":4573},{"edgeType":"calls","source":4792,"target":383},{"edgeType":"calls","source":933,"target":565},{"edgeType":"calls","source":3362,"target":2431},{"edgeType":"calls","source":3121,"target":388},{"edgeType":"contains","source":2647,"target":2846},{"edgeType":"calls","source":3729,"target":567},{"edgeType":"calls","source":561,"target":470},{"edgeType":"calls","source":2246,"target":1088},{"edgeType":"calls","source":4110,"target":383},{"edgeType":"calls","source":2006,"target":1127},{"edgeType":"calls","source":1990,"target":566},{"edgeType":"calls","source":1968,"target":191},{"edgeType":"contains","source":1529,"target":1565},{"edgeType":"calls","source":2746,"target":387},{"edgeType":"calls","source":4792,"target":382},{"edgeType":"calls","source":986,"target":1035},{"edgeType":"calls","source":3121,"target":389},{"edgeType":"contains","source":3115,"target":1023},{"edgeType":"calls","source":4631,"target":88},{"edgeType":"calls","source":4489,"target":4490},{"edgeType":"contains","source":1636,"target":3534},{"edgeType":"calls","source":459,"target":460},{"edgeType":"calls","source":1844,"target":863},{"edgeType":"calls","source":4654,"target":1489},{"edgeType":"calls","source":561,"target":469},{"edgeType":"contains","source":3573,"target":3737},{"edgeType":"calls","source":3729,"target":568},{"edgeType":"calls","source":587,"target":720},{"edgeType":"calls","source":534,"target":249},{"edgeType":"contains","source":1398,"target":1399},{"edgeType":"contains","source":1529,"target":1566},{"edgeType":"calls","source":4110,"target":384},{"edgeType":"contains","source":1485,"target":1873},{"edgeType":"calls","source":587,"target":723},{"edgeType":"calls","source":641,"target":106},{"edgeType":"calls","source":2746,"target":384},{"edgeType":"contains","source":97,"target":505},{"edgeType":"calls","source":3121,"target":386},{"edgeType":"calls","source":3313,"target":777},{"edgeType":"calls","source":933,"target":567},{"edgeType":"contains","source":4569,"target":4571},{"edgeType":"contains","source":4600,"target":4667},{"edgeType":"contains","source":340,"target":371},{"edgeType":"contains","source":3038,"target":3407},{"edgeType":"calls","source":3837,"target":388},{"edgeType":"calls","source":2701,"target":722},{"edgeType":"contains","source":1529,"target":1563},{"edgeType":"calls","source":1996,"target":382},{"edgeType":"calls","source":1990,"target":568},{"edgeType":"calls","source":4313,"target":1489},{"edgeType":"calls","source":2233,"target":1489},{"edgeType":"calls","source":789,"target":802},{"edgeType":"calls","source":4875,"target":2035},{"edgeType":"imports","source":2259,"target":2263},{"edgeType":"calls","source":587,"target":722},{"edgeType":"calls","source":2701,"target":723},{"edgeType":"calls","source":3729,"target":566},{"edgeType":"calls","source":2746,"target":385},{"edgeType":"calls","source":3741,"target":194},{"edgeType":"calls","source":4721,"target":4695},{"edgeType":"imports","source":3643,"target":574},{"edgeType":"calls","source":933,"target":566},{"edgeType":"contains","source":4569,"target":4570},{"edgeType":"calls","source":3121,"target":387},{"edgeType":"contains","source":340,"target":370},{"edgeType":"calls","source":2476,"target":299},{"edgeType":"calls","source":3837,"target":389},{"edgeType":"calls","source":4764,"target":191},{"edgeType":"contains","source":1529,"target":1564},{"edgeType":"calls","source":4110,"target":382},{"edgeType":"calls","source":2323,"target":814},{"edgeType":"calls","source":1990,"target":567},{"edgeType":"extends","source":2710,"target":2264},{"edgeType":"imports","source":2276,"target":1735},{"edgeType":"calls","source":864,"target":586},{"edgeType":"calls","source":3121,"target":384},{"edgeType":"calls","source":3837,"target":386},{"edgeType":"calls","source":1661,"target":191},{"edgeType":"contains","source":2356,"target":2358},{"edgeType":"imports","source":3050,"target":996},{"edgeType":"contains","source":341,"target":343},{"edgeType":"calls","source":3362,"target":1370},{"edgeType":"calls","source":4728,"target":249},{"edgeType":"calls","source":4619,"target":457},{"edgeType":"contains","source":1529,"target":1569},{"edgeType":"calls","source":4046,"target":249},{"edgeType":"calls","source":3929,"target":705},{"edgeType":"calls","source":641,"target":100},{"edgeType":"calls","source":2746,"target":382},{"edgeType":"calls","source":587,"target":717},{"edgeType":"calls","source":2701,"target":720},{"edgeType":"calls","source":529,"target":401},{"edgeType":"calls","source":561,"target":466},{"edgeType":"calls","source":501,"target":212},{"edgeType":"calls","source":864,"target":585},{"edgeType":"contains","source":2647,"target":2851},{"edgeType":"calls","source":2846,"target":454},{"edgeType":"contains","source":4569,"target":4576},{"edgeType":"calls","source":3121,"target":385},{"edgeType":"contains","source":341,"target":342},{"edgeType":"contains","source":2356,"target":2359},{"edgeType":"contains","source":2353,"target":2452},{"edgeType":"calls","source":3290,"target":1489},{"edgeType":"calls","source":2602,"target":619},{"edgeType":"calls","source":4728,"target":248},{"edgeType":"calls","source":1109,"target":389},{"edgeType":"imports","source":4045,"target":799},{"edgeType":"contains","source":3573,"target":3741},{"edgeType":"calls","source":4654,"target":4656},{"edgeType":"calls","source":3837,"target":387},{"edgeType":"calls","source":641,"target":99},{"edgeType":"calls","source":2746,"target":383},{"edgeType":"calls","source":561,"target":465},{"edgeType":"calls","source":4619,"target":456},{"edgeType":"calls","source":587,"target":716},{"edgeType":"calls","source":4347,"target":1489},{"edgeType":"calls","source":501,"target":211},{"edgeType":"imports","source":2259,"target":2260},{"edgeType":"calls","source":4295,"target":985},{"edgeType":"calls","source":3121,"target":382},{"edgeType":"calls","source":2983,"target":1489},{"edgeType":"calls","source":2977,"target":1675},{"edgeType":"contains","source":341,"target":345},{"edgeType":"calls","source":3837,"target":384},{"edgeType":"contains","source":4569,"target":4575},{"edgeType":"contains","source":396,"target":1811},{"edgeType":"contains","source":4404,"target":4405},{"edgeType":"calls","source":1183,"target":212},{"edgeType":"calls","source":4654,"target":4655},{"edgeType":"contains","source":2976,"target":3219},{"edgeType":"calls","source":587,"target":719},{"edgeType":"calls","source":641,"target":102},{"edgeType":"calls","source":561,"target":468},{"edgeType":"calls","source":534,"target":248},{"edgeType":"contains","source":3573,"target":3740},{"edgeType":"calls","source":2738,"target":2742},{"edgeType":"calls","source":2701,"target":718},{"edgeType":"calls","source":2333,"target":499},{"edgeType":"contains","source":1529,"target":1567},{"edgeType":"contains","source":1398,"target":1400},{"edgeType":"calls","source":1528,"target":87},{"edgeType":"contains","source":4103,"target":4221},{"edgeType":"calls","source":3837,"target":385},{"edgeType":"calls","source":3121,"target":383},{"edgeType":"contains","source":2356,"target":2357},{"edgeType":"contains","source":2353,"target":2450},{"edgeType":"calls","source":4722,"target":1489},{"edgeType":"calls","source":1183,"target":211},{"edgeType":"calls","source":4046,"target":248},{"edgeType":"extends","source":1213,"target":1104},{"edgeType":"calls","source":4135,"target":1717},{"edgeType":"calls","source":561,"target":467},{"edgeType":"calls","source":2701,"target":719},{"edgeType":"calls","source":641,"target":101},{"edgeType":"calls","source":587,"target":718},{"edgeType":"calls","source":529,"target":402},{"edgeType":"contains","source":1529,"target":1568},{"edgeType":"calls","source":4547,"target":572},{"edgeType":"contains","source":3413,"target":3414},{"edgeType":"calls","source":4296,"target":985},{"edgeType":"contains","source":2417,"target":3609},{"edgeType":"contains","source":3699,"target":4035},{"edgeType":"imports","source":4001,"target":35},{"edgeType":"contains","source":2285,"target":2416},{"edgeType":"contains","source":16,"target":2989},{"edgeType":"contains","source":2223,"target":2224},{"edgeType":"contains","source":934,"target":957},{"edgeType":"calls","source":4213,"target":386},{"edgeType":"calls","source":4151,"target":194},{"edgeType":"calls","source":4876,"target":2032},{"edgeType":"calls","source":2885,"target":330},{"edgeType":"contains","source":4865,"target":4885},{"edgeType":"calls","source":3909,"target":298},{"edgeType":"calls","source":3401,"target":191},{"edgeType":"contains","source":2803,"target":3271},{"edgeType":"contains","source":3699,"target":4034},{"edgeType":"calls","source":4000,"target":648},{"edgeType":"calls","source":4136,"target":1717},{"edgeType":"calls","source":4895,"target":2499},{"edgeType":"calls","source":4213,"target":387},{"edgeType":"contains","source":4865,"target":4884},{"edgeType":"imports","source":4001,"target":1094},{"edgeType":"calls","source":789,"target":828},{"edgeType":"extends","source":2899,"target":2716},{"edgeType":"contains","source":320,"target":967},{"edgeType":"imports","source":396,"target":798},{"edgeType":"contains","source":1485,"target":1845},{"edgeType":"calls","source":4213,"target":384},{"edgeType":"calls","source":1967,"target":249},{"edgeType":"contains","source":3573,"target":3711},{"edgeType":"contains","source":1009,"target":748},{"edgeType":"contains","source":1364,"target":1368},{"edgeType":"contains","source":4865,"target":4883},{"edgeType":"calls","source":2814,"target":415},{"edgeType":"calls","source":789,"target":827},{"edgeType":"calls","source":1321,"target":191},{"edgeType":"calls","source":4833,"target":191},{"edgeType":"calls","source":1967,"target":248},{"edgeType":"calls","source":4213,"target":385},{"edgeType":"contains","source":3699,"target":4032},{"edgeType":"calls","source":4222,"target":106},{"edgeType":"contains","source":1364,"target":1369},{"edgeType":"contains","source":4865,"target":4882},{"edgeType":"contains","source":3493,"target":905},{"edgeType":"calls","source":2429,"target":724},{"edgeType":"calls","source":625,"target":626},{"edgeType":"calls","source":4860,"target":411},{"edgeType":"calls","source":3810,"target":191},{"edgeType":"calls","source":4543,"target":723},{"edgeType":"calls","source":4313,"target":454},{"edgeType":"calls","source":1913,"target":1917},{"edgeType":"imports","source":4001,"target":39},{"edgeType":"contains","source":3517,"target":2282},{"edgeType":"contains","source":4865,"target":4889},{"edgeType":"calls","source":2673,"target":556},{"edgeType":"calls","source":4213,"target":382},{"edgeType":"contains","source":1529,"target":1544},{"edgeType":"contains","source":3038,"target":3388},{"edgeType":"contains","source":1009,"target":750},{"edgeType":"imports","source":4001,"target":40},{"edgeType":"calls","source":4543,"target":722},{"edgeType":"contains","source":3038,"target":3390},{"edgeType":"calls","source":3862,"target":3865},{"edgeType":"contains","source":1529,"target":1545},{"edgeType":"imports","source":396,"target":797},{"edgeType":"calls","source":4213,"target":383},{"edgeType":"contains","source":3038,"target":3389},{"edgeType":"contains","source":1009,"target":749},{"edgeType":"contains","source":4865,"target":4888},{"edgeType":"imports","source":4001,"target":41},{"edgeType":"imports","source":44,"target":78},{"edgeType":"calls","source":966,"target":622},{"edgeType":"contains","source":320,"target":971},{"edgeType":"calls","source":4370,"target":1856},{"edgeType":"calls","source":2494,"target":817},{"edgeType":"contains","source":3699,"target":4037},{"edgeType":"calls","source":4280,"target":417},{"edgeType":"calls","source":3619,"target":824},{"edgeType":"contains","source":934,"target":963},{"edgeType":"contains","source":603,"target":654},{"edgeType":"calls","source":4725,"target":365},{"edgeType":"contains","source":868,"target":895},{"edgeType":"contains","source":4865,"target":4887},{"edgeType":"calls","source":4450,"target":1489},{"edgeType":"calls","source":4543,"target":720},{"edgeType":"calls","source":1528,"target":1169},{"edgeType":"calls","source":1694,"target":1308},{"edgeType":"contains","source":43,"target":44},{"edgeType":"contains","source":3038,"target":3387},{"edgeType":"calls","source":4668,"target":4245},{"edgeType":"calls","source":4709,"target":1917},{"edgeType":"contains","source":1009,"target":751},{"edgeType":"contains","source":4865,"target":4886},{"edgeType":"contains","source":320,"target":973},{"edgeType":"contains","source":1001,"target":1003},{"edgeType":"calls","source":4543,"target":719},{"edgeType":"contains","source":1529,"target":1548},{"edgeType":"calls","source":2235,"target":388},{"edgeType":"imports","source":44,"target":93},{"edgeType":"calls","source":4844,"target":902},{"edgeType":"calls","source":1528,"target":106},{"edgeType":"contains","source":4865,"target":4893},{"edgeType":"contains","source":868,"target":897},{"edgeType":"contains","source":862,"target":1083},{"edgeType":"calls","source":847,"target":77},{"edgeType":"calls","source":3387,"target":1672},{"edgeType":"contains","source":603,"target":656},{"edgeType":"calls","source":1002,"target":557},{"edgeType":"calls","source":3292,"target":389},{"edgeType":"contains","source":2417,"target":3617},{"edgeType":"contains","source":320,"target":972},{"edgeType":"contains","source":1001,"target":1002},{"edgeType":"calls","source":2551,"target":106},{"edgeType":"calls","source":2541,"target":416},{"edgeType":"contains","source":3115,"target":3121},{"edgeType":"calls","source":4543,"target":718},{"edgeType":"calls","source":4676,"target":1880},{"edgeType":"contains","source":1485,"target":1856},{"edgeType":"calls","source":2235,"target":389},{"edgeType":"contains","source":1529,"target":1549},{"edgeType":"contains","source":4865,"target":4892},{"edgeType":"calls","source":4844,"target":901},{"edgeType":"extends","source":2299,"target":2301},{"edgeType":"contains","source":868,"target":896},{"edgeType":"contains","source":862,"target":1082},{"edgeType":"contains","source":4535,"target":4552},{"edgeType":"contains","source":603,"target":655},{"edgeType":"calls","source":3912,"target":194},{"edgeType":"calls","source":4543,"target":717},{"edgeType":"contains","source":862,"target":1086},{"edgeType":"contains","source":934,"target":968},{"edgeType":"contains","source":1001,"target":1005},{"edgeType":"contains","source":1529,"target":1546},{"edgeType":"imports","source":44,"target":90},{"edgeType":"calls","source":2235,"target":386},{"edgeType":"imports","source":44,"target":91},{"edgeType":"contains","source":4865,"target":4891},{"edgeType":"calls","source":4844,"target":900},{"edgeType":"calls","source":4819,"target":1675},{"edgeType":"contains","source":862,"target":1085},{"edgeType":"calls","source":3292,"target":387},{"edgeType":"contains","source":1001,"target":1004},{"edgeType":"calls","source":1764,"target":191},{"edgeType":"calls","source":2494,"target":814},{"edgeType":"contains","source":320,"target":974},{"edgeType":"calls","source":2480,"target":191},{"edgeType":"contains","source":3115,"target":3119},{"edgeType":"contains","source":1529,"target":1547},{"edgeType":"calls","source":4543,"target":716},{"edgeType":"calls","source":2235,"target":387},{"edgeType":"contains","source":4865,"target":4890},{"edgeType":"imports","source":44,"target":92},{"edgeType":"calls","source":3677,"target":2194},{"edgeType":"contains","source":862,"target":1084},{"edgeType":"calls","source":3292,"target":388},{"edgeType":"calls","source":1153,"target":1162},{"edgeType":"calls","source":1002,"target":558},{"edgeType":"contains","source":603,"target":657},{"edgeType":"calls","source":3292,"target":385},{"edgeType":"contains","source":3643,"target":3669},{"edgeType":"contains","source":2884,"target":2886},{"edgeType":"contains","source":1001,"target":1007},{"edgeType":"calls","source":1762,"target":248},{"edgeType":"contains","source":3002,"target":285},{"edgeType":"contains","source":3699,"target":4047},{"edgeType":"calls","source":2774,"target":587},{"edgeType":"calls","source":4543,"target":715},{"edgeType":"contains","source":1529,"target":1552},{"edgeType":"calls","source":359,"target":402},{"edgeType":"contains","source":2646,"target":2864},{"edgeType":"calls","source":2194,"target":1655},{"edgeType":"calls","source":2235,"target":384},{"edgeType":"calls","source":2985,"target":389},{"edgeType":"calls","source":2859,"target":1124},{"edgeType":"contains","source":4535,"target":4557},{"edgeType":"calls","source":3161,"target":1275},{"edgeType":"contains","source":320,"target":977},{"edgeType":"calls","source":4709,"target":1910},{"edgeType":"contains","source":1529,"target":1553},{"edgeType":"contains","source":1001,"target":1006},{"edgeType":"calls","source":4518,"target":1489},{"edgeType":"calls","source":4543,"target":714},{"edgeType":"calls","source":359,"target":401},{"edgeType":"calls","source":2244,"target":106},{"edgeType":"calls","source":2235,"target":385},{"edgeType":"calls","source":4495,"target":88},{"edgeType":"imports","source":830,"target":35},{"edgeType":"calls","source":4320,"target":1285},{"edgeType":"contains","source":603,"target":659},{"edgeType":"contains","source":2646,"target":2865},{"edgeType":"contains","source":4535,"target":4556},{"edgeType":"calls","source":1347,"target":427},{"edgeType":"contains","source":3,"target":3404},{"edgeType":"contains","source":320,"target":976},{"edgeType":"calls","source":3292,"target":386},{"edgeType":"contains","source":3115,"target":1008},{"edgeType":"calls","source":394,"target":376},{"edgeType":"calls","source":3360,"target":389},{"edgeType":"calls","source":3292,"target":383},{"edgeType":"contains","source":803,"target":805},{"edgeType":"calls","source":1735,"target":30},{"edgeType":"calls","source":1904,"target":1133},{"edgeType":"calls","source":4543,"target":713},{"edgeType":"calls","source":2847,"target":436},{"edgeType":"calls","source":505,"target":106},{"edgeType":"imports","source":2021,"target":1165},{"edgeType":"contains","source":1529,"target":1550},{"edgeType":"calls","source":2542,"target":378},{"edgeType":"calls","source":3661,"target":571},{"edgeType":"contains","source":2646,"target":2862},{"edgeType":"calls","source":2235,"target":382},{"edgeType":"calls","source":2847,"target":437},{"edgeType":"calls","source":705,"target":249},{"edgeType":"calls","source":2985,"target":387},{"edgeType":"calls","source":1695,"target":212},{"edgeType":"calls","source":3342,"target":3061},{"edgeType":"contains","source":320,"target":979},{"edgeType":"calls","source":3489,"target":1675},{"edgeType":"calls","source":3292,"target":384},{"edgeType":"contains","source":2285,"target":2427},{"edgeType":"calls","source":1153,"target":1158},{"edgeType":"contains","source":3699,"target":4044},{"edgeType":"calls","source":1736,"target":1055},{"edgeType":"calls","source":1762,"target":249},{"edgeType":"contains","source":862,"target":1089},{"edgeType":"contains","source":803,"target":804},{"edgeType":"contains","source":2884,"target":2885},{"edgeType":"contains","source":1529,"target":1551},{"edgeType":"calls","source":4628,"target":191},{"edgeType":"calls","source":4543,"target":712},{"edgeType":"calls","source":359,"target":403},{"edgeType":"calls","source":2235,"target":383},{"edgeType":"calls","source":3661,"target":572},{"edgeType":"contains","source":2646,"target":2863},{"edgeType":"calls","source":2847,"target":438},{"edgeType":"calls","source":705,"target":248},{"edgeType":"calls","source":2985,"target":388},{"edgeType":"calls","source":1695,"target":211},{"edgeType":"calls","source":986,"target":1050},{"edgeType":"calls","source":3161,"target":1274},{"edgeType":"calls","source":4696,"target":3334},{"edgeType":"contains","source":868,"target":873},{"edgeType":"calls","source":1251,"target":1253},{"edgeType":"calls","source":3353,"target":571},{"edgeType":"contains","source":4234,"target":4346},{"edgeType":"calls","source":1071,"target":491},{"edgeType":"calls","source":2847,"target":401},{"edgeType":"contains","source":1123,"target":1424},{"edgeType":"contains","source":4865,"target":4869},{"edgeType":"calls","source":4549,"target":492},{"edgeType":"contains","source":1148,"target":1706},{"edgeType":"calls","source":4670,"target":969},{"edgeType":"contains","source":3907,"target":3913},{"edgeType":"calls","source":2984,"target":383},{"edgeType":"calls","source":2978,"target":569},{"edgeType":"contains","source":4600,"target":4627},{"edgeType":"contains","source":320,"target":948},{"edgeType":"contains","source":3699,"target":4019},{"edgeType":"contains","source":2420,"target":2442},{"edgeType":"calls","source":3564,"target":3543},{"edgeType":"contains","source":2285,"target":2399},{"edgeType":"imports","source":2276,"target":1763},{"edgeType":"calls","source":3353,"target":572},{"edgeType":"calls","source":4050,"target":106},{"edgeType":"calls","source":1339,"target":638},{"edgeType":"calls","source":4112,"target":298},{"edgeType":"calls","source":2847,"target":402},{"edgeType":"calls","source":4250,"target":248},{"edgeType":"calls","source":4585,"target":1489},{"edgeType":"calls","source":2869,"target":777},{"edgeType":"calls","source":2804,"target":2792},{"edgeType":"contains","source":4865,"target":4868},{"edgeType":"contains","source":3345,"target":3364},{"edgeType":"calls","source":4549,"target":491},{"edgeType":"contains","source":1123,"target":1423},{"edgeType":"contains","source":3038,"target":3369},{"edgeType":"calls","source":2984,"target":384},{"edgeType":"calls","source":2978,"target":570},{"edgeType":"calls","source":2231,"target":472},{"edgeType":"contains","source":4600,"target":4626},{"edgeType":"contains","source":3775,"target":3776},{"edgeType":"contains","source":6,"target":3282},{"edgeType":"contains","source":2285,"target":2400},{"edgeType":"contains","source":320,"target":947},{"edgeType":"calls","source":1775,"target":863},{"edgeType":"imports","source":4009,"target":1952},{"edgeType":"contains","source":868,"target":875},{"edgeType":"calls","source":1071,"target":493},{"edgeType":"calls","source":3315,"target":690},{"edgeType":"calls","source":3353,"target":569},{"edgeType":"contains","source":4865,"target":4867},{"edgeType":"calls","source":4593,"target":183},{"edgeType":"calls","source":772,"target":248},{"edgeType":"calls","source":2978,"target":566},{"edgeType":"contains","source":1148,"target":1708},{"edgeType":"contains","source":3907,"target":3911},{"edgeType":"calls","source":4549,"target":490},{"edgeType":"contains","source":4600,"target":4625},{"edgeType":"contains","source":2420,"target":2440},{"edgeType":"calls","source":3564,"target":3541},{"edgeType":"calls","source":1691,"target":299},{"edgeType":"contains","source":6,"target":3285},{"edgeType":"contains","source":2285,"target":2397},{"edgeType":"contains","source":868,"target":874},{"edgeType":"calls","source":3353,"target":570},{"edgeType":"calls","source":1071,"target":492},{"edgeType":"contains","source":4865,"target":4866},{"edgeType":"calls","source":2978,"target":567},{"edgeType":"contains","source":3038,"target":3367},{"edgeType":"calls","source":4785,"target":572},{"edgeType":"calls","source":4776,"target":1908},{"edgeType":"contains","source":1148,"target":1707},{"edgeType":"calls","source":2333,"target":479},{"edgeType":"calls","source":4549,"target":489},{"edgeType":"calls","source":2984,"target":382},{"edgeType":"calls","source":2978,"target":568},{"edgeType":"contains","source":3907,"target":3910},{"edgeType":"contains","source":4600,"target":4624},{"edgeType":"calls","source":4224,"target":4222},{"edgeType":"contains","source":320,"target":949},{"edgeType":"contains","source":2420,"target":2441},{"edgeType":"calls","source":3544,"target":991},{"edgeType":"calls","source":3564,"target":3542},{"edgeType":"contains","source":6,"target":3284},{"edgeType":"contains","source":4302,"target":4349},{"edgeType":"contains","source":2285,"target":2398},{"edgeType":"contains","source":4865,"target":4873},{"edgeType":"calls","source":640,"target":106},{"edgeType":"calls","source":1347,"target":387},{"edgeType":"calls","source":3353,"target":567},{"edgeType":"imports","source":4376,"target":91},{"edgeType":"calls","source":3268,"target":1088},{"edgeType":"calls","source":4613,"target":1675},{"edgeType":"contains","source":868,"target":877},{"edgeType":"calls","source":4785,"target":571},{"edgeType":"calls","source":4800,"target":106},{"edgeType":"calls","source":1077,"target":301},{"edgeType":"calls","source":2851,"target":1330},{"edgeType":"calls","source":986,"target":1008},{"edgeType":"calls","source":4549,"target":488},{"edgeType":"contains","source":1148,"target":1710},{"edgeType":"calls","source":4496,"target":4245},{"edgeType":"calls","source":4588,"target":336},{"edgeType":"contains","source":2420,"target":2446},{"edgeType":"calls","source":1809,"target":863},{"edgeType":"contains","source":3699,"target":4023},{"edgeType":"calls","source":4034,"target":1653},{"edgeType":"calls","source":1347,"target":386},{"edgeType":"calls","source":1284,"target":1282},{"edgeType":"calls","source":774,"target":179},{"edgeType":"calls","source":1489,"target":212},{"edgeType":"calls","source":3353,"target":568},{"edgeType":"calls","source":3548,"target":865},{"edgeType":"contains","source":637,"target":638},{"edgeType":"extends","source":3027,"target":3033},{"edgeType":"contains","source":3115,"target":986},{"edgeType":"calls","source":4785,"target":570},{"edgeType":"contains","source":868,"target":876},{"edgeType":"contains","source":4865,"target":4872},{"edgeType":"calls","source":4549,"target":487},{"edgeType":"contains","source":1148,"target":1709},{"edgeType":"imports","source":4001,"target":90},{"edgeType":"contains","source":1648,"target":2068},{"edgeType":"contains","source":11,"target":2074},{"edgeType":"contains","source":3907,"target":3916},{"edgeType":"calls","source":4047,"target":194},{"edgeType":"calls","source":641,"target":77},{"edgeType":"calls","source":1347,"target":389},{"edgeType":"contains","source":2685,"target":2686},{"edgeType":"contains","source":3038,"target":3370},{"edgeType":"calls","source":4785,"target":569},{"edgeType":"imports","source":4001,"target":91},{"edgeType":"contains","source":1148,"target":1712},{"edgeType":"contains","source":2420,"target":2444},{"edgeType":"calls","source":4549,"target":486},{"edgeType":"contains","source":1654,"target":1879},{"edgeType":"calls","source":4081,"target":194},{"edgeType":"contains","source":3907,"target":3915},{"edgeType":"calls","source":1347,"target":388},{"edgeType":"contains","source":3038,"target":3371},{"edgeType":"calls","source":4785,"target":568},{"edgeType":"contains","source":3345,"target":3366},{"edgeType":"calls","source":3353,"target":566},{"edgeType":"contains","source":868,"target":878},{"edgeType":"contains","source":3907,"target":3914},{"edgeType":"contains","source":4600,"target":4628},{"edgeType":"contains","source":1148,"target":1711},{"edgeType":"calls","source":4549,"target":485},{"edgeType":"calls","source":4530,"target":4245},{"edgeType":"calls","source":4630,"target":88},{"edgeType":"contains","source":4865,"target":4877},{"edgeType":"calls","source":1285,"target":191},{"edgeType":"contains","source":868,"target":881},{"edgeType":"calls","source":3390,"target":473},{"edgeType":"calls","source":4785,"target":567},{"edgeType":"calls","source":1347,"target":383},{"edgeType":"calls","source":3209,"target":1856},{"edgeType":"calls","source":3213,"target":675},{"edgeType":"contains","source":1009,"target":738},{"edgeType":"contains","source":3699,"target":4027},{"edgeType":"contains","source":2285,"target":2407},{"edgeType":"calls","source":3999,"target":1677},{"edgeType":"calls","source":1528,"target":1113},{"edgeType":"contains","source":4865,"target":4876},{"edgeType":"calls","source":4874,"target":2035},{"edgeType":"contains","source":868,"target":880},{"edgeType":"calls","source":3390,"target":474},{"edgeType":"contains","source":4535,"target":4536},{"edgeType":"contains","source":603,"target":639},{"edgeType":"calls","source":1347,"target":382},{"edgeType":"calls","source":2475,"target":299},{"edgeType":"calls","source":4607,"target":1856},{"edgeType":"contains","source":2285,"target":2408},{"edgeType":"calls","source":4785,"target":566},{"edgeType":"calls","source":3740,"target":194},{"edgeType":"contains","source":3699,"target":4026},{"edgeType":"contains","source":4865,"target":4875},{"edgeType":"calls","source":1347,"target":385},{"edgeType":"contains","source":32,"target":373},{"edgeType":"imports","source":2259,"target":183},{"edgeType":"calls","source":1489,"target":211},{"edgeType":"calls","source":2602,"target":587},{"edgeType":"calls","source":458,"target":461},{"edgeType":"contains","source":934,"target":951},{"edgeType":"calls","source":4727,"target":249},{"edgeType":"calls","source":1967,"target":191},{"edgeType":"calls","source":2677,"target":376},{"edgeType":"calls","source":1883,"target":1738},{"edgeType":"calls","source":4123,"target":1002},{"edgeType":"contains","source":1648,"target":2069},{"edgeType":"calls","source":4422,"target":191},{"edgeType":"calls","source":2242,"target":2234},{"edgeType":"contains","source":4865,"target":4874},{"edgeType":"calls","source":2942,"target":1675},{"edgeType":"contains","source":16,"target":868},{"edgeType":"contains","source":2255,"target":2279},{"edgeType":"calls","source":3390,"target":472},{"edgeType":"contains","source":868,"target":882},{"edgeType":"calls","source":1347,"target":384},{"edgeType":"contains","source":2803,"target":3261},{"edgeType":"calls","source":4727,"target":248},{"edgeType":"calls","source":4785,"target":564},{"edgeType":"calls","source":2701,"target":690},{"edgeType":"calls","source":2683,"target":191},{"edgeType":"contains","source":4045,"target":1754},{"edgeType":"calls","source":4195,"target":1942},{"edgeType":"contains","source":3699,"target":4024},{"edgeType":"contains","source":2803,"target":3266},{"edgeType":"calls","source":1344,"target":472},{"edgeType":"contains","source":320,"target":961},{"edgeType":"calls","source":3497,"target":3494},{"edgeType":"calls","source":3276,"target":1888},{"edgeType":"contains","source":3573,"target":3709},{"edgeType":"contains","source":4865,"target":4881},{"edgeType":"calls","source":4134,"target":1716},{"edgeType":"calls","source":2282,"target":992},{"edgeType":"contains","source":1364,"target":1366},{"edgeType":"imports","source":1483,"target":2038},{"edgeType":"calls","source":3744,"target":66},{"edgeType":"contains","source":43,"target":1090},{"edgeType":"contains","source":4865,"target":4880},{"edgeType":"contains","source":373,"target":374},{"edgeType":"contains","source":395,"target":3920},{"edgeType":"contains","source":2285,"target":2413},{"edgeType":"calls","source":4716,"target":587},{"edgeType":"calls","source":4598,"target":4245},{"edgeType":"contains","source":2285,"target":2412},{"edgeType":"contains","source":3699,"target":4030},{"edgeType":"contains","source":3643,"target":3652},{"edgeType":"calls","source":4761,"target":249},{"edgeType":"calls","source":4721,"target":1489},{"edgeType":"calls","source":3994,"target":3943},{"edgeType":"contains","source":4865,"target":4879},{"edgeType":"contains","source":2803,"target":3264},{"edgeType":"calls","source":3941,"target":298},{"edgeType":"calls","source":1344,"target":474},{"edgeType":"calls","source":4761,"target":248},{"edgeType":"contains","source":3699,"target":4029},{"edgeType":"calls","source":451,"target":674},{"edgeType":"calls","source":1919,"target":1675},{"edgeType":"contains","source":1009,"target":744},{"edgeType":"calls","source":1965,"target":249},{"edgeType":"extends","source":1939,"target":1884},{"edgeType":"calls","source":2743,"target":1497},{"edgeType":"calls","source":2295,"target":587},{"edgeType":"calls","source":2294,"target":1675},{"edgeType":"calls","source":2300,"target":1489},{"edgeType":"contains","source":4865,"target":4878},{"edgeType":"imports","source":3710,"target":648},{"edgeType":"calls","source":1344,"target":473},{"edgeType":"calls","source":1754,"target":447},{"edgeType":"calls","source":2636,"target":587},{"edgeType":"calls","source":4831,"target":191},{"edgeType":"contains","source":2285,"target":2410},{"edgeType":"calls","source":1183,"target":1235},{"edgeType":"contains","source":3699,"target":4028},{"edgeType":"calls","source":3277,"target":1856},{"edgeType":"calls","source":1071,"target":479},{"edgeType":"calls","source":1965,"target":248},{"edgeType":"contains","source":1080,"target":1713},{"edgeType":"contains","source":1364,"target":1365},{"edgeType":"calls","source":2332,"target":498},{"edgeType":"calls","source":4858,"target":411},{"edgeType":"contains","source":4633,"target":4645},{"edgeType":"contains","source":2420,"target":2426},{"edgeType":"contains","source":2276,"target":3719},{"edgeType":"calls","source":3837,"target":382},{"edgeType":"contains","source":2285,"target":2383},{"edgeType":"calls","source":3352,"target":1675},{"edgeType":"contains","source":4376,"target":3099},{"edgeType":"calls","source":2850,"target":325},{"edgeType":"calls","source":1109,"target":386},{"edgeType":"calls","source":394,"target":354},{"edgeType":"calls","source":587,"target":713},{"edgeType":"calls","source":2689,"target":1088},{"edgeType":"calls","source":2701,"target":716},{"edgeType":"calls","source":4547,"target":571},{"edgeType":"extends","source":3332,"target":3071},{"edgeType":"calls","source":2837,"target":2843},{"edgeType":"contains","source":2647,"target":2789},{"edgeType":"contains","source":4633,"target":4644},{"edgeType":"calls","source":3837,"target":383},{"edgeType":"contains","source":2276,"target":3720},{"edgeType":"contains","source":2285,"target":2384},{"edgeType":"calls","source":1928,"target":365},{"edgeType":"contains","source":4302,"target":4335},{"edgeType":"calls","source":2637,"target":587},{"edgeType":"calls","source":587,"target":712},{"edgeType":"calls","source":4832,"target":191},{"edgeType":"imports","source":3710,"target":1691},{"edgeType":"calls","source":1109,"target":385},{"edgeType":"calls","source":394,"target":353},{"edgeType":"contains","source":3345,"target":3348},{"edgeType":"calls","source":2701,"target":717},{"edgeType":"calls","source":4547,"target":570},{"edgeType":"calls","source":4859,"target":411},{"edgeType":"calls","source":789,"target":792},{"edgeType":"calls","source":4547,"target":568},{"edgeType":"contains","source":4633,"target":4643},{"edgeType":"contains","source":2420,"target":2424},{"edgeType":"contains","source":2276,"target":3717},{"edgeType":"contains","source":4302,"target":4333},{"edgeType":"contains","source":2285,"target":2381},{"edgeType":"contains","source":3642,"target":3653},{"edgeType":"calls","source":2701,"target":714},{"edgeType":"contains","source":2285,"target":2380},{"edgeType":"calls","source":2036,"target":191},{"edgeType":"calls","source":1109,"target":388},{"edgeType":"calls","source":2882,"target":388},{"edgeType":"calls","source":4607,"target":1880},{"edgeType":"calls","source":587,"target":715},{"edgeType":"calls","source":4547,"target":569},{"edgeType":"contains","source":3345,"target":3347},{"edgeType":"calls","source":638,"target":191},{"edgeType":"calls","source":641,"target":98},{"edgeType":"calls","source":4756,"target":1489},{"edgeType":"calls","source":3011,"target":1675},{"edgeType":"calls","source":4547,"target":567},{"edgeType":"contains","source":2511,"target":2775},{"edgeType":"contains","source":4633,"target":4642},{"edgeType":"contains","source":2647,"target":2787},{"edgeType":"contains","source":2420,"target":2425},{"edgeType":"contains","source":2126,"target":2025},{"edgeType":"calls","source":3802,"target":3580},{"edgeType":"contains","source":2023,"target":2047},{"edgeType":"contains","source":2276,"target":3718},{"edgeType":"contains","source":207,"target":208},{"edgeType":"contains","source":4302,"target":4332},{"edgeType":"calls","source":3416,"target":747},{"edgeType":"calls","source":1871,"target":1077},{"edgeType":"calls","source":1109,"target":387},{"edgeType":"contains","source":3699,"target":3999},{"edgeType":"contains","source":1065,"target":1092},{"edgeType":"calls","source":2882,"target":389},{"edgeType":"calls","source":459,"target":454},{"edgeType":"contains","source":3345,"target":3346},{"edgeType":"calls","source":587,"target":714},{"edgeType":"calls","source":2701,"target":715},{"edgeType":"calls","source":2752,"target":191},{"edgeType":"calls","source":4547,"target":566},{"edgeType":"contains","source":1148,"target":1694},{"edgeType":"calls","source":3773,"target":248},{"edgeType":"calls","source":4615,"target":572},{"edgeType":"contains","source":320,"target":936},{"edgeType":"calls","source":2445,"target":191},{"edgeType":"calls","source":4369,"target":1856},{"edgeType":"contains","source":2276,"target":3723},{"edgeType":"contains","source":2285,"target":2387},{"edgeType":"imports","source":2126,"target":2165},{"edgeType":"calls","source":2202,"target":325},{"edgeType":"calls","source":3853,"target":1996},{"edgeType":"calls","source":3941,"target":325},{"edgeType":"calls","source":2786,"target":191},{"edgeType":"contains","source":44,"target":1036},{"edgeType":"calls","source":1307,"target":586},{"edgeType":"calls","source":2701,"target":712},{"edgeType":"calls","source":1428,"target":1063},{"edgeType":"calls","source":2543,"target":325},{"edgeType":"calls","source":1152,"target":106},{"edgeType":"calls","source":1071,"target":503},{"edgeType":"calls","source":1109,"target":382},{"edgeType":"calls","source":2882,"target":386},{"edgeType":"contains","source":1165,"target":1166},{"edgeType":"calls","source":3773,"target":249},{"edgeType":"contains","source":4600,"target":4614},{"edgeType":"imports","source":2126,"target":2164},{"edgeType":"calls","source":4615,"target":571},{"edgeType":"contains","source":603,"target":618},{"edgeType":"contains","source":2276,"target":3724},{"edgeType":"calls","source":4449,"target":1489},{"edgeType":"contains","source":2287,"target":2326},{"edgeType":"contains","source":2285,"target":2388},{"edgeType":"contains","source":4045,"target":1735},{"edgeType":"imports","source":4009,"target":1939},{"edgeType":"calls","source":2701,"target":713},{"edgeType":"calls","source":2677,"target":400},{"edgeType":"calls","source":1307,"target":585},{"edgeType":"contains","source":4302,"target":4339},{"edgeType":"calls","source":1512,"target":572},{"edgeType":"calls","source":2868,"target":1878},{"edgeType":"contains","source":3115,"target":969},{"edgeType":"calls","source":4784,"target":1675},{"edgeType":"calls","source":2971,"target":1856},{"edgeType":"calls","source":1071,"target":502},{"edgeType":"contains","source":1123,"target":1410},{"edgeType":"calls","source":986,"target":1023},{"edgeType":"calls","source":2882,"target":387},{"edgeType":"calls","source":2435,"target":499},{"edgeType":"contains","source":4633,"target":4647},{"edgeType":"contains","source":1148,"target":1696},{"edgeType":"calls","source":4615,"target":570},{"edgeType":"imports","source":4079,"target":1884},{"edgeType":"contains","source":2276,"target":3721},{"edgeType":"contains","source":2285,"target":2385},{"edgeType":"calls","source":4843,"target":902},{"edgeType":"contains","source":44,"target":1038},{"edgeType":"contains","source":43,"target":2126},{"edgeType":"contains","source":4302,"target":4338},{"edgeType":"calls","source":1109,"target":384},{"edgeType":"calls","source":2882,"target":384},{"edgeType":"calls","source":789,"target":791},{"edgeType":"calls","source":954,"target":960},{"edgeType":"contains","source":2511,"target":2779},{"edgeType":"contains","source":4633,"target":4646},{"edgeType":"contains","source":1123,"target":1413},{"edgeType":"calls","source":4615,"target":569},{"edgeType":"contains","source":2276,"target":3722},{"edgeType":"contains","source":44,"target":1037},{"edgeType":"calls","source":3502,"target":191},{"edgeType":"contains","source":4302,"target":4337},{"edgeType":"calls","source":4843,"target":901},{"edgeType":"calls","source":2677,"target":398},{"edgeType":"contains","source":3642,"target":3656},{"edgeType":"calls","source":3415,"target":774},{"edgeType":"calls","source":1493,"target":106},{"edgeType":"contains","source":603,"target":620},{"edgeType":"calls","source":1109,"target":383},{"edgeType":"contains","source":3345,"target":3350},{"edgeType":"contains","source":2716,"target":2766},{"edgeType":"calls","source":2882,"target":385},{"edgeType":"calls","source":4615,"target":568},{"edgeType":"contains","source":2420,"target":2434},{"edgeType":"contains","source":2285,"target":2391},{"edgeType":"contains","source":1165,"target":1171},{"edgeType":"extends","source":285,"target":287},{"edgeType":"contains","source":1148,"target":1698},{"edgeType":"contains","source":3038,"target":3360},{"edgeType":"calls","source":4607,"target":1873},{"edgeType":"calls","source":3676,"target":2194},{"edgeType":"calls","source":4065,"target":705},{"edgeType":"contains","source":1700,"target":1499},{"edgeType":"calls","source":2882,"target":382},{"edgeType":"calls","source":1512,"target":569},{"edgeType":"calls","source":4843,"target":900},{"edgeType":"contains","source":44,"target":1040},{"edgeType":"calls","source":3583,"target":1905},{"edgeType":"contains","source":4189,"target":2562},{"edgeType":"contains","source":2255,"target":2264},{"edgeType":"contains","source":4600,"target":4619},{"edgeType":"calls","source":4615,"target":567},{"edgeType":"calls","source":457,"target":505},{"edgeType":"contains","source":2285,"target":2392},{"edgeType":"calls","source":638,"target":179},{"edgeType":"calls","source":1512,"target":568},{"edgeType":"contains","source":44,"target":1039},{"edgeType":"contains","source":16,"target":850},{"edgeType":"calls","source":2882,"target":383},{"edgeType":"contains","source":3345,"target":3356},{"edgeType":"contains","source":4189,"target":2561},{"edgeType":"contains","source":2420,"target":2432},{"edgeType":"calls","source":4615,"target":566},{"edgeType":"calls","source":4593,"target":191},{"edgeType":"calls","source":4709,"target":1880},{"edgeType":"contains","source":934,"target":935},{"edgeType":"calls","source":4674,"target":1908},{"edgeType":"contains","source":2276,"target":3725},{"edgeType":"contains","source":1123,"target":1418},{"edgeType":"extends","source":1204,"target":340},{"edgeType":"contains","source":2285,"target":2389},{"edgeType":"contains","source":1165,"target":1173},{"edgeType":"calls","source":4437,"target":1856},{"edgeType":"contains","source":4045,"target":1738},{"edgeType":"calls","source":2984,"target":389},{"edgeType":"calls","source":3686,"target":824},{"edgeType":"calls","source":1512,"target":571},{"edgeType":"calls","source":3744,"target":83},{"edgeType":"calls","source":3526,"target":499},{"edgeType":"contains","source":4600,"target":4617},{"edgeType":"contains","source":320,"target":941},{"edgeType":"contains","source":2285,"target":2390},{"edgeType":"contains","source":1165,"target":1172},{"edgeType":"contains","source":1148,"target":1699},{"edgeType":"calls","source":4494,"target":88},{"edgeType":"calls","source":1512,"target":570},{"edgeType":"imports","source":2211,"target":1654},{"edgeType":"contains","source":3345,"target":3354},{"edgeType":"contains","source":868,"target":869},{"edgeType":"calls","source":1071,"target":495},{"edgeType":"calls","source":4078,"target":298},{"edgeType":"contains","source":1123,"target":1420},{"edgeType":"calls","source":330,"target":211},{"edgeType":"calls","source":4549,"target":496},{"edgeType":"contains","source":3573,"target":3692},{"edgeType":"calls","source":4357,"target":4334},{"edgeType":"calls","source":824,"target":753},{"edgeType":"extends","source":4813,"target":4738},{"edgeType":"calls","source":3737,"target":298},{"edgeType":"calls","source":725,"target":651},{"edgeType":"calls","source":2974,"target":1754},{"edgeType":"calls","source":2984,"target":387},{"edgeType":"contains","source":4600,"target":4623},{"edgeType":"imports","source":3643,"target":1649},{"edgeType":"calls","source":1445,"target":528},{"edgeType":"contains","source":320,"target":944},{"edgeType":"calls","source":3341,"target":3061},{"edgeType":"calls","source":4589,"target":4540},{"edgeType":"contains","source":2285,"target":2396},{"edgeType":"contains","source":320,"target":943},{"edgeType":"calls","source":1071,"target":494},{"edgeType":"calls","source":3945,"target":194},{"edgeType":"calls","source":4549,"target":495},{"edgeType":"calls","source":331,"target":179},{"edgeType":"contains","source":1165,"target":1174},{"edgeType":"contains","source":1123,"target":1419},{"edgeType":"calls","source":772,"target":249},{"edgeType":"calls","source":399,"target":185},{"edgeType":"calls","source":824,"target":752},{"edgeType":"calls","source":3695,"target":544},{"edgeType":"calls","source":2984,"target":388},{"edgeType":"contains","source":3907,"target":3908},{"edgeType":"calls","source":1152,"target":1157},{"edgeType":"calls","source":2783,"target":1330},{"edgeType":"calls","source":4250,"target":249},{"edgeType":"contains","source":1123,"target":1422},{"edgeType":"calls","source":4549,"target":494},{"edgeType":"calls","source":4591,"target":249},{"edgeType":"calls","source":758,"target":687},{"edgeType":"calls","source":774,"target":191},{"edgeType":"contains","source":2716,"target":2773},{"edgeType":"calls","source":2984,"target":385},{"edgeType":"calls","source":2978,"target":571},{"edgeType":"calls","source":1512,"target":567},{"edgeType":"contains","source":3345,"target":3359},{"edgeType":"calls","source":2231,"target":473},{"edgeType":"contains","source":4189,"target":2564},{"edgeType":"contains","source":4600,"target":4621},{"edgeType":"calls","source":1071,"target":496},{"edgeType":"calls","source":4591,"target":248},{"edgeType":"contains","source":1123,"target":1421},{"edgeType":"calls","source":2789,"target":88},{"edgeType":"calls","source":4357,"target":4331},{"edgeType":"calls","source":330,"target":212},{"edgeType":"calls","source":4549,"target":493},{"edgeType":"calls","source":2531,"target":687},{"edgeType":"calls","source":1512,"target":566},{"edgeType":"calls","source":3702,"target":325},{"edgeType":"contains","source":621,"target":1127},{"edgeType":"calls","source":2231,"target":474},{"edgeType":"contains","source":4189,"target":2563},{"edgeType":"calls","source":2984,"target":386},{"edgeType":"calls","source":2978,"target":572},{"edgeType":"contains","source":4600,"target":4620},{"edgeType":"calls","source":498,"target":383},{"edgeType":"contains","source":2976,"target":3143},{"edgeType":"contains","source":2948,"target":2954},{"edgeType":"calls","source":4790,"target":519},{"edgeType":"calls","source":1109,"target":469},{"edgeType":"calls","source":3966,"target":3865},{"edgeType":"calls","source":2776,"target":587},{"edgeType":"calls","source":2677,"target":485},{"edgeType":"calls","source":2678,"target":454},{"edgeType":"calls","source":2947,"target":572},{"edgeType":"calls","source":2861,"target":1124},{"edgeType":"contains","source":2715,"target":2777},{"edgeType":"calls","source":1765,"target":1273},{"edgeType":"contains","source":320,"target":915},{"edgeType":"calls","source":498,"target":382},{"edgeType":"contains","source":2948,"target":2955},{"edgeType":"calls","source":2643,"target":483},{"edgeType":"calls","source":1109,"target":468},{"edgeType":"extends","source":4856,"target":4499},{"edgeType":"calls","source":2677,"target":486},{"edgeType":"calls","source":2453,"target":1088},{"edgeType":"calls","source":4520,"target":1489},{"edgeType":"calls","source":2963,"target":77},{"edgeType":"calls","source":3828,"target":744},{"edgeType":"calls","source":1493,"target":191},{"edgeType":"contains","source":2229,"target":4103},{"edgeType":"extends","source":4120,"target":4060},{"edgeType":"contains","source":320,"target":914},{"edgeType":"calls","source":4081,"target":298},{"edgeType":"contains","source":2948,"target":2952},{"edgeType":"calls","source":3344,"target":3061},{"edgeType":"calls","source":3232,"target":191},{"edgeType":"calls","source":4815,"target":1856},{"edgeType":"calls","source":2544,"target":378},{"edgeType":"calls","source":498,"target":385},{"edgeType":"calls","source":2656,"target":77},{"edgeType":"contains","source":1260,"target":1371},{"edgeType":"calls","source":3740,"target":298},{"edgeType":"calls","source":64,"target":98},{"edgeType":"calls","source":2947,"target":570},{"edgeType":"contains","source":320,"target":917},{"edgeType":"calls","source":975,"target":397},{"edgeType":"contains","source":4302,"target":4317},{"edgeType":"calls","source":1109,"target":470},{"edgeType":"calls","source":1922,"target":1693},{"edgeType":"calls","source":641,"target":179},{"edgeType":"calls","source":4772,"target":4245},{"edgeType":"calls","source":498,"target":384},{"edgeType":"calls","source":2947,"target":571},{"edgeType":"contains","source":320,"target":916},{"edgeType":"contains","source":4203,"target":4214},{"edgeType":"contains","source":2072,"target":3683},{"edgeType":"extends","source":3527,"target":3421},{"edgeType":"calls","source":3454,"target":1763},{"edgeType":"contains","source":4302,"target":4323},{"edgeType":"calls","source":1308,"target":638},{"edgeType":"calls","source":1109,"target":465},{"edgeType":"calls","source":2947,"target":567},{"edgeType":"contains","source":2948,"target":2958},{"edgeType":"calls","source":1657,"target":389},{"edgeType":"contains","source":2511,"target":2763},{"edgeType":"imports","source":1918,"target":207},{"edgeType":"calls","source":296,"target":299},{"edgeType":"calls","source":3607,"target":191},{"edgeType":"contains","source":2201,"target":747},{"edgeType":"contains","source":4302,"target":4322},{"edgeType":"calls","source":2947,"target":568},{"edgeType":"calls","source":725,"target":740},{"edgeType":"contains","source":1065,"target":1078},{"edgeType":"calls","source":1657,"target":388},{"edgeType":"calls","source":1659,"target":326},{"edgeType":"calls","source":2947,"target":569},{"edgeType":"calls","source":3121,"target":460},{"edgeType":"calls","source":4293,"target":4294},{"edgeType":"calls","source":1844,"target":933},{"edgeType":"contains","source":2287,"target":2309},{"edgeType":"calls","source":1109,"target":467},{"edgeType":"calls","source":1152,"target":191},{"edgeType":"calls","source":1075,"target":464},{"edgeType":"calls","source":4673,"target":969},{"edgeType":"contains","source":2948,"target":2956},{"edgeType":"calls","source":4794,"target":389},{"edgeType":"calls","source":4806,"target":4245},{"edgeType":"contains","source":1065,"target":1081},{"edgeType":"contains","source":1148,"target":1679},{"edgeType":"imports","source":3484,"target":296},{"edgeType":"contains","source":4302,"target":4320},{"edgeType":"contains","source":603,"target":604},{"edgeType":"calls","source":1109,"target":466},{"edgeType":"contains","source":2948,"target":2957},{"edgeType":"calls","source":4794,"target":388},{"edgeType":"calls","source":2947,"target":566},{"edgeType":"calls","source":2838,"target":774},{"edgeType":"calls","source":4628,"target":249},{"edgeType":"calls","source":325,"target":458},{"edgeType":"calls","source":334,"target":179},{"edgeType":"calls","source":4323,"target":191},{"edgeType":"imports","source":2255,"target":1384},{"edgeType":"calls","source":3828,"target":738},{"edgeType":"calls","source":1394,"target":82},{"edgeType":"calls","source":2844,"target":585},{"edgeType":"contains","source":16,"target":2948},{"edgeType":"calls","source":3565,"target":1489},{"edgeType":"calls","source":4794,"target":387},{"edgeType":"contains","source":2511,"target":2768},{"edgeType":"calls","source":3089,"target":389},{"edgeType":"contains","source":4600,"target":4603},{"edgeType":"calls","source":324,"target":484},{"edgeType":"calls","source":3873,"target":397},{"edgeType":"contains","source":3162,"target":556},{"edgeType":"calls","source":1657,"target":385},{"edgeType":"calls","source":4628,"target":248},{"edgeType":"contains","source":2285,"target":2374},{"edgeType":"calls","source":504,"target":189},{"edgeType":"extends","source":1940,"target":1884},{"edgeType":"calls","source":1856,"target":558},{"edgeType":"contains","source":3642,"target":3647},{"edgeType":"calls","source":2046,"target":2067},{"edgeType":"contains","source":2023,"target":2041},{"edgeType":"calls","source":591,"target":662},{"edgeType":"calls","source":1250,"target":1374},{"edgeType":"calls","source":1267,"target":847},{"edgeType":"calls","source":4794,"target":386},{"edgeType":"calls","source":1325,"target":106},{"edgeType":"calls","source":2844,"target":586},{"edgeType":"contains","source":2511,"target":2769},{"edgeType":"calls","source":2915,"target":499},{"edgeType":"contains","source":4600,"target":4602},{"edgeType":"calls","source":1856,"target":557},{"edgeType":"calls","source":1657,"target":384},{"edgeType":"calls","source":538,"target":191},{"edgeType":"calls","source":3559,"target":2733},{"edgeType":"contains","source":3642,"target":3646},{"edgeType":"calls","source":3519,"target":1856},{"edgeType":"calls","source":2780,"target":453},{"edgeType":"contains","source":4302,"target":4325},{"edgeType":"calls","source":3709,"target":194},{"edgeType":"contains","source":2976,"target":3149},{"edgeType":"calls","source":4794,"target":385},{"edgeType":"calls","source":3089,"target":387},{"edgeType":"contains","source":4600,"target":4601},{"edgeType":"calls","source":1657,"target":387},{"edgeType":"calls","source":1659,"target":325},{"edgeType":"calls","source":3837,"target":454},{"edgeType":"contains","source":1123,"target":1401},{"edgeType":"calls","source":4616,"target":1675},{"edgeType":"calls","source":4622,"target":1489},{"edgeType":"calls","source":1902,"target":191},{"edgeType":"calls","source":2245,"target":2240},{"edgeType":"calls","source":1882,"target":1868},{"edgeType":"imports","source":97,"target":645},{"edgeType":"contains","source":4302,"target":4324},{"edgeType":"calls","source":4794,"target":384},{"edgeType":"calls","source":3089,"target":388},{"edgeType":"contains","source":4633,"target":4634},{"edgeType":"contains","source":320,"target":924},{"edgeType":"calls","source":2476,"target":365},{"edgeType":"calls","source":2452,"target":1109},{"edgeType":"calls","source":2544,"target":371},{"edgeType":"calls","source":1657,"target":386},{"edgeType":"extends","source":1215,"target":1104},{"edgeType":"contains","source":2287,"target":2311},{"edgeType":"contains","source":3642,"target":3644},{"edgeType":"calls","source":4050,"target":194},{"edgeType":"calls","source":4321,"target":249},{"edgeType":"calls","source":2807,"target":2785},{"edgeType":"contains","source":4633,"target":4641},{"edgeType":"contains","source":4045,"target":1728},{"edgeType":"contains","source":2023,"target":2044},{"edgeType":"contains","source":2511,"target":2772},{"edgeType":"calls","source":3464,"target":388},{"edgeType":"calls","source":3089,"target":385},{"edgeType":"contains","source":4402,"target":4403},{"edgeType":"contains","source":2420,"target":2422},{"edgeType":"contains","source":3642,"target":3651},{"edgeType":"contains","source":2287,"target":2316},{"edgeType":"contains","source":2285,"target":2378},{"edgeType":"calls","source":2486,"target":1109},{"edgeType":"contains","source":1065,"target":1087},{"edgeType":"calls","source":1886,"target":1738},{"edgeType":"calls","source":4732,"target":191},{"edgeType":"calls","source":2652,"target":191},{"edgeType":"calls","source":1970,"target":191},{"edgeType":"contains","source":2976,"target":3155},{"edgeType":"calls","source":4794,"target":383},{"edgeType":"contains","source":1123,"target":1403},{"edgeType":"calls","source":4321,"target":248},{"edgeType":"calls","source":1493,"target":179},{"edgeType":"calls","source":3089,"target":386},{"edgeType":"calls","source":1719,"target":572},{"edgeType":"contains","source":4600,"target":4606},{"edgeType":"calls","source":3464,"target":389},{"edgeType":"contains","source":4633,"target":4640},{"edgeType":"calls","source":1629,"target":191},{"edgeType":"contains","source":2420,"target":2423},{"edgeType":"calls","source":3257,"target":464},{"edgeType":"contains","source":2276,"target":3716},{"edgeType":"calls","source":3837,"target":3624},{"edgeType":"contains","source":2285,"target":2379},{"edgeType":"calls","source":4557,"target":4558},{"edgeType":"contains","source":3642,"target":3650},{"edgeType":"calls","source":1152,"target":179},{"edgeType":"contains","source":1123,"target":1402},{"edgeType":"calls","source":4794,"target":382},{"edgeType":"contains","source":3444,"target":3446},{"edgeType":"calls","source":325,"target":448},{"edgeType":"contains","source":2023,"target":2042},{"edgeType":"contains","source":2072,"target":3694},{"edgeType":"calls","source":3464,"target":386},{"edgeType":"calls","source":3089,"target":383},{"edgeType":"contains","source":4600,"target":4605},{"edgeType":"contains","source":4633,"target":4639},{"edgeType":"contains","source":612,"target":3505},{"edgeType":"contains","source":2647,"target":2782},{"edgeType":"calls","source":3315,"target":777},{"edgeType":"contains","source":2285,"target":2376},{"edgeType":"calls","source":1657,"target":383},{"edgeType":"calls","source":196,"target":222},{"edgeType":"contains","source":3642,"target":3649},{"edgeType":"contains","source":3444,"target":3445},{"edgeType":"contains","source":2647,"target":2783},{"edgeType":"calls","source":4877,"target":2035},{"edgeType":"contains","source":2023,"target":2043},{"edgeType":"calls","source":3089,"target":384},{"edgeType":"contains","source":2511,"target":2771},{"edgeType":"contains","source":4600,"target":4604},{"edgeType":"calls","source":1657,"target":382},{"edgeType":"calls","source":3464,"target":387},{"edgeType":"contains","source":320,"target":929},{"edgeType":"calls","source":1287,"target":1282},{"edgeType":"calls","source":2571,"target":587},{"edgeType":"calls","source":461,"target":462},{"edgeType":"calls","source":4557,"target":4556},{"edgeType":"calls","source":1754,"target":546},{"edgeType":"calls","source":587,"target":784},{"edgeType":"calls","source":4155,"target":106},{"edgeType":"contains","source":3642,"target":3648},{"edgeType":"calls","source":4322,"target":1302},{"edgeType":"calls","source":4195,"target":4182},{"edgeType":"calls","source":3680,"target":2177},{"edgeType":"contains","source":1757,"target":1805},{"edgeType":"calls","source":1385,"target":386},{"edgeType":"calls","source":3124,"target":386},{"edgeType":"contains","source":2483,"target":2554},{"edgeType":"contains","source":2287,"target":2288},{"edgeType":"contains","source":4302,"target":4303},{"edgeType":"calls","source":3293,"target":1489},{"edgeType":"calls","source":4710,"target":902},{"edgeType":"calls","source":4651,"target":1674},{"edgeType":"calls","source":3996,"target":4008},{"edgeType":"calls","source":1941,"target":1119},{"edgeType":"calls","source":4426,"target":191},{"edgeType":"contains","source":1757,"target":1806},{"edgeType":"calls","source":1385,"target":385},{"edgeType":"calls","source":3124,"target":387},{"edgeType":"calls","source":1336,"target":847},{"edgeType":"calls","source":1651,"target":1652},{"edgeType":"contains","source":2287,"target":2289},{"edgeType":"calls","source":1528,"target":1237},{"edgeType":"contains","source":320,"target":898},{"edgeType":"calls","source":4710,"target":901},{"edgeType":"calls","source":1941,"target":1118},{"edgeType":"contains","source":799,"target":847},{"edgeType":"calls","source":4878,"target":2035},{"edgeType":"calls","source":4156,"target":106},{"edgeType":"calls","source":4724,"target":4695},{"edgeType":"calls","source":532,"target":402},{"edgeType":"calls","source":4393,"target":4386},{"edgeType":"contains","source":2647,"target":2753},{"edgeType":"calls","source":1498,"target":1113},{"edgeType":"calls","source":3744,"target":191},{"edgeType":"calls","source":4350,"target":1489},{"edgeType":"calls","source":3124,"target":384},{"edgeType":"calls","source":1385,"target":388},{"edgeType":"calls","source":4710,"target":900},{"edgeType":"calls","source":3239,"target":3161},{"edgeType":"imports","source":3643,"target":1688},{"edgeType":"calls","source":1152,"target":211},{"edgeType":"calls","source":1971,"target":191},{"edgeType":"calls","source":3996,"target":4006},{"edgeType":"calls","source":1887,"target":1738},{"edgeType":"contains","source":1757,"target":1803},{"edgeType":"calls","source":2436,"target":572},{"edgeType":"calls","source":573,"target":191},{"edgeType":"contains","source":3443,"target":3447},{"edgeType":"calls","source":2228,"target":1735},{"edgeType":"calls","source":824,"target":865},{"edgeType":"calls","source":3124,"target":385},{"edgeType":"contains","source":11,"target":2022},{"edgeType":"contains","source":2483,"target":2553},{"edgeType":"calls","source":1385,"target":387},{"edgeType":"calls","source":3620,"target":865},{"edgeType":"calls","source":456,"target":646},{"edgeType":"calls","source":1153,"target":179},{"edgeType":"calls","source":3996,"target":4007},{"edgeType":"contains","source":1757,"target":1804},{"edgeType":"imports","source":4001,"target":105},{"edgeType":"contains","source":395,"target":1749},{"edgeType":"calls","source":2436,"target":569},{"edgeType":"calls","source":3124,"target":382},{"edgeType":"calls","source":2262,"target":1735},{"edgeType":"calls","source":4298,"target":985},{"edgeType":"contains","source":4189,"target":2524},{"edgeType":"contains","source":206,"target":209},{"edgeType":"calls","source":3692,"target":744},{"edgeType":"contains","source":16,"target":2928},{"edgeType":"calls","source":3373,"target":1119},{"edgeType":"calls","source":3239,"target":3159},{"edgeType":"contains","source":4302,"target":4307},{"edgeType":"calls","source":1157,"target":1107},{"edgeType":"calls","source":1347,"target":502},{"edgeType":"contains","source":1295,"target":1333},{"edgeType":"calls","source":2436,"target":570},{"edgeType":"calls","source":4895,"target":2562},{"edgeType":"calls","source":641,"target":191},{"edgeType":"calls","source":3748,"target":66},{"edgeType":"calls","source":2985,"target":464},{"edgeType":"calls","source":3124,"target":383},{"edgeType":"extends","source":590,"target":373},{"edgeType":"contains","source":44,"target":1001},{"edgeType":"contains","source":6,"target":2179},{"edgeType":"contains","source":2033,"target":2767},{"edgeType":"contains","source":4203,"target":4204},{"edgeType":"calls","source":3239,"target":3160},{"edgeType":"contains","source":4302,"target":4306},{"edgeType":"calls","source":1289,"target":185},{"edgeType":"calls","source":1157,"target":1106},{"edgeType":"calls","source":2436,"target":571},{"edgeType":"calls","source":4897,"target":2499},{"edgeType":"calls","source":463,"target":423},{"edgeType":"contains","source":2647,"target":2760},{"edgeType":"contains","source":2483,"target":2556},{"edgeType":"calls","source":2512,"target":325},{"edgeType":"calls","source":2436,"target":567},{"edgeType":"calls","source":1385,"target":384},{"edgeType":"contains","source":2287,"target":2290},{"edgeType":"calls","source":1528,"target":179},{"edgeType":"calls","source":3945,"target":298},{"edgeType":"calls","source":1969,"target":249},{"edgeType":"calls","source":532,"target":401},{"edgeType":"calls","source":1941,"target":1117},{"edgeType":"contains","source":2221,"target":2222},{"edgeType":"contains","source":4302,"target":4305},{"edgeType":"calls","source":2677,"target":496},{"edgeType":"calls","source":4109,"target":499},{"edgeType":"calls","source":1888,"target":1703},{"edgeType":"calls","source":3373,"target":1117},{"edgeType":"extends","source":3493,"target":3400},{"edgeType":"calls","source":3355,"target":1675},{"edgeType":"calls","source":3361,"target":1489},{"edgeType":"calls","source":4661,"target":301},{"edgeType":"calls","source":296,"target":318},{"edgeType":"calls","source":2512,"target":326},{"edgeType":"calls","source":2436,"target":568},{"edgeType":"contains","source":2647,"target":2758},{"edgeType":"contains","source":2483,"target":2557},{"edgeType":"calls","source":4494,"target":191},{"edgeType":"calls","source":1385,"target":383},{"edgeType":"contains","source":2287,"target":2291},{"edgeType":"calls","source":3625,"target":1763},{"edgeType":"calls","source":4862,"target":411},{"edgeType":"imports","source":4234,"target":285},{"edgeType":"calls","source":1969,"target":248},{"edgeType":"calls","source":1385,"target":382},{"edgeType":"calls","source":1347,"target":503},{"edgeType":"calls","source":3373,"target":1118},{"edgeType":"calls","source":645,"target":68},{"edgeType":"contains","source":3162,"target":534},{"edgeType":"calls","source":325,"target":469},{"edgeType":"contains","source":320,"target":907},{"edgeType":"calls","source":1951,"target":1858},{"edgeType":"contains","source":3441,"target":3519},{"edgeType":"contains","source":2023,"target":2024},{"edgeType":"calls","source":2677,"target":494},{"edgeType":"calls","source":325,"target":468},{"edgeType":"contains","source":1065,"target":1066},{"edgeType":"calls","source":1629,"target":212},{"edgeType":"calls","source":2436,"target":566},{"edgeType":"calls","source":2677,"target":495},{"edgeType":"imports","source":2255,"target":325},{"edgeType":"calls","source":3419,"target":747},{"edgeType":"contains","source":4302,"target":4310},{"edgeType":"calls","source":4695,"target":301},{"edgeType":"calls","source":815,"target":77},{"edgeType":"calls","source":4754,"target":586},{"edgeType":"calls","source":4790,"target":527},{"edgeType":"calls","source":2985,"target":460},{"edgeType":"contains","source":320,"target":909},{"edgeType":"calls","source":4704,"target":1077},{"edgeType":"contains","source":2353,"target":2362},{"edgeType":"calls","source":4651,"target":606},{"edgeType":"calls","source":3692,"target":738},{"edgeType":"calls","source":4372,"target":1856},{"edgeType":"contains","source":2287,"target":2294},{"edgeType":"calls","source":64,"target":106},{"edgeType":"calls","source":4809,"target":2051},{"edgeType":"calls","source":4869,"target":191},{"edgeType":"contains","source":44,"target":1009},{"edgeType":"contains","source":4302,"target":4309},{"edgeType":"calls","source":2677,"target":492},{"edgeType":"calls","source":4754,"target":585},{"edgeType":"calls","source":3227,"target":354},{"edgeType":"contains","source":320,"target":908},{"edgeType":"contains","source":1065,"target":1068},{"edgeType":"calls","source":325,"target":470},{"edgeType":"calls","source":2546,"target":325},{"edgeType":"calls","source":4651,"target":605},{"edgeType":"calls","source":4446,"target":1675},{"edgeType":"calls","source":4452,"target":1489},{"edgeType":"calls","source":64,"target":105},{"edgeType":"calls","source":3448,"target":1960},{"edgeType":"contains","source":2033,"target":2770},{"edgeType":"contains","source":16,"target":819},{"edgeType":"calls","source":4880,"target":906},{"edgeType":"calls","source":2677,"target":493},{"edgeType":"contains","source":4302,"target":4308},{"edgeType":"extends","source":2301,"target":2303},{"edgeType":"calls","source":4758,"target":460},{"edgeType":"calls","source":4787,"target":1675},{"edgeType":"calls","source":4793,"target":1489},{"edgeType":"contains","source":320,"target":911},{"edgeType":"contains","source":2287,"target":2300},{"edgeType":"calls","source":3736,"target":3600},{"edgeType":"calls","source":2677,"target":489},{"edgeType":"calls","source":325,"target":465},{"edgeType":"calls","source":498,"target":387},{"edgeType":"imports","source":2126,"target":92},{"edgeType":"calls","source":64,"target":100},{"edgeType":"calls","source":2807,"target":2802},{"edgeType":"imports","source":2126,"target":93},{"edgeType":"calls","source":4846,"target":902},{"edgeType":"calls","source":3389,"target":1672},{"edgeType":"contains","source":4302,"target":4315},{"edgeType":"contains","source":320,"target":910},{"edgeType":"calls","source":2677,"target":490},{"edgeType":"calls","source":1999,"target":365},{"edgeType":"calls","source":498,"target":386},{"edgeType":"calls","source":64,"target":99},{"edgeType":"calls","source":4846,"target":901},{"edgeType":"calls","source":2677,"target":491},{"edgeType":"contains","source":4302,"target":4314},{"edgeType":"calls","source":3227,"target":353},{"edgeType":"calls","source":3973,"target":479},{"edgeType":"calls","source":325,"target":467},{"edgeType":"calls","source":4068,"target":705},{"edgeType":"calls","source":1629,"target":211},{"edgeType":"calls","source":4396,"target":4279},{"edgeType":"calls","source":498,"target":389},{"edgeType":"calls","source":2677,"target":487},{"edgeType":"calls","source":64,"target":102},{"edgeType":"imports","source":2126,"target":90},{"edgeType":"imports","source":2255,"target":320},{"edgeType":"calls","source":573,"target":179},{"edgeType":"calls","source":2813,"target":2614},{"edgeType":"calls","source":4846,"target":900},{"edgeType":"calls","source":4821,"target":1675},{"edgeType":"contains","source":3,"target":2284},{"edgeType":"contains","source":4203,"target":4211},{"edgeType":"contains","source":2647,"target":2765},{"edgeType":"calls","source":1088,"target":1125},{"edgeType":"contains","source":2948,"target":2949},{"edgeType":"calls","source":1872,"target":1133},{"edgeType":"calls","source":3932,"target":3865},{"edgeType":"contains","source":1065,"target":1072},{"edgeType":"calls","source":1766,"target":191},{"edgeType":"calls","source":2326,"target":1856},{"edgeType":"calls","source":2677,"target":488},{"edgeType":"calls","source":498,"target":388},{"edgeType":"calls","source":325,"target":466},{"edgeType":"calls","source":2438,"target":498},{"edgeType":"calls","source":2307,"target":331},{"edgeType":"calls","source":64,"target":101},{"edgeType":"calls","source":3548,"target":970},{"edgeType":"contains","source":4203,"target":4210},{"edgeType":"contains","source":4302,"target":4312},{"edgeType":"contains","source":320,"target":912},{"edgeType":"extends","source":4583,"target":4499},{"edgeType":"contains","source":1722,"target":1816},{"edgeType":"calls","source":1109,"target":436},{"edgeType":"calls","source":674,"target":179},{"edgeType":"calls","source":630,"target":486},{"edgeType":"calls","source":847,"target":102},{"edgeType":"contains","source":2483,"target":2537},{"edgeType":"contains","source":6,"target":4274},{"edgeType":"contains","source":4266,"target":4345},{"edgeType":"calls","source":1109,"target":435},{"edgeType":"extends","source":1454,"target":63},{"edgeType":"calls","source":630,"target":485},{"edgeType":"calls","source":847,"target":100},{"edgeType":"contains","source":3405,"target":2495},{"edgeType":"calls","source":774,"target":249},{"edgeType":"calls","source":847,"target":101},{"edgeType":"contains","source":2647,"target":2739},{"edgeType":"calls","source":3454,"target":1735},{"edgeType":"contains","source":16,"target":3963},{"edgeType":"contains","source":2285,"target":2334},{"edgeType":"contains","source":4266,"target":4344},{"edgeType":"contains","source":2285,"target":2331},{"edgeType":"calls","source":1109,"target":438},{"edgeType":"calls","source":630,"target":488},{"edgeType":"calls","source":4530,"target":88},{"edgeType":"calls","source":4651,"target":565},{"edgeType":"contains","source":1857,"target":1858},{"edgeType":"contains","source":2483,"target":2535},{"edgeType":"contains","source":3038,"target":3301},{"edgeType":"calls","source":1109,"target":437},{"edgeType":"calls","source":3283,"target":692},{"edgeType":"calls","source":772,"target":313},{"edgeType":"calls","source":458,"target":534},{"edgeType":"calls","source":630,"target":487},{"edgeType":"calls","source":3149,"target":1675},{"edgeType":"calls","source":3155,"target":1489},{"edgeType":"contains","source":2483,"target":2536},{"edgeType":"calls","source":1350,"target":365},{"edgeType":"extends","source":4516,"target":4499},{"edgeType":"calls","source":3947,"target":191},{"edgeType":"calls","source":3627,"target":1655},{"edgeType":"calls","source":3516,"target":865},{"edgeType":"calls","source":1250,"target":1346},{"edgeType":"calls","source":3358,"target":478},{"edgeType":"contains","source":1262,"target":1282},{"edgeType":"calls","source":3661,"target":1655},{"edgeType":"calls","source":4071,"target":572},{"edgeType":"contains","source":2033,"target":2750},{"edgeType":"calls","source":1341,"target":638},{"edgeType":"calls","source":533,"target":317},{"edgeType":"calls","source":3283,"target":690},{"edgeType":"imports","source":4079,"target":4080},{"edgeType":"contains","source":2716,"target":2719},{"edgeType":"calls","source":4587,"target":1489},{"edgeType":"calls","source":4657,"target":376},{"edgeType":"contains","source":3120,"target":2879},{"edgeType":"calls","source":2847,"target":464},{"edgeType":"calls","source":328,"target":330},{"edgeType":"calls","source":2313,"target":106},{"edgeType":"calls","source":3937,"target":499},{"edgeType":"calls","source":2677,"target":446},{"edgeType":"calls","source":3358,"target":476},{"edgeType":"calls","source":3558,"target":1675},{"edgeType":"calls","source":3299,"target":191},{"edgeType":"calls","source":1109,"target":434},{"edgeType":"calls","source":847,"target":99},{"edgeType":"calls","source":774,"target":248},{"edgeType":"contains","source":1148,"target":1646},{"edgeType":"calls","source":3143,"target":1856},{"edgeType":"contains","source":2483,"target":2539},{"edgeType":"contains","source":320,"target":888},{"edgeType":"contains","source":2511,"target":2728},{"edgeType":"calls","source":2332,"target":571},{"edgeType":"contains","source":2647,"target":2740},{"edgeType":"contains","source":2285,"target":2335},{"edgeType":"calls","source":4071,"target":570},{"edgeType":"calls","source":3358,"target":477},{"edgeType":"calls","source":1185,"target":191},{"edgeType":"calls","source":3334,"target":3335},{"edgeType":"calls","source":772,"target":309},{"edgeType":"contains","source":2716,"target":2717},{"edgeType":"calls","source":459,"target":499},{"edgeType":"calls","source":847,"target":98},{"edgeType":"contains","source":2647,"target":2741},{"edgeType":"calls","source":2332,"target":572},{"edgeType":"contains","source":3773,"target":3774},{"edgeType":"contains","source":2285,"target":2336},{"edgeType":"calls","source":4071,"target":571},{"edgeType":"calls","source":3856,"target":894},{"edgeType":"contains","source":11,"target":956},{"edgeType":"contains","source":2033,"target":2754},{"edgeType":"calls","source":772,"target":304},{"edgeType":"calls","source":642,"target":106},{"edgeType":"calls","source":3235,"target":3230},{"edgeType":"calls","source":2922,"target":248},{"edgeType":"contains","source":2647,"target":2747},{"edgeType":"calls","source":3874,"target":2447},{"edgeType":"calls","source":3856,"target":891},{"edgeType":"calls","source":4590,"target":336},{"edgeType":"calls","source":4598,"target":88},{"edgeType":"calls","source":4071,"target":568},{"edgeType":"calls","source":2332,"target":569},{"edgeType":"contains","source":11,"target":955},{"edgeType":"calls","source":2859,"target":88},{"edgeType":"calls","source":2677,"target":445},{"edgeType":"contains","source":1262,"target":1287},{"edgeType":"calls","source":2922,"target":249},{"edgeType":"contains","source":320,"target":889},{"edgeType":"extends","source":320,"target":340},{"edgeType":"calls","source":2332,"target":570},{"edgeType":"calls","source":4071,"target":569},{"edgeType":"contains","source":16,"target":803},{"edgeType":"calls","source":533,"target":316},{"edgeType":"extends","source":2264,"target":1384},{"edgeType":"contains","source":1262,"target":1284},{"edgeType":"extends","source":2903,"target":2716},{"edgeType":"contains","source":320,"target":892},{"edgeType":"calls","source":2651,"target":191},{"edgeType":"calls","source":4731,"target":191},{"edgeType":"calls","source":2332,"target":567},{"edgeType":"imports","source":3995,"target":331},{"edgeType":"calls","source":4071,"target":566},{"edgeType":"calls","source":4260,"target":4222},{"edgeType":"calls","source":658,"target":668},{"edgeType":"imports","source":4451,"target":2051},{"edgeType":"imports","source":2000,"target":1935},{"edgeType":"calls","source":533,"target":315},{"edgeType":"contains","source":2647,"target":2746},{"edgeType":"calls","source":3333,"target":191},{"edgeType":"calls","source":1250,"target":1343},{"edgeType":"calls","source":324,"target":452},{"edgeType":"calls","source":262,"target":260},{"edgeType":"calls","source":4071,"target":567},{"edgeType":"calls","source":2332,"target":568},{"edgeType":"contains","source":2647,"target":2751},{"edgeType":"calls","source":1307,"target":628},{"edgeType":"contains","source":404,"target":405},{"edgeType":"calls","source":3280,"target":774},{"edgeType":"calls","source":3392,"target":473},{"edgeType":"calls","source":2013,"target":1996},{"edgeType":"contains","source":1757,"target":1801},{"edgeType":"contains","source":3441,"target":3507},{"edgeType":"calls","source":325,"target":416},{"edgeType":"calls","source":3552,"target":1856},{"edgeType":"calls","source":789,"target":829},{"edgeType":"calls","source":4268,"target":1856},{"edgeType":"contains","source":2647,"target":2752},{"edgeType":"calls","source":3392,"target":474},{"edgeType":"calls","source":3358,"target":471},{"edgeType":"calls","source":1156,"target":1079},{"edgeType":"contains","source":320,"target":893},{"edgeType":"calls","source":2570,"target":587},{"edgeType":"calls","source":4765,"target":191},{"edgeType":"calls","source":2332,"target":566},{"edgeType":"calls","source":4722,"target":4695},{"edgeType":"contains","source":1757,"target":1802},{"edgeType":"calls","source":4320,"target":1302},{"edgeType":"contains","source":3443,"target":3444},{"edgeType":"contains","source":2033,"target":2756},{"edgeType":"calls","source":4348,"target":1489},{"edgeType":"calls","source":3363,"target":1370},{"edgeType":"contains","source":2647,"target":2749},{"edgeType":"calls","source":4125,"target":1002},{"edgeType":"calls","source":2395,"target":724},{"edgeType":"calls","source":4213,"target":388},{"edgeType":"calls","source":1969,"target":191},{"edgeType":"calls","source":4620,"target":457},{"edgeType":"contains","source":1757,"target":1799},{"edgeType":"calls","source":4424,"target":191},{"edgeType":"calls","source":2961,"target":2205},{"edgeType":"calls","source":3392,"target":472},{"edgeType":"contains","source":1090,"target":1337},{"edgeType":"extends","source":886,"target":770},{"edgeType":"calls","source":4213,"target":389},{"edgeType":"contains","source":1757,"target":1800},{"edgeType":"calls","source":2300,"target":499},{"edgeType":"calls","source":4620,"target":456},{"edgeType":"calls","source":3625,"target":1735},{"edgeType":"calls","source":3743,"target":191},{"edgeType":"calls","source":2245,"target":2233},{"edgeType":"contains","source":29,"target":1430},{"edgeType":"calls","source":1719,"target":569},{"edgeType":"contains","source":2483,"target":2521},{"edgeType":"contains","source":2033,"target":2729},{"edgeType":"contains","source":302,"target":367},{"edgeType":"calls","source":3464,"target":384},{"edgeType":"imports","source":44,"target":183},{"edgeType":"contains","source":2285,"target":2317},{"edgeType":"contains","source":3623,"target":4178},{"edgeType":"calls","source":1968,"target":249},{"edgeType":"calls","source":4557,"target":4555},{"edgeType":"calls","source":1818,"target":1728},{"edgeType":"contains","source":799,"target":815},{"edgeType":"calls","source":325,"target":445},{"edgeType":"calls","source":724,"target":760},{"edgeType":"calls","source":4621,"target":457},{"edgeType":"contains","source":1295,"target":1296},{"edgeType":"calls","source":4392,"target":4385},{"edgeType":"calls","source":906,"target":402},{"edgeType":"calls","source":3089,"target":382},{"edgeType":"calls","source":2945,"target":1675},{"edgeType":"contains","source":2483,"target":2522},{"edgeType":"extends","source":2174,"target":2038},{"edgeType":"calls","source":1719,"target":568},{"edgeType":"calls","source":3464,"target":385},{"edgeType":"calls","source":1968,"target":248},{"edgeType":"calls","source":1311,"target":531},{"edgeType":"calls","source":4000,"target":2795},{"edgeType":"contains","source":3475,"target":3480},{"edgeType":"calls","source":1071,"target":572},{"edgeType":"calls","source":2737,"target":724},{"edgeType":"contains","source":1295,"target":1297},{"edgeType":"calls","source":4557,"target":4554},{"edgeType":"contains","source":1262,"target":1263},{"edgeType":"calls","source":4621,"target":456},{"edgeType":"calls","source":4297,"target":985},{"edgeType":"calls","source":1336,"target":817},{"edgeType":"contains","source":29,"target":1432},{"edgeType":"calls","source":1719,"target":571},{"edgeType":"calls","source":3464,"target":382},{"edgeType":"calls","source":3798,"target":1655},{"edgeType":"calls","source":3392,"target":499},{"edgeType":"calls","source":4800,"target":191},{"edgeType":"contains","source":799,"target":817},{"edgeType":"calls","source":4152,"target":194},{"edgeType":"contains","source":3475,"target":3479},{"edgeType":"calls","source":587,"target":781},{"edgeType":"contains","source":1776,"target":1181},{"edgeType":"calls","source":2886,"target":330},{"edgeType":"calls","source":4670,"target":1050},{"edgeType":"calls","source":4557,"target":4553},{"edgeType":"calls","source":4658,"target":365},{"edgeType":"calls","source":1719,"target":570},{"edgeType":"contains","source":2483,"target":2520},{"edgeType":"contains","source":29,"target":1431},{"edgeType":"calls","source":3464,"target":383},{"edgeType":"contains","source":302,"target":368},{"edgeType":"contains","source":3162,"target":497},{"edgeType":"calls","source":1920,"target":1738},{"edgeType":"calls","source":325,"target":446},{"edgeType":"calls","source":4896,"target":2499},{"edgeType":"contains","source":4499,"target":4509},{"edgeType":"calls","source":196,"target":211},{"edgeType":"contains","source":2483,"target":2525},{"edgeType":"contains","source":2511,"target":2714},{"edgeType":"contains","source":29,"target":1434},{"edgeType":"calls","source":2691,"target":1088},{"edgeType":"calls","source":4108,"target":499},{"edgeType":"calls","source":404,"target":106},{"edgeType":"calls","source":1071,"target":569},{"edgeType":"contains","source":1227,"target":1294},{"edgeType":"calls","source":692,"target":691},{"edgeType":"calls","source":724,"target":756},{"edgeType":"calls","source":4790,"target":499},{"edgeType":"calls","source":4493,"target":191},{"edgeType":"calls","source":2298,"target":587},{"edgeType":"contains","source":2483,"target":2526},{"edgeType":"contains","source":4499,"target":4508},{"edgeType":"contains","source":1647,"target":2016},{"edgeType":"contains","source":29,"target":1433},{"edgeType":"contains","source":2033,"target":2734},{"edgeType":"contains","source":3623,"target":4181},{"edgeType":"calls","source":1071,"target":568},{"edgeType":"calls","source":824,"target":826},{"edgeType":"calls","source":890,"target":894},{"edgeType":"calls","source":4834,"target":191},{"edgeType":"calls","source":4861,"target":411},{"edgeType":"calls","source":906,"target":401},{"edgeType":"calls","source":2297,"target":1672},{"edgeType":"contains","source":4499,"target":4507},{"edgeType":"calls","source":64,"target":77},{"edgeType":"imports","source":97,"target":648},{"edgeType":"calls","source":1498,"target":1076},{"edgeType":"contains","source":29,"target":1436},{"edgeType":"calls","source":1719,"target":567},{"edgeType":"contains","source":29,"target":1437},{"edgeType":"contains","source":4234,"target":4266},{"edgeType":"calls","source":2674,"target":556},{"edgeType":"contains","source":3623,"target":4180},{"edgeType":"calls","source":1311,"target":530},{"edgeType":"calls","source":724,"target":758},{"edgeType":"contains","source":621,"target":1054},{"edgeType":"calls","source":1071,"target":571},{"edgeType":"calls","source":4635,"target":4245},{"edgeType":"calls","source":4758,"target":1489},{"edgeType":"contains","source":1227,"target":1292},{"edgeType":"calls","source":2257,"target":1856},{"edgeType":"calls","source":196,"target":212},{"edgeType":"contains","source":4499,"target":4506},{"edgeType":"contains","source":302,"target":372},{"edgeType":"calls","source":1719,"target":566},{"edgeType":"contains","source":2285,"target":2320},{"edgeType":"contains","source":29,"target":1435},{"edgeType":"calls","source":2701,"target":777},{"edgeType":"contains","source":3623,"target":4179},{"edgeType":"calls","source":1071,"target":570},{"edgeType":"contains","source":1227,"target":1293},{"edgeType":"calls","source":2758,"target":1124},{"edgeType":"calls","source":724,"target":757},{"edgeType":"calls","source":1754,"target":533},{"edgeType":"contains","source":4499,"target":4513},{"edgeType":"calls","source":2403,"target":498},{"edgeType":"contains","source":2284,"target":3413},{"edgeType":"imports","source":1090,"target":534},{"edgeType":"calls","source":4497,"target":2178},{"edgeType":"contains","source":3623,"target":4186},{"edgeType":"calls","source":4371,"target":1856},{"edgeType":"calls","source":2291,"target":1856},{"edgeType":"calls","source":724,"target":752},{"edgeType":"calls","source":1344,"target":558},{"edgeType":"contains","source":16,"target":3956},{"edgeType":"calls","source":630,"target":495},{"edgeType":"calls","source":3620,"target":824},{"edgeType":"calls","source":4726,"target":365},{"edgeType":"calls","source":890,"target":891},{"edgeType":"calls","source":3234,"target":106},{"edgeType":"calls","source":1765,"target":191},{"edgeType":"calls","source":331,"target":249},{"edgeType":"contains","source":4499,"target":4512},{"edgeType":"calls","source":4538,"target":906},{"edgeType":"calls","source":2545,"target":325},{"edgeType":"contains","source":3623,"target":4185},{"edgeType":"contains","source":1516,"target":1853},{"edgeType":"calls","source":2194,"target":1693},{"edgeType":"contains","source":29,"target":1438},{"edgeType":"contains","source":4169,"target":4172},{"edgeType":"calls","source":630,"target":494},{"edgeType":"contains","source":4266,"target":4336},{"edgeType":"calls","source":4669,"target":4245},{"edgeType":"calls","source":4786,"target":1675},{"edgeType":"calls","source":1344,"target":557},{"edgeType":"calls","source":2973,"target":1856},{"edgeType":"contains","source":2482,"target":2558},{"edgeType":"contains","source":4499,"target":4511},{"edgeType":"calls","source":3837,"target":438},{"edgeType":"contains","source":3623,"target":4184},{"edgeType":"contains","source":4045,"target":1672},{"edgeType":"contains","source":4169,"target":4171},{"edgeType":"calls","source":4845,"target":902},{"edgeType":"contains","source":29,"target":1441},{"edgeType":"calls","source":2765,"target":902},{"edgeType":"calls","source":4800,"target":183},{"edgeType":"calls","source":3388,"target":1672},{"edgeType":"calls","source":1071,"target":567},{"edgeType":"calls","source":1109,"target":446},{"edgeType":"calls","source":2494,"target":847},{"edgeType":"contains","source":2482,"target":2559},{"edgeType":"calls","source":3879,"target":194},{"edgeType":"contains","source":4499,"target":4510},{"edgeType":"contains","source":2285,"target":2324},{"edgeType":"calls","source":4033,"target":705},{"edgeType":"calls","source":2323,"target":863},{"edgeType":"contains","source":3623,"target":4183},{"edgeType":"calls","source":630,"target":496},{"edgeType":"contains","source":29,"target":1440},{"edgeType":"contains","source":4169,"target":4170},{"edgeType":"calls","source":724,"target":753},{"edgeType":"calls","source":4845,"target":901},{"edgeType":"calls","source":1109,"target":445},{"edgeType":"calls","source":1071,"target":566},{"edgeType":"calls","source":4572,"target":906},{"edgeType":"calls","source":1719,"target":557},{"edgeType":"calls","source":3837,"target":436},{"edgeType":"calls","source":630,"target":490},{"edgeType":"imports","source":1918,"target":1288},{"edgeType":"calls","source":4845,"target":900},{"edgeType":"calls","source":4820,"target":1675},{"edgeType":"calls","source":2765,"target":900},{"edgeType":"calls","source":3362,"target":2476},{"edgeType":"contains","source":4266,"target":4341},{"edgeType":"contains","source":2483,"target":2533},{"edgeType":"calls","source":3239,"target":3118},{"edgeType":"calls","source":459,"target":505},{"edgeType":"contains","source":2285,"target":2330},{"edgeType":"calls","source":1055,"target":1056},{"edgeType":"calls","source":3837,"target":437},{"edgeType":"calls","source":1737,"target":1055},{"edgeType":"calls","source":3715,"target":2105},{"edgeType":"calls","source":640,"target":179},{"edgeType":"calls","source":630,"target":489},{"edgeType":"contains","source":1749,"target":2033},{"edgeType":"calls","source":4061,"target":4063},{"edgeType":"contains","source":3441,"target":3489},{"edgeType":"contains","source":29,"target":1442},{"edgeType":"calls","source":2765,"target":901},{"edgeType":"contains","source":4189,"target":2499},{"edgeType":"contains","source":2033,"target":2743},{"edgeType":"calls","source":1701,"target":1113},{"edgeType":"contains","source":4266,"target":4340},{"edgeType":"calls","source":3494,"target":499},{"edgeType":"contains","source":2483,"target":2534},{"edgeType":"calls","source":1083,"target":191},{"edgeType":"calls","source":4591,"target":4543},{"edgeType":"calls","source":4676,"target":1908},{"edgeType":"calls","source":4698,"target":3340},{"edgeType":"calls","source":4000,"target":3837},{"edgeType":"contains","source":2285,"target":2327},{"edgeType":"calls","source":331,"target":248},{"edgeType":"contains","source":3623,"target":4188},{"edgeType":"calls","source":4439,"target":1856},{"edgeType":"calls","source":3688,"target":824},{"edgeType":"calls","source":630,"target":493},{"edgeType":"contains","source":4499,"target":4515},{"edgeType":"contains","source":4499,"target":4514},{"edgeType":"contains","source":3936,"target":826},{"edgeType":"calls","source":1719,"target":558},{"edgeType":"calls","source":1897,"target":325},{"edgeType":"calls","source":4046,"target":298},{"edgeType":"calls","source":3769,"target":3600},{"edgeType":"calls","source":1998,"target":365},{"edgeType":"calls","source":4519,"target":1489},{"edgeType":"calls","source":630,"target":491},{"edgeType":"calls","source":325,"target":433},{"edgeType":"contains","source":3623,"target":4187},{"edgeType":"calls","source":4496,"target":88},{"edgeType":"calls","source":630,"target":492},{"edgeType":"calls","source":1657,"target":365},{"edgeType":"calls","source":3041,"target":1856},{"edgeType":"calls","source":3792,"target":772},{"edgeType":"contains","source":2483,"target":2532},{"edgeType":"calls","source":1873,"target":106},{"edgeType":"calls","source":1964,"target":456},{"edgeType":"calls","source":4102,"target":772},{"edgeType":"contains","source":3540,"target":3563},{"edgeType":"calls","source":4137,"target":744},{"edgeType":"calls","source":4601,"target":102},{"edgeType":"calls","source":4586,"target":567},{"edgeType":"calls","source":2847,"target":567},{"edgeType":"calls","source":2887,"target":384},{"edgeType":"contains","source":2511,"target":2693},{"edgeType":"contains","source":103,"target":177},{"edgeType":"imports","source":4376,"target":3093},{"edgeType":"calls","source":4036,"target":705},{"edgeType":"calls","source":3870,"target":566},{"edgeType":"calls","source":642,"target":212},{"edgeType":"calls","source":4869,"target":249},{"edgeType":"calls","source":4564,"target":191},{"edgeType":"calls","source":4601,"target":101},{"edgeType":"calls","source":4586,"target":566},{"edgeType":"calls","source":2205,"target":1443},{"edgeType":"calls","source":4408,"target":1856},{"edgeType":"calls","source":2887,"target":385},{"edgeType":"calls","source":67,"target":68},{"edgeType":"calls","source":2847,"target":568},{"edgeType":"contains","source":3864,"target":4089},{"edgeType":"extends","source":2631,"target":341},{"edgeType":"contains","source":103,"target":176},{"edgeType":"contains","source":4266,"target":4311},{"edgeType":"calls","source":3106,"target":3109},{"edgeType":"calls","source":1157,"target":106},{"edgeType":"calls","source":3975,"target":479},{"edgeType":"calls","source":4869,"target":248},{"edgeType":"calls","source":2048,"target":2082},{"edgeType":"calls","source":4601,"target":100},{"edgeType":"calls","source":4488,"target":1489},{"edgeType":"calls","source":2887,"target":382},{"edgeType":"contains","source":2021,"target":2026},{"edgeType":"contains","source":3864,"target":4088},{"edgeType":"contains","source":4531,"target":4551},{"edgeType":"contains","source":2285,"target":2299},{"edgeType":"calls","source":1964,"target":457},{"edgeType":"calls","source":3934,"target":3865},{"edgeType":"contains","source":799,"target":800},{"edgeType":"calls","source":669,"target":434},{"edgeType":"calls","source":2531,"target":848},{"edgeType":"contains","source":1384,"target":1690},{"edgeType":"calls","source":4601,"target":99},{"edgeType":"calls","source":2847,"target":566},{"edgeType":"calls","source":669,"target":435},{"edgeType":"calls","source":2887,"target":383},{"edgeType":"contains","source":4234,"target":4244},{"edgeType":"contains","source":2511,"target":2692},{"edgeType":"contains","source":103,"target":178},{"edgeType":"contains","source":302,"target":351},{"edgeType":"calls","source":528,"target":572},{"edgeType":"calls","source":561,"target":606},{"edgeType":"calls","source":4714,"target":1880},{"edgeType":"contains","source":4266,"target":4316},{"edgeType":"calls","source":3252,"target":692},{"edgeType":"contains","source":2715,"target":2716},{"edgeType":"calls","source":4601,"target":98},{"edgeType":"contains","source":1090,"target":1295},{"edgeType":"calls","source":2760,"target":88},{"edgeType":"calls","source":771,"target":438},{"edgeType":"calls","source":4679,"target":1908},{"edgeType":"calls","source":2643,"target":544},{"edgeType":"calls","source":2648,"target":389},{"edgeType":"calls","source":1767,"target":1273},{"edgeType":"calls","source":3691,"target":824},{"edgeType":"calls","source":561,"target":605},{"edgeType":"imports","source":1090,"target":308},{"edgeType":"calls","source":528,"target":571},{"edgeType":"contains","source":2255,"target":2178},{"edgeType":"imports","source":396,"target":1738},{"edgeType":"calls","source":3220,"target":628},{"edgeType":"contains","source":3599,"target":3851},{"edgeType":"calls","source":4609,"target":906},{"edgeType":"calls","source":4399,"target":4245},{"edgeType":"calls","source":2714,"target":458},{"edgeType":"calls","source":4522,"target":1489},{"edgeType":"calls","source":771,"target":437},{"edgeType":"contains","source":3864,"target":4093},{"edgeType":"calls","source":4294,"target":4329},{"edgeType":"calls","source":3830,"target":744},{"edgeType":"contains","source":29,"target":1417},{"edgeType":"calls","source":1941,"target":106},{"edgeType":"calls","source":498,"target":447},{"edgeType":"imports","source":396,"target":1735},{"edgeType":"calls","source":4831,"target":365},{"edgeType":"calls","source":4137,"target":738},{"edgeType":"calls","source":3252,"target":690},{"edgeType":"calls","source":398,"target":376},{"edgeType":"calls","source":2648,"target":387},{"edgeType":"calls","source":642,"target":211},{"edgeType":"calls","source":4422,"target":1417},{"edgeType":"calls","source":4294,"target":4328},{"edgeType":"calls","source":2282,"target":106},{"edgeType":"calls","source":1740,"target":1055},{"edgeType":"calls","source":1766,"target":249},{"edgeType":"calls","source":1445,"target":687},{"edgeType":"contains","source":3,"target":2226},{"edgeType":"calls","source":3829,"target":772},{"edgeType":"contains","source":3540,"target":3564},{"edgeType":"calls","source":4680,"target":817},{"edgeType":"calls","source":331,"target":338},{"edgeType":"contains","source":1123,"target":1330},{"edgeType":"calls","source":2648,"target":388},{"edgeType":"calls","source":643,"target":179},{"edgeType":"calls","source":975,"target":458},{"edgeType":"calls","source":4294,"target":4327},{"edgeType":"calls","source":1766,"target":248},{"edgeType":"contains","source":34,"target":207},{"edgeType":"contains","source":4225,"target":4527},{"edgeType":"contains","source":4266,"target":4313},{"edgeType":"contains","source":103,"target":182},{"edgeType":"calls","source":528,"target":568},{"edgeType":"calls","source":4280,"target":531},{"edgeType":"calls","source":498,"target":441},{"edgeType":"calls","source":1472,"target":901},{"edgeType":"calls","source":463,"target":469},{"edgeType":"calls","source":2648,"target":385},{"edgeType":"imports","source":1090,"target":319},{"edgeType":"calls","source":4701,"target":3336},{"edgeType":"calls","source":4596,"target":249},{"edgeType":"calls","source":4294,"target":4326},{"edgeType":"contains","source":3540,"target":3572},{"edgeType":"contains","source":4266,"target":4319},{"edgeType":"calls","source":528,"target":567},{"edgeType":"calls","source":1472,"target":900},{"edgeType":"calls","source":824,"target":904},{"edgeType":"contains","source":601,"target":602},{"edgeType":"calls","source":1179,"target":470},{"edgeType":"calls","source":772,"target":402},{"edgeType":"calls","source":2648,"target":386},{"edgeType":"calls","source":4596,"target":248},{"edgeType":"calls","source":463,"target":468},{"edgeType":"calls","source":3630,"target":1655},{"edgeType":"calls","source":2036,"target":1385},{"edgeType":"imports","source":2255,"target":2256},{"edgeType":"calls","source":528,"target":570},{"edgeType":"contains","source":3599,"target":3854},{"edgeType":"contains","source":4266,"target":4318},{"edgeType":"calls","source":3526,"target":648},{"edgeType":"calls","source":771,"target":436},{"edgeType":"calls","source":2637,"target":724},{"edgeType":"calls","source":2648,"target":383},{"edgeType":"calls","source":3373,"target":106},{"edgeType":"calls","source":4675,"target":969},{"edgeType":"calls","source":4796,"target":389},{"edgeType":"calls","source":4782,"target":1880},{"edgeType":"contains","source":302,"target":360},{"edgeType":"calls","source":3664,"target":1655},{"edgeType":"contains","source":3540,"target":3568},{"edgeType":"contains","source":3,"target":2229},{"edgeType":"calls","source":528,"target":569},{"edgeType":"calls","source":4280,"target":530},{"edgeType":"calls","source":463,"target":470},{"edgeType":"calls","source":4796,"target":388},{"edgeType":"extends","source":4808,"target":4738},{"edgeType":"calls","source":2648,"target":384},{"edgeType":"calls","source":2927,"target":191},{"edgeType":"calls","source":3830,"target":738},{"edgeType":"contains","source":3864,"target":4095},{"edgeType":"calls","source":4563,"target":212},{"edgeType":"calls","source":1472,"target":902},{"edgeType":"contains","source":2033,"target":2720},{"edgeType":"calls","source":3561,"target":1675},{"edgeType":"calls","source":4796,"target":387},{"edgeType":"calls","source":3320,"target":690},{"edgeType":"calls","source":2961,"target":191},{"edgeType":"calls","source":3302,"target":191},{"edgeType":"contains","source":2483,"target":2517},{"edgeType":"calls","source":1179,"target":467},{"edgeType":"calls","source":4598,"target":183},{"edgeType":"calls","source":463,"target":465},{"edgeType":"calls","source":4563,"target":211},{"edgeType":"calls","source":1693,"target":388},{"edgeType":"calls","source":564,"target":505},{"edgeType":"calls","source":4249,"target":1489},{"edgeType":"calls","source":4788,"target":634},{"edgeType":"calls","source":4790,"target":572},{"edgeType":"calls","source":4796,"target":386},{"edgeType":"calls","source":2648,"target":382},{"edgeType":"calls","source":1179,"target":466},{"edgeType":"calls","source":1128,"target":990},{"edgeType":"contains","source":2483,"target":2518},{"edgeType":"contains","source":4499,"target":4500},{"edgeType":"calls","source":1693,"target":387},{"edgeType":"calls","source":1719,"target":1695},{"edgeType":"calls","source":540,"target":191},{"edgeType":"imports","source":396,"target":689},{"edgeType":"calls","source":4375,"target":753},{"edgeType":"calls","source":4355,"target":2430},{"edgeType":"contains","source":3475,"target":3476},{"edgeType":"calls","source":2856,"target":1330},{"edgeType":"calls","source":772,"target":401},{"edgeType":"calls","source":3711,"target":194},{"edgeType":"contains","source":29,"target":1428},{"edgeType":"calls","source":528,"target":566},{"edgeType":"calls","source":1179,"target":469},{"edgeType":"contains","source":2483,"target":2515},{"edgeType":"calls","source":3373,"target":102},{"edgeType":"calls","source":4501,"target":4245},{"edgeType":"calls","source":4618,"target":1675},{"edgeType":"calls","source":4012,"target":376},{"edgeType":"contains","source":302,"target":364},{"edgeType":"calls","source":463,"target":467},{"edgeType":"calls","source":4788,"target":633},{"edgeType":"calls","source":4790,"target":571},{"edgeType":"calls","source":4796,"target":385},{"edgeType":"calls","source":4148,"target":388},{"edgeType":"calls","source":4454,"target":417},{"edgeType":"calls","source":2409,"target":389},{"edgeType":"calls","source":4375,"target":752},{"edgeType":"contains","source":4266,"target":4321},{"edgeType":"calls","source":3698,"target":1655},{"edgeType":"calls","source":847,"target":189},{"edgeType":"contains","source":2483,"target":2516},{"edgeType":"calls","source":1179,"target":468},{"edgeType":"contains","source":302,"target":363},{"edgeType":"calls","source":397,"target":398},{"edgeType":"calls","source":2484,"target":179},{"edgeType":"calls","source":1693,"target":389},{"edgeType":"calls","source":463,"target":466},{"edgeType":"calls","source":4790,"target":570},{"edgeType":"calls","source":4796,"target":384},{"edgeType":"calls","source":4148,"target":389},{"edgeType":"imports","source":2420,"target":2421},{"edgeType":"calls","source":4355,"target":2428},{"edgeType":"calls","source":3661,"target":718},{"edgeType":"contains","source":612,"target":2351},{"edgeType":"calls","source":954,"target":1128},{"edgeType":"contains","source":103,"target":160},{"edgeType":"contains","source":2511,"target":2677},{"edgeType":"contains","source":4451,"target":4903},{"edgeType":"contains","source":4531,"target":4537},{"edgeType":"contains","source":302,"target":334},{"edgeType":"calls","source":4763,"target":382},{"edgeType":"calls","source":4752,"target":723},{"edgeType":"calls","source":1815,"target":863},{"edgeType":"calls","source":4806,"target":106},{"edgeType":"contains","source":1522,"target":1625},{"edgeType":"calls","source":330,"target":389},{"edgeType":"calls","source":331,"target":358},{"edgeType":"calls","source":2307,"target":411},{"edgeType":"calls","source":3554,"target":865},{"edgeType":"calls","source":3661,"target":719},{"edgeType":"contains","source":16,"target":742},{"edgeType":"calls","source":2783,"target":454},{"edgeType":"contains","source":2118,"target":2176},{"edgeType":"contains","source":103,"target":159},{"edgeType":"contains","source":4451,"target":4902},{"edgeType":"contains","source":2229,"target":4021},{"edgeType":"calls","source":1856,"target":1705},{"edgeType":"calls","source":461,"target":555},{"edgeType":"calls","source":2512,"target":2513},{"edgeType":"calls","source":2455,"target":1109},{"edgeType":"calls","source":4019,"target":191},{"edgeType":"contains","source":1522,"target":1626},{"edgeType":"calls","source":4759,"target":505},{"edgeType":"calls","source":4752,"target":722},{"edgeType":"contains","source":3573,"target":3580},{"edgeType":"calls","source":330,"target":388},{"edgeType":"calls","source":331,"target":357},{"edgeType":"calls","source":3661,"target":716},{"edgeType":"calls","source":1528,"target":249},{"edgeType":"contains","source":2118,"target":2173},{"edgeType":"contains","source":3936,"target":3953},{"edgeType":"contains","source":2511,"target":2675},{"edgeType":"contains","source":103,"target":162},{"edgeType":"calls","source":1159,"target":1118},{"edgeType":"contains","source":4451,"target":4901},{"edgeType":"contains","source":2417,"target":2418},{"edgeType":"contains","source":3672,"target":3681},{"edgeType":"contains","source":2280,"target":2436},{"edgeType":"calls","source":3234,"target":211},{"edgeType":"contains","source":3174,"target":3262},{"edgeType":"calls","source":2037,"target":325},{"edgeType":"imports","source":3443,"target":285},{"edgeType":"calls","source":2489,"target":1109},{"edgeType":"contains","source":3598,"target":3861},{"edgeType":"contains","source":1492,"target":1496},{"edgeType":"calls","source":1528,"target":248},{"edgeType":"calls","source":4318,"target":1489},{"edgeType":"calls","source":3661,"target":717},{"edgeType":"contains","source":3936,"target":3952},{"edgeType":"contains","source":103,"target":161},{"edgeType":"contains","source":302,"target":335},{"edgeType":"calls","source":1159,"target":1117},{"edgeType":"calls","source":3337,"target":191},{"edgeType":"contains","source":4451,"target":4900},{"edgeType":"calls","source":4659,"target":1489},{"edgeType":"calls","source":3234,"target":212},{"edgeType":"calls","source":4752,"target":720},{"edgeType":"calls","source":4833,"target":3494},{"edgeType":"contains","source":3573,"target":3578},{"edgeType":"contains","source":1522,"target":1624},{"edgeType":"contains","source":3598,"target":3860},{"edgeType":"contains","source":3441,"target":3442},{"edgeType":"contains","source":3864,"target":4077},{"edgeType":"contains","source":4451,"target":4907},{"edgeType":"contains","source":3738,"target":3755},{"edgeType":"calls","source":3879,"target":298},{"edgeType":"contains","source":6,"target":2114},{"edgeType":"contains","source":103,"target":164},{"edgeType":"calls","source":3661,"target":714},{"edgeType":"calls","source":4752,"target":719},{"edgeType":"calls","source":1944,"target":1088},{"edgeType":"contains","source":3623,"target":2035},{"edgeType":"contains","source":2219,"target":2220},{"edgeType":"calls","source":398,"target":391},{"edgeType":"calls","source":330,"target":385},{"edgeType":"calls","source":3661,"target":715},{"edgeType":"calls","source":3746,"target":194},{"edgeType":"extends","source":2033,"target":1954},{"edgeType":"calls","source":4428,"target":191},{"edgeType":"calls","source":331,"target":352},{"edgeType":"calls","source":330,"target":383},{"edgeType":"contains","source":3738,"target":3754},{"edgeType":"contains","source":4451,"target":4906},{"edgeType":"contains","source":6,"target":2113},{"edgeType":"contains","source":103,"target":163},{"edgeType":"contains","source":1987,"target":2013},{"edgeType":"contains","source":302,"target":337},{"edgeType":"contains","source":2186,"target":2187},{"edgeType":"contains","source":1485,"target":1720},{"edgeType":"calls","source":4752,"target":718},{"edgeType":"calls","source":4769,"target":191},{"edgeType":"calls","source":3371,"target":191},{"edgeType":"calls","source":330,"target":384},{"edgeType":"calls","source":1055,"target":106},{"edgeType":"calls","source":4880,"target":2035},{"edgeType":"calls","source":4613,"target":1856},{"edgeType":"contains","source":3864,"target":4075},{"edgeType":"contains","source":4531,"target":4539},{"edgeType":"contains","source":4451,"target":4905},{"edgeType":"calls","source":3628,"target":1735},{"edgeType":"calls","source":3661,"target":712},{"edgeType":"contains","source":103,"target":166},{"edgeType":"calls","source":1517,"target":586},{"edgeType":"calls","source":3780,"target":194},{"edgeType":"contains","source":103,"target":167},{"edgeType":"calls","source":1889,"target":1738},{"edgeType":"contains","source":3738,"target":3753},{"edgeType":"calls","source":1973,"target":191},{"edgeType":"calls","source":330,"target":387},{"edgeType":"calls","source":331,"target":356},{"edgeType":"calls","source":4897,"target":2564},{"edgeType":"calls","source":2779,"target":571},{"edgeType":"calls","source":4752,"target":717},{"edgeType":"contains","source":4451,"target":4904},{"edgeType":"contains","source":1933,"target":3685},{"edgeType":"contains","source":103,"target":165},{"edgeType":"calls","source":1517,"target":585},{"edgeType":"calls","source":3618,"target":2046},{"edgeType":"calls","source":3661,"target":713},{"edgeType":"calls","source":4121,"target":194},{"edgeType":"calls","source":3361,"target":499},{"edgeType":"calls","source":4201,"target":1942},{"edgeType":"calls","source":330,"target":386},{"edgeType":"calls","source":331,"target":355},{"edgeType":"calls","source":2851,"target":454},{"edgeType":"calls","source":4624,"target":456},{"edgeType":"calls","source":2779,"target":572},{"edgeType":"calls","source":563,"target":562},{"edgeType":"calls","source":4752,"target":716},{"edgeType":"calls","source":2318,"target":1118},{"edgeType":"calls","source":1498,"target":1169},{"edgeType":"contains","source":3738,"target":3759},{"edgeType":"contains","source":3864,"target":4081},{"edgeType":"contains","source":103,"target":169},{"edgeType":"calls","source":2666,"target":901},{"edgeType":"calls","source":643,"target":191},{"edgeType":"contains","source":1384,"target":1683},{"edgeType":"contains","source":4266,"target":4304},{"edgeType":"calls","source":4752,"target":715},{"edgeType":"imports","source":4045,"target":645},{"edgeType":"calls","source":2779,"target":569},{"edgeType":"calls","source":4803,"target":191},{"edgeType":"imports","source":1090,"target":302},{"edgeType":"calls","source":325,"target":534},{"edgeType":"calls","source":2318,"target":1119},{"edgeType":"contains","source":103,"target":168},{"edgeType":"contains","source":1384,"target":1684},{"edgeType":"calls","source":2666,"target":902},{"edgeType":"calls","source":534,"target":398},{"edgeType":"contains","source":2196,"target":3995},{"edgeType":"calls","source":4899,"target":2499},{"edgeType":"calls","source":4752,"target":714},{"edgeType":"calls","source":4797,"target":376},{"edgeType":"calls","source":4721,"target":1675},{"edgeType":"calls","source":4727,"target":1489},{"edgeType":"calls","source":2779,"target":570},{"edgeType":"calls","source":3870,"target":571},{"edgeType":"imports","source":4240,"target":2001},{"edgeType":"calls","source":330,"target":382},{"edgeType":"calls","source":2514,"target":325},{"edgeType":"contains","source":3738,"target":3757},{"edgeType":"contains","source":3995,"target":4246},{"edgeType":"calls","source":2779,"target":567},{"edgeType":"contains","source":3540,"target":3553},{"edgeType":"calls","source":1971,"target":249},{"edgeType":"calls","source":2713,"target":499},{"edgeType":"contains","source":103,"target":171},{"edgeType":"calls","source":4752,"target":713},{"edgeType":"calls","source":2942,"target":1856},{"edgeType":"contains","source":3864,"target":4078},{"edgeType":"extends","source":4048,"target":798},{"edgeType":"calls","source":2514,"target":326},{"edgeType":"calls","source":4611,"target":1911},{"edgeType":"calls","source":2318,"target":1117},{"edgeType":"calls","source":2300,"target":1675},{"edgeType":"calls","source":331,"target":350},{"edgeType":"calls","source":4586,"target":572},{"edgeType":"contains","source":3738,"target":3756},{"edgeType":"calls","source":1971,"target":248},{"edgeType":"calls","source":3870,"target":572},{"edgeType":"calls","source":2779,"target":568},{"edgeType":"calls","source":4864,"target":411},{"edgeType":"contains","source":103,"target":170},{"edgeType":"calls","source":4226,"target":106},{"edgeType":"calls","source":2666,"target":900},{"edgeType":"contains","source":4201,"target":4202},{"edgeType":"calls","source":1385,"target":1501},{"edgeType":"calls","source":3439,"target":191},{"edgeType":"calls","source":3453,"target":1871},{"edgeType":"contains","source":1384,"target":1682},{"edgeType":"imports","source":4045,"target":648},{"edgeType":"calls","source":4752,"target":712},{"edgeType":"calls","source":4837,"target":191},{"edgeType":"calls","source":3106,"target":3112},{"edgeType":"calls","source":4586,"target":571},{"edgeType":"calls","source":3870,"target":569},{"edgeType":"calls","source":1840,"target":1133},{"edgeType":"contains","source":3864,"target":4085},{"edgeType":"contains","source":6,"target":9},{"edgeType":"calls","source":2847,"target":571},{"edgeType":"calls","source":2887,"target":388},{"edgeType":"contains","source":103,"target":173},{"edgeType":"calls","source":2676,"target":587},{"edgeType":"contains","source":2186,"target":2194},{"edgeType":"calls","source":4755,"target":1675},{"edgeType":"contains","source":2229,"target":2975},{"edgeType":"calls","source":1325,"target":185},{"edgeType":"calls","source":992,"target":995},{"edgeType":"contains","source":4531,"target":4549},{"edgeType":"calls","source":3870,"target":570},{"edgeType":"calls","source":1839,"target":106},{"edgeType":"calls","source":4586,"target":570},{"edgeType":"calls","source":3807,"target":3580},{"edgeType":"calls","source":2847,"target":572},{"edgeType":"calls","source":1498,"target":106},{"edgeType":"calls","source":2779,"target":566},{"edgeType":"calls","source":2713,"target":498},{"edgeType":"contains","source":103,"target":172},{"edgeType":"calls","source":2887,"target":389},{"edgeType":"contains","source":4531,"target":4548},{"edgeType":"calls","source":3858,"target":1996},{"edgeType":"calls","source":4586,"target":569},{"edgeType":"calls","source":3870,"target":567},{"edgeType":"calls","source":2294,"target":1856},{"edgeType":"contains","source":1384,"target":1685},{"edgeType":"calls","source":2847,"target":569},{"edgeType":"calls","source":2887,"target":386},{"edgeType":"contains","source":103,"target":175},{"edgeType":"calls","source":3455,"target":747},{"edgeType":"calls","source":3106,"target":3110},{"edgeType":"contains","source":302,"target":347},{"edgeType":"calls","source":3870,"target":568},{"edgeType":"contains","source":320,"target":846},{"edgeType":"calls","source":4586,"target":568},{"edgeType":"calls","source":4448,"target":1675},{"edgeType":"calls","source":4454,"target":1489},{"edgeType":"imports","source":396,"target":1728},{"edgeType":"calls","source":4541,"target":906},{"edgeType":"contains","source":3738,"target":3760},{"edgeType":"calls","source":2847,"target":570},{"edgeType":"calls","source":2887,"target":387},{"edgeType":"calls","source":3450,"target":1960},{"edgeType":"contains","source":6,"target":10},{"edgeType":"contains","source":103,"target":174},{"edgeType":"calls","source":4789,"target":1675},{"edgeType":"calls","source":4795,"target":1489},{"edgeType":"calls","source":2880,"target":2718},{"edgeType":"calls","source":3106,"target":3111},{"edgeType":"calls","source":4011,"target":389},{"edgeType":"calls","source":3261,"target":384},{"edgeType":"contains","source":1648,"target":1930},{"edgeType":"contains","source":830,"target":862},{"edgeType":"contains","source":1062,"target":1069},{"edgeType":"calls","source":3974,"target":479},{"edgeType":"calls","source":4487,"target":1489},{"edgeType":"calls","source":4868,"target":248},{"edgeType":"contains","source":4894,"target":4895},{"edgeType":"calls","source":4574,"target":906},{"edgeType":"contains","source":1522,"target":1608},{"edgeType":"calls","source":849,"target":106},{"edgeType":"contains","source":1987,"target":1992},{"edgeType":"calls","source":774,"target":317},{"edgeType":"calls","source":2202,"target":445},{"edgeType":"contains","source":2647,"target":2672},{"edgeType":"contains","source":2777,"target":2870},{"edgeType":"calls","source":991,"target":989},{"edgeType":"contains","source":103,"target":144},{"edgeType":"calls","source":1739,"target":1055},{"edgeType":"calls","source":1444,"target":687},{"edgeType":"calls","source":3261,"target":385},{"edgeType":"extends","source":3122,"target":3123},{"edgeType":"calls","source":1071,"target":622},{"edgeType":"calls","source":3837,"target":499},{"edgeType":"contains","source":1095,"target":1102},{"edgeType":"calls","source":774,"target":315},{"edgeType":"contains","source":1522,"target":1609},{"edgeType":"calls","source":2308,"target":331},{"edgeType":"calls","source":2439,"target":498},{"edgeType":"calls","source":2202,"target":446},{"edgeType":"contains","source":3995,"target":4223},{"edgeType":"calls","source":815,"target":102},{"edgeType":"calls","source":774,"target":316},{"edgeType":"contains","source":3864,"target":4056},{"edgeType":"contains","source":103,"target":143},{"edgeType":"contains","source":16,"target":2840},{"edgeType":"contains","source":696,"target":786},{"edgeType":"calls","source":4678,"target":1908},{"edgeType":"calls","source":3261,"target":382},{"edgeType":"calls","source":1963,"target":456},{"edgeType":"imports","source":3710,"target":519},{"edgeType":"calls","source":4011,"target":387},{"edgeType":"contains","source":831,"target":833},{"edgeType":"contains","source":3864,"target":4054},{"edgeType":"calls","source":2679,"target":454},{"edgeType":"contains","source":1522,"target":1606},{"edgeType":"calls","source":4293,"target":4330},{"edgeType":"calls","source":3748,"target":83},{"edgeType":"contains","source":3936,"target":3937},{"edgeType":"calls","source":3837,"target":495},{"edgeType":"contains","source":103,"target":146},{"edgeType":"calls","source":3261,"target":383},{"edgeType":"contains","source":3797,"target":4016},{"edgeType":"contains","source":3162,"target":448},{"edgeType":"calls","source":1739,"target":1057},{"edgeType":"calls","source":4011,"target":388},{"edgeType":"contains","source":1522,"target":1607},{"edgeType":"calls","source":4521,"target":1489},{"edgeType":"calls","source":4608,"target":906},{"edgeType":"contains","source":2647,"target":2671},{"edgeType":"calls","source":2247,"target":106},{"edgeType":"contains","source":103,"target":145},{"edgeType":"calls","source":1738,"target":30},{"edgeType":"calls","source":3837,"target":496},{"edgeType":"contains","source":862,"target":931},{"edgeType":"contains","source":831,"target":835},{"edgeType":"contains","source":1522,"target":1612},{"edgeType":"calls","source":534,"target":353},{"edgeType":"calls","source":1957,"target":1693},{"edgeType":"calls","source":4011,"target":385},{"edgeType":"calls","source":3323,"target":572},{"edgeType":"calls","source":1290,"target":1229},{"edgeType":"contains","source":4894,"target":4899},{"edgeType":"calls","source":815,"target":98},{"edgeType":"contains","source":3936,"target":3943},{"edgeType":"calls","source":2279,"target":2282},{"edgeType":"imports","source":38,"target":184},{"edgeType":"calls","source":4349,"target":478},{"edgeType":"contains","source":3738,"target":3739},{"edgeType":"contains","source":1723,"target":1724},{"edgeType":"calls","source":4011,"target":384},{"edgeType":"calls","source":3837,"target":493},{"edgeType":"calls","source":3828,"target":772},{"edgeType":"contains","source":103,"target":148},{"edgeType":"contains","source":1987,"target":1996},{"edgeType":"calls","source":3741,"target":298},{"edgeType":"contains","source":1522,"target":1613},{"edgeType":"contains","source":862,"target":930},{"edgeType":"calls","source":4011,"target":386},{"edgeType":"contains","source":831,"target":834},{"edgeType":"imports","source":3534,"target":1750},{"edgeType":"contains","source":4894,"target":4898},{"edgeType":"calls","source":4773,"target":4245},{"edgeType":"calls","source":4349,"target":477},{"edgeType":"imports","source":38,"target":185},{"edgeType":"contains","source":1723,"target":1725},{"edgeType":"contains","source":103,"target":147},{"edgeType":"calls","source":1727,"target":365},{"edgeType":"calls","source":3837,"target":494},{"edgeType":"calls","source":3808,"target":336},{"edgeType":"contains","source":862,"target":933},{"edgeType":"contains","source":831,"target":837},{"edgeType":"contains","source":1522,"target":1610},{"edgeType":"contains","source":696,"target":794},{"edgeType":"calls","source":3455,"target":1763},{"edgeType":"calls","source":4254,"target":249},{"edgeType":"contains","source":2803,"target":3124},{"edgeType":"calls","source":3373,"target":77},{"edgeType":"calls","source":3323,"target":570},{"edgeType":"contains","source":3699,"target":3888},{"edgeType":"extends","source":3226,"target":3071},{"edgeType":"calls","source":301,"target":179},{"edgeType":"calls","source":4595,"target":249},{"edgeType":"contains","source":4894,"target":4897},{"edgeType":"calls","source":815,"target":100},{"edgeType":"calls","source":2656,"target":106},{"edgeType":"calls","source":2787,"target":1330},{"edgeType":"calls","source":2963,"target":102},{"edgeType":"contains","source":1062,"target":1075},{"edgeType":"contains","source":1987,"target":1994},{"edgeType":"calls","source":815,"target":101},{"edgeType":"contains","source":3864,"target":4059},{"edgeType":"calls","source":2476,"target":401},{"edgeType":"calls","source":4349,"target":476},{"edgeType":"contains","source":2777,"target":2872},{"edgeType":"calls","source":4011,"target":382},{"edgeType":"calls","source":1321,"target":1327},{"edgeType":"calls","source":3837,"target":491},{"edgeType":"contains","source":103,"target":150},{"edgeType":"contains","source":831,"target":836},{"edgeType":"calls","source":534,"target":354},{"edgeType":"contains","source":1522,"target":1611},{"edgeType":"contains","source":862,"target":932},{"edgeType":"calls","source":3323,"target":571},{"edgeType":"contains","source":696,"target":793},{"edgeType":"contains","source":4894,"target":4896},{"edgeType":"calls","source":2476,"target":402},{"edgeType":"calls","source":2551,"target":191},{"edgeType":"calls","source":815,"target":99},{"edgeType":"contains","source":1062,"target":1074},{"edgeType":"calls","source":591,"target":701},{"edgeType":"calls","source":4595,"target":248},{"edgeType":"contains","source":2033,"target":2683},{"edgeType":"calls","source":4011,"target":383},{"edgeType":"calls","source":3495,"target":2638},{"edgeType":"calls","source":4020,"target":1161},{"edgeType":"calls","source":3629,"target":1655},{"edgeType":"contains","source":103,"target":149},{"edgeType":"calls","source":1656,"target":454},{"edgeType":"calls","source":3837,"target":492},{"edgeType":"contains","source":103,"target":152},{"edgeType":"contains","source":696,"target":796},{"edgeType":"calls","source":4247,"target":464},{"edgeType":"contains","source":1522,"target":1616},{"edgeType":"calls","source":2877,"target":2766},{"edgeType":"calls","source":2963,"target":100},{"edgeType":"calls","source":3323,"target":568},{"edgeType":"calls","source":771,"target":401},{"edgeType":"calls","source":4795,"target":389},{"edgeType":"contains","source":831,"target":839},{"edgeType":"calls","source":4807,"target":4245},{"edgeType":"calls","source":2350,"target":77},{"edgeType":"calls","source":1622,"target":446},{"edgeType":"calls","source":2246,"target":2244},{"edgeType":"contains","source":4451,"target":4894},{"edgeType":"calls","source":3568,"target":3543},{"edgeType":"contains","source":3672,"target":3675},{"edgeType":"imports","source":38,"target":196},{"edgeType":"contains","source":3864,"target":4065},{"edgeType":"contains","source":103,"target":151},{"edgeType":"contains","source":831,"target":838},{"edgeType":"calls","source":774,"target":307},{"edgeType":"contains","source":1522,"target":1617},{"edgeType":"calls","source":4254,"target":248},{"edgeType":"calls","source":4280,"target":499},{"edgeType":"calls","source":3323,"target":569},{"edgeType":"calls","source":4795,"target":388},{"edgeType":"contains","source":2777,"target":2880},{"edgeType":"calls","source":2963,"target":101},{"edgeType":"calls","source":3829,"target":738},{"edgeType":"contains","source":3162,"target":458},{"edgeType":"calls","source":4589,"target":1489},{"edgeType":"calls","source":1622,"target":445},{"edgeType":"contains","source":1522,"target":1618},{"edgeType":"contains","source":3936,"target":3946},{"edgeType":"contains","source":3738,"target":3742},{"edgeType":"contains","source":1723,"target":1729},{"edgeType":"calls","source":1309,"target":638},{"edgeType":"contains","source":103,"target":154},{"edgeType":"calls","source":591,"target":698},{"edgeType":"calls","source":3568,"target":3541},{"edgeType":"contains","source":1522,"target":1614},{"edgeType":"calls","source":2656,"target":102},{"edgeType":"calls","source":2963,"target":98},{"edgeType":"contains","source":2647,"target":2679},{"edgeType":"calls","source":4795,"target":387},{"edgeType":"calls","source":3323,"target":566},{"edgeType":"contains","source":2777,"target":2877},{"edgeType":"contains","source":831,"target":841},{"edgeType":"calls","source":906,"target":446},{"edgeType":"calls","source":994,"target":890},{"edgeType":"imports","source":3571,"target":1649},{"edgeType":"contains","source":2647,"target":2678},{"edgeType":"calls","source":1528,"target":191},{"edgeType":"calls","source":4372,"target":1873},{"edgeType":"contains","source":3672,"target":3673},{"edgeType":"contains","source":1723,"target":1726},{"edgeType":"contains","source":3,"target":2196},{"edgeType":"contains","source":103,"target":153},{"edgeType":"contains","source":16,"target":3907},{"edgeType":"calls","source":4242,"target":1675},{"edgeType":"calls","source":3336,"target":3335},{"edgeType":"contains","source":1522,"target":1615},{"edgeType":"contains","source":1485,"target":1705},{"edgeType":"calls","source":3548,"target":991},{"edgeType":"calls","source":3323,"target":567},{"edgeType":"contains","source":3098,"target":1383},{"edgeType":"calls","source":2963,"target":99},{"edgeType":"calls","source":4795,"target":386},{"edgeType":"calls","source":771,"target":402},{"edgeType":"calls","source":906,"target":445},{"edgeType":"contains","source":831,"target":840},{"edgeType":"contains","source":3864,"target":4062},{"edgeType":"calls","source":4393,"target":4392},{"edgeType":"calls","source":4354,"target":2430},{"edgeType":"calls","source":3568,"target":3542},{"edgeType":"calls","source":4349,"target":471},{"edgeType":"contains","source":3936,"target":3944},{"edgeType":"contains","source":2777,"target":2883},{"edgeType":"contains","source":3995,"target":4236},{"edgeType":"contains","source":103,"target":156},{"edgeType":"calls","source":4795,"target":385},{"edgeType":"calls","source":1185,"target":248},{"edgeType":"calls","source":3272,"target":1088},{"edgeType":"contains","source":2483,"target":2484},{"edgeType":"contains","source":2511,"target":2673},{"edgeType":"contains","source":3738,"target":3747},{"edgeType":"calls","source":1813,"target":863},{"edgeType":"calls","source":4592,"target":336},{"edgeType":"calls","source":2538,"target":587},{"edgeType":"calls","source":2475,"target":426},{"edgeType":"calls","source":462,"target":463},{"edgeType":"calls","source":2656,"target":100},{"edgeType":"calls","source":4122,"target":106},{"edgeType":"contains","source":1492,"target":1494},{"edgeType":"calls","source":4213,"target":456},{"edgeType":"calls","source":2278,"target":191},{"edgeType":"contains","source":3598,"target":3859},{"edgeType":"contains","source":3540,"target":3543},{"edgeType":"calls","source":2861,"target":88},{"edgeType":"contains","source":3,"target":2198},{"edgeType":"calls","source":1528,"target":1241},{"edgeType":"contains","source":103,"target":155},{"edgeType":"extends","source":4244,"target":63},{"edgeType":"contains","source":3995,"target":4235},{"edgeType":"calls","source":1701,"target":106},{"edgeType":"calls","source":1385,"target":389},{"edgeType":"contains","source":4531,"target":4532},{"edgeType":"calls","source":3219,"target":1675},{"edgeType":"contains","source":831,"target":842},{"edgeType":"contains","source":2511,"target":2674},{"edgeType":"calls","source":2475,"target":427},{"edgeType":"calls","source":1152,"target":212},{"edgeType":"calls","source":3872,"target":458},{"edgeType":"contains","source":396,"target":2699},{"edgeType":"calls","source":2656,"target":101},{"edgeType":"calls","source":4795,"target":384},{"edgeType":"contains","source":1492,"target":1495},{"edgeType":"calls","source":3697,"target":1655},{"edgeType":"calls","source":4354,"target":2428},{"edgeType":"calls","source":4051,"target":194},{"edgeType":"contains","source":3864,"target":4068},{"edgeType":"contains","source":3672,"target":3678},{"edgeType":"contains","source":3540,"target":3542},{"edgeType":"contains","source":2777,"target":2881},{"edgeType":"calls","source":774,"target":306},{"edgeType":"contains","source":103,"target":158},{"edgeType":"calls","source":3124,"target":388},{"edgeType":"calls","source":2487,"target":1109},{"edgeType":"calls","source":2656,"target":98},{"edgeType":"calls","source":4085,"target":194},{"edgeType":"contains","source":1123,"target":1306},{"edgeType":"calls","source":4795,"target":383},{"edgeType":"contains","source":1522,"target":1619},{"edgeType":"calls","source":4213,"target":454},{"edgeType":"extends","source":4060,"target":3652},{"edgeType":"contains","source":3540,"target":3541},{"edgeType":"contains","source":3738,"target":3745},{"edgeType":"contains","source":1723,"target":1730},{"edgeType":"calls","source":4316,"target":1489},{"edgeType":"contains","source":103,"target":157},{"edgeType":"calls","source":774,"target":305},{"edgeType":"calls","source":4831,"target":3494},{"edgeType":"calls","source":3124,"target":389},{"edgeType":"calls","source":975,"target":416},{"edgeType":"calls","source":985,"target":106},{"edgeType":"calls","source":1185,"target":249},{"edgeType":"calls","source":4657,"target":1489},{"edgeType":"calls","source":2475,"target":425},{"edgeType":"calls","source":2656,"target":99},{"edgeType":"calls","source":4795,"target":382},{"edgeType":"contains","source":1522,"target":1620},{"edgeType":"calls","source":539,"target":191},{"edgeType":"extends","source":4115,"target":4060},{"edgeType":"contains","source":3995,"target":4233},{"edgeType":"calls","source":771,"target":426},{"edgeType":"contains","source":37,"target":59},{"edgeType":"contains","source":3864,"target":4040},{"edgeType":"contains","source":103,"target":127},{"edgeType":"calls","source":1693,"target":384},{"edgeType":"calls","source":3373,"target":100},{"edgeType":"imports","source":2353,"target":285},{"edgeType":"calls","source":1498,"target":87},{"edgeType":"contains","source":3099,"target":1328},{"edgeType":"contains","source":3699,"target":3870},{"edgeType":"calls","source":4790,"target":569},{"edgeType":"calls","source":4796,"target":383},{"edgeType":"calls","source":1972,"target":191},{"edgeType":"extends","source":3621,"target":3493},{"edgeType":"contains","source":1749,"target":1954},{"edgeType":"calls","source":4148,"target":386},{"edgeType":"contains","source":3175,"target":3200},{"edgeType":"calls","source":4286,"target":336},{"edgeType":"contains","source":1522,"target":1592},{"edgeType":"calls","source":2350,"target":102},{"edgeType":"calls","source":2409,"target":387},{"edgeType":"calls","source":771,"target":425},{"edgeType":"contains","source":37,"target":58},{"edgeType":"calls","source":4832,"target":3494},{"edgeType":"contains","source":103,"target":126},{"edgeType":"calls","source":1693,"target":383},{"edgeType":"calls","source":3373,"target":101},{"edgeType":"contains","source":3699,"target":3869},{"edgeType":"contains","source":953,"target":1259},{"edgeType":"imports","source":3162,"target":574},{"edgeType":"calls","source":3260,"target":1489},{"edgeType":"contains","source":3162,"target":433},{"edgeType":"calls","source":4790,"target":568},{"edgeType":"calls","source":4796,"target":382},{"edgeType":"contains","source":3175,"target":3201},{"edgeType":"contains","source":3174,"target":3232},{"edgeType":"calls","source":4148,"target":387},{"edgeType":"contains","source":1522,"target":1593},{"edgeType":"calls","source":4237,"target":1856},{"edgeType":"calls","source":2409,"target":388},{"edgeType":"calls","source":2350,"target":99},{"edgeType":"extends","source":4816,"target":4499},{"edgeType":"calls","source":741,"target":301},{"edgeType":"calls","source":800,"target":586},{"edgeType":"contains","source":37,"target":61},{"edgeType":"calls","source":1693,"target":386},{"edgeType":"contains","source":103,"target":129},{"edgeType":"contains","source":97,"target":1372},{"edgeType":"contains","source":302,"target":303},{"edgeType":"calls","source":1179,"target":465},{"edgeType":"calls","source":4790,"target":567},{"edgeType":"calls","source":4148,"target":384},{"edgeType":"contains","source":3175,"target":3198},{"edgeType":"imports","source":1090,"target":325},{"edgeType":"calls","source":1814,"target":863},{"edgeType":"calls","source":2403,"target":571},{"edgeType":"calls","source":2409,"target":385},{"edgeType":"contains","source":3864,"target":4038},{"edgeType":"calls","source":529,"target":531},{"edgeType":"calls","source":2786,"target":325},{"edgeType":"calls","source":2350,"target":100},{"edgeType":"calls","source":4498,"target":106},{"edgeType":"contains","source":1522,"target":1590},{"edgeType":"calls","source":800,"target":585},{"edgeType":"imports","source":4045,"target":1746},{"edgeType":"calls","source":771,"target":427},{"edgeType":"imports","source":4045,"target":689},{"edgeType":"contains","source":6,"target":1021},{"edgeType":"contains","source":37,"target":60},{"edgeType":"calls","source":1289,"target":1282},{"edgeType":"calls","source":1693,"target":385},{"edgeType":"contains","source":103,"target":128},{"edgeType":"calls","source":3373,"target":99},{"edgeType":"calls","source":4768,"target":191},{"edgeType":"calls","source":4790,"target":566},{"edgeType":"calls","source":3373,"target":98},{"edgeType":"calls","source":4148,"target":385},{"edgeType":"imports","source":1090,"target":326},{"edgeType":"calls","source":2403,"target":572},{"edgeType":"calls","source":2409,"target":386},{"edgeType":"calls","source":4879,"target":2035},{"edgeType":"contains","source":3175,"target":3199},{"edgeType":"calls","source":529,"target":530},{"edgeType":"calls","source":2350,"target":101},{"edgeType":"imports","source":1483,"target":1884},{"edgeType":"contains","source":1522,"target":1591},{"edgeType":"calls","source":2475,"target":454},{"edgeType":"contains","source":3275,"target":3276},{"edgeType":"calls","source":2409,"target":382},{"edgeType":"calls","source":2403,"target":568},{"edgeType":"calls","source":3933,"target":705},{"edgeType":"contains","source":103,"target":131},{"edgeType":"contains","source":16,"target":3885},{"edgeType":"contains","source":4266,"target":4267},{"edgeType":"calls","source":3360,"target":498},{"edgeType":"contains","source":1522,"target":1596},{"edgeType":"calls","source":1970,"target":249},{"edgeType":"calls","source":4148,"target":382},{"edgeType":"contains","source":3404,"target":3506},{"edgeType":"calls","source":2742,"target":2744},{"edgeType":"calls","source":2403,"target":569},{"edgeType":"calls","source":2409,"target":383},{"edgeType":"calls","source":4651,"target":1703},{"edgeType":"calls","source":4517,"target":572},{"edgeType":"calls","source":2785,"target":354},{"edgeType":"contains","source":1227,"target":1228},{"edgeType":"calls","source":1657,"target":438},{"edgeType":"calls","source":2350,"target":98},{"edgeType":"calls","source":4517,"target":570},{"edgeType":"contains","source":3864,"target":4043},{"edgeType":"contains","source":37,"target":62},{"edgeType":"contains","source":3936,"target":754},{"edgeType":"contains","source":103,"target":130},{"edgeType":"calls","source":3773,"target":381},{"edgeType":"contains","source":302,"target":304},{"edgeType":"calls","source":4790,"target":564},{"edgeType":"contains","source":1522,"target":1597},{"edgeType":"calls","source":1970,"target":248},{"edgeType":"imports","source":396,"target":1754},{"edgeType":"calls","source":4139,"target":1719},{"edgeType":"calls","source":4148,"target":383},{"edgeType":"calls","source":4623,"target":456},{"edgeType":"calls","source":4200,"target":1942},{"edgeType":"calls","source":2742,"target":2745},{"edgeType":"calls","source":2403,"target":570},{"edgeType":"calls","source":2409,"target":384},{"edgeType":"calls","source":4896,"target":2563},{"edgeType":"calls","source":847,"target":179},{"edgeType":"calls","source":4532,"target":106},{"edgeType":"calls","source":4517,"target":571},{"edgeType":"contains","source":2976,"target":3032},{"edgeType":"calls","source":760,"target":762},{"edgeType":"calls","source":4517,"target":569},{"edgeType":"calls","source":4551,"target":572},{"edgeType":"calls","source":2403,"target":566},{"edgeType":"calls","source":4299,"target":985},{"edgeType":"calls","source":2206,"target":331},{"edgeType":"calls","source":1693,"target":382},{"edgeType":"contains","source":103,"target":133},{"edgeType":"contains","source":1522,"target":1594},{"edgeType":"contains","source":3175,"target":3202},{"edgeType":"calls","source":4599,"target":2256},{"edgeType":"calls","source":2323,"target":933},{"edgeType":"calls","source":4517,"target":568},{"edgeType":"calls","source":4551,"target":571},{"edgeType":"calls","source":2403,"target":567},{"edgeType":"calls","source":3912,"target":298},{"edgeType":"contains","source":103,"target":132},{"edgeType":"contains","source":2284,"target":2285},{"edgeType":"contains","source":1522,"target":1595},{"edgeType":"contains","source":3699,"target":3871},{"edgeType":"calls","source":3328,"target":1489},{"edgeType":"calls","source":4766,"target":249},{"edgeType":"calls","source":2785,"target":353},{"edgeType":"extends","source":1209,"target":1104},{"edgeType":"calls","source":4898,"target":2499},{"edgeType":"contains","source":1260,"target":1261},{"edgeType":"contains","source":3175,"target":3203},{"edgeType":"calls","source":4796,"target":376},{"edgeType":"calls","source":4517,"target":567},{"edgeType":"calls","source":4551,"target":570},{"edgeType":"contains","source":1749,"target":1962},{"edgeType":"calls","source":4601,"target":77},{"edgeType":"calls","source":2436,"target":1655},{"edgeType":"calls","source":1517,"target":547},{"edgeType":"contains","source":302,"target":309},{"edgeType":"calls","source":4110,"target":499},{"edgeType":"calls","source":3869,"target":571},{"edgeType":"contains","source":103,"target":136},{"edgeType":"contains","source":31,"target":2368},{"edgeType":"calls","source":561,"target":586},{"edgeType":"contains","source":1522,"target":1600},{"edgeType":"calls","source":3528,"target":571},{"edgeType":"calls","source":1176,"target":547},{"edgeType":"contains","source":1227,"target":1232},{"edgeType":"calls","source":4615,"target":701},{"edgeType":"contains","source":2647,"target":2664},{"edgeType":"calls","source":4766,"target":248},{"edgeType":"calls","source":4551,"target":569},{"edgeType":"calls","source":1653,"target":558},{"edgeType":"calls","source":4517,"target":566},{"edgeType":"imports","source":1934,"target":1654},{"edgeType":"contains","source":103,"target":134},{"edgeType":"calls","source":3869,"target":572},{"edgeType":"contains","source":103,"target":135},{"edgeType":"calls","source":3452,"target":814},{"edgeType":"calls","source":4863,"target":411},{"edgeType":"imports","source":2259,"target":1093},{"edgeType":"calls","source":561,"target":585},{"edgeType":"contains","source":1522,"target":1601},{"edgeType":"calls","source":3528,"target":572},{"edgeType":"contains","source":4266,"target":4270},{"edgeType":"calls","source":2476,"target":2531},{"edgeType":"contains","source":1257,"target":1360},{"edgeType":"contains","source":2647,"target":2665},{"edgeType":"calls","source":4836,"target":191},{"edgeType":"calls","source":1657,"target":437},{"edgeType":"calls","source":3869,"target":569},{"edgeType":"contains","source":3864,"target":4046},{"edgeType":"contains","source":1062,"target":1063},{"edgeType":"calls","source":4551,"target":568},{"edgeType":"calls","source":1898,"target":365},{"edgeType":"calls","source":3528,"target":569},{"edgeType":"imports","source":2259,"target":35},{"edgeType":"contains","source":4266,"target":4269},{"edgeType":"contains","source":103,"target":138},{"edgeType":"contains","source":1522,"target":1598},{"edgeType":"calls","source":457,"target":641},{"edgeType":"calls","source":1088,"target":106},{"edgeType":"calls","source":3296,"target":2476},{"edgeType":"contains","source":1227,"target":1230},{"edgeType":"calls","source":1699,"target":191},{"edgeType":"calls","source":3869,"target":570},{"edgeType":"calls","source":1657,"target":436},{"edgeType":"contains","source":302,"target":310},{"edgeType":"calls","source":4551,"target":567},{"edgeType":"calls","source":2513,"target":324},{"edgeType":"contains","source":2276,"target":3594},{"edgeType":"calls","source":3692,"target":772},{"edgeType":"imports","source":2276,"target":564},{"edgeType":"calls","source":2760,"target":1124},{"edgeType":"contains","source":103,"target":137},{"edgeType":"contains","source":1522,"target":1599},{"edgeType":"calls","source":3528,"target":570},{"edgeType":"calls","source":2635,"target":771},{"edgeType":"calls","source":747,"target":106},{"edgeType":"calls","source":1073,"target":565},{"edgeType":"calls","source":3869,"target":567},{"edgeType":"calls","source":3945,"target":325},{"edgeType":"calls","source":4529,"target":191},{"edgeType":"calls","source":3837,"target":502},{"edgeType":"contains","source":1095,"target":1099},{"edgeType":"calls","source":4551,"target":566},{"edgeType":"contains","source":302,"target":313},{"edgeType":"contains","source":1522,"target":1604},{"edgeType":"calls","source":2051,"target":901},{"edgeType":"calls","source":3528,"target":567},{"edgeType":"calls","source":4810,"target":2051},{"edgeType":"contains","source":3995,"target":4220},{"edgeType":"contains","source":103,"target":140},{"edgeType":"calls","source":827,"target":792},{"edgeType":"contains","source":43,"target":2000},{"edgeType":"contains","source":395,"target":2715},{"edgeType":"calls","source":3454,"target":747},{"edgeType":"calls","source":1156,"target":1163},{"edgeType":"calls","source":3261,"target":388},{"edgeType":"contains","source":3797,"target":4014},{"edgeType":"calls","source":3837,"target":503},{"edgeType":"calls","source":3869,"target":568},{"edgeType":"imports","source":396,"target":1763},{"edgeType":"contains","source":2976,"target":3041},{"edgeType":"calls","source":2547,"target":325},{"edgeType":"contains","source":302,"target":312},{"edgeType":"contains","source":1522,"target":1605},{"edgeType":"calls","source":1963,"target":457},{"edgeType":"contains","source":3995,"target":4218},{"edgeType":"calls","source":2051,"target":900},{"edgeType":"calls","source":4447,"target":1675},{"edgeType":"calls","source":4453,"target":1489},{"edgeType":"calls","source":3528,"target":568},{"edgeType":"contains","source":6,"target":2089},{"edgeType":"calls","source":3449,"target":1960},{"edgeType":"contains","source":103,"target":139},{"edgeType":"contains","source":1954,"target":1955},{"edgeType":"contains","source":3995,"target":4219},{"edgeType":"calls","source":4834,"target":249},{"edgeType":"calls","source":4794,"target":1489},{"edgeType":"calls","source":3261,"target":389},{"edgeType":"calls","source":3151,"target":628},{"edgeType":"calls","source":3261,"target":386},{"edgeType":"contains","source":3797,"target":4013},{"edgeType":"calls","source":1733,"target":191},{"edgeType":"calls","source":1653,"target":557},{"edgeType":"contains","source":1062,"target":1067},{"edgeType":"calls","source":4551,"target":564},{"edgeType":"contains","source":1522,"target":1602},{"edgeType":"contains","source":3995,"target":4217},{"edgeType":"contains","source":1688,"target":1741},{"edgeType":"calls","source":4847,"target":902},{"edgeType":"contains","source":103,"target":142},{"edgeType":"contains","source":1257,"target":1361},{"edgeType":"contains","source":1227,"target":1234},{"edgeType":"calls","source":3390,"target":1672},{"edgeType":"calls","source":4834,"target":248},{"edgeType":"contains","source":2647,"target":2666},{"edgeType":"contains","source":302,"target":314},{"edgeType":"calls","source":4679,"target":1880},{"edgeType":"contains","source":3038,"target":3231},{"edgeType":"calls","source":3869,"target":566},{"edgeType":"calls","source":4847,"target":900},{"edgeType":"calls","source":4868,"target":249},{"edgeType":"calls","source":4822,"target":1675},{"edgeType":"contains","source":1522,"target":1603},{"edgeType":"calls","source":2051,"target":902},{"edgeType":"contains","source":1688,"target":1742},{"edgeType":"calls","source":2048,"target":2052},{"edgeType":"contains","source":3797,"target":4012},{"edgeType":"calls","source":1497,"target":106},{"edgeType":"calls","source":3528,"target":566},{"edgeType":"contains","source":6,"target":1034},{"edgeType":"contains","source":103,"target":141},{"edgeType":"contains","source":1257,"target":1362},{"edgeType":"calls","source":4847,"target":901},{"edgeType":"calls","source":3121,"target":499},{"edgeType":"contains","source":2647,"target":2667},{"edgeType":"calls","source":3261,"target":387},{"edgeType":"calls","source":4628,"target":388},{"edgeType":"contains","source":320,"target":783},{"edgeType":"calls","source":2548,"target":388},{"edgeType":"contains","source":3162,"target":416},{"edgeType":"contains","source":2976,"target":3011},{"edgeType":"contains","source":3175,"target":3184},{"edgeType":"imports","source":3571,"target":1688},{"edgeType":"imports","source":3162,"target":625},{"edgeType":"calls","source":4213,"target":568},{"edgeType":"calls","source":4280,"target":1663},{"edgeType":"contains","source":4001,"target":4005},{"edgeType":"contains","source":4099,"target":4138},{"edgeType":"contains","source":2777,"target":2837},{"edgeType":"contains","source":103,"target":111},{"edgeType":"imports","source":44,"target":35},{"edgeType":"contains","source":2201,"target":2724},{"edgeType":"contains","source":4451,"target":4853},{"edgeType":"calls","source":3809,"target":3580},{"edgeType":"calls","source":2548,"target":389},{"edgeType":"calls","source":4628,"target":387},{"edgeType":"contains","source":320,"target":782},{"edgeType":"contains","source":1090,"target":1224},{"edgeType":"contains","source":3175,"target":3185},{"edgeType":"calls","source":4498,"target":189},{"edgeType":"calls","source":4213,"target":569},{"edgeType":"calls","source":4280,"target":1662},{"edgeType":"contains","source":4099,"target":4137},{"edgeType":"calls","source":2759,"target":191},{"edgeType":"contains","source":103,"target":110},{"edgeType":"contains","source":2201,"target":2725},{"edgeType":"calls","source":2548,"target":386},{"edgeType":"calls","source":4628,"target":386},{"edgeType":"contains","source":3175,"target":3182},{"edgeType":"calls","source":4674,"target":4245},{"edgeType":"calls","source":4762,"target":460},{"edgeType":"contains","source":953,"target":1246},{"edgeType":"contains","source":3099,"target":1310},{"edgeType":"contains","source":1090,"target":1227},{"edgeType":"calls","source":4213,"target":566},{"edgeType":"calls","source":2452,"target":191},{"edgeType":"calls","source":3625,"target":824},{"edgeType":"contains","source":2777,"target":2835},{"edgeType":"contains","source":2118,"target":2124},{"edgeType":"calls","source":1258,"target":212},{"edgeType":"contains","source":2204,"target":2629},{"edgeType":"contains","source":103,"target":113},{"edgeType":"contains","source":2511,"target":2625},{"edgeType":"calls","source":2550,"target":325},{"edgeType":"calls","source":2548,"target":387},{"edgeType":"calls","source":433,"target":417},{"edgeType":"contains","source":953,"target":1245},{"edgeType":"imports","source":1160,"target":320},{"edgeType":"contains","source":3175,"target":3183},{"edgeType":"calls","source":4628,"target":385},{"edgeType":"calls","source":4213,"target":567},{"edgeType":"calls","source":4450,"target":1675},{"edgeType":"contains","source":2777,"target":2836},{"edgeType":"contains","source":103,"target":112},{"edgeType":"contains","source":2204,"target":2630},{"edgeType":"contains","source":320,"target":784},{"edgeType":"calls","source":1258,"target":211},{"edgeType":"calls","source":1250,"target":454},{"edgeType":"contains","source":1522,"target":1579},{"edgeType":"contains","source":953,"target":1248},{"edgeType":"calls","source":4104,"target":772},{"edgeType":"calls","source":4051,"target":301},{"edgeType":"calls","source":747,"target":191},{"edgeType":"calls","source":4628,"target":384},{"edgeType":"calls","source":2476,"target":502},{"edgeType":"contains","source":3175,"target":3188},{"edgeType":"calls","source":2548,"target":384},{"edgeType":"calls","source":1728,"target":434},{"edgeType":"imports","source":2259,"target":2188},{"edgeType":"contains","source":2019,"target":2028},{"edgeType":"contains","source":37,"target":47},{"edgeType":"contains","source":103,"target":115},{"edgeType":"calls","source":3639,"target":388},{"edgeType":"contains","source":1522,"target":1580},{"edgeType":"calls","source":1185,"target":354},{"edgeType":"calls","source":4038,"target":705},{"edgeType":"contains","source":1688,"target":1719},{"edgeType":"contains","source":3175,"target":3189},{"edgeType":"calls","source":4696,"target":389},{"edgeType":"calls","source":2548,"target":385},{"edgeType":"calls","source":4628,"target":383},{"edgeType":"calls","source":2476,"target":503},{"edgeType":"calls","source":644,"target":212},{"edgeType":"calls","source":3639,"target":389},{"edgeType":"calls","source":3854,"target":66},{"edgeType":"contains","source":1722,"target":1723},{"edgeType":"contains","source":3,"target":43},{"edgeType":"contains","source":103,"target":114},{"edgeType":"calls","source":1385,"target":496},{"edgeType":"contains","source":44,"target":886},{"edgeType":"contains","source":4451,"target":4856},{"edgeType":"calls","source":1660,"target":427},{"edgeType":"calls","source":1159,"target":106},{"edgeType":"contains","source":1688,"target":1716},{"edgeType":"calls","source":3977,"target":479},{"edgeType":"contains","source":2806,"target":2998},{"edgeType":"imports","source":1918,"target":2186},{"edgeType":"calls","source":2850,"target":533},{"edgeType":"calls","source":4577,"target":906},{"edgeType":"contains","source":3175,"target":3186},{"edgeType":"calls","source":2036,"target":402},{"edgeType":"calls","source":4696,"target":388},{"edgeType":"contains","source":1522,"target":1577},{"edgeType":"calls","source":2548,"target":382},{"edgeType":"calls","source":4628,"target":382},{"edgeType":"calls","source":1770,"target":191},{"edgeType":"calls","source":3639,"target":386},{"edgeType":"contains","source":37,"target":49},{"edgeType":"contains","source":103,"target":117},{"edgeType":"calls","source":1876,"target":1133},{"edgeType":"contains","source":1522,"target":1578},{"edgeType":"contains","source":1688,"target":1717},{"edgeType":"calls","source":2036,"target":401},{"edgeType":"calls","source":2778,"target":2766},{"edgeType":"calls","source":2548,"target":383},{"edgeType":"imports","source":1722,"target":862},{"edgeType":"contains","source":3175,"target":3187},{"edgeType":"calls","source":4696,"target":387},{"edgeType":"calls","source":4330,"target":4334},{"edgeType":"calls","source":1728,"target":435},{"edgeType":"contains","source":37,"target":48},{"edgeType":"calls","source":1258,"target":1264},{"edgeType":"contains","source":103,"target":116},{"edgeType":"contains","source":2201,"target":2727},{"edgeType":"calls","source":1429,"target":191},{"edgeType":"calls","source":3639,"target":387},{"edgeType":"calls","source":3507,"target":3422},{"edgeType":"contains","source":103,"target":119},{"edgeType":"calls","source":1385,"target":493},{"edgeType":"contains","source":1522,"target":1583},{"edgeType":"contains","source":1485,"target":1673},{"edgeType":"calls","source":3254,"target":692},{"edgeType":"calls","source":3292,"target":571},{"edgeType":"contains","source":953,"target":1252},{"edgeType":"contains","source":2647,"target":2648},{"edgeType":"calls","source":4696,"target":386},{"edgeType":"contains","source":3175,"target":3192},{"edgeType":"calls","source":304,"target":179},{"edgeType":"calls","source":3639,"target":384},{"edgeType":"calls","source":3751,"target":83},{"edgeType":"contains","source":37,"target":51},{"edgeType":"calls","source":3292,"target":572},{"edgeType":"contains","source":1522,"target":1584},{"edgeType":"contains","source":1485,"target":1674},{"edgeType":"calls","source":4138,"target":772},{"edgeType":"calls","source":1385,"target":492},{"edgeType":"contains","source":2647,"target":2649},{"edgeType":"calls","source":771,"target":499},{"edgeType":"calls","source":4696,"target":385},{"edgeType":"contains","source":3099,"target":1321},{"edgeType":"calls","source":2476,"target":499},{"edgeType":"imports","source":3710,"target":3714},{"edgeType":"contains","source":3175,"target":3193},{"edgeType":"calls","source":4501,"target":88},{"edgeType":"calls","source":2307,"target":453},{"edgeType":"calls","source":4518,"target":1675},{"edgeType":"calls","source":404,"target":249},{"edgeType":"contains","source":37,"target":50},{"edgeType":"calls","source":3639,"target":385},{"edgeType":"calls","source":1960,"target":1693},{"edgeType":"contains","source":103,"target":118},{"edgeType":"calls","source":1244,"target":638},{"edgeType":"contains","source":1522,"target":1581},{"edgeType":"calls","source":4819,"target":1856},{"edgeType":"contains","source":37,"target":53},{"edgeType":"calls","source":2780,"target":585},{"edgeType":"calls","source":2784,"target":461},{"edgeType":"contains","source":103,"target":121},{"edgeType":"calls","source":3366,"target":389},{"edgeType":"calls","source":1185,"target":353},{"edgeType":"calls","source":4696,"target":384},{"edgeType":"calls","source":3254,"target":690},{"edgeType":"calls","source":3292,"target":569},{"edgeType":"contains","source":2777,"target":2844},{"edgeType":"calls","source":644,"target":211},{"edgeType":"contains","source":3175,"target":3190},{"edgeType":"calls","source":4710,"target":3121},{"edgeType":"calls","source":2985,"target":572},{"edgeType":"calls","source":4833,"target":365},{"edgeType":"calls","source":4424,"target":1417},{"edgeType":"calls","source":4330,"target":4331},{"edgeType":"contains","source":2019,"target":2030},{"edgeType":"calls","source":3639,"target":382},{"edgeType":"calls","source":1385,"target":495},{"edgeType":"imports","source":44,"target":41},{"edgeType":"calls","source":3870,"target":1677},{"edgeType":"calls","source":1660,"target":426},{"edgeType":"contains","source":103,"target":120},{"edgeType":"contains","source":6,"target":2070},{"edgeType":"calls","source":1385,"target":494},{"edgeType":"calls","source":3292,"target":570},{"edgeType":"contains","source":1522,"target":1582},{"edgeType":"calls","source":4696,"target":383},{"edgeType":"calls","source":4724,"target":572},{"edgeType":"calls","source":645,"target":179},{"edgeType":"calls","source":639,"target":365},{"edgeType":"calls","source":3001,"target":77},{"edgeType":"calls","source":2780,"target":586},{"edgeType":"calls","source":1660,"target":425},{"edgeType":"contains","source":3175,"target":3191},{"edgeType":"calls","source":986,"target":179},{"edgeType":"calls","source":2206,"target":411},{"edgeType":"calls","source":3639,"target":383},{"edgeType":"calls","source":4085,"target":298},{"edgeType":"imports","source":44,"target":42},{"edgeType":"contains","source":37,"target":52},{"edgeType":"contains","source":2019,"target":2031},{"edgeType":"calls","source":1385,"target":489},{"edgeType":"imports","source":2255,"target":206},{"edgeType":"contains","source":37,"target":55},{"edgeType":"contains","source":103,"target":123},{"edgeType":"calls","source":1489,"target":1493},{"edgeType":"calls","source":2985,"target":570},{"edgeType":"calls","source":4724,"target":571},{"edgeType":"calls","source":1258,"target":198},{"edgeType":"calls","source":3366,"target":387},{"edgeType":"calls","source":4696,"target":382},{"edgeType":"calls","source":3292,"target":567},{"edgeType":"contains","source":953,"target":1256},{"edgeType":"calls","source":3230,"target":375},{"edgeType":"contains","source":4451,"target":4865},{"edgeType":"contains","source":3175,"target":3196},{"edgeType":"contains","source":1522,"target":1588},{"edgeType":"contains","source":1485,"target":1678},{"edgeType":"contains","source":3864,"target":4036},{"edgeType":"imports","source":44,"target":39},{"edgeType":"contains","source":3534,"target":3696},{"edgeType":"contains","source":37,"target":54},{"edgeType":"calls","source":1385,"target":488},{"edgeType":"contains","source":103,"target":122},{"edgeType":"calls","source":3366,"target":388},{"edgeType":"calls","source":3487,"target":865},{"edgeType":"calls","source":3292,"target":568},{"edgeType":"calls","source":1258,"target":197},{"edgeType":"calls","source":4724,"target":570},{"edgeType":"contains","source":953,"target":1255},{"edgeType":"contains","source":2482,"target":2483},{"edgeType":"calls","source":2985,"target":571},{"edgeType":"imports","source":1160,"target":1383},{"edgeType":"contains","source":1722,"target":1731},{"edgeType":"contains","source":3797,"target":3998},{"edgeType":"contains","source":3175,"target":3197},{"edgeType":"calls","source":2510,"target":498},{"edgeType":"imports","source":2488,"target":2495},{"edgeType":"contains","source":1522,"target":1589},{"edgeType":"contains","source":1643,"target":2066},{"edgeType":"imports","source":44,"target":40},{"edgeType":"contains","source":1522,"target":1585},{"edgeType":"contains","source":1485,"target":1675},{"edgeType":"contains","source":37,"target":57},{"edgeType":"contains","source":103,"target":125},{"edgeType":"calls","source":1385,"target":491},{"edgeType":"contains","source":2229,"target":2923},{"edgeType":"calls","source":3366,"target":385},{"edgeType":"calls","source":2985,"target":568},{"edgeType":"calls","source":4784,"target":1880},{"edgeType":"calls","source":2880,"target":2766},{"edgeType":"contains","source":302,"target":298},{"edgeType":"contains","source":3175,"target":3194},{"edgeType":"calls","source":4677,"target":969},{"edgeType":"calls","source":4724,"target":569},{"edgeType":"calls","source":404,"target":248},{"edgeType":"calls","source":1888,"target":753},{"edgeType":"calls","source":4076,"target":572},{"edgeType":"calls","source":4333,"target":1063},{"edgeType":"contains","source":1522,"target":1586},{"edgeType":"calls","source":1385,"target":490},{"edgeType":"contains","source":37,"target":56},{"edgeType":"contains","source":1485,"target":1676},{"edgeType":"calls","source":1428,"target":1271},{"edgeType":"contains","source":103,"target":124},{"edgeType":"calls","source":3529,"target":1675},{"edgeType":"calls","source":2985,"target":569},{"edgeType":"calls","source":3292,"target":566},{"edgeType":"calls","source":1261,"target":106},{"edgeType":"contains","source":395,"target":1643},{"edgeType":"calls","source":3366,"target":386},{"edgeType":"contains","source":3175,"target":3195},{"edgeType":"calls","source":4724,"target":568},{"edgeType":"calls","source":1888,"target":752},{"edgeType":"contains","source":1522,"target":1587},{"edgeType":"calls","source":4299,"target":1059},{"edgeType":"contains","source":3864,"target":4033},{"edgeType":"contains","source":1324,"target":1354},{"edgeType":"imports","source":2021,"target":40},{"edgeType":"calls","source":3522,"target":865},{"edgeType":"calls","source":4811,"target":4245},{"edgeType":"contains","source":36,"target":57},{"edgeType":"calls","source":3702,"target":570},{"edgeType":"contains","source":2806,"target":2979},{"edgeType":"imports","source":2259,"target":1118},{"edgeType":"contains","source":320,"target":766},{"edgeType":"calls","source":1765,"target":365},{"edgeType":"calls","source":2685,"target":386},{"edgeType":"calls","source":2037,"target":389},{"edgeType":"contains","source":1324,"target":1355},{"edgeType":"calls","source":2930,"target":191},{"edgeType":"contains","source":36,"target":56},{"edgeType":"imports","source":2021,"target":39},{"edgeType":"calls","source":2685,"target":387},{"edgeType":"calls","source":3702,"target":571},{"edgeType":"imports","source":2259,"target":1117},{"edgeType":"calls","source":4587,"target":1675},{"edgeType":"calls","source":4593,"target":1489},{"edgeType":"calls","source":1063,"target":985},{"edgeType":"calls","source":4720,"target":723},{"edgeType":"contains","source":3797,"target":3969},{"edgeType":"calls","source":2037,"target":388},{"edgeType":"contains","source":1324,"target":1356},{"edgeType":"contains","source":1324,"target":1352},{"edgeType":"calls","source":3572,"target":3541},{"edgeType":"imports","source":1918,"target":2174},{"edgeType":"calls","source":3702,"target":568},{"edgeType":"calls","source":3001,"target":101},{"edgeType":"contains","source":36,"target":59},{"edgeType":"calls","source":2887,"target":464},{"edgeType":"contains","source":2204,"target":2612},{"edgeType":"contains","source":2481,"target":2482},{"edgeType":"contains","source":3162,"target":397},{"edgeType":"calls","source":3229,"target":1489},{"edgeType":"calls","source":4609,"target":992},{"edgeType":"calls","source":2632,"target":970},{"edgeType":"calls","source":4720,"target":722},{"edgeType":"calls","source":2685,"target":384},{"edgeType":"contains","source":1654,"target":1693},{"edgeType":"contains","source":1324,"target":1353},{"edgeType":"calls","source":3001,"target":102},{"edgeType":"imports","source":2201,"target":799},{"edgeType":"calls","source":3702,"target":569},{"edgeType":"contains","source":6,"target":2045},{"edgeType":"contains","source":36,"target":58},{"edgeType":"contains","source":2204,"target":2613},{"edgeType":"calls","source":3381,"target":3121},{"edgeType":"contains","source":2226,"target":2988},{"edgeType":"contains","source":2806,"target":2978},{"edgeType":"calls","source":3149,"target":1856},{"edgeType":"calls","source":4703,"target":191},{"edgeType":"contains","source":320,"target":767},{"edgeType":"calls","source":4793,"target":572},{"edgeType":"contains","source":1090,"target":1209},{"edgeType":"contains","source":3162,"target":398},{"edgeType":"calls","source":2685,"target":385},{"edgeType":"calls","source":4396,"target":4423},{"edgeType":"calls","source":498,"target":533},{"edgeType":"calls","source":3702,"target":566},{"edgeType":"calls","source":906,"target":564},{"edgeType":"calls","source":2859,"target":1330},{"edgeType":"calls","source":3001,"target":99},{"edgeType":"contains","source":36,"target":61},{"edgeType":"calls","source":3868,"target":705},{"edgeType":"contains","source":320,"target":771},{"edgeType":"contains","source":2204,"target":2618},{"edgeType":"contains","source":4099,"target":4125},{"edgeType":"calls","source":4667,"target":249},{"edgeType":"calls","source":1258,"target":1279},{"edgeType":"calls","source":4720,"target":720},{"edgeType":"calls","source":1817,"target":863},{"edgeType":"calls","source":4111,"target":571},{"edgeType":"calls","source":4793,"target":571},{"edgeType":"contains","source":953,"target":1231},{"edgeType":"calls","source":2037,"target":385},{"edgeType":"calls","source":2728,"target":106},{"edgeType":"calls","source":2753,"target":388},{"edgeType":"calls","source":2685,"target":382},{"edgeType":"contains","source":1324,"target":1359},{"edgeType":"calls","source":4596,"target":336},{"edgeType":"calls","source":534,"target":469},{"edgeType":"calls","source":2543,"target":556},{"edgeType":"calls","source":2542,"target":587},{"edgeType":"calls","source":2548,"target":401},{"edgeType":"calls","source":2282,"target":191},{"edgeType":"calls","source":3702,"target":567},{"edgeType":"calls","source":3001,"target":100},{"edgeType":"calls","source":3462,"target":608},{"edgeType":"imports","source":2259,"target":2170},{"edgeType":"contains","source":36,"target":60},{"edgeType":"contains","source":696,"target":741},{"edgeType":"calls","source":1307,"target":817},{"edgeType":"contains","source":4451,"target":4840},{"edgeType":"contains","source":2204,"target":2619},{"edgeType":"contains","source":2204,"target":2620},{"edgeType":"calls","source":4720,"target":719},{"edgeType":"calls","source":2548,"target":402},{"edgeType":"contains","source":3599,"target":3769},{"edgeType":"calls","source":1289,"target":317},{"edgeType":"calls","source":4793,"target":570},{"edgeType":"calls","source":2037,"target":384},{"edgeType":"calls","source":4111,"target":572},{"edgeType":"calls","source":2753,"target":389},{"edgeType":"imports","source":2021,"target":35},{"edgeType":"calls","source":2685,"target":383},{"edgeType":"calls","source":4667,"target":248},{"edgeType":"calls","source":534,"target":468},{"edgeType":"calls","source":1498,"target":1241},{"edgeType":"calls","source":4330,"target":4351},{"edgeType":"calls","source":4396,"target":191},{"edgeType":"imports","source":2201,"target":796},{"edgeType":"calls","source":3812,"target":325},{"edgeType":"contains","source":2204,"target":2616},{"edgeType":"contains","source":4099,"target":4123},{"edgeType":"calls","source":4089,"target":194},{"edgeType":"calls","source":4720,"target":718},{"edgeType":"calls","source":4737,"target":191},{"edgeType":"calls","source":4793,"target":569},{"edgeType":"calls","source":4694,"target":4695},{"edgeType":"calls","source":4111,"target":569},{"edgeType":"calls","source":1897,"target":499},{"edgeType":"contains","source":3797,"target":3972},{"edgeType":"calls","source":2037,"target":387},{"edgeType":"extends","source":3166,"target":1776},{"edgeType":"calls","source":4330,"target":4352},{"edgeType":"calls","source":2753,"target":386},{"edgeType":"contains","source":1324,"target":1357},{"edgeType":"calls","source":2998,"target":191},{"edgeType":"calls","source":3001,"target":98},{"edgeType":"contains","source":4099,"target":4122},{"edgeType":"calls","source":906,"target":565},{"edgeType":"imports","source":2259,"target":2168},{"edgeType":"contains","source":36,"target":62},{"edgeType":"contains","source":3,"target":28},{"edgeType":"contains","source":2204,"target":2617},{"edgeType":"calls","source":4793,"target":568},{"edgeType":"calls","source":1157,"target":183},{"edgeType":"calls","source":2036,"target":417},{"edgeType":"calls","source":2037,"target":386},{"edgeType":"contains","source":3797,"target":3971},{"edgeType":"calls","source":4111,"target":570},{"edgeType":"contains","source":1090,"target":1213},{"edgeType":"calls","source":2753,"target":387},{"edgeType":"contains","source":1324,"target":1358},{"edgeType":"calls","source":4661,"target":1489},{"edgeType":"calls","source":534,"target":470},{"edgeType":"calls","source":4720,"target":717},{"edgeType":"contains","source":3208,"target":3210},{"edgeType":"contains","source":3175,"target":3176},{"edgeType":"calls","source":4536,"target":77},{"edgeType":"calls","source":338,"target":198},{"edgeType":"contains","source":3,"target":31},{"edgeType":"contains","source":1952,"target":1978},{"edgeType":"calls","source":4111,"target":567},{"edgeType":"calls","source":4793,"target":567},{"edgeType":"calls","source":534,"target":465},{"edgeType":"contains","source":4166,"target":4167},{"edgeType":"contains","source":2204,"target":2623},{"edgeType":"calls","source":1075,"target":606},{"edgeType":"calls","source":2683,"target":1497},{"edgeType":"calls","source":4720,"target":716},{"edgeType":"calls","source":2753,"target":384},{"edgeType":"contains","source":3175,"target":3177},{"edgeType":"contains","source":3208,"target":3211},{"edgeType":"calls","source":338,"target":197},{"edgeType":"calls","source":3902,"target":705},{"edgeType":"calls","source":1517,"target":645},{"edgeType":"calls","source":3558,"target":1856},{"edgeType":"calls","source":1873,"target":179},{"edgeType":"calls","source":4111,"target":568},{"edgeType":"contains","source":2118,"target":2119},{"edgeType":"contains","source":2204,"target":2624},{"edgeType":"calls","source":3320,"target":777},{"edgeType":"contains","source":3599,"target":3773},{"edgeType":"calls","source":1283,"target":499},{"edgeType":"calls","source":1075,"target":605},{"edgeType":"contains","source":1090,"target":1215},{"edgeType":"calls","source":4720,"target":715},{"edgeType":"calls","source":2753,"target":385},{"edgeType":"calls","source":4861,"target":572},{"edgeType":"calls","source":4771,"target":191},{"edgeType":"calls","source":4793,"target":566},{"edgeType":"contains","source":1090,"target":1219},{"edgeType":"calls","source":2447,"target":354},{"edgeType":"calls","source":4348,"target":1675},{"edgeType":"calls","source":1839,"target":179},{"edgeType":"contains","source":3797,"target":3976},{"edgeType":"calls","source":1498,"target":1237},{"edgeType":"calls","source":3748,"target":191},{"edgeType":"calls","source":534,"target":467},{"edgeType":"calls","source":1975,"target":191},{"edgeType":"calls","source":1289,"target":316},{"edgeType":"contains","source":2204,"target":2621},{"edgeType":"calls","source":2753,"target":382},{"edgeType":"calls","source":1891,"target":1738},{"edgeType":"calls","source":2037,"target":383},{"edgeType":"calls","source":3292,"target":585},{"edgeType":"calls","source":4654,"target":1703},{"edgeType":"contains","source":3174,"target":3204},{"edgeType":"contains","source":1257,"target":1324},{"edgeType":"calls","source":4720,"target":714},{"edgeType":"contains","source":3099,"target":1301},{"edgeType":"calls","source":4861,"target":571},{"edgeType":"calls","source":908,"target":499},{"edgeType":"contains","source":3174,"target":3206},{"edgeType":"calls","source":2350,"target":191},{"edgeType":"contains","source":2021,"target":1952},{"edgeType":"calls","source":4280,"target":1668},{"edgeType":"calls","source":4012,"target":464},{"edgeType":"calls","source":1851,"target":863},{"edgeType":"calls","source":1289,"target":315},{"edgeType":"calls","source":4861,"target":570},{"edgeType":"calls","source":4727,"target":4724},{"edgeType":"calls","source":534,"target":466},{"edgeType":"calls","source":1990,"target":1839},{"edgeType":"contains","source":2204,"target":2622},{"edgeType":"calls","source":2037,"target":382},{"edgeType":"calls","source":4123,"target":194},{"edgeType":"calls","source":4111,"target":566},{"edgeType":"calls","source":1157,"target":179},{"edgeType":"calls","source":3292,"target":586},{"edgeType":"calls","source":3347,"target":995},{"edgeType":"calls","source":4703,"target":183},{"edgeType":"calls","source":4720,"target":713},{"edgeType":"calls","source":4626,"target":456},{"edgeType":"contains","source":3174,"target":3205},{"edgeType":"contains","source":1090,"target":1217},{"edgeType":"calls","source":2753,"target":383},{"edgeType":"imports","source":3534,"target":1757},{"edgeType":"contains","source":1090,"target":1221},{"edgeType":"contains","source":3043,"target":3044},{"edgeType":"contains","source":3175,"target":3180},{"edgeType":"calls","source":4280,"target":1667},{"edgeType":"contains","source":3534,"target":3679},{"edgeType":"calls","source":1919,"target":1921},{"edgeType":"imports","source":2259,"target":1123},{"edgeType":"contains","source":2777,"target":2833},{"edgeType":"calls","source":4213,"target":572},{"edgeType":"calls","source":4861,"target":569},{"edgeType":"contains","source":2019,"target":2020},{"edgeType":"calls","source":2681,"target":498},{"edgeType":"contains","source":2204,"target":2627},{"edgeType":"calls","source":4720,"target":712},{"edgeType":"calls","source":2891,"target":330},{"edgeType":"calls","source":4882,"target":2032},{"edgeType":"calls","source":1653,"target":653},{"edgeType":"contains","source":3175,"target":3181},{"edgeType":"imports","source":396,"target":1796},{"edgeType":"calls","source":4456,"target":438},{"edgeType":"calls","source":2447,"target":353},{"edgeType":"contains","source":1952,"target":1983},{"edgeType":"calls","source":4280,"target":1666},{"edgeType":"imports","source":2259,"target":1121},{"edgeType":"calls","source":4861,"target":568},{"edgeType":"contains","source":1952,"target":1984},{"edgeType":"contains","source":2204,"target":2628},{"edgeType":"calls","source":4729,"target":1489},{"edgeType":"calls","source":2979,"target":774},{"edgeType":"calls","source":2877,"target":2879},{"edgeType":"contains","source":320,"target":781},{"edgeType":"contains","source":3175,"target":3178},{"edgeType":"calls","source":2524,"target":77},{"edgeType":"imports","source":2021,"target":42},{"edgeType":"calls","source":4456,"target":437},{"edgeType":"calls","source":4454,"target":499},{"edgeType":"imports","source":2259,"target":63},{"edgeType":"calls","source":1973,"target":249},{"edgeType":"calls","source":4280,"target":1665},{"edgeType":"calls","source":4213,"target":570},{"edgeType":"imports","source":2259,"target":1120},{"edgeType":"contains","source":3797,"target":3980},{"edgeType":"calls","source":4861,"target":567},{"edgeType":"calls","source":1250,"target":464},{"edgeType":"calls","source":4628,"target":389},{"edgeType":"imports","source":2021,"target":41},{"edgeType":"imports","source":1918,"target":63},{"edgeType":"contains","source":3175,"target":3179},{"edgeType":"calls","source":4456,"target":436},{"edgeType":"imports","source":2259,"target":1119},{"edgeType":"calls","source":4280,"target":1664},{"edgeType":"calls","source":1973,"target":248},{"edgeType":"calls","source":4213,"target":571},{"edgeType":"contains","source":4166,"target":4168},{"edgeType":"calls","source":4861,"target":566},{"edgeType":"contains","source":2204,"target":2626},{"edgeType":"contains","source":953,"target":1240},{"edgeType":"calls","source":970,"target":687},{"edgeType":"calls","source":986,"target":191},{"edgeType":"calls","source":433,"target":383},{"edgeType":"contains","source":3099,"target":1279},{"edgeType":"calls","source":3945,"target":387},{"edgeType":"contains","source":1647,"target":4009},{"edgeType":"calls","source":4587,"target":569},{"edgeType":"calls","source":3871,"target":567},{"edgeType":"calls","source":4707,"target":1077},{"edgeType":"contains","source":1148,"target":1508},{"edgeType":"calls","source":510,"target":110},{"edgeType":"contains","source":4099,"target":4105},{"edgeType":"calls","source":3606,"target":325},{"edgeType":"calls","source":2748,"target":498},{"edgeType":"contains","source":395,"target":3710},{"edgeType":"calls","source":3456,"target":747},{"edgeType":"extends","source":4130,"target":3652},{"edgeType":"contains","source":4524,"target":4671},{"edgeType":"calls","source":3945,"target":388},{"edgeType":"contains","source":2255,"target":4189},{"edgeType":"calls","source":1124,"target":1159},{"edgeType":"calls","source":2549,"target":325},{"edgeType":"calls","source":4636,"target":106},{"edgeType":"calls","source":1965,"target":457},{"edgeType":"calls","source":2656,"target":179},{"edgeType":"calls","source":1769,"target":191},{"edgeType":"calls","source":3871,"target":568},{"edgeType":"calls","source":1951,"target":1948},{"edgeType":"calls","source":4849,"target":902},{"edgeType":"calls","source":4396,"target":4375},{"edgeType":"calls","source":4449,"target":1675},{"edgeType":"calls","source":4542,"target":906},{"edgeType":"calls","source":4587,"target":568},{"edgeType":"contains","source":3599,"target":3748},{"edgeType":"calls","source":433,"target":382},{"edgeType":"calls","source":817,"target":106},{"edgeType":"contains","source":3,"target":6},{"edgeType":"calls","source":2813,"target":1655},{"edgeType":"contains","source":4099,"target":4104},{"edgeType":"calls","source":2881,"target":2718},{"edgeType":"contains","source":2084,"target":2091},{"edgeType":"calls","source":2748,"target":499},{"edgeType":"calls","source":1733,"target":249},{"edgeType":"calls","source":2977,"target":1856},{"edgeType":"calls","source":3451,"target":1960},{"edgeType":"contains","source":2631,"target":989},{"edgeType":"calls","source":433,"target":385},{"edgeType":"contains","source":3797,"target":3951},{"edgeType":"contains","source":862,"target":863},{"edgeType":"calls","source":1841,"target":1133},{"edgeType":"contains","source":2269,"target":2695},{"edgeType":"calls","source":3945,"target":385},{"edgeType":"calls","source":4396,"target":4374},{"edgeType":"calls","source":4849,"target":901},{"edgeType":"calls","source":533,"target":456},{"edgeType":"contains","source":1148,"target":1510},{"edgeType":"calls","source":4587,"target":567},{"edgeType":"calls","source":2475,"target":502},{"edgeType":"calls","source":3011,"target":1856},{"edgeType":"contains","source":4524,"target":4669},{"edgeType":"calls","source":1258,"target":179},{"edgeType":"calls","source":433,"target":384},{"edgeType":"contains","source":2976,"target":2977},{"edgeType":"calls","source":3945,"target":386},{"edgeType":"contains","source":3099,"target":1278},{"edgeType":"calls","source":3871,"target":566},{"edgeType":"contains","source":1148,"target":1509},{"edgeType":"calls","source":4849,"target":900},{"edgeType":"calls","source":2475,"target":503},{"edgeType":"calls","source":4587,"target":566},{"edgeType":"contains","source":1952,"target":1953},{"edgeType":"contains","source":4099,"target":4102},{"edgeType":"contains","source":2806,"target":2961},{"edgeType":"contains","source":4524,"target":4668},{"edgeType":"calls","source":3352,"target":1856},{"edgeType":"calls","source":1909,"target":1133},{"edgeType":"calls","source":3945,"target":383},{"edgeType":"calls","source":1077,"target":499},{"edgeType":"calls","source":325,"target":556},{"edgeType":"contains","source":3099,"target":1283},{"edgeType":"contains","source":1148,"target":1512},{"edgeType":"calls","source":4675,"target":1008},{"edgeType":"calls","source":665,"target":586},{"edgeType":"contains","source":4045,"target":498},{"edgeType":"calls","source":975,"target":490},{"edgeType":"contains","source":2084,"target":2094},{"edgeType":"contains","source":3797,"target":3958},{"edgeType":"contains","source":3,"target":11},{"edgeType":"calls","source":3945,"target":382},{"edgeType":"calls","source":1385,"target":464},{"edgeType":"calls","source":1394,"target":185},{"edgeType":"contains","source":31,"target":1257},{"edgeType":"calls","source":3773,"target":3600},{"edgeType":"calls","source":1678,"target":894},{"edgeType":"calls","source":3945,"target":384},{"edgeType":"contains","source":862,"target":864},{"edgeType":"contains","source":3795,"target":4018},{"edgeType":"calls","source":331,"target":369},{"edgeType":"contains","source":1148,"target":1511},{"edgeType":"calls","source":665,"target":585},{"edgeType":"contains","source":1952,"target":1959},{"edgeType":"calls","source":985,"target":179},{"edgeType":"calls","source":975,"target":489},{"edgeType":"contains","source":2084,"target":2095},{"edgeType":"calls","source":3917,"target":194},{"edgeType":"contains","source":4524,"target":4674},{"edgeType":"contains","source":2255,"target":4193},{"edgeType":"contains","source":3669,"target":3695},{"edgeType":"calls","source":3969,"target":3865},{"edgeType":"calls","source":4044,"target":483},{"edgeType":"contains","source":1654,"target":1680},{"edgeType":"contains","source":3599,"target":3751},{"edgeType":"contains","source":3795,"target":4017},{"edgeType":"calls","source":1965,"target":456},{"edgeType":"calls","source":4498,"target":2265},{"edgeType":"contains","source":1148,"target":1514},{"edgeType":"calls","source":1733,"target":248},{"edgeType":"contains","source":320,"target":756},{"edgeType":"contains","source":36,"target":47},{"edgeType":"contains","source":4099,"target":4107},{"edgeType":"contains","source":65,"target":205},{"edgeType":"calls","source":3597,"target":1655},{"edgeType":"calls","source":4137,"target":772},{"edgeType":"calls","source":4523,"target":1489},{"edgeType":"contains","source":1148,"target":1513},{"edgeType":"contains","source":1952,"target":1957},{"edgeType":"contains","source":2631,"target":991},{"edgeType":"contains","source":4099,"target":4106},{"edgeType":"imports","source":2209,"target":1654},{"edgeType":"contains","source":2806,"target":2965},{"edgeType":"contains","source":4524,"target":4672},{"edgeType":"contains","source":65,"target":204},{"edgeType":"calls","source":3709,"target":298},{"edgeType":"calls","source":4222,"target":248},{"edgeType":"calls","source":3239,"target":3238},{"edgeType":"contains","source":664,"target":665},{"edgeType":"calls","source":2850,"target":498},{"edgeType":"calls","source":4832,"target":365},{"edgeType":"calls","source":975,"target":486},{"edgeType":"contains","source":4524,"target":4679},{"edgeType":"calls","source":331,"target":366},{"edgeType":"calls","source":2308,"target":388},{"edgeType":"contains","source":2255,"target":4196},{"edgeType":"contains","source":320,"target":758},{"edgeType":"contains","source":36,"target":49},{"edgeType":"contains","source":3797,"target":3962},{"edgeType":"calls","source":3830,"target":772},{"edgeType":"calls","source":3869,"target":1677},{"edgeType":"imports","source":2126,"target":2127},{"edgeType":"calls","source":4222,"target":249},{"edgeType":"calls","source":4681,"target":817},{"edgeType":"contains","source":2646,"target":2647},{"edgeType":"calls","source":3000,"target":77},{"edgeType":"calls","source":4763,"target":389},{"edgeType":"calls","source":2850,"target":499},{"edgeType":"calls","source":975,"target":485},{"edgeType":"calls","source":1735,"target":179},{"edgeType":"calls","source":2308,"target":389},{"edgeType":"contains","source":4524,"target":4678},{"edgeType":"contains","source":320,"target":757},{"edgeType":"contains","source":2255,"target":4197},{"edgeType":"contains","source":4099,"target":4112},{"edgeType":"contains","source":36,"target":48},{"edgeType":"calls","source":2789,"target":1330},{"edgeType":"calls","source":4763,"target":388},{"edgeType":"calls","source":887,"target":45},{"edgeType":"calls","source":975,"target":488},{"edgeType":"contains","source":320,"target":760},{"edgeType":"calls","source":2308,"target":386},{"edgeType":"contains","source":36,"target":51},{"edgeType":"contains","source":2084,"target":2096},{"edgeType":"calls","source":1701,"target":179},{"edgeType":"calls","source":4083,"target":326},{"edgeType":"calls","source":544,"target":106},{"edgeType":"calls","source":4763,"target":387},{"edgeType":"calls","source":4714,"target":1906},{"edgeType":"extends","source":4853,"target":4499},{"edgeType":"calls","source":1678,"target":891},{"edgeType":"calls","source":975,"target":487},{"edgeType":"calls","source":2476,"target":464},{"edgeType":"calls","source":2308,"target":387},{"edgeType":"contains","source":4524,"target":4676},{"edgeType":"contains","source":1688,"target":1689},{"edgeType":"contains","source":3,"target":16},{"edgeType":"contains","source":36,"target":50},{"edgeType":"contains","source":36,"target":53},{"edgeType":"calls","source":741,"target":336},{"edgeType":"calls","source":774,"target":370},{"edgeType":"calls","source":3661,"target":722},{"edgeType":"calls","source":4763,"target":386},{"edgeType":"calls","source":3239,"target":3234},{"edgeType":"contains","source":3797,"target":3966},{"edgeType":"calls","source":331,"target":362},{"edgeType":"contains","source":320,"target":762},{"edgeType":"contains","source":1523,"target":1524},{"edgeType":"contains","source":1952,"target":1966},{"edgeType":"calls","source":4332,"target":1063},{"edgeType":"calls","source":2248,"target":2244},{"edgeType":"calls","source":2308,"target":384},{"edgeType":"contains","source":3534,"target":3663},{"edgeType":"calls","source":4019,"target":194},{"edgeType":"contains","source":3571,"target":3573},{"edgeType":"contains","source":36,"target":52},{"edgeType":"contains","source":4225,"target":4438},{"edgeType":"calls","source":906,"target":505},{"edgeType":"calls","source":4764,"target":354},{"edgeType":"calls","source":4763,"target":385},{"edgeType":"calls","source":3287,"target":690},{"edgeType":"calls","source":1159,"target":1119},{"edgeType":"calls","source":4468,"target":4245},{"edgeType":"calls","source":331,"target":361},{"edgeType":"calls","source":4585,"target":1675},{"edgeType":"calls","source":4591,"target":1489},{"edgeType":"calls","source":3661,"target":723},{"edgeType":"calls","source":2308,"target":385},{"edgeType":"contains","source":1688,"target":1695},{"edgeType":"contains","source":1654,"target":1692},{"edgeType":"contains","source":36,"target":55},{"edgeType":"calls","source":578,"target":106},{"edgeType":"calls","source":3661,"target":720},{"edgeType":"contains","source":1165,"target":995},{"edgeType":"calls","source":4763,"target":384},{"edgeType":"calls","source":4764,"target":353},{"edgeType":"contains","source":2255,"target":4198},{"edgeType":"calls","source":2308,"target":382},{"edgeType":"contains","source":2021,"target":1939},{"edgeType":"calls","source":4250,"target":1489},{"edgeType":"contains","source":36,"target":54},{"edgeType":"calls","source":774,"target":371},{"edgeType":"calls","source":3239,"target":3233},{"edgeType":"calls","source":3151,"target":675},{"edgeType":"imports","source":2021,"target":91},{"edgeType":"calls","source":4710,"target":969},{"edgeType":"calls","source":398,"target":400},{"edgeType":"contains","source":2255,"target":4199},{"edgeType":"calls","source":4763,"target":383},{"edgeType":"calls","source":2308,"target":383},{"edgeType":"calls","source":4395,"target":4392},{"edgeType":"calls","source":2876,"target":774},{"edgeType":"calls","source":3000,"target":101},{"edgeType":"calls","source":2985,"target":566},{"edgeType":"calls","source":747,"target":179},{"edgeType":"calls","source":3322,"target":690},{"edgeType":"calls","source":1385,"target":485},{"edgeType":"imports","source":4209,"target":953},{"edgeType":"calls","source":3366,"target":383},{"edgeType":"calls","source":3944,"target":434},{"edgeType":"calls","source":4608,"target":992},{"edgeType":"calls","source":1113,"target":460},{"edgeType":"contains","source":2269,"target":2680},{"edgeType":"calls","source":4724,"target":567},{"edgeType":"calls","source":2637,"target":784},{"edgeType":"calls","source":2036,"target":387},{"edgeType":"calls","source":2337,"target":571},{"edgeType":"calls","source":4076,"target":570},{"edgeType":"calls","source":3489,"target":1856},{"edgeType":"calls","source":988,"target":106},{"edgeType":"imports","source":2488,"target":2508},{"edgeType":"calls","source":3366,"target":384},{"edgeType":"imports","source":2259,"target":93},{"edgeType":"calls","source":3000,"target":102},{"edgeType":"calls","source":2985,"target":567},{"edgeType":"contains","source":4524,"target":4654},{"edgeType":"calls","source":3944,"target":435},{"edgeType":"calls","source":3980,"target":376},{"edgeType":"contains","source":2255,"target":3115},{"edgeType":"contains","source":2269,"target":2681},{"edgeType":"calls","source":4724,"target":566},{"edgeType":"calls","source":2693,"target":106},{"edgeType":"calls","source":2036,"target":386},{"edgeType":"calls","source":2337,"target":572},{"edgeType":"calls","source":4076,"target":571},{"edgeType":"calls","source":2247,"target":191},{"edgeType":"calls","source":1385,"target":487},{"edgeType":"calls","source":2959,"target":1370},{"edgeType":"calls","source":3000,"target":99},{"edgeType":"calls","source":2953,"target":499},{"edgeType":"contains","source":6,"target":3070},{"edgeType":"contains","source":2631,"target":970},{"edgeType":"calls","source":899,"target":754},{"edgeType":"calls","source":331,"target":393},{"edgeType":"calls","source":397,"target":461},{"edgeType":"calls","source":4076,"target":568},{"edgeType":"calls","source":4110,"target":571},{"edgeType":"calls","source":4807,"target":106},{"edgeType":"calls","source":1886,"target":1868},{"edgeType":"calls","source":2036,"target":389},{"edgeType":"calls","source":4595,"target":336},{"edgeType":"calls","source":2249,"target":2240},{"edgeType":"calls","source":2337,"target":569},{"edgeType":"calls","source":3000,"target":100},{"edgeType":"contains","source":6,"target":3069},{"edgeType":"imports","source":2259,"target":91},{"edgeType":"calls","source":1385,"target":486},{"edgeType":"calls","source":3366,"target":382},{"edgeType":"contains","source":3797,"target":3934},{"edgeType":"calls","source":1088,"target":179},{"edgeType":"contains","source":4524,"target":4651},{"edgeType":"calls","source":4076,"target":569},{"edgeType":"calls","source":4054,"target":194},{"edgeType":"calls","source":4110,"target":572},{"edgeType":"calls","source":2036,"target":388},{"edgeType":"calls","source":2337,"target":570},{"edgeType":"contains","source":1257,"target":1288},{"edgeType":"calls","source":4395,"target":191},{"edgeType":"calls","source":2337,"target":566},{"edgeType":"contains","source":3936,"target":1746},{"edgeType":"contains","source":6,"target":2015},{"edgeType":"imports","source":2259,"target":90},{"edgeType":"contains","source":4524,"target":4659},{"edgeType":"contains","source":4451,"target":4808},{"edgeType":"contains","source":2269,"target":2685},{"edgeType":"calls","source":1890,"target":1738},{"edgeType":"calls","source":501,"target":402},{"edgeType":"calls","source":1974,"target":191},{"edgeType":"calls","source":2036,"target":383},{"edgeType":"calls","source":4076,"target":566},{"edgeType":"calls","source":4088,"target":194},{"edgeType":"calls","source":4110,"target":569},{"edgeType":"calls","source":762,"target":767},{"edgeType":"calls","source":2332,"target":722},{"edgeType":"calls","source":2337,"target":567},{"edgeType":"calls","source":907,"target":499},{"edgeType":"calls","source":4319,"target":1489},{"edgeType":"calls","source":3000,"target":98},{"edgeType":"imports","source":4234,"target":183},{"edgeType":"calls","source":501,"target":401},{"edgeType":"contains","source":3599,"target":3736},{"edgeType":"calls","source":1325,"target":1282},{"edgeType":"calls","source":4110,"target":570},{"edgeType":"calls","source":2036,"target":382},{"edgeType":"imports","source":3050,"target":3051},{"edgeType":"calls","source":4076,"target":567},{"edgeType":"calls","source":1156,"target":179},{"edgeType":"calls","source":4834,"target":3494},{"edgeType":"calls","source":762,"target":766},{"edgeType":"calls","source":2332,"target":723},{"edgeType":"calls","source":2296,"target":1839},{"edgeType":"calls","source":2337,"target":568},{"edgeType":"calls","source":4660,"target":1489},{"edgeType":"imports","source":44,"target":45},{"edgeType":"calls","source":2332,"target":719},{"edgeType":"calls","source":4365,"target":4290},{"edgeType":"contains","source":4524,"target":4657},{"edgeType":"contains","source":2115,"target":2171},{"edgeType":"contains","source":6,"target":2017},{"edgeType":"contains","source":6,"target":3074},{"edgeType":"calls","source":3810,"target":354},{"edgeType":"contains","source":3099,"target":1264},{"edgeType":"calls","source":3363,"target":469},{"edgeType":"calls","source":4110,"target":567},{"edgeType":"contains","source":2269,"target":2682},{"edgeType":"contains","source":3599,"target":3735},{"edgeType":"calls","source":3290,"target":1675},{"edgeType":"calls","source":2036,"target":385},{"edgeType":"calls","source":647,"target":106},{"edgeType":"calls","source":564,"target":565},{"edgeType":"calls","source":4456,"target":411},{"edgeType":"imports","source":44,"target":46},{"edgeType":"calls","source":2233,"target":1675},{"edgeType":"calls","source":2332,"target":720},{"edgeType":"calls","source":4429,"target":191},{"edgeType":"calls","source":4365,"target":4289},{"edgeType":"contains","source":2115,"target":2172},{"edgeType":"contains","source":65,"target":187},{"edgeType":"calls","source":3363,"target":470},{"edgeType":"contains","source":3099,"target":1265},{"edgeType":"extends","source":953,"target":650},{"edgeType":"calls","source":3220,"target":675},{"edgeType":"calls","source":4110,"target":568},{"edgeType":"calls","source":2036,"target":384},{"edgeType":"contains","source":1324,"target":1325},{"edgeType":"contains","source":3405,"target":3406},{"edgeType":"contains","source":1148,"target":1500},{"edgeType":"calls","source":4365,"target":4288},{"edgeType":"extends","source":1260,"target":650},{"edgeType":"calls","source":4347,"target":1675},{"edgeType":"calls","source":4353,"target":1489},{"edgeType":"contains","source":4524,"target":4663},{"edgeType":"calls","source":2332,"target":717},{"edgeType":"calls","source":2249,"target":2233},{"edgeType":"contains","source":2269,"target":2689},{"edgeType":"calls","source":1972,"target":249},{"edgeType":"calls","source":3837,"target":572},{"edgeType":"calls","source":1330,"target":1124},{"edgeType":"calls","source":3363,"target":467},{"edgeType":"calls","source":462,"target":550},{"edgeType":"calls","source":4863,"target":478},{"edgeType":"calls","source":2332,"target":718},{"edgeType":"calls","source":2349,"target":191},{"edgeType":"calls","source":2231,"target":1735},{"edgeType":"contains","source":4524,"target":4662},{"edgeType":"calls","source":4279,"target":1668},{"edgeType":"calls","source":1972,"target":248},{"edgeType":"calls","source":3810,"target":353},{"edgeType":"calls","source":4122,"target":194},{"edgeType":"calls","source":4110,"target":566},{"edgeType":"calls","source":3346,"target":995},{"edgeType":"calls","source":3363,"target":468},{"edgeType":"calls","source":4702,"target":183},{"edgeType":"calls","source":4625,"target":456},{"edgeType":"calls","source":849,"target":179},{"edgeType":"calls","source":4863,"target":477},{"edgeType":"calls","source":3837,"target":570},{"edgeType":"extends","source":1095,"target":482},{"edgeType":"contains","source":4524,"target":4661},{"edgeType":"calls","source":2332,"target":715},{"edgeType":"calls","source":2476,"target":479},{"edgeType":"calls","source":4279,"target":1667},{"edgeType":"calls","source":1528,"target":1331},{"edgeType":"calls","source":4863,"target":476},{"edgeType":"contains","source":65,"target":193},{"edgeType":"contains","source":31,"target":1247},{"edgeType":"calls","source":2680,"target":498},{"edgeType":"calls","source":3363,"target":465},{"edgeType":"calls","source":2983,"target":1675},{"edgeType":"calls","source":462,"target":552},{"edgeType":"calls","source":2890,"target":330},{"edgeType":"calls","source":4881,"target":2032},{"edgeType":"contains","source":4524,"target":4660},{"edgeType":"calls","source":2332,"target":716},{"edgeType":"contains","source":3797,"target":3942},{"edgeType":"calls","source":4279,"target":1666},{"edgeType":"calls","source":3751,"target":66},{"edgeType":"calls","source":3837,"target":571},{"edgeType":"calls","source":3363,"target":466},{"edgeType":"calls","source":1290,"target":1308},{"edgeType":"calls","source":4722,"target":1675},{"edgeType":"calls","source":2978,"target":774},{"edgeType":"calls","source":4898,"target":2561},{"edgeType":"calls","source":3871,"target":571},{"edgeType":"calls","source":2477,"target":446},{"edgeType":"calls","source":3837,"target":568},{"edgeType":"contains","source":4451,"target":4816},{"edgeType":"calls","source":433,"target":387},{"edgeType":"calls","source":4696,"target":365},{"edgeType":"calls","source":4548,"target":725},{"edgeType":"calls","source":2332,"target":713},{"edgeType":"calls","source":4279,"target":1665},{"edgeType":"calls","source":2006,"target":248},{"edgeType":"calls","source":725,"target":849},{"edgeType":"calls","source":2750,"target":1497},{"edgeType":"calls","source":2688,"target":248},{"edgeType":"contains","source":4099,"target":4101},{"edgeType":"calls","source":3837,"target":569},{"edgeType":"calls","source":4587,"target":572},{"edgeType":"calls","source":3875,"target":448},{"edgeType":"calls","source":3871,"target":572},{"edgeType":"calls","source":433,"target":386},{"edgeType":"contains","source":4524,"target":4666},{"edgeType":"calls","source":2332,"target":714},{"edgeType":"calls","source":1699,"target":1308},{"edgeType":"contains","source":2269,"target":2694},{"edgeType":"calls","source":4612,"target":1911},{"edgeType":"calls","source":3628,"target":1763},{"edgeType":"calls","source":2302,"target":587},{"edgeType":"contains","source":3599,"target":3744},{"edgeType":"calls","source":4279,"target":1664},{"edgeType":"calls","source":4227,"target":106},{"edgeType":"calls","source":2688,"target":249},{"edgeType":"contains","source":4099,"target":4100},{"edgeType":"calls","source":3353,"target":774},{"edgeType":"calls","source":966,"target":776},{"edgeType":"contains","source":2806,"target":2959},{"edgeType":"calls","source":4587,"target":571},{"edgeType":"calls","source":3871,"target":569},{"edgeType":"calls","source":3945,"target":389},{"edgeType":"calls","source":3837,"target":566},{"edgeType":"calls","source":433,"target":389},{"edgeType":"calls","source":4757,"target":586},{"edgeType":"contains","source":2269,"target":2691},{"edgeType":"contains","source":3599,"target":3743},{"edgeType":"calls","source":4279,"target":1663},{"edgeType":"contains","source":3797,"target":3947},{"edgeType":"calls","source":644,"target":191},{"edgeType":"calls","source":4756,"target":1675},{"edgeType":"calls","source":4762,"target":1489},{"edgeType":"contains","source":463,"target":543},{"edgeType":"calls","source":2477,"target":445},{"edgeType":"contains","source":4524,"target":4664},{"edgeType":"calls","source":3837,"target":567},{"edgeType":"calls","source":4587,"target":570},{"edgeType":"calls","source":3871,"target":570},{"edgeType":"contains","source":4451,"target":4813},{"edgeType":"calls","source":433,"target":388},{"edgeType":"calls","source":4757,"target":585},{"edgeType":"calls","source":2332,"target":712},{"edgeType":"calls","source":2006,"target":249},{"edgeType":"calls","source":4279,"target":1662},{"edgeType":"calls","source":666,"target":565},{"edgeType":"contains","source":2084,"target":2085},{"edgeType":"calls","source":4863,"target":471},{"edgeType":"extends","source":4648,"target":4499},{"edgeType":"calls","source":2476,"target":572},{"edgeType":"calls","source":3702,"target":1677},{"edgeType":"contains","source":2230,"target":2287},{"edgeType":"contains","source":2924,"target":2971},{"edgeType":"calls","source":2048,"target":98},{"edgeType":"calls","source":4884,"target":2032},{"edgeType":"calls","source":1385,"target":567},{"edgeType":"calls","source":2789,"target":383},{"edgeType":"calls","source":2893,"target":330},{"edgeType":"calls","source":669,"target":566},{"edgeType":"calls","source":4790,"target":718},{"edgeType":"calls","source":4807,"target":191},{"edgeType":"contains","source":3652,"target":3659},{"edgeType":"contains","source":3520,"target":3523},{"edgeType":"contains","source":1538,"target":1542},{"edgeType":"calls","source":1059,"target":102},{"edgeType":"calls","source":3917,"target":298},{"edgeType":"calls","source":4571,"target":106},{"edgeType":"calls","source":4771,"target":248},{"edgeType":"imports","source":4009,"target":1654},{"edgeType":"contains","source":2806,"target":3459},{"edgeType":"calls","source":2789,"target":384},{"edgeType":"calls","source":2683,"target":499},{"edgeType":"contains","source":3115,"target":3393},{"edgeType":"calls","source":4771,"target":249},{"edgeType":"calls","source":4790,"target":717},{"edgeType":"calls","source":4731,"target":1489},{"edgeType":"calls","source":1385,"target":566},{"edgeType":"contains","source":1538,"target":1543},{"edgeType":"contains","source":3517,"target":3615},{"edgeType":"calls","source":2476,"target":570},{"edgeType":"calls","source":4790,"target":715},{"edgeType":"calls","source":2445,"target":474},{"edgeType":"contains","source":2806,"target":3456},{"edgeType":"calls","source":2281,"target":1330},{"edgeType":"calls","source":1975,"target":249},{"edgeType":"calls","source":2207,"target":453},{"edgeType":"calls","source":2048,"target":100},{"edgeType":"calls","source":669,"target":568},{"edgeType":"calls","source":1385,"target":569},{"edgeType":"contains","source":3123,"target":3142},{"edgeType":"calls","source":1351,"target":566},{"edgeType":"calls","source":1325,"target":315},{"edgeType":"contains","source":1009,"target":1029},{"edgeType":"calls","source":4790,"target":716},{"edgeType":"contains","source":1538,"target":1540},{"edgeType":"calls","source":4818,"target":905},{"edgeType":"calls","source":3361,"target":1675},{"edgeType":"contains","source":3520,"target":3521},{"edgeType":"contains","source":1337,"target":1429},{"edgeType":"calls","source":412,"target":77},{"edgeType":"calls","source":2476,"target":571},{"edgeType":"calls","source":3837,"target":3833},{"edgeType":"calls","source":2491,"target":106},{"edgeType":"calls","source":4577,"target":975},{"edgeType":"calls","source":4790,"target":714},{"edgeType":"calls","source":4765,"target":1489},{"edgeType":"calls","source":1975,"target":248},{"edgeType":"calls","source":2048,"target":99},{"edgeType":"calls","source":669,"target":567},{"edgeType":"calls","source":1385,"target":568},{"edgeType":"calls","source":1351,"target":565},{"edgeType":"calls","source":2789,"target":382},{"edgeType":"contains","source":3115,"target":3391},{"edgeType":"contains","source":1090,"target":1688},{"edgeType":"contains","source":1538,"target":1541},{"edgeType":"contains","source":1535,"target":1634},{"edgeType":"contains","source":1833,"target":1909},{"edgeType":"contains","source":4009,"target":4216},{"edgeType":"calls","source":4790,"target":713},{"edgeType":"calls","source":1059,"target":99},{"edgeType":"extends","source":210,"target":213},{"edgeType":"calls","source":4818,"target":902},{"edgeType":"calls","source":208,"target":54},{"edgeType":"calls","source":2476,"target":568},{"edgeType":"calls","source":2510,"target":571},{"edgeType":"calls","source":2445,"target":472},{"edgeType":"calls","source":2339,"target":587},{"edgeType":"contains","source":4346,"target":4347},{"edgeType":"contains","source":1009,"target":1031},{"edgeType":"contains","source":2806,"target":3462},{"edgeType":"contains","source":3115,"target":3396},{"edgeType":"calls","source":1261,"target":179},{"edgeType":"imports","source":3811,"target":397},{"edgeType":"calls","source":3837,"target":3831},{"edgeType":"calls","source":2510,"target":572},{"edgeType":"contains","source":1833,"target":1915},{"edgeType":"calls","source":4790,"target":712},{"edgeType":"calls","source":4818,"target":901},{"edgeType":"calls","source":1059,"target":98},{"edgeType":"extends","source":3517,"target":3400},{"edgeType":"contains","source":395,"target":4209},{"edgeType":"calls","source":2476,"target":569},{"edgeType":"calls","source":2445,"target":473},{"edgeType":"contains","source":2226,"target":3473},{"edgeType":"calls","source":208,"target":53},{"edgeType":"contains","source":1009,"target":1030},{"edgeType":"calls","source":2765,"target":1124},{"edgeType":"contains","source":3115,"target":3397},{"edgeType":"calls","source":1258,"target":1328},{"edgeType":"calls","source":1059,"target":101},{"edgeType":"calls","source":4818,"target":900},{"edgeType":"calls","source":4793,"target":1675},{"edgeType":"contains","source":3936,"target":2256},{"edgeType":"contains","source":2806,"target":3460},{"edgeType":"calls","source":2476,"target":566},{"edgeType":"calls","source":2479,"target":473},{"edgeType":"calls","source":2510,"target":569},{"edgeType":"contains","source":3115,"target":3394},{"edgeType":"contains","source":1833,"target":1912},{"edgeType":"contains","source":1009,"target":1033},{"edgeType":"contains","source":3421,"target":3423},{"edgeType":"imports","source":1160,"target":1175},{"edgeType":"calls","source":4807,"target":183},{"edgeType":"imports","source":1918,"target":1987},{"edgeType":"calls","source":1059,"target":100},{"edgeType":"contains","source":2806,"target":3461},{"edgeType":"contains","source":2209,"target":1884},{"edgeType":"calls","source":2510,"target":570},{"edgeType":"calls","source":4452,"target":1675},{"edgeType":"calls","source":2552,"target":325},{"edgeType":"calls","source":2476,"target":567},{"edgeType":"calls","source":2479,"target":474},{"edgeType":"calls","source":4545,"target":906},{"edgeType":"calls","source":774,"target":479},{"edgeType":"calls","source":3731,"target":772},{"edgeType":"contains","source":3652,"target":3660},{"edgeType":"calls","source":3156,"target":628},{"edgeType":"contains","source":3115,"target":3395},{"edgeType":"contains","source":3421,"target":3422},{"edgeType":"calls","source":1968,"target":456},{"edgeType":"calls","source":4106,"target":772},{"edgeType":"calls","source":2510,"target":567},{"edgeType":"contains","source":28,"target":1849},{"edgeType":"calls","source":786,"target":101},{"edgeType":"calls","source":4536,"target":1184},{"edgeType":"calls","source":674,"target":402},{"edgeType":"calls","source":208,"target":50},{"edgeType":"calls","source":2235,"target":1693},{"edgeType":"contains","source":2806,"target":3466},{"edgeType":"contains","source":3652,"target":3667},{"edgeType":"calls","source":1395,"target":249},{"edgeType":"calls","source":4040,"target":705},{"edgeType":"calls","source":3355,"target":1856},{"edgeType":"calls","source":1395,"target":248},{"edgeType":"calls","source":2479,"target":472},{"edgeType":"calls","source":674,"target":401},{"edgeType":"calls","source":4552,"target":687},{"edgeType":"calls","source":2510,"target":568},{"edgeType":"calls","source":4744,"target":1077},{"edgeType":"calls","source":741,"target":438},{"edgeType":"calls","source":786,"target":100},{"edgeType":"calls","source":4730,"target":454},{"edgeType":"contains","source":4280,"target":4282},{"edgeType":"contains","source":4346,"target":4350},{"edgeType":"calls","source":208,"target":49},{"edgeType":"contains","source":3520,"target":3530},{"edgeType":"calls","source":1912,"target":1133},{"edgeType":"contains","source":1175,"target":1177},{"edgeType":"calls","source":1161,"target":106},{"edgeType":"calls","source":1995,"target":1735},{"edgeType":"calls","source":374,"target":191},{"edgeType":"calls","source":4579,"target":906},{"edgeType":"calls","source":208,"target":52},{"edgeType":"contains","source":3066,"target":689},{"edgeType":"calls","source":4492,"target":1489},{"edgeType":"contains","source":3652,"target":3665},{"edgeType":"contains","source":3115,"target":3398},{"edgeType":"calls","source":1772,"target":191},{"edgeType":"calls","source":1968,"target":457},{"edgeType":"contains","source":1749,"target":3464},{"edgeType":"calls","source":2510,"target":566},{"edgeType":"calls","source":397,"target":534},{"edgeType":"calls","source":786,"target":102},{"edgeType":"contains","source":1535,"target":1642},{"edgeType":"calls","source":208,"target":51},{"edgeType":"contains","source":2232,"target":2233},{"edgeType":"contains","source":4346,"target":4348},{"edgeType":"contains","source":2806,"target":3465},{"edgeType":"calls","source":3979,"target":479},{"edgeType":"contains","source":3115,"target":3399},{"edgeType":"calls","source":639,"target":426},{"edgeType":"imports","source":1090,"target":183},{"edgeType":"calls","source":1258,"target":1321},{"edgeType":"calls","source":1429,"target":248},{"edgeType":"contains","source":2292,"target":2492},{"edgeType":"calls","source":3256,"target":692},{"edgeType":"calls","source":954,"target":1231},{"edgeType":"contains","source":3710,"target":3987},{"edgeType":"calls","source":4365,"target":4367},{"edgeType":"calls","source":4446,"target":1856},{"edgeType":"calls","source":2478,"target":498},{"edgeType":"contains","source":4115,"target":4117},{"edgeType":"contains","source":4376,"target":1311},{"edgeType":"imports","source":830,"target":843},{"edgeType":"calls","source":1840,"target":191},{"edgeType":"calls","source":639,"target":425},{"edgeType":"calls","source":3257,"target":662},{"edgeType":"contains","source":798,"target":1237},{"edgeType":"calls","source":335,"target":336},{"edgeType":"calls","source":4520,"target":1675},{"edgeType":"calls","source":4526,"target":1489},{"edgeType":"contains","source":4115,"target":4116},{"edgeType":"calls","source":4365,"target":4366},{"edgeType":"contains","source":2226,"target":3482},{"edgeType":"calls","source":3972,"target":3865},{"edgeType":"calls","source":4821,"target":1856},{"edgeType":"calls","source":2810,"target":774},{"edgeType":"calls","source":786,"target":99},{"edgeType":"calls","source":3256,"target":690},{"edgeType":"calls","source":741,"target":437},{"edgeType":"calls","source":4426,"target":1417},{"edgeType":"calls","source":208,"target":48},{"edgeType":"contains","source":4346,"target":4353},{"edgeType":"calls","source":3746,"target":298},{"edgeType":"calls","source":639,"target":427},{"edgeType":"calls","source":647,"target":179},{"edgeType":"calls","source":4204,"target":1957},{"edgeType":"calls","source":1429,"target":249},{"edgeType":"calls","source":3497,"target":2733},{"edgeType":"contains","source":1175,"target":1180},{"edgeType":"calls","source":786,"target":98},{"edgeType":"contains","source":3652,"target":3668},{"edgeType":"calls","source":741,"target":436},{"edgeType":"calls","source":3121,"target":648},{"edgeType":"contains","source":44,"target":302},{"edgeType":"calls","source":208,"target":47},{"edgeType":"calls","source":4684,"target":817},{"edgeType":"contains","source":340,"target":609},{"edgeType":"calls","source":2811,"target":774},{"edgeType":"contains","source":1009,"target":1011},{"edgeType":"calls","source":4213,"target":651},{"edgeType":"calls","source":2847,"target":715},{"edgeType":"calls","source":4822,"target":1856},{"edgeType":"contains","source":3123,"target":3128},{"edgeType":"calls","source":573,"target":387},{"edgeType":"contains","source":1516,"target":2207},{"edgeType":"calls","source":2945,"target":1905},{"edgeType":"calls","source":3301,"target":383},{"edgeType":"calls","source":4836,"target":365},{"edgeType":"calls","source":1159,"target":191},{"edgeType":"calls","source":1008,"target":643},{"edgeType":"contains","source":2033,"target":2036},{"edgeType":"calls","source":1817,"target":933},{"edgeType":"contains","source":11,"target":2352},{"edgeType":"contains","source":1933,"target":4079},{"edgeType":"contains","source":4009,"target":4203},{"edgeType":"calls","source":2238,"target":568},{"edgeType":"contains","source":340,"target":608},{"edgeType":"contains","source":1009,"target":1010},{"edgeType":"calls","source":2847,"target":716},{"edgeType":"calls","source":3553,"target":2085},{"edgeType":"contains","source":3123,"target":3129},{"edgeType":"calls","source":772,"target":559},{"edgeType":"calls","source":3301,"target":384},{"edgeType":"calls","source":2887,"target":533},{"edgeType":"calls","source":2984,"target":1754},{"edgeType":"extends","source":511,"target":373},{"edgeType":"calls","source":4628,"target":470},{"edgeType":"calls","source":4637,"target":191},{"edgeType":"calls","source":573,"target":386},{"edgeType":"calls","source":2238,"target":569},{"edgeType":"calls","source":4088,"target":298},{"edgeType":"contains","source":3123,"target":3126},{"edgeType":"calls","source":2847,"target":713},{"edgeType":"contains","source":340,"target":611},{"edgeType":"calls","source":3628,"target":1871},{"edgeType":"contains","source":207,"target":506},{"edgeType":"calls","source":573,"target":389},{"edgeType":"contains","source":1009,"target":1013},{"edgeType":"calls","source":4628,"target":469},{"edgeType":"calls","source":4601,"target":249},{"edgeType":"contains","source":2033,"target":2034},{"edgeType":"imports","source":1160,"target":1161},{"edgeType":"contains","source":4048,"target":4049},{"edgeType":"calls","source":4122,"target":298},{"edgeType":"calls","source":2238,"target":566},{"edgeType":"contains","source":2806,"target":3439},{"edgeType":"calls","source":4260,"target":248},{"edgeType":"calls","source":2207,"target":470},{"edgeType":"contains","source":1009,"target":1012},{"edgeType":"calls","source":2847,"target":714},{"edgeType":"calls","source":4280,"target":687},{"edgeType":"calls","source":3490,"target":865},{"edgeType":"contains","source":340,"target":610},{"edgeType":"imports","source":4001,"target":4002},{"edgeType":"calls","source":573,"target":388},{"edgeType":"contains","source":3123,"target":3127},{"edgeType":"contains","source":1516,"target":2206},{"edgeType":"calls","source":3301,"target":382},{"edgeType":"calls","source":4628,"target":468},{"edgeType":"calls","source":4601,"target":248},{"edgeType":"contains","source":2000,"target":2001},{"edgeType":"imports","source":4001,"target":831},{"edgeType":"calls","source":2238,"target":567},{"edgeType":"calls","source":4260,"target":249},{"edgeType":"calls","source":2207,"target":467},{"edgeType":"extends","source":1384,"target":799},{"edgeType":"imports","source":4001,"target":4003},{"edgeType":"contains","source":1009,"target":1015},{"edgeType":"contains","source":3123,"target":3132},{"edgeType":"calls","source":3524,"target":865},{"edgeType":"calls","source":4023,"target":194},{"edgeType":"calls","source":4628,"target":467},{"edgeType":"contains","source":18,"target":25},{"edgeType":"contains","source":1833,"target":1898},{"edgeType":"calls","source":4787,"target":1880},{"edgeType":"calls","source":573,"target":383},{"edgeType":"calls","source":4254,"target":1489},{"edgeType":"calls","source":2207,"target":468},{"edgeType":"imports","source":4001,"target":4004},{"edgeType":"contains","source":207,"target":507},{"edgeType":"contains","source":1009,"target":1014},{"edgeType":"calls","source":2847,"target":712},{"edgeType":"contains","source":3517,"target":3602},{"edgeType":"contains","source":3123,"target":3133},{"edgeType":"contains","source":3115,"target":3381},{"edgeType":"contains","source":3175,"target":464},{"edgeType":"calls","source":1622,"target":631},{"edgeType":"calls","source":3291,"target":690},{"edgeType":"calls","source":1152,"target":402},{"edgeType":"calls","source":4628,"target":466},{"edgeType":"calls","source":4589,"target":1675},{"edgeType":"contains","source":18,"target":24},{"edgeType":"calls","source":573,"target":382},{"edgeType":"calls","source":2207,"target":469},{"edgeType":"calls","source":2207,"target":465},{"edgeType":"calls","source":4330,"target":189},{"edgeType":"contains","source":3123,"target":3130},{"edgeType":"calls","source":1622,"target":634},{"edgeType":"contains","source":1009,"target":1017},{"edgeType":"calls","source":4803,"target":325},{"edgeType":"calls","source":573,"target":385},{"edgeType":"contains","source":18,"target":27},{"edgeType":"calls","source":2037,"target":453},{"edgeType":"imports","source":97,"target":285},{"edgeType":"calls","source":4628,"target":465},{"edgeType":"contains","source":340,"target":615},{"edgeType":"calls","source":2555,"target":248},{"edgeType":"contains","source":207,"target":509},{"edgeType":"calls","source":1528,"target":376},{"edgeType":"calls","source":2207,"target":466},{"edgeType":"contains","source":1009,"target":1016},{"edgeType":"calls","source":1622,"target":633},{"edgeType":"contains","source":3123,"target":3131},{"edgeType":"calls","source":3307,"target":191},{"edgeType":"contains","source":2000,"target":2005},{"edgeType":"calls","source":2555,"target":249},{"edgeType":"calls","source":4795,"target":572},{"edgeType":"calls","source":1897,"target":564},{"edgeType":"calls","source":1851,"target":933},{"edgeType":"contains","source":18,"target":26},{"edgeType":"calls","source":573,"target":384},{"edgeType":"contains","source":340,"target":614},{"edgeType":"calls","source":301,"target":354},{"edgeType":"contains","source":1009,"target":1019},{"edgeType":"contains","source":3123,"target":3136},{"edgeType":"calls","source":1261,"target":191},{"edgeType":"calls","source":4795,"target":571},{"edgeType":"imports","source":3002,"target":93},{"edgeType":"contains","source":1833,"target":1902},{"edgeType":"calls","source":3872,"target":3814},{"edgeType":"calls","source":1351,"target":572},{"edgeType":"imports","source":830,"target":831},{"edgeType":"imports","source":2923,"target":1485},{"edgeType":"contains","source":340,"target":617},{"edgeType":"calls","source":2861,"target":1330},{"edgeType":"calls","source":2545,"target":556},{"edgeType":"calls","source":2544,"target":587},{"edgeType":"calls","source":4629,"target":1489},{"edgeType":"calls","source":666,"target":667},{"edgeType":"calls","source":4268,"target":4222},{"edgeType":"calls","source":301,"target":353},{"edgeType":"contains","source":1535,"target":1627},{"edgeType":"contains","source":1009,"target":1018},{"edgeType":"contains","source":4808,"target":4810},{"edgeType":"calls","source":3780,"target":325},{"edgeType":"contains","source":3123,"target":3137},{"edgeType":"calls","source":4795,"target":570},{"edgeType":"calls","source":1351,"target":571},{"edgeType":"calls","source":3872,"target":3815},{"edgeType":"imports","source":3002,"target":92},{"edgeType":"calls","source":4023,"target":191},{"edgeType":"contains","source":340,"target":616},{"edgeType":"calls","source":2787,"target":454},{"edgeType":"calls","source":2676,"target":724},{"edgeType":"extends","source":3447,"target":3444},{"edgeType":"contains","source":3123,"target":3134},{"edgeType":"contains","source":4808,"target":4809},{"edgeType":"calls","source":3872,"target":3812},{"edgeType":"calls","source":3980,"target":464},{"edgeType":"contains","source":3420,"target":3441},{"edgeType":"calls","source":1673,"target":106},{"edgeType":"calls","source":4795,"target":569},{"edgeType":"contains","source":1934,"target":1940},{"edgeType":"imports","source":3002,"target":91},{"edgeType":"calls","source":1152,"target":401},{"edgeType":"calls","source":3238,"target":211},{"edgeType":"contains","source":207,"target":514},{"edgeType":"calls","source":2789,"target":389},{"edgeType":"calls","source":4739,"target":191},{"edgeType":"contains","source":1009,"target":1020},{"edgeType":"contains","source":3517,"target":3604},{"edgeType":"calls","source":1657,"target":1658},{"edgeType":"calls","source":3830,"target":887},{"edgeType":"contains","source":3123,"target":3135},{"edgeType":"calls","source":1981,"target":1127},{"edgeType":"calls","source":3238,"target":212},{"edgeType":"calls","source":4242,"target":1856},{"edgeType":"contains","source":207,"target":513},{"edgeType":"calls","source":4842,"target":2282},{"edgeType":"calls","source":4657,"target":1675},{"edgeType":"calls","source":4663,"target":1489},{"edgeType":"calls","source":4703,"target":249},{"edgeType":"calls","source":4790,"target":723},{"edgeType":"calls","source":4795,"target":568},{"edgeType":"imports","source":3710,"target":331},{"edgeType":"calls","source":1660,"target":503},{"edgeType":"calls","source":1659,"target":534},{"edgeType":"contains","source":1535,"target":1630},{"edgeType":"imports","source":32,"target":196},{"edgeType":"calls","source":4201,"target":4182},{"edgeType":"calls","source":1941,"target":248},{"edgeType":"contains","source":2806,"target":3454},{"edgeType":"calls","source":1351,"target":568},{"edgeType":"calls","source":1325,"target":317},{"edgeType":"calls","source":2048,"target":102},{"edgeType":"calls","source":669,"target":570},{"edgeType":"contains","source":3123,"target":3140},{"edgeType":"calls","source":1289,"target":376},{"edgeType":"calls","source":1385,"target":571},{"edgeType":"calls","source":3293,"target":1675},{"edgeType":"contains","source":2280,"target":2847},{"edgeType":"contains","source":3652,"target":3655},{"edgeType":"calls","source":4703,"target":248},{"edgeType":"contains","source":207,"target":516},{"edgeType":"calls","source":2494,"target":1076},{"edgeType":"contains","source":4009,"target":4215},{"edgeType":"calls","source":4761,"target":564},{"edgeType":"calls","source":4790,"target":722},{"edgeType":"calls","source":2789,"target":387},{"edgeType":"calls","source":4795,"target":567},{"edgeType":"calls","source":2365,"target":847},{"edgeType":"contains","source":681,"target":3791},{"edgeType":"contains","source":11,"target":2363},{"edgeType":"calls","source":1660,"target":502},{"edgeType":"imports","source":97,"target":296},{"edgeType":"contains","source":2923,"target":2999},{"edgeType":"calls","source":2048,"target":101},{"edgeType":"contains","source":2806,"target":3455},{"edgeType":"calls","source":1385,"target":570},{"edgeType":"calls","source":1351,"target":567},{"edgeType":"contains","source":3123,"target":3141},{"edgeType":"calls","source":1325,"target":316},{"edgeType":"calls","source":669,"target":569},{"edgeType":"contains","source":2255,"target":3623},{"edgeType":"calls","source":1528,"target":365},{"edgeType":"calls","source":3322,"target":777},{"edgeType":"calls","source":3219,"target":1856},{"edgeType":"contains","source":3652,"target":3654},{"edgeType":"contains","source":1538,"target":1539},{"edgeType":"contains","source":207,"target":515},{"edgeType":"calls","source":4795,"target":566},{"edgeType":"calls","source":2789,"target":388},{"edgeType":"calls","source":4628,"target":456},{"edgeType":"calls","source":4537,"target":106},{"edgeType":"calls","source":4529,"target":354},{"edgeType":"calls","source":4350,"target":1675},{"edgeType":"calls","source":4356,"target":1489},{"edgeType":"contains","source":3123,"target":3138},{"edgeType":"calls","source":2789,"target":385},{"edgeType":"contains","source":1833,"target":1904},{"edgeType":"contains","source":1009,"target":1025},{"edgeType":"calls","source":1261,"target":189},{"edgeType":"calls","source":1351,"target":570},{"edgeType":"imports","source":1160,"target":1165},{"edgeType":"contains","source":3685,"target":3687},{"edgeType":"contains","source":4010,"target":4182},{"edgeType":"calls","source":4697,"target":1489},{"edgeType":"calls","source":669,"target":572},{"edgeType":"calls","source":4790,"target":720},{"edgeType":"calls","source":2491,"target":1167},{"edgeType":"calls","source":4665,"target":365},{"edgeType":"imports","source":4209,"target":721},{"edgeType":"contains","source":3517,"target":3608},{"edgeType":"calls","source":4529,"target":353},{"edgeType":"calls","source":1941,"target":249},{"edgeType":"contains","source":1009,"target":1024},{"edgeType":"contains","source":4808,"target":4812},{"edgeType":"calls","source":4125,"target":194},{"edgeType":"calls","source":4144,"target":1719},{"edgeType":"calls","source":2789,"target":386},{"edgeType":"contains","source":3123,"target":3139},{"edgeType":"calls","source":1385,"target":572},{"edgeType":"calls","source":1351,"target":569},{"edgeType":"calls","source":1159,"target":179},{"edgeType":"contains","source":2255,"target":3621},{"edgeType":"calls","source":4790,"target":719},{"edgeType":"contains","source":1647,"target":3443},{"edgeType":"calls","source":669,"target":571},{"edgeType":"calls","source":1128,"target":45},{"edgeType":"calls","source":1077,"target":569},{"edgeType":"contains","source":4840,"target":4851},{"edgeType":"calls","source":2436,"target":722},{"edgeType":"calls","source":4536,"target":102},{"edgeType":"contains","source":511,"target":577},{"edgeType":"calls","source":544,"target":179},{"edgeType":"calls","source":2206,"target":453},{"edgeType":"calls","source":2085,"target":2090},{"edgeType":"calls","source":3572,"target":388},{"edgeType":"calls","source":786,"target":77},{"edgeType":"calls","source":776,"target":387},{"edgeType":"contains","source":1833,"target":1877},{"edgeType":"calls","source":2945,"target":1856},{"edgeType":"calls","source":1127,"target":1133},{"edgeType":"calls","source":3231,"target":389},{"edgeType":"calls","source":1077,"target":568},{"edgeType":"calls","source":2447,"target":382},{"edgeType":"calls","source":2436,"target":723},{"edgeType":"contains","source":4840,"target":4850},{"edgeType":"calls","source":4758,"target":1675},{"edgeType":"calls","source":2309,"target":1489},{"edgeType":"calls","source":4536,"target":101},{"edgeType":"contains","source":2462,"target":2463},{"edgeType":"calls","source":325,"target":625},{"edgeType":"contains","source":843,"target":854},{"edgeType":"calls","source":3572,"target":389},{"edgeType":"calls","source":3489,"target":1905},{"edgeType":"calls","source":2812,"target":2809},{"edgeType":"contains","source":1204,"target":1290},{"edgeType":"calls","source":776,"target":386},{"edgeType":"calls","source":995,"target":996},{"edgeType":"contains","source":2098,"target":2116},{"edgeType":"calls","source":2543,"target":574},{"edgeType":"contains","source":4840,"target":4849},{"edgeType":"calls","source":3231,"target":387},{"edgeType":"calls","source":1902,"target":365},{"edgeType":"calls","source":4536,"target":100},{"edgeType":"calls","source":2436,"target":720},{"edgeType":"contains","source":511,"target":579},{"edgeType":"calls","source":2338,"target":587},{"edgeType":"calls","source":3572,"target":386},{"edgeType":"contains","source":3056,"target":3072},{"edgeType":"calls","source":776,"target":389},{"edgeType":"calls","source":1077,"target":571},{"edgeType":"calls","source":1077,"target":570},{"edgeType":"calls","source":3231,"target":388},{"edgeType":"contains","source":4840,"target":4848},{"edgeType":"calls","source":2375,"target":498},{"edgeType":"calls","source":4121,"target":1338},{"edgeType":"calls","source":4536,"target":99},{"edgeType":"contains","source":3936,"target":1161},{"edgeType":"calls","source":3572,"target":387},{"edgeType":"calls","source":776,"target":388},{"edgeType":"calls","source":1258,"target":1301},{"edgeType":"contains","source":1833,"target":1876},{"edgeType":"contains","source":637,"target":903},{"edgeType":"calls","source":3231,"target":385},{"edgeType":"calls","source":2409,"target":498},{"edgeType":"calls","source":4536,"target":98},{"edgeType":"contains","source":2462,"target":2466},{"edgeType":"contains","source":511,"target":581},{"edgeType":"calls","source":4280,"target":634},{"edgeType":"calls","source":2436,"target":718},{"edgeType":"calls","source":2478,"target":473},{"edgeType":"calls","source":2453,"target":191},{"edgeType":"calls","source":3626,"target":824},{"edgeType":"calls","source":776,"target":383},{"edgeType":"contains","source":2924,"target":2942},{"edgeType":"contains","source":3517,"target":3587},{"edgeType":"contains","source":3120,"target":3208},{"edgeType":"calls","source":1771,"target":191},{"edgeType":"calls","source":3572,"target":384},{"edgeType":"calls","source":1528,"target":325},{"edgeType":"calls","source":1877,"target":1133},{"edgeType":"calls","source":2551,"target":325},{"edgeType":"calls","source":3231,"target":386},{"edgeType":"calls","source":4806,"target":183},{"edgeType":"calls","source":4817,"target":899},{"edgeType":"calls","source":1077,"target":564},{"edgeType":"calls","source":1967,"target":457},{"edgeType":"contains","source":2462,"target":2467},{"edgeType":"calls","source":4544,"target":906},{"edgeType":"extends","source":3152,"target":3122},{"edgeType":"contains","source":2098,"target":2123},{"edgeType":"calls","source":2478,"target":474},{"edgeType":"calls","source":2436,"target":719},{"edgeType":"contains","source":511,"target":580},{"edgeType":"contains","source":3056,"target":3079},{"edgeType":"calls","source":776,"target":382},{"edgeType":"contains","source":3162,"target":2964},{"edgeType":"contains","source":3122,"target":3147},{"edgeType":"calls","source":3572,"target":385},{"edgeType":"calls","source":3360,"target":1672},{"edgeType":"contains","source":511,"target":583},{"edgeType":"calls","source":1077,"target":567},{"edgeType":"contains","source":2098,"target":2120},{"edgeType":"calls","source":3231,"target":383},{"edgeType":"calls","source":1843,"target":1133},{"edgeType":"calls","source":4105,"target":772},{"edgeType":"calls","source":2436,"target":716},{"edgeType":"contains","source":2806,"target":3427},{"edgeType":"calls","source":498,"target":546},{"edgeType":"calls","source":2524,"target":102},{"edgeType":"calls","source":776,"target":385},{"edgeType":"contains","source":3122,"target":3144},{"edgeType":"calls","source":1695,"target":435},{"edgeType":"calls","source":1443,"target":848},{"edgeType":"calls","source":3572,"target":382},{"edgeType":"contains","source":3420,"target":3421},{"edgeType":"calls","source":4743,"target":1077},{"edgeType":"calls","source":1077,"target":566},{"edgeType":"calls","source":3231,"target":384},{"edgeType":"contains","source":4840,"target":4852},{"edgeType":"calls","source":2436,"target":717},{"edgeType":"calls","source":4280,"target":633},{"edgeType":"contains","source":511,"target":582},{"edgeType":"contains","source":2462,"target":2465},{"edgeType":"calls","source":2478,"target":472},{"edgeType":"calls","source":776,"target":384},{"edgeType":"imports","source":2255,"target":30},{"edgeType":"contains","source":3122,"target":3145},{"edgeType":"contains","source":2923,"target":2972},{"edgeType":"calls","source":1695,"target":434},{"edgeType":"calls","source":3572,"target":383},{"edgeType":"calls","source":497,"target":571},{"edgeType":"calls","source":1298,"target":1109},{"edgeType":"calls","source":1328,"target":179},{"edgeType":"calls","source":2524,"target":100},{"edgeType":"calls","source":4578,"target":906},{"edgeType":"calls","source":2436,"target":714},{"edgeType":"calls","source":2960,"target":325},{"edgeType":"calls","source":4491,"target":1489},{"edgeType":"contains","source":4009,"target":4194},{"edgeType":"calls","source":4368,"target":4245},{"edgeType":"calls","source":4468,"target":88},{"edgeType":"contains","source":681,"target":3771},{"edgeType":"calls","source":3544,"target":191},{"edgeType":"calls","source":1524,"target":445},{"edgeType":"contains","source":3122,"target":3150},{"edgeType":"calls","source":497,"target":570},{"edgeType":"contains","source":2462,"target":2471},{"edgeType":"calls","source":3231,"target":382},{"edgeType":"calls","source":2524,"target":101},{"edgeType":"calls","source":400,"target":406},{"edgeType":"calls","source":2436,"target":715},{"edgeType":"calls","source":2443,"target":498},{"edgeType":"calls","source":2538,"target":724},{"edgeType":"calls","source":2649,"target":454},{"edgeType":"contains","source":2198,"target":2199},{"edgeType":"calls","source":1475,"target":906},{"edgeType":"calls","source":3978,"target":479},{"edgeType":"imports","source":38,"target":65},{"edgeType":"calls","source":1967,"target":456},{"edgeType":"calls","source":3971,"target":3865},{"edgeType":"calls","source":4178,"target":2733},{"edgeType":"calls","source":2524,"target":98},{"edgeType":"contains","source":2462,"target":2468},{"edgeType":"calls","source":4601,"target":191},{"edgeType":"contains","source":2292,"target":2453},{"edgeType":"calls","source":2781,"target":587},{"edgeType":"calls","source":2436,"target":712},{"edgeType":"contains","source":3056,"target":3080},{"edgeType":"calls","source":3851,"target":185},{"edgeType":"calls","source":497,"target":572},{"edgeType":"contains","source":2098,"target":2125},{"edgeType":"contains","source":2462,"target":2469},{"edgeType":"calls","source":2524,"target":99},{"edgeType":"calls","source":2881,"target":2773},{"edgeType":"contains","source":3,"target":1535},{"edgeType":"contains","source":2264,"target":2265},{"edgeType":"imports","source":3520,"target":3099},{"edgeType":"calls","source":4519,"target":1675},{"edgeType":"calls","source":4525,"target":1489},{"edgeType":"extends","source":2033,"target":1874},{"edgeType":"contains","source":2924,"target":2945},{"edgeType":"calls","source":2436,"target":713},{"edgeType":"calls","source":2308,"target":453},{"edgeType":"imports","source":38,"target":63},{"edgeType":"calls","source":1524,"target":446},{"edgeType":"contains","source":3056,"target":3081},{"edgeType":"calls","source":3711,"target":298},{"edgeType":"calls","source":4820,"target":1856},{"edgeType":"contains","source":3120,"target":3217},{"edgeType":"calls","source":4224,"target":248},{"edgeType":"calls","source":4250,"target":499},{"edgeType":"contains","source":511,"target":589},{"edgeType":"calls","source":497,"target":567},{"edgeType":"calls","source":1157,"target":191},{"edgeType":"calls","source":4834,"target":365},{"edgeType":"imports","source":34,"target":184},{"edgeType":"calls","source":4425,"target":1417},{"edgeType":"calls","source":3871,"target":1677},{"edgeType":"contains","source":3123,"target":3125},{"edgeType":"calls","source":4224,"target":249},{"edgeType":"contains","source":511,"target":588},{"edgeType":"calls","source":921,"target":106},{"edgeType":"calls","source":2982,"target":1754},{"edgeType":"calls","source":497,"target":566},{"edgeType":"imports","source":34,"target":185},{"edgeType":"calls","source":1873,"target":191},{"edgeType":"calls","source":497,"target":569},{"edgeType":"calls","source":1428,"target":1305},{"edgeType":"contains","source":340,"target":607},{"edgeType":"calls","source":2685,"target":388},{"edgeType":"contains","source":2462,"target":2472},{"edgeType":"calls","source":887,"target":106},{"edgeType":"contains","source":3517,"target":3593},{"edgeType":"calls","source":4599,"target":249},{"edgeType":"calls","source":4436,"target":4245},{"edgeType":"calls","source":3702,"target":572},{"edgeType":"calls","source":2307,"target":479},{"edgeType":"contains","source":3120,"target":3214},{"edgeType":"calls","source":3488,"target":865},{"edgeType":"contains","source":3120,"target":3216},{"edgeType":"calls","source":2685,"target":389},{"edgeType":"calls","source":546,"target":106},{"edgeType":"calls","source":497,"target":568},{"edgeType":"calls","source":1498,"target":191},{"edgeType":"calls","source":4599,"target":248},{"edgeType":"calls","source":3155,"target":1675},{"edgeType":"calls","source":3817,"target":179},{"edgeType":"contains","source":2165,"target":2167},{"edgeType":"contains","source":28,"target":3936},{"edgeType":"imports","source":1918,"target":2029},{"edgeType":"contains","source":1516,"target":2202},{"edgeType":"calls","source":2320,"target":77},{"edgeType":"calls","source":2235,"target":1655},{"edgeType":"contains","source":3120,"target":3215},{"edgeType":"imports","source":38,"target":39},{"edgeType":"calls","source":2887,"target":499},{"edgeType":"calls","source":903,"target":694},{"edgeType":"contains","source":3517,"target":3566},{"edgeType":"calls","source":1077,"target":585},{"edgeType":"calls","source":4529,"target":336},{"edgeType":"calls","source":4437,"target":4245},{"edgeType":"calls","source":1728,"target":488},{"edgeType":"imports","source":3710,"target":369},{"edgeType":"contains","source":799,"target":1145},{"edgeType":"contains","source":798,"target":1176},{"edgeType":"imports","source":38,"target":40},{"edgeType":"imports","source":97,"target":325},{"edgeType":"imports","source":830,"target":857},{"edgeType":"contains","source":3936,"target":2203},{"edgeType":"calls","source":1728,"target":487},{"edgeType":"contains","source":799,"target":1144},{"edgeType":"contains","source":340,"target":578},{"edgeType":"contains","source":1104,"target":1206},{"edgeType":"calls","source":817,"target":191},{"edgeType":"calls","source":3362,"target":571},{"edgeType":"calls","source":1728,"target":490},{"edgeType":"contains","source":17,"target":21},{"edgeType":"calls","source":4800,"target":389},{"edgeType":"contains","source":799,"target":1147},{"edgeType":"calls","source":4335,"target":1063},{"edgeType":"calls","source":2238,"target":533},{"edgeType":"calls","source":2887,"target":498},{"edgeType":"contains","source":3056,"target":3057},{"edgeType":"extends","source":1337,"target":1227},{"edgeType":"contains","source":2292,"target":2429},{"edgeType":"calls","source":1263,"target":106},{"edgeType":"calls","source":3362,"target":572},{"edgeType":"calls","source":3286,"target":1871},{"edgeType":"calls","source":3272,"target":191},{"edgeType":"calls","source":1077,"target":586},{"edgeType":"calls","source":3841,"target":3692},{"edgeType":"contains","source":17,"target":20},{"edgeType":"contains","source":2098,"target":2101},{"edgeType":"calls","source":4594,"target":1489},{"edgeType":"calls","source":1728,"target":489},{"edgeType":"imports","source":1257,"target":302},{"edgeType":"calls","source":4800,"target":388},{"edgeType":"calls","source":3780,"target":298},{"edgeType":"contains","source":799,"target":1146},{"edgeType":"calls","source":4193,"target":179},{"edgeType":"calls","source":3565,"target":1675},{"edgeType":"calls","source":2779,"target":2786},{"edgeType":"calls","source":741,"target":427},{"edgeType":"calls","source":2965,"target":191},{"edgeType":"contains","source":1104,"target":1208},{"edgeType":"calls","source":1672,"target":106},{"edgeType":"calls","source":3362,"target":569},{"edgeType":"calls","source":3324,"target":690},{"edgeType":"imports","source":396,"target":564},{"edgeType":"calls","source":1810,"target":1113},{"edgeType":"calls","source":4802,"target":325},{"edgeType":"calls","source":4800,"target":387},{"edgeType":"calls","source":2048,"target":77},{"edgeType":"contains","source":799,"target":1149},{"edgeType":"imports","source":38,"target":35},{"edgeType":"calls","source":2339,"target":571},{"edgeType":"contains","source":4407,"target":4520},{"edgeType":"calls","source":849,"target":249},{"edgeType":"contains","source":1104,"target":1207},{"edgeType":"contains","source":3517,"target":3569},{"edgeType":"calls","source":1350,"target":574},{"edgeType":"calls","source":3362,"target":570},{"edgeType":"calls","source":2516,"target":2484},{"edgeType":"imports","source":1257,"target":300},{"edgeType":"calls","source":4799,"target":417},{"edgeType":"calls","source":4794,"target":572},{"edgeType":"calls","source":4800,"target":386},{"edgeType":"calls","source":741,"target":426},{"edgeType":"contains","source":2255,"target":411},{"edgeType":"contains","source":2226,"target":2367},{"edgeType":"calls","source":2339,"target":572},{"edgeType":"contains","source":4407,"target":4519},{"edgeType":"contains","source":4407,"target":4518},{"edgeType":"calls","source":2207,"target":1489},{"edgeType":"calls","source":2339,"target":568},{"edgeType":"calls","source":2320,"target":100},{"edgeType":"calls","source":3287,"target":777},{"edgeType":"calls","source":3340,"target":191},{"edgeType":"calls","source":3362,"target":566},{"edgeType":"calls","source":4794,"target":571},{"edgeType":"calls","source":4800,"target":385},{"edgeType":"contains","source":1933,"target":1934},{"edgeType":"calls","source":1728,"target":486},{"edgeType":"imports","source":3710,"target":375},{"edgeType":"calls","source":2781,"target":608},{"edgeType":"calls","source":2339,"target":569},{"edgeType":"calls","source":4622,"target":1675},{"edgeType":"calls","source":2251,"target":2240},{"edgeType":"calls","source":2320,"target":101},{"edgeType":"contains","source":2924,"target":2925},{"edgeType":"calls","source":1728,"target":485},{"edgeType":"calls","source":3362,"target":568},{"edgeType":"contains","source":3517,"target":3567},{"edgeType":"calls","source":3362,"target":567},{"edgeType":"calls","source":4794,"target":570},{"edgeType":"calls","source":4800,"target":384},{"edgeType":"calls","source":4836,"target":325},{"edgeType":"contains","source":2098,"target":2105},{"edgeType":"calls","source":4056,"target":194},{"edgeType":"contains","source":3,"target":1515},{"edgeType":"calls","source":2339,"target":570},{"edgeType":"calls","source":2320,"target":102},{"edgeType":"imports","source":97,"target":319},{"edgeType":"calls","source":2339,"target":566},{"edgeType":"calls","source":2320,"target":98},{"edgeType":"calls","source":2365,"target":817},{"edgeType":"calls","source":4397,"target":191},{"edgeType":"calls","source":325,"target":634},{"edgeType":"contains","source":3701,"target":2098},{"edgeType":"contains","source":4840,"target":4843},{"edgeType":"calls","source":1695,"target":446},{"edgeType":"imports","source":2201,"target":645},{"edgeType":"calls","source":578,"target":191},{"edgeType":"imports","source":4045,"target":546},{"edgeType":"calls","source":3276,"target":3230},{"edgeType":"calls","source":4794,"target":569},{"edgeType":"calls","source":4800,"target":383},{"edgeType":"calls","source":1892,"target":1738},{"edgeType":"calls","source":1157,"target":211},{"edgeType":"calls","source":2320,"target":99},{"edgeType":"calls","source":909,"target":499},{"edgeType":"contains","source":2255,"target":1472},{"edgeType":"calls","source":2339,"target":567},{"edgeType":"calls","source":4527,"target":388},{"edgeType":"calls","source":325,"target":633},{"edgeType":"calls","source":4321,"target":1489},{"edgeType":"calls","source":3829,"target":887},{"edgeType":"contains","source":4840,"target":4842},{"edgeType":"calls","source":1695,"target":445},{"edgeType":"contains","source":3123,"target":990},{"edgeType":"imports","source":4045,"target":547},{"edgeType":"calls","source":4794,"target":568},{"edgeType":"calls","source":4800,"target":382},{"edgeType":"calls","source":4786,"target":1873},{"edgeType":"calls","source":4836,"target":3494},{"edgeType":"calls","source":1059,"target":77},{"edgeType":"contains","source":4407,"target":4523},{"edgeType":"calls","source":4527,"target":389},{"edgeType":"calls","source":4841,"target":2282},{"edgeType":"contains","source":2098,"target":2111},{"edgeType":"calls","source":4662,"target":1489},{"edgeType":"calls","source":4527,"target":387},{"edgeType":"calls","source":849,"target":248},{"edgeType":"calls","source":2447,"target":387},{"edgeType":"contains","source":2806,"target":3415},{"edgeType":"imports","source":3643,"target":325},{"edgeType":"calls","source":4200,"target":4182},{"edgeType":"contains","source":4840,"target":4841},{"edgeType":"contains","source":3056,"target":3064},{"edgeType":"calls","source":1258,"target":1310},{"edgeType":"contains","source":4001,"target":196},{"edgeType":"calls","source":725,"target":921},{"edgeType":"calls","source":741,"target":425},{"edgeType":"contains","source":4407,"target":4522},{"edgeType":"contains","source":4278,"target":4293},{"edgeType":"calls","source":4794,"target":567},{"edgeType":"calls","source":4527,"target":386},{"edgeType":"calls","source":2447,"target":388},{"edgeType":"calls","source":4593,"target":454},{"edgeType":"contains","source":2806,"target":3416},{"edgeType":"calls","source":1932,"target":499},{"edgeType":"calls","source":1897,"target":527},{"edgeType":"calls","source":1157,"target":212},{"edgeType":"calls","source":4616,"target":1856},{"edgeType":"calls","source":308,"target":106},{"edgeType":"calls","source":2447,"target":389},{"edgeType":"contains","source":4407,"target":4521},{"edgeType":"calls","source":4794,"target":566},{"edgeType":"calls","source":2763,"target":106},{"edgeType":"calls","source":4819,"target":1905},{"edgeType":"calls","source":4527,"target":385},{"edgeType":"calls","source":2512,"target":484},{"edgeType":"calls","source":4627,"target":456},{"edgeType":"contains","source":4277,"target":4330},{"edgeType":"calls","source":2251,"target":2233},{"edgeType":"calls","source":2447,"target":385},{"edgeType":"contains","source":612,"target":613},{"edgeType":"contains","source":4840,"target":4847},{"edgeType":"calls","source":1974,"target":249},{"edgeType":"contains","source":97,"target":721},{"edgeType":"calls","source":400,"target":418},{"edgeType":"calls","source":2447,"target":386},{"edgeType":"calls","source":2365,"target":814},{"edgeType":"calls","source":4527,"target":384},{"edgeType":"contains","source":2989,"target":3034},{"edgeType":"calls","source":3625,"target":865},{"edgeType":"contains","source":1090,"target":1649},{"edgeType":"calls","source":1974,"target":248},{"edgeType":"contains","source":4840,"target":4846},{"edgeType":"calls","source":4124,"target":194},{"edgeType":"calls","source":4143,"target":1719},{"edgeType":"calls","source":3348,"target":995},{"edgeType":"calls","source":3414,"target":3177},{"edgeType":"calls","source":863,"target":864},{"edgeType":"calls","source":1077,"target":572},{"edgeType":"calls","source":2447,"target":383},{"edgeType":"contains","source":2806,"target":3419},{"edgeType":"imports","source":29,"target":320},{"edgeType":"imports","source":38,"target":41},{"edgeType":"calls","source":4527,"target":383},{"edgeType":"imports","source":97,"target":326},{"edgeType":"contains","source":511,"target":575},{"edgeType":"contains","source":4840,"target":4845},{"edgeType":"contains","source":843,"target":853},{"edgeType":"contains","source":2989,"target":3031},{"edgeType":"calls","source":4015,"target":2513},{"edgeType":"calls","source":4883,"target":2032},{"edgeType":"calls","source":2726,"target":191},{"edgeType":"calls","source":1258,"target":249},{"edgeType":"calls","source":2682,"target":498},{"edgeType":"calls","source":2632,"target":991},{"edgeType":"calls","source":4806,"target":191},{"edgeType":"calls","source":2447,"target":384},{"edgeType":"calls","source":4527,"target":382},{"edgeType":"calls","source":325,"target":631},{"edgeType":"calls","source":4570,"target":106},{"edgeType":"imports","source":38,"target":42},{"edgeType":"contains","source":843,"target":852},{"edgeType":"contains","source":4840,"target":4844},{"edgeType":"calls","source":4076,"target":623},{"edgeType":"contains","source":1833,"target":1872},{"edgeType":"calls","source":2036,"target":1499},{"edgeType":"calls","source":665,"target":662},{"edgeType":"calls","source":1258,"target":248},{"edgeType":"contains","source":1636,"target":1637},{"edgeType":"calls","source":4730,"target":1489},{"edgeType":"calls","source":4607,"target":4245},{"edgeType":"contains","source":2280,"target":2813},{"edgeType":"calls","source":1693,"target":1656},{"edgeType":"imports","source":3811,"target":458},{"edgeType":"contains","source":799,"target":1129},{"edgeType":"contains","source":2806,"target":3392},{"edgeType":"calls","source":2790,"target":418},{"edgeType":"contains","source":1090,"target":1621},{"edgeType":"calls","source":3628,"target":865},{"edgeType":"calls","source":2625,"target":248},{"edgeType":"calls","source":1261,"target":249},{"edgeType":"calls","source":4724,"target":716},{"edgeType":"calls","source":4731,"target":499},{"edgeType":"calls","source":4831,"target":570},{"edgeType":"calls","source":965,"target":969},{"edgeType":"calls","source":2985,"target":715},{"edgeType":"contains","source":4376,"target":4402},{"edgeType":"contains","source":612,"target":1640},{"edgeType":"calls","source":2766,"target":106},{"edgeType":"contains","source":3782,"target":3790},{"edgeType":"calls","source":669,"target":631},{"edgeType":"calls","source":2713,"target":692},{"edgeType":"calls","source":1328,"target":1342},{"edgeType":"calls","source":4724,"target":715},{"edgeType":"calls","source":3324,"target":777},{"edgeType":"calls","source":1261,"target":248},{"edgeType":"calls","source":2625,"target":249},{"edgeType":"calls","source":4831,"target":569},{"edgeType":"calls","source":2985,"target":716},{"edgeType":"calls","source":3863,"target":978},{"edgeType":"calls","source":3786,"target":194},{"edgeType":"calls","source":4724,"target":713},{"edgeType":"contains","source":4244,"target":4265},{"edgeType":"calls","source":2278,"target":1489},{"edgeType":"contains","source":799,"target":1131},{"edgeType":"imports","source":1918,"target":1001},{"edgeType":"calls","source":1895,"target":1738},{"edgeType":"calls","source":4872,"target":354},{"edgeType":"calls","source":2985,"target":713},{"edgeType":"calls","source":4699,"target":1489},{"edgeType":"calls","source":4724,"target":714},{"edgeType":"calls","source":2953,"target":648},{"edgeType":"calls","source":4831,"target":568},{"edgeType":"contains","source":1864,"target":1938},{"edgeType":"contains","source":4244,"target":4264},{"edgeType":"calls","source":4724,"target":712},{"edgeType":"calls","source":2254,"target":2234},{"edgeType":"contains","source":799,"target":1130},{"edgeType":"calls","source":635,"target":630},{"edgeType":"contains","source":3115,"target":3325},{"edgeType":"calls","source":1297,"target":191},{"edgeType":"calls","source":2713,"target":690},{"edgeType":"contains","source":3050,"target":3226},{"edgeType":"calls","source":4872,"target":353},{"edgeType":"contains","source":4407,"target":4496},{"edgeType":"calls","source":2985,"target":714},{"edgeType":"calls","source":2651,"target":498},{"edgeType":"calls","source":4831,"target":567},{"edgeType":"calls","source":3367,"target":499},{"edgeType":"contains","source":1833,"target":1843},{"edgeType":"contains","source":3782,"target":3788},{"edgeType":"imports","source":4451,"target":1763},{"edgeType":"contains","source":4079,"target":1987},{"edgeType":"calls","source":4012,"target":585},{"edgeType":"calls","source":1911,"target":179},{"edgeType":"calls","source":4727,"target":1675},{"edgeType":"contains","source":798,"target":1164},{"edgeType":"extends","source":1864,"target":1857},{"edgeType":"calls","source":2895,"target":330},{"edgeType":"calls","source":4886,"target":2032},{"edgeType":"contains","source":3749,"target":3761},{"edgeType":"calls","source":954,"target":249},{"edgeType":"calls","source":4831,"target":566},{"edgeType":"contains","source":3162,"target":2930},{"edgeType":"calls","source":3271,"target":301},{"edgeType":"imports","source":396,"target":1672},{"edgeType":"calls","source":4764,"target":527},{"edgeType":"calls","source":1796,"target":572},{"edgeType":"calls","source":2685,"target":498},{"edgeType":"contains","source":799,"target":1132},{"edgeType":"calls","source":4012,"target":586},{"edgeType":"calls","source":3658,"target":2046},{"edgeType":"calls","source":2980,"target":2981},{"edgeType":"calls","source":954,"target":248},{"edgeType":"calls","source":2985,"target":712},{"edgeType":"calls","source":1728,"target":565},{"edgeType":"calls","source":1229,"target":179},{"edgeType":"calls","source":4701,"target":365},{"edgeType":"calls","source":1659,"target":1651},{"edgeType":"calls","source":4843,"target":191},{"edgeType":"calls","source":573,"target":434},{"edgeType":"calls","source":4182,"target":1655},{"edgeType":"imports","source":38,"target":82},{"edgeType":"contains","source":4407,"target":4501},{"edgeType":"calls","source":573,"target":435},{"edgeType":"contains","source":799,"target":1135},{"edgeType":"calls","source":2895,"target":328},{"edgeType":"contains","source":799,"target":1134},{"edgeType":"contains","source":4376,"target":4404},{"edgeType":"calls","source":4579,"target":975},{"edgeType":"calls","source":4592,"target":572},{"edgeType":"contains","source":3749,"target":3758},{"edgeType":"contains","source":1864,"target":1943},{"edgeType":"imports","source":2255,"target":78},{"edgeType":"calls","source":2656,"target":335},{"edgeType":"calls","source":3950,"target":389},{"edgeType":"calls","source":673,"target":499},{"edgeType":"calls","source":301,"target":404},{"edgeType":"calls","source":4592,"target":571},{"edgeType":"contains","source":4278,"target":4279},{"edgeType":"contains","source":799,"target":1137},{"edgeType":"calls","source":978,"target":558},{"edgeType":"contains","source":3115,"target":3334},{"edgeType":"calls","source":1796,"target":568},{"edgeType":"calls","source":1845,"target":106},{"edgeType":"calls","source":3392,"target":774},{"edgeType":"calls","source":1941,"target":301},{"edgeType":"calls","source":2664,"target":88},{"edgeType":"calls","source":3813,"target":3580},{"edgeType":"calls","source":4124,"target":1338},{"edgeType":"calls","source":4592,"target":570},{"edgeType":"imports","source":396,"target":627},{"edgeType":"calls","source":978,"target":557},{"edgeType":"contains","source":799,"target":1136},{"edgeType":"calls","source":1796,"target":567},{"edgeType":"contains","source":2989,"target":3013},{"edgeType":"calls","source":3595,"target":824},{"edgeType":"calls","source":3427,"target":747},{"edgeType":"contains","source":3115,"target":3335},{"edgeType":"calls","source":4795,"target":1675},{"edgeType":"contains","source":1864,"target":1946},{"edgeType":"calls","source":1796,"target":571},{"edgeType":"calls","source":4592,"target":569},{"edgeType":"calls","source":2037,"target":499},{"edgeType":"calls","source":4712,"target":1077},{"edgeType":"contains","source":799,"target":1139},{"edgeType":"calls","source":2300,"target":1856},{"edgeType":"imports","source":3506,"target":2508},{"edgeType":"calls","source":3888,"target":194},{"edgeType":"calls","source":3950,"target":386},{"edgeType":"calls","source":3461,"target":747},{"edgeType":"calls","source":3854,"target":191},{"edgeType":"imports","source":2201,"target":1750},{"edgeType":"calls","source":2656,"target":334},{"edgeType":"calls","source":1796,"target":570},{"edgeType":"calls","source":3950,"target":388},{"edgeType":"calls","source":4592,"target":568},{"edgeType":"calls","source":4587,"target":723},{"edgeType":"imports","source":4209,"target":799},{"edgeType":"calls","source":4547,"target":906},{"edgeType":"calls","source":4454,"target":1675},{"edgeType":"contains","source":3749,"target":3762},{"edgeType":"contains","source":798,"target":1169},{"edgeType":"contains","source":799,"target":1138},{"edgeType":"calls","source":3158,"target":628},{"edgeType":"calls","source":3950,"target":387},{"edgeType":"calls","source":1796,"target":569},{"edgeType":"contains","source":3221,"target":3224},{"edgeType":"calls","source":1970,"target":456},{"edgeType":"calls","source":2085,"target":1119},{"edgeType":"calls","source":4592,"target":567},{"edgeType":"calls","source":4587,"target":722},{"edgeType":"contains","source":4001,"target":185},{"edgeType":"calls","source":2831,"target":191},{"edgeType":"contains","source":799,"target":1141},{"edgeType":"contains","source":4146,"target":4147},{"edgeType":"calls","source":2205,"target":571},{"edgeType":"calls","source":3950,"target":384},{"edgeType":"imports","source":4376,"target":4080},{"edgeType":"contains","source":4001,"target":184},{"edgeType":"calls","source":3360,"target":1763},{"edgeType":"imports","source":3050,"target":797},{"edgeType":"contains","source":3115,"target":3340},{"edgeType":"calls","source":2085,"target":1118},{"edgeType":"calls","source":4700,"target":389},{"edgeType":"extends","source":4738,"target":4734},{"edgeType":"calls","source":1064,"target":1058},{"edgeType":"calls","source":4592,"target":566},{"edgeType":"calls","source":705,"target":559},{"edgeType":"calls","source":4764,"target":519},{"edgeType":"calls","source":1672,"target":179},{"edgeType":"contains","source":799,"target":1140},{"edgeType":"calls","source":2205,"target":572},{"edgeType":"calls","source":3950,"target":385},{"edgeType":"calls","source":3744,"target":3600},{"edgeType":"contains","source":3221,"target":3222},{"edgeType":"calls","source":3460,"target":774},{"edgeType":"calls","source":4700,"target":388},{"edgeType":"calls","source":4371,"target":4245},{"edgeType":"calls","source":4488,"target":1675},{"edgeType":"calls","source":4494,"target":1489},{"edgeType":"contains","source":2230,"target":2232},{"edgeType":"calls","source":906,"target":674},{"edgeType":"contains","source":4212,"target":4213},{"edgeType":"contains","source":3701,"target":2084},{"edgeType":"calls","source":4581,"target":906},{"edgeType":"calls","source":4587,"target":720},{"edgeType":"calls","source":1796,"target":566},{"edgeType":"calls","source":2205,"target":569},{"edgeType":"calls","source":2239,"target":572},{"edgeType":"contains","source":3066,"target":627},{"edgeType":"contains","source":799,"target":1143},{"edgeType":"contains","source":3115,"target":3336},{"edgeType":"calls","source":1774,"target":191},{"edgeType":"calls","source":3950,"target":382},{"edgeType":"contains","source":3221,"target":3223},{"edgeType":"calls","source":1970,"target":457},{"edgeType":"contains","source":1204,"target":1272},{"edgeType":"calls","source":4700,"target":387},{"edgeType":"calls","source":849,"target":325},{"edgeType":"contains","source":799,"target":1142},{"edgeType":"contains","source":4278,"target":4280},{"edgeType":"calls","source":4587,"target":719},{"edgeType":"contains","source":3517,"target":3559},{"edgeType":"calls","source":2205,"target":570},{"edgeType":"calls","source":3950,"target":383},{"edgeType":"calls","source":3888,"target":191},{"edgeType":"contains","source":1062,"target":1416},{"edgeType":"imports","source":34,"target":196},{"edgeType":"calls","source":4869,"target":465},{"edgeType":"calls","source":4876,"target":248},{"edgeType":"calls","source":1302,"target":1109},{"edgeType":"calls","source":4667,"target":385},{"edgeType":"calls","source":774,"target":564},{"edgeType":"calls","source":4701,"target":388},{"edgeType":"calls","source":2922,"target":570},{"edgeType":"calls","source":4495,"target":1489},{"edgeType":"contains","source":16,"target":17},{"edgeType":"calls","source":4582,"target":906},{"edgeType":"calls","source":4372,"target":4245},{"edgeType":"contains","source":2951,"target":3108},{"edgeType":"calls","source":3945,"target":568},{"edgeType":"calls","source":4056,"target":298},{"edgeType":"calls","source":4230,"target":191},{"edgeType":"calls","source":4869,"target":464},{"edgeType":"contains","source":1062,"target":1415},{"edgeType":"calls","source":2542,"target":724},{"edgeType":"calls","source":4701,"target":387},{"edgeType":"calls","source":800,"target":814},{"edgeType":"calls","source":2922,"target":571},{"edgeType":"calls","source":4667,"target":384},{"edgeType":"calls","source":2248,"target":325},{"edgeType":"calls","source":4077,"target":705},{"edgeType":"calls","source":3945,"target":569},{"edgeType":"calls","source":1328,"target":305},{"edgeType":"contains","source":3084,"target":3212},{"edgeType":"calls","source":2763,"target":212},{"edgeType":"calls","source":1290,"target":426},{"edgeType":"calls","source":3546,"target":3422},{"edgeType":"contains","source":2292,"target":2395},{"edgeType":"calls","source":4721,"target":1880},{"edgeType":"calls","source":774,"target":566},{"edgeType":"calls","source":3346,"target":1166},{"edgeType":"calls","source":2922,"target":568},{"edgeType":"contains","source":4045,"target":904},{"edgeType":"contains","source":16,"target":19},{"edgeType":"calls","source":3945,"target":566},{"edgeType":"calls","source":1658,"target":645},{"edgeType":"calls","source":4667,"target":383},{"edgeType":"contains","source":34,"target":518},{"edgeType":"calls","source":4701,"target":386},{"edgeType":"calls","source":2282,"target":325},{"edgeType":"calls","source":2175,"target":471},{"edgeType":"contains","source":4738,"target":4790},{"edgeType":"calls","source":1336,"target":1113},{"edgeType":"contains","source":3084,"target":3213},{"edgeType":"calls","source":2866,"target":191},{"edgeType":"calls","source":1290,"target":425},{"edgeType":"calls","source":3546,"target":3423},{"edgeType":"calls","source":2922,"target":569},{"edgeType":"contains","source":16,"target":18},{"edgeType":"calls","source":1673,"target":179},{"edgeType":"contains","source":34,"target":517},{"edgeType":"calls","source":4701,"target":385},{"edgeType":"calls","source":4523,"target":1675},{"edgeType":"calls","source":4667,"target":382},{"edgeType":"contains","source":2951,"target":3107},{"edgeType":"contains","source":799,"target":1113},{"edgeType":"calls","source":1809,"target":191},{"edgeType":"calls","source":3945,"target":567},{"edgeType":"calls","source":1915,"target":1133},{"edgeType":"calls","source":2922,"target":566},{"edgeType":"contains","source":2989,"target":2992},{"edgeType":"contains","source":2923,"target":2924},{"edgeType":"contains","source":4738,"target":4796},{"edgeType":"calls","source":4745,"target":77},{"edgeType":"calls","source":4701,"target":384},{"edgeType":"contains","source":4407,"target":4487},{"edgeType":"contains","source":2989,"target":2993},{"edgeType":"calls","source":1500,"target":1308},{"edgeType":"calls","source":2922,"target":567},{"edgeType":"imports","source":2259,"target":2038},{"edgeType":"calls","source":2763,"target":211},{"edgeType":"contains","source":2951,"target":3114},{"edgeType":"calls","source":2986,"target":1754},{"edgeType":"calls","source":1735,"target":365},{"edgeType":"calls","source":4701,"target":383},{"edgeType":"calls","source":1877,"target":191},{"edgeType":"calls","source":4755,"target":1880},{"edgeType":"contains","source":396,"target":3038},{"edgeType":"calls","source":641,"target":454},{"edgeType":"calls","source":4047,"target":574},{"edgeType":"calls","source":2320,"target":2317},{"edgeType":"contains","source":2989,"target":2990},{"edgeType":"contains","source":798,"target":1150},{"edgeType":"calls","source":4650,"target":906},{"edgeType":"calls","source":4701,"target":382},{"edgeType":"calls","source":309,"target":179},{"edgeType":"imports","source":3811,"target":448},{"edgeType":"calls","source":1701,"target":365},{"edgeType":"calls","source":3925,"target":1182},{"edgeType":"imports","source":1918,"target":2038},{"edgeType":"calls","source":2238,"target":628},{"edgeType":"calls","source":4338,"target":1063},{"edgeType":"contains","source":2989,"target":2991},{"edgeType":"calls","source":3492,"target":865},{"edgeType":"imports","source":4079,"target":1654},{"edgeType":"contains","source":4079,"target":4082},{"edgeType":"calls","source":2650,"target":2655},{"edgeType":"calls","source":2308,"target":573},{"edgeType":"calls","source":2885,"target":2766},{"edgeType":"contains","source":2989,"target":2996},{"edgeType":"calls","source":4332,"target":191},{"edgeType":"calls","source":2252,"target":191},{"edgeType":"calls","source":4815,"target":4245},{"edgeType":"calls","source":2985,"target":723},{"edgeType":"imports","source":38,"target":80},{"edgeType":"calls","source":1911,"target":191},{"edgeType":"calls","source":1891,"target":1868},{"edgeType":"calls","source":4789,"target":1880},{"edgeType":"contains","source":3782,"target":3783},{"edgeType":"contains","source":4407,"target":4491},{"edgeType":"imports","source":3795,"target":1987},{"edgeType":"calls","source":4250,"target":1675},{"edgeType":"contains","source":16,"target":4253},{"edgeType":"calls","source":371,"target":365},{"edgeType":"contains","source":4244,"target":4259},{"edgeType":"calls","source":2998,"target":2435},{"edgeType":"contains","source":2989,"target":2997},{"edgeType":"calls","source":4724,"target":723},{"edgeType":"calls","source":1229,"target":191},{"edgeType":"contains","source":4738,"target":4799},{"edgeType":"calls","source":311,"target":110},{"edgeType":"contains","source":4244,"target":4258},{"edgeType":"calls","source":4591,"target":1675},{"edgeType":"calls","source":4597,"target":1489},{"edgeType":"calls","source":635,"target":636},{"edgeType":"calls","source":4448,"target":1880},{"edgeType":"contains","source":2989,"target":2994},{"edgeType":"calls","source":2323,"target":102},{"edgeType":"contains","source":3084,"target":3220},{"edgeType":"calls","source":4724,"target":722},{"edgeType":"contains","source":4738,"target":4798},{"edgeType":"contains","source":4244,"target":4257},{"edgeType":"calls","source":2985,"target":722},{"edgeType":"contains","source":2989,"target":2995},{"edgeType":"imports","source":38,"target":79},{"edgeType":"calls","source":3157,"target":675},{"edgeType":"contains","source":1260,"target":1628},{"edgeType":"contains","source":4738,"target":4797},{"edgeType":"calls","source":3309,"target":191},{"edgeType":"calls","source":3327,"target":690},{"edgeType":"contains","source":4407,"target":4488},{"edgeType":"contains","source":798,"target":1156},{"edgeType":"calls","source":899,"target":905},{"edgeType":"contains","source":4244,"target":4263},{"edgeType":"calls","source":2985,"target":719},{"edgeType":"calls","source":2323,"target":100},{"edgeType":"contains","source":4738,"target":4805},{"edgeType":"calls","source":3874,"target":3814},{"edgeType":"calls","source":4755,"target":1873},{"edgeType":"contains","source":1833,"target":1840},{"edgeType":"calls","source":3357,"target":1871},{"edgeType":"contains","source":4407,"target":4495},{"edgeType":"calls","source":1127,"target":179},{"edgeType":"calls","source":4869,"target":3624},{"edgeType":"contains","source":3782,"target":3787},{"edgeType":"calls","source":4631,"target":1489},{"edgeType":"contains","source":32,"target":590},{"edgeType":"calls","source":4724,"target":720},{"edgeType":"calls","source":4498,"target":325},{"edgeType":"contains","source":4244,"target":4262},{"edgeType":"calls","source":2323,"target":101},{"edgeType":"imports","source":2021,"target":2025},{"edgeType":"calls","source":2985,"target":720},{"edgeType":"contains","source":4738,"target":4804},{"edgeType":"calls","source":3874,"target":3815},{"edgeType":"calls","source":3925,"target":1177},{"edgeType":"calls","source":4059,"target":194},{"edgeType":"contains","source":4407,"target":4494},{"edgeType":"contains","source":3749,"target":3752},{"edgeType":"calls","source":1159,"target":1300},{"edgeType":"calls","source":4724,"target":719},{"edgeType":"calls","source":2789,"target":454},{"edgeType":"calls","source":906,"target":687},{"edgeType":"contains","source":1833,"target":1841},{"edgeType":"contains","source":1864,"target":1937},{"edgeType":"imports","source":3506,"target":2495},{"edgeType":"calls","source":4447,"target":1905},{"edgeType":"contains","source":4244,"target":4261},{"edgeType":"calls","source":2323,"target":98},{"edgeType":"calls","source":3874,"target":3812},{"edgeType":"contains","source":4738,"target":4803},{"edgeType":"calls","source":4093,"target":194},{"edgeType":"calls","source":1528,"target":435},{"edgeType":"calls","source":2665,"target":1124},{"edgeType":"calls","source":3307,"target":248},{"edgeType":"contains","source":4407,"target":4493},{"edgeType":"contains","source":3782,"target":3785},{"edgeType":"calls","source":4585,"target":1856},{"edgeType":"calls","source":2661,"target":191},{"edgeType":"contains","source":2259,"target":3430},{"edgeType":"calls","source":2985,"target":717},{"edgeType":"calls","source":4724,"target":718},{"edgeType":"calls","source":4741,"target":191},{"edgeType":"calls","source":4831,"target":572},{"edgeType":"contains","source":4277,"target":4294},{"edgeType":"calls","source":3157,"target":671},{"edgeType":"calls","source":2323,"target":99},{"edgeType":"contains","source":4738,"target":4802},{"edgeType":"calls","source":1528,"target":434},{"edgeType":"contains","source":4738,"target":4801},{"edgeType":"calls","source":3307,"target":249},{"edgeType":"calls","source":1229,"target":189},{"edgeType":"contains","source":3749,"target":3750},{"edgeType":"calls","source":4659,"target":1675},{"edgeType":"calls","source":2915,"target":774},{"edgeType":"contains","source":4407,"target":4492},{"edgeType":"calls","source":4724,"target":717},{"edgeType":"contains","source":2259,"target":3431},{"edgeType":"calls","source":411,"target":179},{"edgeType":"contains","source":3782,"target":3784},{"edgeType":"calls","source":2985,"target":718},{"edgeType":"calls","source":4831,"target":571},{"edgeType":"calls","source":4844,"target":2282},{"edgeType":"calls","source":2415,"target":382},{"edgeType":"contains","source":6,"target":3481},{"edgeType":"calls","source":378,"target":106},{"edgeType":"calls","source":1693,"target":566},{"edgeType":"calls","source":4398,"target":1275},{"edgeType":"calls","source":4148,"target":568},{"edgeType":"calls","source":1995,"target":717},{"edgeType":"calls","source":3939,"target":705},{"edgeType":"calls","source":4864,"target":571},{"edgeType":"imports","source":4234,"target":63},{"edgeType":"contains","source":213,"target":235},{"edgeType":"contains","source":1535,"target":1536},{"edgeType":"calls","source":3323,"target":774},{"edgeType":"calls","source":975,"target":626},{"edgeType":"calls","source":1063,"target":1069},{"edgeType":"calls","source":2415,"target":383},{"edgeType":"calls","source":2375,"target":566},{"edgeType":"calls","source":4398,"target":1274},{"edgeType":"calls","source":1995,"target":716},{"edgeType":"calls","source":4126,"target":194},{"edgeType":"contains","source":2803,"target":3453},{"edgeType":"calls","source":4148,"target":569},{"edgeType":"calls","source":4145,"target":1719},{"edgeType":"calls","source":4864,"target":570},{"edgeType":"calls","source":4730,"target":4724},{"edgeType":"calls","source":3372,"target":1370},{"edgeType":"contains","source":1535,"target":1537},{"edgeType":"contains","source":213,"target":234},{"edgeType":"calls","source":3350,"target":995},{"edgeType":"calls","source":2856,"target":454},{"edgeType":"calls","source":1692,"target":1656},{"edgeType":"calls","source":1693,"target":568},{"edgeType":"calls","source":1699,"target":382},{"edgeType":"calls","source":4467,"target":191},{"edgeType":"calls","source":4070,"target":4041},{"edgeType":"calls","source":4148,"target":566},{"edgeType":"calls","source":1949,"target":1088},{"edgeType":"calls","source":1995,"target":719},{"edgeType":"contains","source":340,"target":528},{"edgeType":"calls","source":604,"target":502},{"edgeType":"calls","source":2894,"target":330},{"edgeType":"calls","source":4885,"target":2032},{"edgeType":"calls","source":4765,"target":4695},{"edgeType":"calls","source":4864,"target":569},{"edgeType":"calls","source":2719,"target":470},{"edgeType":"calls","source":2728,"target":191},{"edgeType":"contains","source":213,"target":237},{"edgeType":"contains","source":16,"target":2115},{"edgeType":"calls","source":1693,"target":567},{"edgeType":"contains","source":511,"target":512},{"edgeType":"calls","source":1995,"target":718},{"edgeType":"calls","source":4368,"target":88},{"edgeType":"calls","source":2050,"target":1127},{"edgeType":"calls","source":4148,"target":567},{"edgeType":"contains","source":395,"target":3050},{"edgeType":"calls","source":2720,"target":1497},{"edgeType":"calls","source":4864,"target":568},{"edgeType":"contains","source":4045,"target":4058},{"edgeType":"contains","source":213,"target":236},{"edgeType":"calls","source":3328,"target":1675},{"edgeType":"contains","source":3701,"target":2038},{"edgeType":"calls","source":4505,"target":3239},{"edgeType":"calls","source":1810,"target":106},{"edgeType":"contains","source":16,"target":2118},{"edgeType":"contains","source":2029,"target":2081},{"edgeType":"calls","source":2719,"target":467},{"edgeType":"calls","source":1995,"target":713},{"edgeType":"calls","source":2762,"target":191},{"edgeType":"contains","source":2806,"target":3363},{"edgeType":"calls","source":2894,"target":328},{"edgeType":"calls","source":887,"target":179},{"edgeType":"contains","source":213,"target":239},{"edgeType":"calls","source":4864,"target":567},{"edgeType":"calls","source":2754,"target":1497},{"edgeType":"calls","source":1328,"target":249},{"edgeType":"contains","source":1204,"target":1229},{"edgeType":"calls","source":1659,"target":558},{"edgeType":"calls","source":3442,"target":3423},{"edgeType":"calls","source":1261,"target":1269},{"edgeType":"calls","source":3368,"target":1489},{"edgeType":"calls","source":1128,"target":106},{"edgeType":"calls","source":4731,"target":460},{"edgeType":"contains","source":4738,"target":4779},{"edgeType":"calls","source":1995,"target":712},{"edgeType":"calls","source":2719,"target":468},{"edgeType":"calls","source":2311,"target":1489},{"edgeType":"calls","source":4578,"target":975},{"edgeType":"calls","source":4591,"target":572},{"edgeType":"contains","source":1104,"target":1157},{"edgeType":"contains","source":213,"target":238},{"edgeType":"calls","source":2719,"target":469},{"edgeType":"calls","source":4864,"target":566},{"edgeType":"calls","source":1328,"target":248},{"edgeType":"calls","source":3360,"target":1738},{"edgeType":"calls","source":1659,"target":557},{"edgeType":"calls","source":3268,"target":2476},{"edgeType":"calls","source":1063,"target":1067},{"edgeType":"calls","source":1904,"target":365},{"edgeType":"calls","source":1659,"target":561},{"edgeType":"contains","source":2280,"target":1697},{"edgeType":"calls","source":2719,"target":465},{"edgeType":"calls","source":1995,"target":715},{"edgeType":"calls","source":2726,"target":248},{"edgeType":"calls","source":301,"target":377},{"edgeType":"calls","source":4591,"target":571},{"edgeType":"calls","source":4398,"target":212},{"edgeType":"contains","source":4407,"target":4468},{"edgeType":"contains","source":213,"target":241},{"edgeType":"contains","source":1062,"target":1405},{"edgeType":"contains","source":2292,"target":2382},{"edgeType":"calls","source":966,"target":903},{"edgeType":"contains","source":3484,"target":3485},{"edgeType":"calls","source":3363,"target":585},{"edgeType":"contains","source":2029,"target":2080},{"edgeType":"calls","source":1719,"target":814},{"edgeType":"calls","source":1995,"target":714},{"edgeType":"calls","source":2719,"target":466},{"edgeType":"calls","source":2726,"target":249},{"edgeType":"calls","source":4876,"target":191},{"edgeType":"contains","source":2806,"target":3362},{"edgeType":"imports","source":32,"target":302},{"edgeType":"calls","source":4591,"target":570},{"edgeType":"calls","source":301,"target":376},{"edgeType":"calls","source":2377,"target":498},{"edgeType":"calls","source":4398,"target":211},{"edgeType":"contains","source":1062,"target":1404},{"edgeType":"contains","source":213,"target":240},{"edgeType":"contains","source":3517,"target":3518},{"edgeType":"calls","source":1228,"target":179},{"edgeType":"calls","source":3363,"target":586},{"edgeType":"calls","source":3442,"target":3422},{"edgeType":"calls","source":549,"target":82},{"edgeType":"calls","source":4711,"target":1077},{"edgeType":"calls","source":4794,"target":1675},{"edgeType":"calls","source":4800,"target":1489},{"edgeType":"calls","source":4282,"target":634},{"edgeType":"calls","source":412,"target":101},{"edgeType":"calls","source":2847,"target":723},{"edgeType":"imports","source":4234,"target":2168},{"edgeType":"calls","source":674,"target":435},{"edgeType":"calls","source":4591,"target":569},{"edgeType":"contains","source":2951,"target":3100},{"edgeType":"contains","source":213,"target":243},{"edgeType":"calls","source":1773,"target":191},{"edgeType":"contains","source":1062,"target":1407},{"edgeType":"calls","source":3628,"target":824},{"edgeType":"calls","source":1969,"target":457},{"edgeType":"calls","source":1290,"target":365},{"edgeType":"calls","source":1328,"target":1301},{"edgeType":"calls","source":4020,"target":301},{"edgeType":"contains","source":4738,"target":4783},{"edgeType":"calls","source":754,"target":68},{"edgeType":"calls","source":4591,"target":568},{"edgeType":"calls","source":339,"target":249},{"edgeType":"calls","source":412,"target":100},{"edgeType":"calls","source":4453,"target":1675},{"edgeType":"calls","source":4546,"target":906},{"edgeType":"calls","source":674,"target":434},{"edgeType":"calls","source":208,"target":82},{"edgeType":"contains","source":213,"target":242},{"edgeType":"calls","source":3157,"target":628},{"edgeType":"contains","source":1062,"target":1406},{"edgeType":"calls","source":4107,"target":772},{"edgeType":"calls","source":3301,"target":389},{"edgeType":"calls","source":4591,"target":567},{"edgeType":"contains","source":213,"target":246},{"edgeType":"contains","source":2292,"target":2386},{"edgeType":"extends","source":2098,"target":2038},{"edgeType":"contains","source":1062,"target":1409},{"edgeType":"calls","source":1429,"target":1344},{"edgeType":"calls","source":1475,"target":975},{"edgeType":"contains","source":1337,"target":1338},{"edgeType":"calls","source":3766,"target":772},{"edgeType":"contains","source":1864,"target":1914},{"edgeType":"calls","source":4213,"target":658},{"edgeType":"calls","source":2847,"target":722},{"edgeType":"calls","source":4282,"target":633},{"edgeType":"calls","source":4591,"target":566},{"edgeType":"calls","source":2550,"target":416},{"edgeType":"calls","source":412,"target":102},{"edgeType":"contains","source":213,"target":245},{"edgeType":"calls","source":2656,"target":301},{"edgeType":"contains","source":213,"target":244},{"edgeType":"contains","source":1515,"target":4277},{"edgeType":"calls","source":2207,"target":479},{"edgeType":"calls","source":921,"target":179},{"edgeType":"contains","source":1731,"target":1809},{"edgeType":"contains","source":1062,"target":1408},{"edgeType":"calls","source":3743,"target":3600},{"edgeType":"imports","source":2255,"target":1165},{"edgeType":"calls","source":3459,"target":774},{"edgeType":"calls","source":4075,"target":705},{"edgeType":"calls","source":3301,"target":387},{"edgeType":"calls","source":1185,"target":446},{"edgeType":"calls","source":4580,"target":906},{"edgeType":"contains","source":1731,"target":1814},{"edgeType":"calls","source":2656,"target":298},{"edgeType":"calls","source":2962,"target":325},{"edgeType":"calls","source":2847,"target":719},{"edgeType":"imports","source":1918,"target":2098},{"edgeType":"contains","source":4244,"target":4247},{"edgeType":"calls","source":4487,"target":1675},{"edgeType":"calls","source":4493,"target":1489},{"edgeType":"calls","source":2453,"target":249},{"edgeType":"calls","source":2238,"target":572},{"edgeType":"contains","source":4738,"target":4788},{"edgeType":"contains","source":1337,"target":1344},{"edgeType":"calls","source":3580,"target":194},{"edgeType":"calls","source":3671,"target":544},{"edgeType":"calls","source":4054,"target":298},{"edgeType":"contains","source":1062,"target":1411},{"edgeType":"contains","source":3120,"target":3152},{"edgeType":"calls","source":3301,"target":388},{"edgeType":"contains","source":2259,"target":3417},{"edgeType":"calls","source":784,"target":191},{"edgeType":"calls","source":1185,"target":445},{"edgeType":"contains","source":1636,"target":2646},{"edgeType":"contains","source":1731,"target":1815},{"edgeType":"contains","source":213,"target":247},{"edgeType":"contains","source":28,"target":696},{"edgeType":"calls","source":2847,"target":720},{"edgeType":"contains","source":1864,"target":1920},{"edgeType":"contains","source":2806,"target":3372},{"edgeType":"calls","source":2445,"target":498},{"edgeType":"imports","source":4234,"target":2174},{"edgeType":"contains","source":4376,"target":4382},{"edgeType":"contains","source":3115,"target":3306},{"edgeType":"contains","source":2951,"target":3105},{"edgeType":"contains","source":1062,"target":1414},{"edgeType":"calls","source":1969,"target":456},{"edgeType":"calls","source":2765,"target":88},{"edgeType":"calls","source":3301,"target":385},{"edgeType":"calls","source":412,"target":99},{"edgeType":"imports","source":4045,"target":1691},{"edgeType":"calls","source":369,"target":375},{"edgeType":"calls","source":1063,"target":1059},{"edgeType":"calls","source":2847,"target":717},{"edgeType":"contains","source":2201,"target":983},{"edgeType":"contains","source":2229,"target":2230},{"edgeType":"contains","source":4244,"target":4245},{"edgeType":"calls","source":339,"target":248},{"edgeType":"calls","source":4447,"target":1856},{"edgeType":"calls","source":2479,"target":498},{"edgeType":"calls","source":2238,"target":570},{"edgeType":"contains","source":3084,"target":3207},{"edgeType":"calls","source":3601,"target":1655},{"edgeType":"calls","source":2006,"target":365},{"edgeType":"contains","source":4738,"target":4785},{"edgeType":"calls","source":3301,"target":386},{"edgeType":"calls","source":412,"target":98},{"edgeType":"contains","source":1731,"target":1813},{"edgeType":"calls","source":4804,"target":301},{"edgeType":"calls","source":2847,"target":718},{"edgeType":"contains","source":4277,"target":4278},{"edgeType":"calls","source":4521,"target":1675},{"edgeType":"contains","source":2196,"target":2197},{"edgeType":"contains","source":97,"target":674},{"edgeType":"contains","source":2803,"target":3463},{"edgeType":"calls","source":3121,"target":2795},{"edgeType":"contains","source":3517,"target":3526},{"edgeType":"calls","source":2453,"target":248},{"edgeType":"calls","source":4396,"target":3436},{"edgeType":"calls","source":4019,"target":325},{"edgeType":"calls","source":2238,"target":571},{"edgeType":"contains","source":1062,"target":1412},{"edgeType":"calls","source":1944,"target":1229},{"edgeType":"contains","source":3120,"target":3122},{"edgeType":"calls","source":618,"target":82},{"edgeType":"contains","source":4407,"target":4450},{"edgeType":"calls","source":1231,"target":106},{"edgeType":"calls","source":890,"target":106},{"edgeType":"contains","source":213,"target":219},{"edgeType":"calls","source":4700,"target":386},{"edgeType":"calls","source":4694,"target":572},{"edgeType":"calls","source":3258,"target":692},{"edgeType":"contains","source":1864,"target":1890},{"edgeType":"calls","source":1767,"target":402},{"edgeType":"calls","source":3854,"target":185},{"edgeType":"contains","source":3351,"target":3361},{"edgeType":"calls","source":2480,"target":498},{"edgeType":"calls","source":4587,"target":718},{"edgeType":"calls","source":2205,"target":567},{"edgeType":"calls","source":2239,"target":570},{"edgeType":"contains","source":1062,"target":1382},{"edgeType":"contains","source":4407,"target":4449},{"edgeType":"contains","source":213,"target":218},{"edgeType":"contains","source":1864,"target":1891},{"edgeType":"calls","source":3102,"target":1301},{"edgeType":"calls","source":1767,"target":401},{"edgeType":"calls","source":3801,"target":772},{"edgeType":"calls","source":4700,"target":385},{"edgeType":"calls","source":4694,"target":571},{"edgeType":"calls","source":2480,"target":499},{"edgeType":"calls","source":4522,"target":1675},{"edgeType":"calls","source":4528,"target":1489},{"edgeType":"calls","source":4587,"target":717},{"edgeType":"calls","source":2239,"target":571},{"edgeType":"calls","source":2242,"target":478},{"edgeType":"calls","source":2205,"target":568},{"edgeType":"calls","source":2085,"target":1117},{"edgeType":"contains","source":396,"target":1947},{"edgeType":"contains","source":4407,"target":4448},{"edgeType":"contains","source":213,"target":221},{"edgeType":"calls","source":2676,"target":762},{"edgeType":"calls","source":1064,"target":1057},{"edgeType":"calls","source":3258,"target":690},{"edgeType":"calls","source":865,"target":883},{"edgeType":"calls","source":4587,"target":716},{"edgeType":"calls","source":4700,"target":384},{"edgeType":"calls","source":4694,"target":570},{"edgeType":"calls","source":404,"target":376},{"edgeType":"extends","source":2029,"target":2038},{"edgeType":"calls","source":2239,"target":568},{"edgeType":"calls","source":1992,"target":1885},{"edgeType":"calls","source":2760,"target":1330},{"edgeType":"imports","source":2201,"target":1757},{"edgeType":"contains","source":4407,"target":4447},{"edgeType":"contains","source":213,"target":220},{"edgeType":"contains","source":2259,"target":3386},{"edgeType":"calls","source":4800,"target":454},{"edgeType":"contains","source":1864,"target":1889},{"edgeType":"calls","source":4638,"target":191},{"edgeType":"calls","source":4587,"target":715},{"edgeType":"calls","source":4700,"target":383},{"edgeType":"calls","source":4694,"target":569},{"edgeType":"calls","source":3692,"target":978},{"edgeType":"calls","source":4089,"target":298},{"edgeType":"calls","source":2239,"target":569},{"edgeType":"calls","source":2205,"target":566},{"edgeType":"calls","source":4303,"target":1063},{"edgeType":"calls","source":4123,"target":301},{"edgeType":"contains","source":4407,"target":4454},{"edgeType":"contains","source":213,"target":223},{"edgeType":"contains","source":1062,"target":1387},{"edgeType":"calls","source":1393,"target":365},{"edgeType":"calls","source":1185,"target":470},{"edgeType":"calls","source":4587,"target":714},{"edgeType":"calls","source":1752,"target":863},{"edgeType":"calls","source":4439,"target":4245},{"edgeType":"calls","source":4700,"target":382},{"edgeType":"calls","source":4694,"target":568},{"edgeType":"calls","source":2239,"target":566},{"edgeType":"calls","source":771,"target":619},{"edgeType":"contains","source":4407,"target":4453},{"edgeType":"contains","source":1864,"target":1895},{"edgeType":"calls","source":4694,"target":567},{"edgeType":"calls","source":1185,"target":469},{"edgeType":"calls","source":4587,"target":713},{"edgeType":"contains","source":4045,"target":4048},{"edgeType":"calls","source":2323,"target":77},{"edgeType":"calls","source":2239,"target":567},{"edgeType":"contains","source":4407,"target":4452},{"edgeType":"contains","source":213,"target":225},{"edgeType":"contains","source":1864,"target":1892},{"edgeType":"calls","source":3525,"target":865},{"edgeType":"calls","source":4024,"target":194},{"edgeType":"calls","source":4694,"target":566},{"edgeType":"contains","source":97,"target":650},{"edgeType":"contains","source":2280,"target":1681},{"edgeType":"calls","source":4536,"target":179},{"edgeType":"imports","source":32,"target":285},{"edgeType":"calls","source":4587,"target":712},{"edgeType":"calls","source":4249,"target":1675},{"edgeType":"calls","source":301,"target":394},{"edgeType":"contains","source":2803,"target":3437},{"edgeType":"calls","source":4337,"target":1063},{"edgeType":"imports","source":4045,"target":627},{"edgeType":"contains","source":213,"target":224},{"edgeType":"contains","source":1062,"target":1388},{"edgeType":"calls","source":1336,"target":1076},{"edgeType":"calls","source":3288,"target":1871},{"edgeType":"calls","source":1734,"target":365},{"edgeType":"calls","source":1876,"target":191},{"edgeType":"calls","source":3843,"target":3692},{"edgeType":"calls","source":4536,"target":1235},{"edgeType":"contains","source":213,"target":227},{"edgeType":"calls","source":2241,"target":499},{"edgeType":"imports","source":3534,"target":1654},{"edgeType":"calls","source":1699,"target":388},{"edgeType":"calls","source":1185,"target":466},{"edgeType":"contains","source":3,"target":395},{"edgeType":"contains","source":4045,"target":4053},{"edgeType":"calls","source":4649,"target":902},{"edgeType":"calls","source":4527,"target":456},{"edgeType":"imports","source":1918,"target":2084},{"edgeType":"contains","source":213,"target":226},{"edgeType":"calls","source":3156,"target":675},{"edgeType":"contains","source":1062,"target":1390},{"edgeType":"calls","source":1699,"target":387},{"edgeType":"contains","source":3351,"target":3368},{"edgeType":"imports","source":32,"target":300},{"edgeType":"calls","source":546,"target":191},{"edgeType":"contains","source":4045,"target":4052},{"edgeType":"calls","source":2050,"target":1133},{"edgeType":"contains","source":4738,"target":4766},{"edgeType":"calls","source":1185,"target":465},{"edgeType":"calls","source":4649,"target":901},{"edgeType":"calls","source":4453,"target":1692},{"edgeType":"calls","source":784,"target":212},{"edgeType":"extends","source":1227,"target":482},{"edgeType":"calls","source":817,"target":249},{"edgeType":"contains","source":2255,"target":3517},{"edgeType":"calls","source":2375,"target":571},{"edgeType":"calls","source":2415,"target":388},{"edgeType":"contains","source":742,"target":743},{"edgeType":"calls","source":1701,"target":1385},{"edgeType":"calls","source":3873,"target":3814},{"edgeType":"imports","source":2276,"target":498},{"edgeType":"calls","source":1185,"target":468},{"edgeType":"calls","source":1890,"target":1868},{"edgeType":"contains","source":1864,"target":1897},{"edgeType":"calls","source":4599,"target":336},{"edgeType":"calls","source":4607,"target":88},{"edgeType":"calls","source":2886,"target":586},{"edgeType":"calls","source":2415,"target":389},{"edgeType":"contains","source":213,"target":229},{"edgeType":"calls","source":4649,"target":900},{"edgeType":"calls","source":4630,"target":1489},{"edgeType":"contains","source":213,"target":228},{"edgeType":"calls","source":817,"target":248},{"edgeType":"contains","source":3701,"target":2029},{"edgeType":"calls","source":2375,"target":572},{"edgeType":"contains","source":1062,"target":1392},{"edgeType":"calls","source":1350,"target":638},{"edgeType":"calls","source":1699,"target":389},{"edgeType":"calls","source":3924,"target":1177},{"edgeType":"calls","source":1427,"target":365},{"edgeType":"contains","source":4738,"target":4764},{"edgeType":"calls","source":1185,"target":467},{"edgeType":"calls","source":3873,"target":3815},{"edgeType":"calls","source":2460,"target":1109},{"edgeType":"calls","source":2375,"target":569},{"edgeType":"calls","source":4446,"target":1905},{"edgeType":"calls","source":1693,"target":570},{"edgeType":"calls","source":1699,"target":384},{"edgeType":"contains","source":742,"target":745},{"edgeType":"calls","source":2415,"target":386},{"edgeType":"calls","source":3873,"target":3812},{"edgeType":"calls","source":4148,"target":572},{"edgeType":"calls","source":2664,"target":1124},{"edgeType":"calls","source":1251,"target":530},{"edgeType":"calls","source":4292,"target":336},{"edgeType":"calls","source":2813,"target":2847},{"edgeType":"calls","source":3239,"target":211},{"edgeType":"calls","source":4899,"target":2661},{"edgeType":"calls","source":863,"target":931},{"edgeType":"contains","source":213,"target":231},{"edgeType":"calls","source":2925,"target":1489},{"edgeType":"calls","source":1693,"target":569},{"edgeType":"calls","source":1699,"target":383},{"edgeType":"calls","source":2375,"target":570},{"edgeType":"calls","source":3001,"target":191},{"edgeType":"calls","source":2415,"target":387},{"edgeType":"calls","source":4364,"target":1275},{"edgeType":"contains","source":4738,"target":4771},{"edgeType":"calls","source":1995,"target":720},{"edgeType":"contains","source":2951,"target":3089},{"edgeType":"calls","source":604,"target":503},{"edgeType":"calls","source":3260,"target":1675},{"edgeType":"calls","source":3239,"target":212},{"edgeType":"calls","source":2886,"target":585},{"edgeType":"calls","source":4664,"target":1489},{"edgeType":"calls","source":2914,"target":774},{"edgeType":"contains","source":6,"target":2419},{"edgeType":"calls","source":4843,"target":2282},{"edgeType":"contains","source":213,"target":230},{"edgeType":"calls","source":863,"target":930},{"edgeType":"calls","source":4697,"target":4694},{"edgeType":"calls","source":2415,"target":384},{"edgeType":"contains","source":2806,"target":3353},{"edgeType":"calls","source":2375,"target":567},{"edgeType":"calls","source":4364,"target":1274},{"edgeType":"contains","source":1062,"target":1397},{"edgeType":"calls","source":1693,"target":572},{"edgeType":"calls","source":1699,"target":386},{"edgeType":"contains","source":1104,"target":1152},{"edgeType":"calls","source":4148,"target":570},{"edgeType":"calls","source":1995,"target":723},{"edgeType":"calls","source":369,"target":392},{"edgeType":"contains","source":2029,"target":2071},{"edgeType":"contains","source":213,"target":233},{"edgeType":"calls","source":784,"target":211},{"edgeType":"contains","source":4045,"target":4055},{"edgeType":"calls","source":921,"target":191},{"edgeType":"contains","source":742,"target":746},{"edgeType":"calls","source":369,"target":390},{"edgeType":"calls","source":2375,"target":568},{"edgeType":"calls","source":2415,"target":385},{"edgeType":"calls","source":3561,"target":1856},{"edgeType":"contains","source":1062,"target":1396},{"edgeType":"calls","source":1693,"target":571},{"edgeType":"calls","source":1699,"target":385},{"edgeType":"calls","source":1995,"target":722},{"edgeType":"calls","source":4864,"target":572},{"edgeType":"calls","source":4731,"target":4695},{"edgeType":"calls","source":4148,"target":571},{"edgeType":"imports","source":1080,"target":574},{"edgeType":"calls","source":1251,"target":531},{"edgeType":"calls","source":3390,"target":814},{"edgeType":"contains","source":1700,"target":1701},{"edgeType":"calls","source":3289,"target":774},{"edgeType":"calls","source":4618,"target":1856},{"edgeType":"contains","source":213,"target":232},{"edgeType":"calls","source":863,"target":932},{"edgeType":"calls","source":4498,"target":388},{"edgeType":"calls","source":4464,"target":385},{"edgeType":"calls","source":1528,"target":495},{"edgeType":"imports","source":32,"target":76},{"edgeType":"imports","source":3643,"target":183},{"edgeType":"calls","source":2037,"target":571},{"edgeType":"calls","source":1265,"target":191},{"edgeType":"calls","source":1261,"target":315},{"edgeType":"calls","source":1261,"target":1372},{"edgeType":"calls","source":2548,"target":587},{"edgeType":"calls","source":1150,"target":585},{"edgeType":"contains","source":1535,"target":2560},{"edgeType":"calls","source":4765,"target":568},{"edgeType":"calls","source":4805,"target":385},{"edgeType":"contains","source":1731,"target":1769},{"edgeType":"calls","source":4628,"target":585},{"edgeType":"calls","source":4587,"target":1856},{"edgeType":"calls","source":404,"target":455},{"edgeType":"contains","source":2204,"target":848},{"edgeType":"calls","source":4498,"target":387},{"edgeType":"calls","source":4464,"target":384},{"edgeType":"calls","source":1528,"target":494},{"edgeType":"calls","source":2037,"target":570},{"edgeType":"calls","source":671,"target":635},{"edgeType":"calls","source":1264,"target":1278},{"edgeType":"calls","source":1261,"target":1371},{"edgeType":"calls","source":1528,"target":493},{"edgeType":"calls","source":1229,"target":249},{"edgeType":"calls","source":4628,"target":586},{"edgeType":"calls","source":4805,"target":384},{"edgeType":"calls","source":4765,"target":567},{"edgeType":"calls","source":4841,"target":325},{"edgeType":"calls","source":2784,"target":2785},{"edgeType":"contains","source":1731,"target":1770},{"edgeType":"contains","source":1722,"target":2049},{"edgeType":"calls","source":1677,"target":106},{"edgeType":"calls","source":4464,"target":383},{"edgeType":"calls","source":4532,"target":389},{"edgeType":"calls","source":4498,"target":386},{"edgeType":"calls","source":4449,"target":1905},{"edgeType":"calls","source":1877,"target":248},{"edgeType":"calls","source":4095,"target":194},{"edgeType":"calls","source":4295,"target":336},{"edgeType":"calls","source":2667,"target":1124},{"edgeType":"calls","source":1261,"target":317},{"edgeType":"calls","source":4765,"target":566},{"edgeType":"calls","source":4805,"target":383},{"edgeType":"calls","source":4833,"target":572},{"edgeType":"calls","source":4498,"target":385},{"edgeType":"calls","source":4464,"target":382},{"edgeType":"calls","source":4532,"target":388},{"edgeType":"contains","source":4738,"target":4740},{"edgeType":"contains","source":3094,"target":1796},{"edgeType":"calls","source":1528,"target":496},{"edgeType":"calls","source":2037,"target":572},{"edgeType":"calls","source":4846,"target":2282},{"edgeType":"calls","source":1261,"target":316},{"edgeType":"calls","source":1150,"target":586},{"edgeType":"contains","source":2255,"target":3493},{"edgeType":"calls","source":4661,"target":1675},{"edgeType":"calls","source":4805,"target":382},{"edgeType":"calls","source":4833,"target":571},{"edgeType":"calls","source":339,"target":353},{"edgeType":"calls","source":4532,"target":387},{"edgeType":"calls","source":4498,"target":384},{"edgeType":"calls","source":2653,"target":498},{"edgeType":"calls","source":1629,"target":1588},{"edgeType":"calls","source":549,"target":185},{"edgeType":"calls","source":3690,"target":2177},{"edgeType":"calls","source":508,"target":399},{"edgeType":"calls","source":3980,"target":586},{"edgeType":"calls","source":2037,"target":567},{"edgeType":"contains","source":2511,"target":2962},{"edgeType":"contains","source":4407,"target":4437},{"edgeType":"contains","source":1731,"target":1773},{"edgeType":"calls","source":1528,"target":490},{"edgeType":"calls","source":2734,"target":102},{"edgeType":"calls","source":1264,"target":1275},{"edgeType":"calls","source":954,"target":315},{"edgeType":"calls","source":3403,"target":503},{"edgeType":"calls","source":4833,"target":570},{"edgeType":"contains","source":4738,"target":4746},{"edgeType":"calls","source":4532,"target":386},{"edgeType":"calls","source":1871,"target":427},{"edgeType":"calls","source":4536,"target":4490},{"edgeType":"contains","source":2511,"target":2963},{"edgeType":"calls","source":4498,"target":383},{"edgeType":"calls","source":2037,"target":566},{"edgeType":"calls","source":208,"target":185},{"edgeType":"calls","source":4193,"target":3497},{"edgeType":"contains","source":4407,"target":4436},{"edgeType":"calls","source":1528,"target":489},{"edgeType":"contains","source":1731,"target":1774},{"edgeType":"calls","source":847,"target":460},{"edgeType":"calls","source":1264,"target":1274},{"edgeType":"calls","source":4833,"target":569},{"edgeType":"calls","source":969,"target":906},{"edgeType":"contains","source":1535,"target":2565},{"edgeType":"contains","source":2029,"target":2046},{"edgeType":"calls","source":2734,"target":99},{"edgeType":"calls","source":1897,"target":1738},{"edgeType":"contains","source":2975,"target":3374},{"edgeType":"calls","source":4532,"target":385},{"edgeType":"calls","source":4498,"target":382},{"edgeType":"calls","source":1845,"target":179},{"edgeType":"calls","source":1958,"target":1961},{"edgeType":"contains","source":2511,"target":2960},{"edgeType":"calls","source":1981,"target":191},{"edgeType":"calls","source":2037,"target":569},{"edgeType":"contains","source":1731,"target":1771},{"edgeType":"calls","source":1498,"target":365},{"edgeType":"calls","source":1528,"target":492},{"edgeType":"calls","source":2748,"target":723},{"edgeType":"calls","source":2734,"target":100},{"edgeType":"calls","source":1229,"target":248},{"edgeType":"calls","source":4833,"target":568},{"edgeType":"calls","source":1264,"target":1277},{"edgeType":"calls","source":954,"target":317},{"edgeType":"calls","source":3369,"target":498},{"edgeType":"calls","source":339,"target":354},{"edgeType":"calls","source":3980,"target":585},{"edgeType":"calls","source":4811,"target":191},{"edgeType":"calls","source":4833,"target":566},{"edgeType":"imports","source":1934,"target":302},{"edgeType":"calls","source":4532,"target":384},{"edgeType":"calls","source":2037,"target":568},{"edgeType":"calls","source":4148,"target":1719},{"edgeType":"calls","source":2238,"target":1735},{"edgeType":"calls","source":4137,"target":1003},{"edgeType":"contains","source":1731,"target":1772},{"edgeType":"calls","source":1528,"target":491},{"edgeType":"contains","source":2975,"target":3375},{"edgeType":"calls","source":2734,"target":101},{"edgeType":"calls","source":3403,"target":502},{"edgeType":"calls","source":4833,"target":567},{"edgeType":"calls","source":1264,"target":1276},{"edgeType":"calls","source":954,"target":316},{"edgeType":"contains","source":3573,"target":3863},{"edgeType":"calls","source":2656,"target":401},{"edgeType":"contains","source":1864,"target":1882},{"edgeType":"calls","source":1971,"target":495},{"edgeType":"calls","source":1764,"target":570},{"edgeType":"calls","source":642,"target":469},{"edgeType":"calls","source":2748,"target":720},{"edgeType":"calls","source":4532,"target":383},{"edgeType":"calls","source":4497,"target":411},{"edgeType":"calls","source":4536,"target":259},{"edgeType":"calls","source":1528,"target":486},{"edgeType":"calls","source":2238,"target":675},{"edgeType":"calls","source":4888,"target":2032},{"edgeType":"calls","source":4768,"target":4695},{"edgeType":"calls","source":2861,"target":389},{"edgeType":"calls","source":1764,"target":569},{"edgeType":"calls","source":4766,"target":527},{"edgeType":"calls","source":1231,"target":179},{"edgeType":"calls","source":2656,"target":402},{"edgeType":"contains","source":1864,"target":1883},{"edgeType":"calls","source":1971,"target":494},{"edgeType":"calls","source":4532,"target":382},{"edgeType":"calls","source":2731,"target":191},{"edgeType":"calls","source":642,"target":468},{"edgeType":"calls","source":2734,"target":98},{"edgeType":"extends","source":3679,"target":3535},{"edgeType":"contains","source":4404,"target":4534},{"edgeType":"contains","source":1062,"target":1373},{"edgeType":"calls","source":2748,"target":722},{"edgeType":"calls","source":1764,"target":568},{"edgeType":"contains","source":3351,"target":3352},{"edgeType":"calls","source":1528,"target":485},{"edgeType":"calls","source":3147,"target":3148},{"edgeType":"calls","source":4845,"target":191},{"edgeType":"calls","source":1871,"target":426},{"edgeType":"calls","source":1764,"target":572},{"edgeType":"imports","source":4234,"target":1939},{"edgeType":"calls","source":2748,"target":718},{"edgeType":"calls","source":2861,"target":386},{"edgeType":"calls","source":2484,"target":446},{"edgeType":"contains","source":4404,"target":4533},{"edgeType":"calls","source":1528,"target":488},{"edgeType":"contains","source":799,"target":1073},{"edgeType":"contains","source":1731,"target":1775},{"edgeType":"calls","source":2861,"target":387},{"edgeType":"contains","source":1062,"target":1376},{"edgeType":"calls","source":1308,"target":966},{"edgeType":"calls","source":4769,"target":1489},{"edgeType":"calls","source":1764,"target":571},{"edgeType":"calls","source":1971,"target":496},{"edgeType":"calls","source":1871,"target":425},{"edgeType":"calls","source":642,"target":470},{"edgeType":"calls","source":2748,"target":719},{"edgeType":"calls","source":4581,"target":975},{"edgeType":"contains","source":4407,"target":4439},{"edgeType":"calls","source":4594,"target":572},{"edgeType":"calls","source":4348,"target":1856},{"edgeType":"calls","source":1528,"target":487},{"edgeType":"calls","source":2861,"target":388},{"edgeType":"contains","source":1062,"target":1375},{"edgeType":"calls","source":3204,"target":325},{"edgeType":"contains","source":1864,"target":1886},{"edgeType":"calls","source":1971,"target":491},{"edgeType":"contains","source":1204,"target":1205},{"edgeType":"contains","source":2483,"target":667},{"edgeType":"contains","source":621,"target":1308},{"edgeType":"calls","source":2861,"target":384},{"edgeType":"contains","source":4407,"target":4446},{"edgeType":"calls","source":4594,"target":571},{"edgeType":"calls","source":2447,"target":534},{"edgeType":"calls","source":404,"target":444},{"edgeType":"calls","source":2755,"target":499},{"edgeType":"calls","source":2748,"target":716},{"edgeType":"calls","source":642,"target":465},{"edgeType":"calls","source":4700,"target":456},{"edgeType":"contains","source":213,"target":215},{"edgeType":"imports","source":32,"target":81},{"edgeType":"contains","source":4234,"target":4524},{"edgeType":"calls","source":1872,"target":388},{"edgeType":"calls","source":1629,"target":1579},{"edgeType":"calls","source":2666,"target":88},{"edgeType":"contains","source":1864,"target":1887},{"edgeType":"calls","source":4126,"target":1338},{"edgeType":"calls","source":404,"target":443},{"edgeType":"calls","source":2484,"target":445},{"edgeType":"calls","source":4594,"target":570},{"edgeType":"calls","source":2861,"target":385},{"edgeType":"calls","source":849,"target":389},{"edgeType":"calls","source":2748,"target":717},{"edgeType":"contains","source":16,"target":2092},{"edgeType":"contains","source":213,"target":214},{"edgeType":"imports","source":32,"target":82},{"edgeType":"calls","source":4396,"target":366},{"edgeType":"contains","source":1062,"target":1377},{"edgeType":"calls","source":1872,"target":387},{"edgeType":"calls","source":1264,"target":212},{"edgeType":"calls","source":1971,"target":493},{"edgeType":"imports","source":4234,"target":886},{"edgeType":"calls","source":4594,"target":569},{"edgeType":"contains","source":213,"target":217},{"edgeType":"calls","source":642,"target":467},{"edgeType":"calls","source":2748,"target":714},{"edgeType":"calls","source":2861,"target":382},{"edgeType":"calls","source":2792,"target":407},{"edgeType":"contains","source":799,"target":1077},{"edgeType":"imports","source":32,"target":79},{"edgeType":"calls","source":4538,"target":191},{"edgeType":"calls","source":1764,"target":567},{"edgeType":"calls","source":3949,"target":479},{"edgeType":"calls","source":3524,"target":970},{"edgeType":"contains","source":3351,"target":3355},{"edgeType":"calls","source":1264,"target":211},{"edgeType":"calls","source":1971,"target":492},{"edgeType":"contains","source":4738,"target":4752},{"edgeType":"calls","source":2861,"target":383},{"edgeType":"contains","source":2483,"target":666},{"edgeType":"calls","source":4594,"target":568},{"edgeType":"contains","source":213,"target":216},{"edgeType":"calls","source":4811,"target":183},{"edgeType":"imports","source":4001,"target":1768},{"edgeType":"calls","source":642,"target":466},{"edgeType":"calls","source":2748,"target":715},{"edgeType":"contains","source":799,"target":1076},{"edgeType":"imports","source":32,"target":80},{"edgeType":"calls","source":802,"target":792},{"edgeType":"calls","source":2395,"target":1088},{"edgeType":"calls","source":1764,"target":566},{"edgeType":"calls","source":3458,"target":1960},{"edgeType":"calls","source":1872,"target":389},{"edgeType":"calls","source":1298,"target":1299},{"edgeType":"contains","source":3152,"target":3154},{"edgeType":"contains","source":1104,"target":1105},{"edgeType":"calls","source":1958,"target":1980},{"edgeType":"contains","source":1090,"target":482},{"edgeType":"contains","source":1962,"target":1990},{"edgeType":"calls","source":776,"target":568},{"edgeType":"contains","source":210,"target":279},{"edgeType":"contains","source":3573,"target":3845},{"edgeType":"calls","source":4715,"target":1077},{"edgeType":"contains","source":1731,"target":1752},{"edgeType":"contains","source":32,"target":511},{"edgeType":"calls","source":2793,"target":407},{"edgeType":"contains","source":2126,"target":2192},{"edgeType":"calls","source":2415,"target":498},{"edgeType":"calls","source":1973,"target":457},{"edgeType":"contains","source":3002,"target":404},{"edgeType":"calls","source":1839,"target":383},{"edgeType":"calls","source":1958,"target":1979},{"edgeType":"calls","source":3950,"target":479},{"edgeType":"imports","source":3571,"target":285},{"edgeType":"calls","source":776,"target":567},{"edgeType":"calls","source":4715,"target":1076},{"edgeType":"calls","source":4740,"target":301},{"edgeType":"contains","source":210,"target":278},{"edgeType":"contains","source":6,"target":2373},{"edgeType":"contains","source":2126,"target":2193},{"edgeType":"contains","source":2127,"target":2162},{"edgeType":"contains","source":4209,"target":4212},{"edgeType":"calls","source":1735,"target":435},{"edgeType":"calls","source":1715,"target":1055},{"edgeType":"calls","source":2453,"target":378},{"edgeType":"calls","source":2178,"target":447},{"edgeType":"calls","source":1524,"target":634},{"edgeType":"calls","source":1871,"target":447},{"edgeType":"calls","source":1839,"target":382},{"edgeType":"calls","source":1973,"target":456},{"edgeType":"imports","source":2259,"target":786},{"edgeType":"contains","source":1104,"target":1107},{"edgeType":"calls","source":546,"target":301},{"edgeType":"calls","source":1972,"target":491},{"edgeType":"contains","source":210,"target":281},{"edgeType":"calls","source":644,"target":434},{"edgeType":"contains","source":2126,"target":2189},{"edgeType":"calls","source":776,"target":570},{"edgeType":"contains","source":2126,"target":2190},{"edgeType":"contains","source":4176,"target":4177},{"edgeType":"contains","source":2806,"target":3307},{"edgeType":"contains","source":3573,"target":3843},{"edgeType":"calls","source":1839,"target":385},{"edgeType":"contains","source":1062,"target":1351},{"edgeType":"contains","source":3152,"target":3153},{"edgeType":"contains","source":1104,"target":1106},{"edgeType":"calls","source":776,"target":569},{"edgeType":"contains","source":210,"target":280},{"edgeType":"calls","source":4557,"target":687},{"edgeType":"contains","source":2127,"target":2160},{"edgeType":"contains","source":2126,"target":2191},{"edgeType":"contains","source":3084,"target":3146},{"edgeType":"calls","source":1839,"target":384},{"edgeType":"calls","source":1524,"target":631},{"edgeType":"contains","source":210,"target":283},{"edgeType":"calls","source":3307,"target":325},{"edgeType":"calls","source":1185,"target":570},{"edgeType":"calls","source":1775,"target":249},{"edgeType":"calls","source":406,"target":407},{"edgeType":"calls","source":4491,"target":1675},{"edgeType":"contains","source":28,"target":3811},{"edgeType":"calls","source":4584,"target":906},{"edgeType":"calls","source":2242,"target":572},{"edgeType":"calls","source":1517,"target":847},{"edgeType":"contains","source":1104,"target":1108},{"edgeType":"contains","source":210,"target":282},{"edgeType":"calls","source":3227,"target":692},{"edgeType":"calls","source":1185,"target":569},{"edgeType":"contains","source":3573,"target":3848},{"edgeType":"calls","source":2449,"target":498},{"edgeType":"calls","source":1775,"target":248},{"edgeType":"calls","source":1728,"target":648},{"edgeType":"calls","source":2544,"target":724},{"edgeType":"contains","source":2483,"target":643},{"edgeType":"calls","source":1367,"target":1272},{"edgeType":"calls","source":1336,"target":1176},{"edgeType":"calls","source":3605,"target":1655},{"edgeType":"calls","source":1524,"target":633},{"edgeType":"calls","source":1185,"target":572},{"edgeType":"calls","source":3348,"target":1166},{"edgeType":"calls","source":776,"target":566},{"edgeType":"contains","source":3573,"target":3847},{"edgeType":"calls","source":1735,"target":434},{"edgeType":"calls","source":2242,"target":570},{"edgeType":"calls","source":4230,"target":249},{"edgeType":"imports","source":396,"target":397},{"edgeType":"contains","source":3084,"target":3151},{"edgeType":"calls","source":2868,"target":191},{"edgeType":"contains","source":210,"target":284},{"edgeType":"calls","source":4876,"target":307},{"edgeType":"calls","source":1185,"target":571},{"edgeType":"calls","source":3227,"target":690},{"edgeType":"contains","source":1636,"target":3643},{"edgeType":"calls","source":4525,"target":1675},{"edgeType":"calls","source":3839,"target":744},{"edgeType":"contains","source":2126,"target":2195},{"edgeType":"calls","source":505,"target":510},{"edgeType":"calls","source":4408,"target":4245},{"edgeType":"calls","source":4023,"target":325},{"edgeType":"calls","source":2242,"target":571},{"edgeType":"calls","source":4294,"target":3551},{"edgeType":"calls","source":2178,"target":441},{"edgeType":"calls","source":4306,"target":1063},{"edgeType":"contains","source":2292,"target":2339},{"edgeType":"calls","source":2242,"target":567},{"edgeType":"calls","source":2178,"target":437},{"edgeType":"contains","source":3811,"target":3874},{"edgeType":"calls","source":2813,"target":2950},{"edgeType":"calls","source":4876,"target":306},{"edgeType":"calls","source":989,"target":299},{"edgeType":"imports","source":3643,"target":1215},{"edgeType":"contains","source":3084,"target":3156},{"edgeType":"calls","source":3237,"target":376},{"edgeType":"calls","source":1809,"target":248},{"edgeType":"contains","source":3811,"target":3875},{"edgeType":"calls","source":4294,"target":3550},{"edgeType":"calls","source":411,"target":248},{"edgeType":"calls","source":2242,"target":568},{"edgeType":"calls","source":2178,"target":438},{"edgeType":"contains","source":210,"target":286},{"edgeType":"contains","source":3811,"target":3873},{"edgeType":"calls","source":1336,"target":1169},{"edgeType":"contains","source":3084,"target":3157},{"edgeType":"calls","source":1735,"target":427},{"edgeType":"calls","source":1737,"target":365},{"edgeType":"calls","source":1234,"target":102},{"edgeType":"imports","source":1749,"target":1807},{"edgeType":"calls","source":4650,"target":969},{"edgeType":"calls","source":4876,"target":305},{"edgeType":"contains","source":2483,"target":647},{"edgeType":"calls","source":4230,"target":248},{"edgeType":"calls","source":2242,"target":569},{"edgeType":"contains","source":3811,"target":3872},{"edgeType":"calls","source":2866,"target":248},{"edgeType":"imports","source":2259,"target":794},{"edgeType":"calls","source":1185,"target":568},{"edgeType":"calls","source":1234,"target":106},{"edgeType":"calls","source":4652,"target":906},{"edgeType":"calls","source":3295,"target":690},{"edgeType":"imports","source":4001,"target":1747},{"edgeType":"imports","source":1090,"target":1093},{"edgeType":"calls","source":4064,"target":106},{"edgeType":"contains","source":2511,"target":2947},{"edgeType":"contains","source":16,"target":2075},{"edgeType":"calls","source":2436,"target":894},{"edgeType":"calls","source":2242,"target":566},{"edgeType":"contains","source":2292,"target":2338},{"edgeType":"calls","source":2178,"target":436},{"edgeType":"calls","source":2866,"target":249},{"edgeType":"contains","source":1731,"target":1759},{"edgeType":"contains","source":3573,"target":3850},{"edgeType":"calls","source":1185,"target":567},{"edgeType":"contains","source":1483,"target":2048},{"edgeType":"calls","source":411,"target":249},{"edgeType":"calls","source":1185,"target":566},{"edgeType":"imports","source":4001,"target":1748},{"edgeType":"calls","source":1809,"target":249},{"edgeType":"calls","source":1871,"target":441},{"edgeType":"imports","source":1090,"target":1094},{"edgeType":"contains","source":1864,"target":1865},{"edgeType":"calls","source":3927,"target":1183},{"edgeType":"calls","source":4874,"target":365},{"edgeType":"calls","source":4224,"target":1489},{"edgeType":"calls","source":4501,"target":301},{"edgeType":"contains","source":3573,"target":3857},{"edgeType":"calls","source":4464,"target":389},{"edgeType":"contains","source":4209,"target":4225},{"edgeType":"imports","source":3643,"target":1219},{"edgeType":"calls","source":3528,"target":865},{"edgeType":"contains","source":4738,"target":4739},{"edgeType":"calls","source":4765,"target":572},{"edgeType":"calls","source":4805,"target":389},{"edgeType":"calls","source":4027,"target":194},{"edgeType":"calls","source":1234,"target":99},{"edgeType":"calls","source":4519,"target":1856},{"edgeType":"imports","source":32,"target":65},{"edgeType":"contains","source":2806,"target":3323},{"edgeType":"calls","source":4464,"target":388},{"edgeType":"contains","source":3573,"target":3856},{"edgeType":"calls","source":3839,"target":738},{"edgeType":"calls","source":1877,"target":249},{"edgeType":"imports","source":1090,"target":35},{"edgeType":"calls","source":4747,"target":1129},{"edgeType":"calls","source":4805,"target":388},{"edgeType":"calls","source":4765,"target":571},{"edgeType":"calls","source":1231,"target":191},{"edgeType":"calls","source":1234,"target":98},{"edgeType":"contains","source":1731,"target":1766},{"edgeType":"calls","source":2693,"target":325},{"edgeType":"calls","source":4568,"target":336},{"edgeType":"calls","source":4593,"target":1675},{"edgeType":"calls","source":4464,"target":387},{"edgeType":"contains","source":3573,"target":3855},{"edgeType":"contains","source":1731,"target":1762},{"edgeType":"calls","source":1735,"target":426},{"edgeType":"calls","source":1728,"target":643},{"edgeType":"contains","source":3084,"target":3158},{"edgeType":"calls","source":1234,"target":101},{"edgeType":"calls","source":4805,"target":387},{"edgeType":"contains","source":1160,"target":1497},{"edgeType":"contains","source":1864,"target":1868},{"edgeType":"calls","source":1290,"target":479},{"edgeType":"calls","source":3229,"target":1675},{"edgeType":"calls","source":4607,"target":183},{"edgeType":"contains","source":3811,"target":3877},{"edgeType":"calls","source":4765,"target":570},{"edgeType":"calls","source":4498,"target":389},{"edgeType":"calls","source":4464,"target":386},{"edgeType":"imports","source":32,"target":63},{"edgeType":"calls","source":4530,"target":454},{"edgeType":"calls","source":3155,"target":1856},{"edgeType":"calls","source":1735,"target":425},{"edgeType":"calls","source":1629,"target":1597},{"edgeType":"calls","source":1234,"target":100},{"edgeType":"contains","source":1864,"target":1869},{"edgeType":"calls","source":3329,"target":690},{"edgeType":"contains","source":3811,"target":3876},{"edgeType":"calls","source":2436,"target":891},{"edgeType":"calls","source":4567,"target":365},{"edgeType":"calls","source":4805,"target":386},{"edgeType":"calls","source":4765,"target":569},{"edgeType":"contains","source":3,"target":2481},{"edgeType":"calls","source":3817,"target":325},{"edgeType":"contains","source":2127,"target":2144},{"edgeType":"calls","source":1695,"target":570},{"edgeType":"calls","source":1735,"target":387},{"edgeType":"contains","source":3573,"target":3828},{"edgeType":"contains","source":2259,"target":2280},{"edgeType":"calls","source":2321,"target":191},{"edgeType":"calls","source":2377,"target":569},{"edgeType":"calls","source":4448,"target":1905},{"edgeType":"contains","source":3094,"target":1764},{"edgeType":"calls","source":3875,"target":3812},{"edgeType":"calls","source":2666,"target":1124},{"edgeType":"contains","source":1962,"target":1974},{"edgeType":"calls","source":4745,"target":98},{"edgeType":"calls","source":4742,"target":191},{"edgeType":"contains","source":210,"target":262},{"edgeType":"contains","source":3573,"target":3829},{"edgeType":"calls","source":4832,"target":572},{"edgeType":"contains","source":2127,"target":2145},{"edgeType":"calls","source":1735,"target":386},{"edgeType":"calls","source":1695,"target":569},{"edgeType":"contains","source":3573,"target":3827},{"edgeType":"calls","source":2377,"target":570},{"edgeType":"calls","source":4449,"target":1873},{"edgeType":"contains","source":1065,"target":1239},{"edgeType":"calls","source":4845,"target":2282},{"edgeType":"contains","source":1204,"target":1158},{"edgeType":"imports","source":97,"target":210},{"edgeType":"calls","source":1235,"target":30},{"edgeType":"imports","source":3162,"target":326},{"edgeType":"contains","source":1962,"target":1975},{"edgeType":"calls","source":1298,"target":191},{"edgeType":"calls","source":4660,"target":1675},{"edgeType":"calls","source":4666,"target":1489},{"edgeType":"contains","source":210,"target":261},{"edgeType":"calls","source":4832,"target":571},{"edgeType":"calls","source":4699,"target":4694},{"edgeType":"imports","source":3050,"target":627},{"edgeType":"contains","source":28,"target":621},{"edgeType":"calls","source":1695,"target":572},{"edgeType":"calls","source":2453,"target":325},{"edgeType":"contains","source":3573,"target":3826},{"edgeType":"calls","source":2377,"target":567},{"edgeType":"calls","source":4634,"target":365},{"edgeType":"calls","source":4204,"target":4182},{"edgeType":"imports","source":2201,"target":519},{"edgeType":"calls","source":1735,"target":389},{"edgeType":"imports","source":97,"target":206},{"edgeType":"calls","source":4098,"target":68},{"edgeType":"calls","source":2713,"target":722},{"edgeType":"contains","source":2511,"target":2922},{"edgeType":"contains","source":210,"target":264},{"edgeType":"calls","source":1128,"target":179},{"edgeType":"calls","source":4832,"target":570},{"edgeType":"calls","source":670,"target":636},{"edgeType":"contains","source":2127,"target":2142},{"edgeType":"calls","source":2953,"target":2795},{"edgeType":"contains","source":1962,"target":1972},{"edgeType":"calls","source":1695,"target":571},{"edgeType":"contains","source":2127,"target":2143},{"edgeType":"calls","source":1735,"target":388},{"edgeType":"calls","source":2377,"target":568},{"edgeType":"contains","source":3094,"target":1763},{"edgeType":"contains","source":1090,"target":1523},{"edgeType":"contains","source":1080,"target":1833},{"edgeType":"calls","source":2713,"target":723},{"edgeType":"contains","source":210,"target":263},{"edgeType":"contains","source":2292,"target":2313},{"edgeType":"calls","source":4832,"target":569},{"edgeType":"calls","source":2974,"target":1088},{"edgeType":"contains","source":1962,"target":1973},{"edgeType":"imports","source":1257,"target":184},{"edgeType":"calls","source":3941,"target":705},{"edgeType":"contains","source":2126,"target":1122},{"edgeType":"calls","source":4766,"target":499},{"edgeType":"calls","source":1735,"target":383},{"edgeType":"calls","source":1695,"target":566},{"edgeType":"contains","source":2127,"target":2148},{"edgeType":"calls","source":4708,"target":183},{"edgeType":"calls","source":4353,"target":1675},{"edgeType":"calls","source":3507,"target":417},{"edgeType":"calls","source":4873,"target":354},{"edgeType":"calls","source":2713,"target":720},{"edgeType":"contains","source":210,"target":266},{"edgeType":"calls","source":670,"target":630},{"edgeType":"calls","source":4832,"target":568},{"edgeType":"calls","source":1166,"target":1109},{"edgeType":"imports","source":1257,"target":185},{"edgeType":"calls","source":1735,"target":382},{"edgeType":"contains","source":2127,"target":2149},{"edgeType":"calls","source":1970,"target":496},{"edgeType":"calls","source":2377,"target":566},{"edgeType":"imports","source":2208,"target":299},{"edgeType":"calls","source":674,"target":505},{"edgeType":"calls","source":849,"target":365},{"edgeType":"calls","source":4873,"target":353},{"edgeType":"contains","source":1204,"target":1162},{"edgeType":"contains","source":210,"target":265},{"edgeType":"calls","source":4798,"target":564},{"edgeType":"calls","source":3368,"target":499},{"edgeType":"calls","source":4832,"target":567},{"edgeType":"contains","source":2126,"target":1120},{"edgeType":"calls","source":1735,"target":385},{"edgeType":"contains","source":2127,"target":2146},{"edgeType":"calls","source":1695,"target":568},{"edgeType":"calls","source":3808,"target":1655},{"edgeType":"calls","source":1951,"target":1088},{"edgeType":"calls","source":2713,"target":717},{"edgeType":"imports","source":34,"target":41},{"edgeType":"imports","source":2259,"target":831},{"edgeType":"calls","source":4293,"target":3533},{"edgeType":"calls","source":2233,"target":1856},{"edgeType":"calls","source":4293,"target":361},{"edgeType":"contains","source":210,"target":268},{"edgeType":"calls","source":4887,"target":2032},{"edgeType":"calls","source":2748,"target":690},{"edgeType":"calls","source":4832,"target":566},{"edgeType":"contains","source":1962,"target":1976},{"edgeType":"contains","source":4001,"target":76},{"edgeType":"contains","source":2126,"target":1121},{"edgeType":"calls","source":4742,"target":183},{"edgeType":"calls","source":1695,"target":567},{"edgeType":"calls","source":1872,"target":365},{"edgeType":"calls","source":1735,"target":384},{"edgeType":"contains","source":2127,"target":2147},{"edgeType":"calls","source":2713,"target":718},{"edgeType":"contains","source":2806,"target":3296},{"edgeType":"calls","source":4293,"target":3532},{"edgeType":"calls","source":4293,"target":362},{"edgeType":"calls","source":774,"target":578},{"edgeType":"contains","source":210,"target":267},{"edgeType":"calls","source":2713,"target":719},{"edgeType":"contains","source":3573,"target":3830},{"edgeType":"calls","source":4844,"target":191},{"edgeType":"contains","source":46,"target":69},{"edgeType":"contains","source":4001,"target":82},{"edgeType":"calls","source":1970,"target":493},{"edgeType":"contains","source":6,"target":2366},{"edgeType":"contains","source":2127,"target":2152},{"edgeType":"calls","source":2713,"target":715},{"edgeType":"imports","source":1257,"target":196},{"edgeType":"calls","source":2347,"target":434},{"edgeType":"contains","source":210,"target":270},{"edgeType":"calls","source":2178,"target":388},{"edgeType":"calls","source":889,"target":179},{"edgeType":"calls","source":1693,"target":1680},{"edgeType":"imports","source":4079,"target":434},{"edgeType":"calls","source":1263,"target":1268},{"edgeType":"calls","source":4762,"target":1675},{"edgeType":"calls","source":4768,"target":1489},{"edgeType":"calls","source":1970,"target":492},{"edgeType":"contains","source":4001,"target":81},{"edgeType":"contains","source":2127,"target":2153},{"edgeType":"calls","source":2756,"target":1497},{"edgeType":"calls","source":2713,"target":716},{"edgeType":"calls","source":789,"target":106},{"edgeType":"calls","source":774,"target":571},{"edgeType":"calls","source":2347,"target":435},{"edgeType":"calls","source":4580,"target":975},{"edgeType":"contains","source":4407,"target":4408},{"edgeType":"calls","source":4347,"target":1856},{"edgeType":"calls","source":2178,"target":389},{"edgeType":"calls","source":774,"target":572},{"edgeType":"contains","source":210,"target":269},{"edgeType":"calls","source":1498,"target":325},{"edgeType":"calls","source":3290,"target":1856},{"edgeType":"imports","source":4079,"target":435},{"edgeType":"contains","source":621,"target":1273},{"edgeType":"contains","source":2127,"target":2150},{"edgeType":"calls","source":3237,"target":325},{"edgeType":"calls","source":1970,"target":495},{"edgeType":"contains","source":46,"target":71},{"edgeType":"calls","source":4293,"target":357},{"edgeType":"calls","source":2713,"target":713},{"edgeType":"contains","source":210,"target":272},{"edgeType":"calls","source":2178,"target":386},{"edgeType":"contains","source":3002,"target":394},{"edgeType":"contains","source":4001,"target":80},{"edgeType":"calls","source":2665,"target":88},{"edgeType":"contains","source":637,"target":776},{"edgeType":"calls","source":1970,"target":494},{"edgeType":"contains","source":46,"target":70},{"edgeType":"contains","source":2127,"target":2151},{"edgeType":"calls","source":4293,"target":358},{"edgeType":"calls","source":2713,"target":714},{"edgeType":"calls","source":4869,"target":470},{"edgeType":"calls","source":4878,"target":191},{"edgeType":"contains","source":2292,"target":2321},{"edgeType":"contains","source":210,"target":271},{"edgeType":"calls","source":2281,"target":365},{"edgeType":"calls","source":2178,"target":387},{"edgeType":"calls","source":755,"target":106},{"edgeType":"calls","source":2980,"target":894},{"edgeType":"contains","source":4001,"target":79},{"edgeType":"contains","source":1204,"target":1168},{"edgeType":"extends","source":4402,"target":2301},{"edgeType":"calls","source":1328,"target":307},{"edgeType":"calls","source":4293,"target":355},{"edgeType":"contains","source":46,"target":73},{"edgeType":"calls","source":2436,"target":1899},{"edgeType":"contains","source":6,"target":2370},{"edgeType":"calls","source":4869,"target":469},{"edgeType":"contains","source":210,"target":275},{"edgeType":"calls","source":4667,"target":389},{"edgeType":"calls","source":774,"target":568},{"edgeType":"calls","source":4713,"target":1077},{"edgeType":"contains","source":3573,"target":3841},{"edgeType":"calls","source":2980,"target":891},{"edgeType":"contains","source":770,"target":884},{"edgeType":"calls","source":107,"target":105},{"edgeType":"calls","source":2178,"target":384},{"edgeType":"calls","source":2175,"target":477},{"edgeType":"calls","source":3948,"target":479},{"edgeType":"calls","source":3945,"target":572},{"edgeType":"imports","source":2923,"target":1398},{"edgeType":"calls","source":3889,"target":194},{"edgeType":"contains","source":2975,"target":3351},{"edgeType":"calls","source":1775,"target":191},{"edgeType":"calls","source":1971,"target":457},{"edgeType":"calls","source":1290,"target":427},{"edgeType":"calls","source":1328,"target":306},{"edgeType":"calls","source":774,"target":567},{"edgeType":"calls","source":4667,"target":388},{"edgeType":"calls","source":4293,"target":356},{"edgeType":"contains","source":6,"target":2369},{"edgeType":"contains","source":4404,"target":4505},{"edgeType":"contains","source":46,"target":72},{"edgeType":"contains","source":2126,"target":2188},{"edgeType":"calls","source":2798,"target":191},{"edgeType":"calls","source":2713,"target":712},{"edgeType":"calls","source":4869,"target":468},{"edgeType":"contains","source":210,"target":274},{"edgeType":"contains","source":210,"target":273},{"edgeType":"calls","source":3734,"target":772},{"edgeType":"calls","source":2983,"target":1856},{"edgeType":"calls","source":2178,"target":385},{"edgeType":"calls","source":2175,"target":478},{"edgeType":"calls","source":3457,"target":1960},{"edgeType":"calls","source":1971,"target":456},{"edgeType":"calls","source":1880,"target":106},{"edgeType":"calls","source":1970,"target":491},{"edgeType":"contains","source":2511,"target":2935},{"edgeType":"calls","source":2922,"target":572},{"edgeType":"calls","source":4667,"target":387},{"edgeType":"contains","source":2127,"target":2154},{"edgeType":"contains","source":46,"target":75},{"edgeType":"contains","source":210,"target":277},{"edgeType":"calls","source":774,"target":570},{"edgeType":"calls","source":2788,"target":498},{"edgeType":"contains","source":2292,"target":2325},{"edgeType":"contains","source":6,"target":2372},{"edgeType":"calls","source":4869,"target":467},{"edgeType":"contains","source":3573,"target":3839},{"edgeType":"calls","source":2178,"target":382},{"edgeType":"calls","source":3945,"target":570},{"edgeType":"calls","source":4876,"target":249},{"edgeType":"calls","source":4869,"target":466},{"edgeType":"calls","source":4043,"target":705},{"edgeType":"calls","source":1306,"target":990},{"edgeType":"calls","source":4701,"target":389},{"edgeType":"calls","source":2930,"target":325},{"edgeType":"calls","source":338,"target":344},{"edgeType":"contains","source":373,"target":508},{"edgeType":"calls","source":4667,"target":386},{"edgeType":"contains","source":6,"target":2371},{"edgeType":"contains","source":210,"target":276},{"edgeType":"contains","source":46,"target":74},{"edgeType":"calls","source":4760,"target":674},{"edgeType":"calls","source":774,"target":569},{"edgeType":"contains","source":2127,"target":2155},{"edgeType":"contains","source":16,"target":4176},{"edgeType":"calls","source":107,"target":106},{"edgeType":"contains","source":770,"target":885},{"edgeType":"contains","source":3573,"target":3838},{"edgeType":"calls","source":2175,"target":476},{"edgeType":"calls","source":2178,"target":383},{"edgeType":"calls","source":3837,"target":3919},{"edgeType":"calls","source":3945,"target":571},{"edgeType":"calls","source":2748,"target":712},{"edgeType":"contains","source":4600,"target":4743},{"edgeType":"imports","source":2201,"target":505},{"edgeType":"calls","source":1429,"target":376},{"edgeType":"calls","source":849,"target":386},{"edgeType":"contains","source":2292,"target":2298},{"edgeType":"contains","source":97,"target":1635},{"edgeType":"calls","source":2998,"target":2476},{"edgeType":"calls","source":3726,"target":2105},{"edgeType":"contains","source":2127,"target":2128},{"edgeType":"calls","source":4594,"target":567},{"edgeType":"calls","source":2429,"target":1088},{"edgeType":"calls","source":2207,"target":571},{"edgeType":"calls","source":1872,"target":384},{"edgeType":"calls","source":2247,"target":388},{"edgeType":"calls","source":3942,"target":3865},{"edgeType":"calls","source":2748,"target":713},{"edgeType":"calls","source":1336,"target":87},{"edgeType":"imports","source":2201,"target":504},{"edgeType":"calls","source":849,"target":385},{"edgeType":"calls","source":3272,"target":325},{"edgeType":"calls","source":1159,"target":289},{"edgeType":"calls","source":4766,"target":519},{"edgeType":"contains","source":2127,"target":2129},{"edgeType":"calls","source":1810,"target":191},{"edgeType":"calls","source":1659,"target":644},{"edgeType":"calls","source":4594,"target":566},{"edgeType":"calls","source":2247,"target":389},{"edgeType":"calls","source":4396,"target":362},{"edgeType":"calls","source":2207,"target":572},{"edgeType":"calls","source":1872,"target":383},{"edgeType":"calls","source":3462,"target":774},{"edgeType":"calls","source":1264,"target":1265},{"edgeType":"calls","source":824,"target":106},{"edgeType":"calls","source":849,"target":388},{"edgeType":"calls","source":1629,"target":1577},{"edgeType":"calls","source":4496,"target":1489},{"edgeType":"calls","source":4396,"target":361},{"edgeType":"calls","source":2207,"target":569},{"edgeType":"calls","source":2247,"target":386},{"edgeType":"calls","source":1972,"target":457},{"edgeType":"imports","source":97,"target":190},{"edgeType":"calls","source":1872,"target":386},{"edgeType":"contains","source":3316,"target":3321},{"edgeType":"calls","source":1050,"target":499},{"edgeType":"calls","source":849,"target":387},{"edgeType":"contains","source":3573,"target":3809},{"edgeType":"contains","source":29,"target":573},{"edgeType":"calls","source":1714,"target":1055},{"edgeType":"contains","source":28,"target":3775},{"edgeType":"contains","source":1535,"target":2509},{"edgeType":"calls","source":2476,"target":687},{"edgeType":"calls","source":2448,"target":498},{"edgeType":"calls","source":1872,"target":385},{"edgeType":"calls","source":2247,"target":387},{"edgeType":"calls","source":2207,"target":570},{"edgeType":"calls","source":1972,"target":456},{"edgeType":"calls","source":4078,"target":705},{"edgeType":"calls","source":2831,"target":249},{"edgeType":"calls","source":1499,"target":316},{"edgeType":"calls","source":636,"target":643},{"edgeType":"calls","source":849,"target":382},{"edgeType":"contains","source":2292,"target":2302},{"edgeType":"contains","source":210,"target":250},{"edgeType":"calls","source":3347,"target":1166},{"edgeType":"calls","source":4722,"target":1880},{"edgeType":"calls","source":1325,"target":425},{"edgeType":"contains","source":3573,"target":3816},{"edgeType":"calls","source":1844,"target":191},{"edgeType":"calls","source":4696,"target":572},{"edgeType":"contains","source":4010,"target":4011},{"edgeType":"contains","source":97,"target":1639},{"edgeType":"contains","source":2127,"target":2132},{"edgeType":"calls","source":505,"target":476},{"edgeType":"contains","source":2975,"target":3326},{"edgeType":"calls","source":2207,"target":567},{"edgeType":"calls","source":310,"target":179},{"edgeType":"calls","source":2247,"target":384},{"edgeType":"contains","source":2806,"target":3280},{"edgeType":"contains","source":4600,"target":4747},{"edgeType":"calls","source":1499,"target":315},{"edgeType":"calls","source":1517,"target":814},{"edgeType":"extends","source":4153,"target":3652},{"edgeType":"contains","source":2127,"target":2133},{"edgeType":"contains","source":16,"target":4149},{"edgeType":"contains","source":97,"target":1638},{"edgeType":"contains","source":1962,"target":1963},{"edgeType":"calls","source":4530,"target":1489},{"edgeType":"calls","source":4696,"target":571},{"edgeType":"calls","source":578,"target":326},{"edgeType":"calls","source":3976,"target":3865},{"edgeType":"imports","source":32,"target":90},{"edgeType":"calls","source":2247,"target":385},{"edgeType":"calls","source":4396,"target":358},{"edgeType":"calls","source":2207,"target":568},{"edgeType":"calls","source":1325,"target":427},{"edgeType":"calls","source":3507,"target":1489},{"edgeType":"contains","source":210,"target":252},{"edgeType":"calls","source":1517,"target":817},{"edgeType":"calls","source":1234,"target":77},{"edgeType":"calls","source":849,"target":384},{"edgeType":"calls","source":3206,"target":249},{"edgeType":"contains","source":2127,"target":2130},{"edgeType":"calls","source":4696,"target":570},{"edgeType":"contains","source":2259,"target":2266},{"edgeType":"calls","source":505,"target":478},{"edgeType":"imports","source":97,"target":186},{"edgeType":"calls","source":1872,"target":382},{"edgeType":"contains","source":4600,"target":4745},{"edgeType":"calls","source":4396,"target":357},{"edgeType":"calls","source":2247,"target":382},{"edgeType":"calls","source":1499,"target":317},{"edgeType":"calls","source":771,"target":687},{"edgeType":"contains","source":210,"target":251},{"edgeType":"calls","source":2831,"target":248},{"edgeType":"calls","source":849,"target":383},{"edgeType":"calls","source":1325,"target":426},{"edgeType":"contains","source":3573,"target":3813},{"edgeType":"calls","source":1128,"target":191},{"edgeType":"calls","source":4649,"target":969},{"edgeType":"calls","source":4696,"target":569},{"edgeType":"calls","source":4640,"target":191},{"edgeType":"contains","source":2127,"target":2131},{"edgeType":"calls","source":4756,"target":1880},{"edgeType":"calls","source":505,"target":477},{"edgeType":"calls","source":2247,"target":383},{"edgeType":"contains","source":4600,"target":4744},{"edgeType":"calls","source":4396,"target":356},{"edgeType":"imports","source":3571,"target":325},{"edgeType":"contains","source":637,"target":755},{"edgeType":"calls","source":4305,"target":1063},{"edgeType":"calls","source":2207,"target":566},{"edgeType":"contains","source":210,"target":254},{"edgeType":"imports","source":34,"target":39},{"edgeType":"calls","source":1395,"target":365},{"edgeType":"calls","source":3294,"target":690},{"edgeType":"calls","source":4696,"target":568},{"edgeType":"calls","source":3276,"target":191},{"edgeType":"calls","source":2657,"target":354},{"edgeType":"contains","source":2127,"target":2136},{"edgeType":"calls","source":2683,"target":605},{"edgeType":"calls","source":510,"target":317},{"edgeType":"calls","source":4396,"target":355},{"edgeType":"calls","source":4339,"target":1063},{"edgeType":"calls","source":3638,"target":1655},{"edgeType":"contains","source":210,"target":253},{"edgeType":"imports","source":34,"target":40},{"edgeType":"contains","source":3573,"target":3819},{"edgeType":"calls","source":3206,"target":248},{"edgeType":"contains","source":1962,"target":1967},{"edgeType":"calls","source":3232,"target":499},{"edgeType":"calls","source":1878,"target":189},{"edgeType":"calls","source":4696,"target":567},{"edgeType":"calls","source":3926,"target":1183},{"edgeType":"calls","source":3958,"target":191},{"edgeType":"contains","source":4001,"target":65},{"edgeType":"contains","source":2127,"target":2137},{"edgeType":"contains","source":2126,"target":2168},{"edgeType":"contains","source":43,"target":2259},{"edgeType":"calls","source":4873,"target":365},{"edgeType":"contains","source":4600,"target":4750},{"edgeType":"calls","source":2683,"target":606},{"edgeType":"calls","source":4500,"target":301},{"edgeType":"calls","source":505,"target":471},{"edgeType":"calls","source":510,"target":316},{"edgeType":"contains","source":210,"target":256},{"edgeType":"imports","source":34,"target":37},{"edgeType":"calls","source":2965,"target":2431},{"edgeType":"contains","source":4001,"target":63},{"edgeType":"imports","source":2259,"target":1884},{"edgeType":"contains","source":1204,"target":1153},{"edgeType":"calls","source":4696,"target":566},{"edgeType":"imports","source":1749,"target":1839},{"edgeType":"contains","source":2127,"target":2134},{"edgeType":"contains","source":1962,"target":1964},{"edgeType":"calls","source":4026,"target":194},{"edgeType":"calls","source":4518,"target":1856},{"edgeType":"contains","source":4600,"target":4749},{"edgeType":"contains","source":3002,"target":377},{"edgeType":"calls","source":578,"target":325},{"edgeType":"calls","source":338,"target":366},{"edgeType":"calls","source":4438,"target":106},{"edgeType":"contains","source":210,"target":255},{"edgeType":"contains","source":1065,"target":1233},{"edgeType":"calls","source":1736,"target":365},{"edgeType":"calls","source":1878,"target":191},{"edgeType":"calls","source":2657,"target":353},{"edgeType":"calls","source":3845,"target":3692},{"edgeType":"contains","source":1962,"target":1965},{"edgeType":"contains","source":4600,"target":4748},{"edgeType":"imports","source":1918,"target":1884},{"edgeType":"contains","source":2127,"target":2135},{"edgeType":"calls","source":4598,"target":1489},{"edgeType":"calls","source":4567,"target":336},{"edgeType":"imports","source":34,"target":35},{"edgeType":"contains","source":2806,"target":3289},{"edgeType":"calls","source":4237,"target":4222},{"edgeType":"contains","source":1065,"target":1236},{"edgeType":"contains","source":1260,"target":1534},{"edgeType":"contains","source":1731,"target":1732},{"edgeType":"contains","source":4404,"target":4489},{"edgeType":"contains","source":1962,"target":1970},{"edgeType":"contains","source":6,"target":2354},{"edgeType":"calls","source":2717,"target":2718},{"edgeType":"calls","source":2548,"target":558},{"edgeType":"contains","source":2276,"target":2806},{"edgeType":"calls","source":2734,"target":77},{"edgeType":"calls","source":2726,"target":325},{"edgeType":"calls","source":4745,"target":102},{"edgeType":"contains","source":210,"target":258},{"edgeType":"contains","source":2127,"target":2140},{"edgeType":"contains","source":210,"target":257},{"edgeType":"calls","source":994,"target":106},{"edgeType":"calls","source":3158,"target":675},{"edgeType":"contains","source":1731,"target":1733},{"edgeType":"contains","source":2127,"target":2141},{"edgeType":"contains","source":1962,"target":1971},{"edgeType":"calls","source":4745,"target":101},{"edgeType":"calls","source":2377,"target":571},{"edgeType":"calls","source":960,"target":106},{"edgeType":"calls","source":3875,"target":3814},{"edgeType":"contains","source":4869,"target":4871},{"edgeType":"calls","source":3529,"target":1856},{"edgeType":"calls","source":1456,"target":586},{"edgeType":"calls","source":1660,"target":1661},{"edgeType":"contains","source":1065,"target":1238},{"edgeType":"contains","source":1260,"target":1532},{"edgeType":"contains","source":1090,"target":1520},{"edgeType":"calls","source":1892,"target":1868},{"edgeType":"calls","source":510,"target":315},{"edgeType":"contains","source":1962,"target":1968},{"edgeType":"calls","source":4047,"target":1653},{"edgeType":"calls","source":3358,"target":1871},{"edgeType":"calls","source":3291,"target":777},{"edgeType":"imports","source":1918,"target":1881},{"edgeType":"contains","source":2127,"target":2138},{"edgeType":"calls","source":4632,"target":1489},{"edgeType":"calls","source":2555,"target":339},{"edgeType":"calls","source":4745,"target":100},{"edgeType":"calls","source":3007,"target":68},{"edgeType":"calls","source":2959,"target":499},{"edgeType":"calls","source":4756,"target":1873},{"edgeType":"calls","source":2377,"target":572},{"edgeType":"imports","source":4451,"target":519},{"edgeType":"contains","source":4869,"target":4870},{"edgeType":"calls","source":1456,"target":585},{"edgeType":"calls","source":3875,"target":3815},{"edgeType":"contains","source":1260,"target":1533},{"edgeType":"contains","source":1962,"target":1969},{"edgeType":"contains","source":1776,"target":336},{"edgeType":"calls","source":2548,"target":557},{"edgeType":"contains","source":6,"target":2355},{"edgeType":"calls","source":4745,"target":99},{"edgeType":"contains","source":2127,"target":2139},{"edgeType":"contains","source":2126,"target":2170},{"edgeType":"calls","source":4789,"target":1906},{"edgeType":"imports","source":3920,"target":1175},{"edgeType":"extends","source":340,"target":341},{"edgeType":"contains","source":2715,"target":2910},{"edgeType":"calls","source":4029,"target":194},{"edgeType":"imports","source":34,"target":80},{"edgeType":"calls","source":4807,"target":389},{"edgeType":"extends","source":3400,"target":2730},{"edgeType":"calls","source":4254,"target":1675},{"edgeType":"calls","source":4260,"target":1489},{"edgeType":"contains","source":1631,"target":1632},{"edgeType":"contains","source":2353,"target":2504},{"edgeType":"calls","source":4501,"target":3533},{"edgeType":"calls","source":4819,"target":4245},{"edgeType":"calls","source":672,"target":671},{"edgeType":"calls","source":4521,"target":1856},{"edgeType":"contains","source":3811,"target":3817},{"edgeType":"contains","source":16,"target":958},{"edgeType":"calls","source":4714,"target":101},{"edgeType":"calls","source":4532,"target":456},{"edgeType":"contains","source":3051,"target":3065},{"edgeType":"calls","source":3848,"target":3692},{"edgeType":"contains","source":2715,"target":2911},{"edgeType":"imports","source":34,"target":82},{"edgeType":"contains","source":2353,"target":2505},{"edgeType":"imports","source":4209,"target":674},{"edgeType":"calls","source":4671,"target":376},{"edgeType":"calls","source":4501,"target":3532},{"edgeType":"contains","source":1631,"target":1633},{"edgeType":"contains","source":3679,"target":3680},{"edgeType":"calls","source":4714,"target":100},{"edgeType":"calls","source":4807,"target":388},{"edgeType":"contains","source":3,"target":2417},{"edgeType":"contains","source":1398,"target":1453},{"edgeType":"calls","source":1839,"target":435},{"edgeType":"calls","source":1696,"target":640},{"edgeType":"calls","source":1875,"target":376},{"edgeType":"contains","source":1062,"target":1302},{"edgeType":"calls","source":3403,"target":571},{"edgeType":"contains","source":396,"target":1864},{"edgeType":"calls","source":705,"target":707},{"edgeType":"calls","source":1063,"target":179},{"edgeType":"calls","source":4714,"target":99},{"edgeType":"calls","source":3277,"target":249},{"edgeType":"contains","source":3811,"target":3815},{"edgeType":"calls","source":772,"target":744},{"edgeType":"contains","source":2204,"target":779},{"edgeType":"calls","source":4758,"target":1906},{"edgeType":"calls","source":4807,"target":387},{"edgeType":"calls","source":4498,"target":451},{"edgeType":"contains","source":3573,"target":3792},{"edgeType":"contains","source":3051,"target":3063},{"edgeType":"calls","source":1839,"target":434},{"edgeType":"contains","source":2715,"target":2909},{"edgeType":"imports","source":34,"target":79},{"edgeType":"calls","source":1843,"target":1367},{"edgeType":"calls","source":3403,"target":572},{"edgeType":"calls","source":3319,"target":3176},{"edgeType":"calls","source":3313,"target":191},{"edgeType":"calls","source":3331,"target":690},{"edgeType":"contains","source":2353,"target":2503},{"edgeType":"calls","source":4714,"target":98},{"edgeType":"contains","source":3811,"target":3814},{"edgeType":"calls","source":4807,"target":386},{"edgeType":"calls","source":4841,"target":389},{"edgeType":"calls","source":705,"target":706},{"edgeType":"calls","source":338,"target":450},{"edgeType":"contains","source":16,"target":2019},{"edgeType":"calls","source":2491,"target":301},{"edgeType":"calls","source":4134,"target":106},{"edgeType":"imports","source":2209,"target":302},{"edgeType":"contains","source":2803,"target":3357},{"edgeType":"calls","source":4050,"target":1653},{"edgeType":"calls","source":673,"target":636},{"edgeType":"calls","source":2728,"target":354},{"edgeType":"calls","source":3403,"target":569},{"edgeType":"calls","source":3437,"target":572},{"edgeType":"calls","source":1267,"target":191},{"edgeType":"calls","source":4629,"target":1675},{"edgeType":"calls","source":4635,"target":1489},{"edgeType":"calls","source":772,"target":738},{"edgeType":"calls","source":3294,"target":777},{"edgeType":"calls","source":4807,"target":385},{"edgeType":"imports","source":4451,"target":574},{"edgeType":"calls","source":4841,"target":388},{"edgeType":"calls","source":4873,"target":3624},{"edgeType":"calls","source":3786,"target":325},{"edgeType":"contains","source":97,"target":564},{"edgeType":"calls","source":4589,"target":1856},{"edgeType":"calls","source":4410,"target":1063},{"edgeType":"contains","source":2803,"target":3358},{"edgeType":"calls","source":3403,"target":570},{"edgeType":"calls","source":3277,"target":248},{"edgeType":"calls","source":4807,"target":384},{"edgeType":"calls","source":2847,"target":894},{"edgeType":"calls","source":4841,"target":387},{"edgeType":"calls","source":969,"target":975},{"edgeType":"calls","source":4663,"target":1675},{"edgeType":"calls","source":4669,"target":1489},{"edgeType":"contains","source":2715,"target":2912},{"edgeType":"calls","source":4015,"target":622},{"edgeType":"calls","source":1796,"target":1764},{"edgeType":"imports","source":2209,"target":300},{"edgeType":"calls","source":4297,"target":336},{"edgeType":"calls","source":2847,"target":891},{"edgeType":"contains","source":2353,"target":2506},{"edgeType":"contains","source":2280,"target":2655},{"edgeType":"calls","source":2665,"target":191},{"edgeType":"calls","source":4807,"target":383},{"edgeType":"calls","source":3403,"target":567},{"edgeType":"calls","source":3437,"target":570},{"edgeType":"calls","source":4835,"target":572},{"edgeType":"calls","source":4841,"target":386},{"edgeType":"imports","source":3811,"target":2447},{"edgeType":"contains","source":830,"target":1098},{"edgeType":"contains","source":2715,"target":2913},{"edgeType":"contains","source":1062,"target":1305},{"edgeType":"calls","source":2763,"target":325},{"edgeType":"imports","source":4086,"target":3436},{"edgeType":"contains","source":2353,"target":2507},{"edgeType":"calls","source":2728,"target":353},{"edgeType":"calls","source":3437,"target":571},{"edgeType":"contains","source":2280,"target":2656},{"edgeType":"calls","source":4807,"target":382},{"edgeType":"calls","source":3403,"target":568},{"edgeType":"calls","source":4835,"target":571},{"edgeType":"calls","source":4841,"target":385},{"edgeType":"calls","source":4702,"target":4694},{"edgeType":"calls","source":3231,"target":1672},{"edgeType":"calls","source":1839,"target":425},{"edgeType":"calls","source":1050,"target":572},{"edgeType":"calls","source":3889,"target":298},{"edgeType":"calls","source":1880,"target":211},{"edgeType":"contains","source":16,"target":2023},{"edgeType":"calls","source":4640,"target":4500},{"edgeType":"calls","source":619,"target":191},{"edgeType":"contains","source":2806,"target":3268},{"edgeType":"calls","source":1957,"target":995},{"edgeType":"contains","source":830,"target":1101},{"edgeType":"calls","source":1498,"target":425},{"edgeType":"calls","source":1429,"target":1507},{"edgeType":"calls","source":2105,"target":1693},{"edgeType":"calls","source":824,"target":179},{"edgeType":"calls","source":3437,"target":568},{"edgeType":"calls","source":4835,"target":570},{"edgeType":"calls","source":4841,"target":384},{"edgeType":"calls","source":3373,"target":438},{"edgeType":"calls","source":1325,"target":503},{"edgeType":"calls","source":3873,"target":1852},{"edgeType":"calls","source":1050,"target":571},{"edgeType":"contains","source":4045,"target":798},{"edgeType":"calls","source":4835,"target":568},{"edgeType":"calls","source":4841,"target":382},{"edgeType":"contains","source":830,"target":1100},{"edgeType":"calls","source":4438,"target":191},{"edgeType":"calls","source":4869,"target":572},{"edgeType":"calls","source":1325,"target":502},{"edgeType":"calls","source":3403,"target":566},{"edgeType":"calls","source":4835,"target":569},{"edgeType":"calls","source":4841,"target":383},{"edgeType":"contains","source":1204,"target":1133},{"edgeType":"calls","source":3437,"target":569},{"edgeType":"calls","source":1429,"target":1506},{"edgeType":"calls","source":1839,"target":427},{"edgeType":"calls","source":4835,"target":567},{"edgeType":"calls","source":4869,"target":570},{"edgeType":"calls","source":4873,"target":446},{"edgeType":"calls","source":4227,"target":388},{"edgeType":"calls","source":4356,"target":1675},{"edgeType":"calls","source":1498,"target":427},{"edgeType":"imports","source":4451,"target":564},{"edgeType":"contains","source":830,"target":1103},{"edgeType":"calls","source":4848,"target":2279},{"edgeType":"contains","source":3084,"target":3104},{"edgeType":"calls","source":4869,"target":571},{"edgeType":"contains","source":3573,"target":3802},{"edgeType":"contains","source":3571,"target":3864},{"edgeType":"extends","source":2269,"target":1857},{"edgeType":"calls","source":3373,"target":436},{"edgeType":"calls","source":3437,"target":566},{"edgeType":"calls","source":3415,"target":191},{"edgeType":"calls","source":1839,"target":426},{"edgeType":"calls","source":4536,"target":4550},{"edgeType":"calls","source":1880,"target":212},{"edgeType":"calls","source":4835,"target":566},{"edgeType":"calls","source":1728,"target":1753},{"edgeType":"calls","source":4869,"target":569},{"edgeType":"calls","source":4873,"target":445},{"edgeType":"calls","source":2281,"target":464},{"edgeType":"calls","source":4227,"target":389},{"edgeType":"calls","source":1498,"target":426},{"edgeType":"calls","source":3603,"target":1763},{"edgeType":"calls","source":786,"target":301},{"edgeType":"calls","source":3437,"target":567},{"edgeType":"contains","source":3573,"target":3801},{"edgeType":"calls","source":3373,"target":437},{"edgeType":"calls","source":1909,"target":365},{"edgeType":"calls","source":2652,"target":587},{"edgeType":"contains","source":3316,"target":3318},{"edgeType":"calls","source":4731,"target":1675},{"edgeType":"calls","source":4737,"target":1489},{"edgeType":"calls","source":1973,"target":495},{"edgeType":"calls","source":1050,"target":568},{"edgeType":"calls","source":4227,"target":386},{"edgeType":"calls","source":4869,"target":568},{"edgeType":"calls","source":771,"target":760},{"edgeType":"calls","source":407,"target":417},{"edgeType":"calls","source":475,"target":423},{"edgeType":"calls","source":2256,"target":179},{"edgeType":"contains","source":2806,"target":3272},{"edgeType":"calls","source":4890,"target":2032},{"edgeType":"calls","source":1429,"target":1503},{"edgeType":"calls","source":1973,"target":494},{"edgeType":"calls","source":2656,"target":464},{"edgeType":"calls","source":724,"target":102},{"edgeType":"calls","source":1050,"target":567},{"edgeType":"calls","source":2733,"target":191},{"edgeType":"calls","source":4227,"target":387},{"edgeType":"calls","source":4869,"target":567},{"edgeType":"calls","source":2689,"target":498},{"edgeType":"contains","source":2292,"target":2295},{"edgeType":"calls","source":2386,"target":378},{"edgeType":"contains","source":2226,"target":2227},{"edgeType":"contains","source":3573,"target":3807},{"edgeType":"calls","source":1728,"target":1746},{"edgeType":"calls","source":3888,"target":325},{"edgeType":"calls","source":1429,"target":1502},{"edgeType":"calls","source":1133,"target":1168},{"edgeType":"calls","source":1050,"target":570},{"edgeType":"calls","source":4227,"target":384},{"edgeType":"extends","source":1807,"target":1384},{"edgeType":"calls","source":4705,"target":365},{"edgeType":"calls","source":4869,"target":566},{"edgeType":"contains","source":3573,"target":3806},{"edgeType":"imports","source":3002,"target":1094},{"edgeType":"calls","source":1429,"target":1505},{"edgeType":"calls","source":4765,"target":1675},{"edgeType":"contains","source":3316,"target":3317},{"edgeType":"contains","source":396,"target":2933},{"edgeType":"calls","source":3362,"target":774},{"edgeType":"calls","source":3293,"target":1856},{"edgeType":"calls","source":1050,"target":569},{"edgeType":"calls","source":1973,"target":496},{"edgeType":"imports","source":3811,"target":325},{"edgeType":"calls","source":4227,"target":385},{"edgeType":"imports","source":3710,"target":285},{"edgeType":"contains","source":97,"target":1631},{"edgeType":"contains","source":2292,"target":2293},{"edgeType":"contains","source":3679,"target":3690},{"edgeType":"contains","source":1516,"target":2037},{"edgeType":"calls","source":4350,"target":1856},{"edgeType":"calls","source":2316,"target":1489},{"edgeType":"calls","source":3124,"target":1810},{"edgeType":"calls","source":1273,"target":1055},{"edgeType":"calls","source":1429,"target":1504},{"edgeType":"calls","source":3368,"target":1675},{"edgeType":"calls","source":3424,"target":996},{"edgeType":"calls","source":1974,"target":493},{"edgeType":"calls","source":4228,"target":384},{"edgeType":"calls","source":2523,"target":387},{"edgeType":"calls","source":1077,"target":817},{"edgeType":"calls","source":781,"target":479},{"edgeType":"calls","source":784,"target":386},{"edgeType":"contains","source":3,"target":2401},{"edgeType":"contains","source":16,"target":3056},{"edgeType":"contains","source":4240,"target":4243},{"edgeType":"calls","source":4456,"target":716},{"edgeType":"contains","source":3447,"target":3457},{"edgeType":"contains","source":1485,"target":1913},{"edgeType":"calls","source":1500,"target":388},{"edgeType":"calls","source":1702,"target":468},{"edgeType":"calls","source":3363,"target":774},{"edgeType":"imports","source":34,"target":65},{"edgeType":"calls","source":1974,"target":492},{"edgeType":"contains","source":2353,"target":2489},{"edgeType":"calls","source":4228,"target":385},{"edgeType":"calls","source":784,"target":385},{"edgeType":"calls","source":2523,"target":388},{"edgeType":"calls","source":4597,"target":572},{"edgeType":"calls","source":4772,"target":1489},{"edgeType":"calls","source":4456,"target":715},{"edgeType":"calls","source":1702,"target":467},{"edgeType":"calls","source":2311,"target":1675},{"edgeType":"calls","source":1500,"target":387},{"edgeType":"calls","source":1974,"target":491},{"edgeType":"calls","source":1974,"target":495},{"edgeType":"imports","source":2276,"target":325},{"edgeType":"calls","source":4228,"target":382},{"edgeType":"calls","source":3328,"target":1856},{"edgeType":"calls","source":2523,"target":385},{"edgeType":"contains","source":2353,"target":2486},{"edgeType":"calls","source":4597,"target":571},{"edgeType":"calls","source":784,"target":388},{"edgeType":"calls","source":573,"target":587},{"edgeType":"calls","source":2900,"target":325},{"edgeType":"calls","source":4838,"target":499},{"edgeType":"contains","source":1485,"target":1911},{"edgeType":"calls","source":4456,"target":714},{"edgeType":"contains","source":4240,"target":4241},{"edgeType":"contains","source":3413,"target":3452},{"edgeType":"calls","source":1702,"target":470},{"edgeType":"calls","source":4098,"target":183},{"edgeType":"contains","source":1062,"target":1285},{"edgeType":"calls","source":1974,"target":494},{"edgeType":"calls","source":2687,"target":587},{"edgeType":"calls","source":2664,"target":1300},{"edgeType":"calls","source":4228,"target":383},{"edgeType":"calls","source":1234,"target":179},{"edgeType":"calls","source":1151,"target":638},{"edgeType":"contains","source":4600,"target":4707},{"edgeType":"contains","source":2353,"target":2487},{"edgeType":"calls","source":2900,"target":326},{"edgeType":"calls","source":2523,"target":386},{"edgeType":"calls","source":784,"target":387},{"edgeType":"calls","source":4597,"target":570},{"edgeType":"calls","source":4456,"target":713},{"edgeType":"calls","source":1500,"target":389},{"edgeType":"imports","source":34,"target":63},{"edgeType":"contains","source":3163,"target":631},{"edgeType":"calls","source":1702,"target":469},{"edgeType":"contains","source":3051,"target":3052},{"edgeType":"calls","source":1500,"target":384},{"edgeType":"imports","source":1090,"target":92},{"edgeType":"calls","source":1168,"target":106},{"edgeType":"calls","source":4717,"target":1077},{"edgeType":"calls","source":784,"target":382},{"edgeType":"calls","source":4800,"target":1675},{"edgeType":"calls","source":4806,"target":1489},{"edgeType":"calls","source":2523,"target":383},{"edgeType":"calls","source":4597,"target":569},{"edgeType":"calls","source":4467,"target":1428},{"edgeType":"calls","source":4405,"target":179},{"edgeType":"calls","source":4456,"target":712},{"edgeType":"imports","source":2201,"target":534},{"edgeType":"calls","source":1975,"target":457},{"edgeType":"calls","source":1500,"target":383},{"edgeType":"contains","source":3050,"target":3084},{"edgeType":"calls","source":3348,"target":3349},{"edgeType":"imports","source":1090,"target":93},{"edgeType":"calls","source":2523,"target":384},{"edgeType":"calls","source":4597,"target":568},{"edgeType":"calls","source":4405,"target":1235},{"edgeType":"calls","source":4405,"target":4406},{"edgeType":"calls","source":1975,"target":456},{"edgeType":"imports","source":3643,"target":1295},{"edgeType":"contains","source":4600,"target":4713},{"edgeType":"calls","source":3402,"target":1672},{"edgeType":"calls","source":3442,"target":1489},{"edgeType":"calls","source":784,"target":384},{"edgeType":"calls","source":3307,"target":389},{"edgeType":"imports","source":1090,"target":90},{"edgeType":"calls","source":1702,"target":466},{"edgeType":"calls","source":4597,"target":567},{"edgeType":"calls","source":1500,"target":386},{"edgeType":"calls","source":2349,"target":490},{"edgeType":"contains","source":4600,"target":4712},{"edgeType":"imports","source":2021,"target":1884},{"edgeType":"calls","source":1839,"target":447},{"edgeType":"calls","source":3518,"target":191},{"edgeType":"contains","source":3084,"target":3085},{"edgeType":"contains","source":4600,"target":4711},{"edgeType":"contains","source":2353,"target":2491},{"edgeType":"calls","source":2693,"target":397},{"edgeType":"calls","source":1500,"target":385},{"edgeType":"imports","source":1090,"target":91},{"edgeType":"calls","source":784,"target":383},{"edgeType":"calls","source":1063,"target":191},{"edgeType":"contains","source":704,"target":759},{"edgeType":"calls","source":4597,"target":566},{"edgeType":"calls","source":1702,"target":465},{"edgeType":"contains","source":3573,"target":3780},{"edgeType":"calls","source":4705,"target":389},{"edgeType":"contains","source":3447,"target":3458},{"edgeType":"calls","source":2523,"target":382},{"edgeType":"calls","source":4622,"target":1905},{"edgeType":"calls","source":1885,"target":77},{"edgeType":"calls","source":2178,"target":503},{"edgeType":"calls","source":4872,"target":496},{"edgeType":"calls","source":1629,"target":1666},{"edgeType":"contains","source":3162,"target":2786},{"edgeType":"contains","source":1398,"target":1447},{"edgeType":"calls","source":3307,"target":387},{"edgeType":"imports","source":2259,"target":862},{"edgeType":"calls","source":1839,"target":441},{"edgeType":"calls","source":4586,"target":906},{"edgeType":"calls","source":4493,"target":1675},{"edgeType":"contains","source":78,"target":85},{"edgeType":"calls","source":4705,"target":388},{"edgeType":"calls","source":2349,"target":488},{"edgeType":"contains","source":4240,"target":4251},{"edgeType":"contains","source":4600,"target":4718},{"edgeType":"contains","source":4189,"target":2661},{"edgeType":"calls","source":4224,"target":499},{"edgeType":"calls","source":4855,"target":4193},{"edgeType":"calls","source":4872,"target":495},{"edgeType":"contains","source":1062,"target":1291},{"edgeType":"calls","source":1629,"target":1665},{"edgeType":"calls","source":4794,"target":1856},{"edgeType":"contains","source":3573,"target":3786},{"edgeType":"calls","source":3307,"target":388},{"edgeType":"contains","source":1398,"target":1448},{"edgeType":"calls","source":2451,"target":498},{"edgeType":"calls","source":4705,"target":387},{"edgeType":"contains","source":78,"target":84},{"edgeType":"contains","source":4600,"target":4717},{"edgeType":"calls","source":4081,"target":705},{"edgeType":"calls","source":2349,"target":489},{"edgeType":"calls","source":4435,"target":301},{"edgeType":"calls","source":573,"target":576},{"edgeType":"contains","source":2204,"target":774},{"edgeType":"contains","source":704,"target":761},{"edgeType":"calls","source":1344,"target":990},{"edgeType":"contains","source":2280,"target":2643},{"edgeType":"calls","source":1500,"target":382},{"edgeType":"calls","source":4872,"target":494},{"edgeType":"contains","source":1485,"target":1919},{"edgeType":"calls","source":3307,"target":385},{"edgeType":"calls","source":3350,"target":1166},{"edgeType":"contains","source":2715,"target":2899},{"edgeType":"calls","source":3261,"target":1810},{"edgeType":"calls","source":3307,"target":384},{"edgeType":"calls","source":4705,"target":386},{"edgeType":"calls","source":2529,"target":191},{"edgeType":"calls","source":408,"target":409},{"edgeType":"calls","source":1629,"target":1668},{"edgeType":"contains","source":78,"target":87},{"edgeType":"contains","source":4600,"target":4716},{"edgeType":"calls","source":4453,"target":1856},{"edgeType":"contains","source":704,"target":764},{"edgeType":"calls","source":2286,"target":325},{"edgeType":"calls","source":4211,"target":1957},{"edgeType":"calls","source":2485,"target":498},{"edgeType":"imports","source":4209,"target":650},{"edgeType":"calls","source":2349,"target":486},{"edgeType":"calls","source":2178,"target":502},{"edgeType":"calls","source":772,"target":751},{"edgeType":"imports","source":2255,"target":983},{"edgeType":"calls","source":1234,"target":1228},{"edgeType":"calls","source":969,"target":986},{"edgeType":"contains","source":1398,"target":1446},{"edgeType":"calls","source":3307,"target":386},{"edgeType":"calls","source":3263,"target":692},{"edgeType":"calls","source":4705,"target":385},{"edgeType":"calls","source":1813,"target":191},{"edgeType":"calls","source":2485,"target":499},{"edgeType":"imports","source":1749,"target":1871},{"edgeType":"contains","source":4009,"target":4010},{"edgeType":"calls","source":1839,"target":1499},{"edgeType":"calls","source":1677,"target":179},{"edgeType":"calls","source":1629,"target":1667},{"edgeType":"calls","source":2349,"target":487},{"edgeType":"calls","source":4872,"target":493},{"edgeType":"contains","source":78,"target":86},{"edgeType":"contains","source":4240,"target":4248},{"edgeType":"contains","source":704,"target":763},{"edgeType":"contains","source":4600,"target":4715},{"edgeType":"calls","source":4308,"target":1063},{"edgeType":"calls","source":991,"target":299},{"edgeType":"contains","source":1398,"target":1451},{"edgeType":"calls","source":1273,"target":1071},{"edgeType":"calls","source":1629,"target":1662},{"edgeType":"calls","source":3261,"target":1808},{"edgeType":"calls","source":3307,"target":382},{"edgeType":"calls","source":4705,"target":384},{"edgeType":"calls","source":4013,"target":3865},{"edgeType":"calls","source":4842,"target":365},{"edgeType":"calls","source":4872,"target":492},{"edgeType":"contains","source":78,"target":89},{"edgeType":"calls","source":2817,"target":774},{"edgeType":"calls","source":408,"target":403},{"edgeType":"contains","source":2353,"target":2500},{"edgeType":"calls","source":4396,"target":450},{"edgeType":"contains","source":3084,"target":3095},{"edgeType":"contains","source":1398,"target":1452},{"edgeType":"contains","source":3051,"target":3061},{"edgeType":"calls","source":3307,"target":383},{"edgeType":"calls","source":3263,"target":690},{"edgeType":"calls","source":4705,"target":383},{"edgeType":"contains","source":3811,"target":3812},{"edgeType":"calls","source":2765,"target":1330},{"edgeType":"calls","source":374,"target":399},{"edgeType":"contains","source":704,"target":765},{"edgeType":"contains","source":2353,"target":2501},{"edgeType":"calls","source":4872,"target":491},{"edgeType":"contains","source":78,"target":88},{"edgeType":"calls","source":4109,"target":4061},{"edgeType":"contains","source":2280,"target":2650},{"edgeType":"calls","source":4643,"target":191},{"edgeType":"calls","source":4652,"target":969},{"edgeType":"calls","source":2349,"target":485},{"edgeType":"contains","source":396,"target":1857},{"edgeType":"contains","source":4103,"target":4273},{"edgeType":"calls","source":4487,"target":1856},{"edgeType":"calls","source":772,"target":748},{"edgeType":"contains","source":3573,"target":3789},{"edgeType":"calls","source":3851,"target":3600},{"edgeType":"calls","source":1629,"target":1664},{"edgeType":"contains","source":1485,"target":1923},{"edgeType":"contains","source":1062,"target":1298},{"edgeType":"contains","source":1398,"target":1449},{"edgeType":"calls","source":4066,"target":106},{"edgeType":"contains","source":4600,"target":4720},{"edgeType":"calls","source":3297,"target":690},{"edgeType":"contains","source":2715,"target":2903},{"edgeType":"calls","source":4705,"target":382},{"edgeType":"contains","source":4103,"target":4272},{"edgeType":"calls","source":4536,"target":336},{"edgeType":"calls","source":3641,"target":1655},{"edgeType":"calls","source":776,"target":623},{"edgeType":"calls","source":4434,"target":325},{"edgeType":"contains","source":1398,"target":1450},{"edgeType":"calls","source":1629,"target":1663},{"edgeType":"contains","source":3051,"target":3059},{"edgeType":"calls","source":1429,"target":464},{"edgeType":"calls","source":4749,"target":1131},{"edgeType":"contains","source":4600,"target":4719},{"edgeType":"calls","source":4714,"target":102},{"edgeType":"contains","source":4240,"target":4252},{"edgeType":"calls","source":2519,"target":498},{"edgeType":"imports","source":3162,"target":2508},{"edgeType":"calls","source":4549,"target":954},{"edgeType":"contains","source":4302,"target":4418},{"edgeType":"calls","source":2245,"target":499},{"edgeType":"calls","source":3657,"target":66},{"edgeType":"contains","source":2948,"target":3053},{"edgeType":"calls","source":3815,"target":453},{"edgeType":"calls","source":2726,"target":387},{"edgeType":"calls","source":1367,"target":1290},{"edgeType":"calls","source":2927,"target":498},{"edgeType":"calls","source":4653,"target":902},{"edgeType":"contains","source":2092,"target":2106},{"edgeType":"contains","source":3777,"target":3781},{"edgeType":"calls","source":996,"target":106},{"edgeType":"contains","source":4302,"target":4417},{"edgeType":"contains","source":2948,"target":3054},{"edgeType":"calls","source":3330,"target":690},{"edgeType":"calls","source":4653,"target":901},{"edgeType":"calls","source":4710,"target":191},{"edgeType":"contains","source":2092,"target":2107},{"edgeType":"calls","source":4800,"target":572},{"edgeType":"calls","source":2726,"target":388},{"edgeType":"contains","source":4302,"target":4416},{"edgeType":"calls","source":2207,"target":1675},{"edgeType":"contains","source":3017,"target":3026},{"edgeType":"imports","source":3685,"target":39},{"edgeType":"calls","source":2760,"target":388},{"edgeType":"calls","source":2726,"target":385},{"edgeType":"calls","source":1152,"target":558},{"edgeType":"calls","source":4740,"target":317},{"edgeType":"contains","source":3777,"target":3779},{"edgeType":"calls","source":4653,"target":900},{"edgeType":"calls","source":4872,"target":3624},{"edgeType":"calls","source":4758,"target":1873},{"edgeType":"calls","source":4800,"target":571},{"edgeType":"contains","source":2092,"target":2104},{"edgeType":"calls","source":2869,"target":1237},{"edgeType":"contains","source":4302,"target":4415},{"edgeType":"calls","source":339,"target":391},{"edgeType":"calls","source":4409,"target":1063},{"edgeType":"imports","source":3685,"target":40},{"edgeType":"calls","source":3708,"target":1655},{"edgeType":"calls","source":4062,"target":194},{"edgeType":"imports","source":3643,"target":285},{"edgeType":"contains","source":3115,"target":1046},{"edgeType":"calls","source":2726,"target":386},{"edgeType":"calls","source":2760,"target":389},{"edgeType":"calls","source":4270,"target":88},{"edgeType":"contains","source":3777,"target":3778},{"edgeType":"calls","source":1152,"target":557},{"edgeType":"contains","source":2353,"target":2470},{"edgeType":"calls","source":4687,"target":902},{"edgeType":"calls","source":4740,"target":316},{"edgeType":"calls","source":671,"target":670},{"edgeType":"calls","source":4800,"target":570},{"edgeType":"contains","source":2092,"target":2110},{"edgeType":"calls","source":4450,"target":1905},{"edgeType":"calls","source":4687,"target":900},{"edgeType":"calls","source":4668,"target":1489},{"edgeType":"imports","source":3685,"target":41},{"edgeType":"calls","source":2187,"target":179},{"edgeType":"contains","source":803,"target":844},{"edgeType":"contains","source":3175,"target":248},{"edgeType":"calls","source":2754,"target":572},{"edgeType":"calls","source":4296,"target":336},{"edgeType":"calls","source":2760,"target":386},{"edgeType":"calls","source":4304,"target":88},{"edgeType":"contains","source":2481,"target":2735},{"edgeType":"contains","source":1065,"target":1178},{"edgeType":"contains","source":1062,"target":1271},{"edgeType":"calls","source":2726,"target":383},{"edgeType":"calls","source":1497,"target":427},{"edgeType":"calls","source":3603,"target":1735},{"edgeType":"calls","source":3565,"target":1856},{"edgeType":"calls","source":4740,"target":315},{"edgeType":"calls","source":4687,"target":901},{"edgeType":"calls","source":4800,"target":569},{"edgeType":"calls","source":1695,"target":631},{"edgeType":"contains","source":3175,"target":249},{"edgeType":"calls","source":1497,"target":426},{"edgeType":"calls","source":4847,"target":2282},{"edgeType":"calls","source":2726,"target":384},{"edgeType":"calls","source":2760,"target":387},{"edgeType":"contains","source":2255,"target":3400},{"edgeType":"calls","source":4800,"target":568},{"edgeType":"calls","source":3270,"target":1489},{"edgeType":"imports","source":3050,"target":689},{"edgeType":"contains","source":3573,"target":3766},{"edgeType":"contains","source":2092,"target":2108},{"edgeType":"calls","source":2654,"target":498},{"edgeType":"calls","source":4622,"target":1856},{"edgeType":"contains","source":4302,"target":4420},{"edgeType":"contains","source":2948,"target":3055},{"edgeType":"calls","source":672,"target":636},{"edgeType":"imports","source":2923,"target":1454},{"edgeType":"calls","source":2754,"target":570},{"edgeType":"calls","source":2760,"target":384},{"edgeType":"calls","source":3627,"target":2046},{"edgeType":"contains","source":2353,"target":2473},{"edgeType":"calls","source":4766,"target":564},{"edgeType":"calls","source":4800,"target":567},{"edgeType":"calls","source":792,"target":87},{"edgeType":"calls","source":1728,"target":667},{"edgeType":"contains","source":2092,"target":2109},{"edgeType":"calls","source":3872,"target":1852},{"edgeType":"calls","source":3909,"target":705},{"edgeType":"contains","source":4302,"target":4419},{"edgeType":"calls","source":4567,"target":389},{"edgeType":"calls","source":4702,"target":1489},{"edgeType":"imports","source":3710,"target":326},{"edgeType":"contains","source":3115,"target":1050},{"edgeType":"contains","source":803,"target":845},{"edgeType":"calls","source":1371,"target":106},{"edgeType":"calls","source":2754,"target":571},{"edgeType":"calls","source":2726,"target":382},{"edgeType":"calls","source":2760,"target":385},{"edgeType":"contains","source":2353,"target":2474},{"edgeType":"calls","source":4805,"target":411},{"edgeType":"calls","source":4800,"target":566},{"edgeType":"calls","source":3327,"target":777},{"edgeType":"calls","source":789,"target":179},{"edgeType":"calls","source":4650,"target":986},{"edgeType":"contains","source":6,"target":1243},{"edgeType":"calls","source":4768,"target":499},{"edgeType":"calls","source":4778,"target":189},{"edgeType":"calls","source":2754,"target":567},{"edgeType":"calls","source":4567,"target":388},{"edgeType":"calls","source":4226,"target":388},{"edgeType":"calls","source":2321,"target":249},{"edgeType":"calls","source":2754,"target":568},{"edgeType":"calls","source":4875,"target":354},{"edgeType":"calls","source":2760,"target":382},{"edgeType":"contains","source":3447,"target":3449},{"edgeType":"calls","source":3414,"target":191},{"edgeType":"contains","source":1485,"target":1905},{"edgeType":"imports","source":3066,"target":206},{"edgeType":"calls","source":1166,"target":1170},{"edgeType":"calls","source":4670,"target":365},{"edgeType":"calls","source":1972,"target":496},{"edgeType":"contains","source":6,"target":1242},{"edgeType":"calls","source":4872,"target":445},{"edgeType":"calls","source":4138,"target":1003},{"edgeType":"calls","source":4567,"target":387},{"edgeType":"calls","source":4226,"target":389},{"edgeType":"contains","source":621,"target":1204},{"edgeType":"calls","source":2239,"target":1735},{"edgeType":"contains","source":3050,"target":3071},{"edgeType":"calls","source":2793,"target":417},{"edgeType":"calls","source":2754,"target":569},{"edgeType":"calls","source":4872,"target":446},{"edgeType":"calls","source":4875,"target":353},{"edgeType":"calls","source":2760,"target":383},{"edgeType":"imports","source":32,"target":185},{"edgeType":"calls","source":3789,"target":194},{"edgeType":"contains","source":1485,"target":1906},{"edgeType":"calls","source":3354,"target":995},{"edgeType":"contains","source":3447,"target":3448},{"edgeType":"calls","source":4730,"target":1675},{"edgeType":"calls","source":4613,"target":4245},{"edgeType":"imports","source":1648,"target":1881},{"edgeType":"calls","source":1735,"target":447},{"edgeType":"calls","source":3837,"target":3989},{"edgeType":"contains","source":4600,"target":4700},{"edgeType":"calls","source":4567,"target":386},{"edgeType":"calls","source":4518,"target":1905},{"edgeType":"calls","source":4164,"target":194},{"edgeType":"calls","source":4226,"target":386},{"edgeType":"imports","source":4234,"target":2038},{"edgeType":"contains","source":2353,"target":2477},{"edgeType":"calls","source":1497,"target":425},{"edgeType":"calls","source":724,"target":77},{"edgeType":"calls","source":4889,"target":2032},{"edgeType":"calls","source":4769,"target":4695},{"edgeType":"contains","source":2715,"target":2884},{"edgeType":"calls","source":1880,"target":179},{"edgeType":"contains","source":16,"target":934},{"edgeType":"calls","source":2754,"target":566},{"edgeType":"calls","source":4567,"target":385},{"edgeType":"calls","source":4519,"target":1873},{"edgeType":"calls","source":2732,"target":191},{"edgeType":"calls","source":4226,"target":387},{"edgeType":"calls","source":4074,"target":4042},{"edgeType":"calls","source":2321,"target":248},{"edgeType":"calls","source":4667,"target":456},{"edgeType":"calls","source":3661,"target":2046},{"edgeType":"calls","source":2793,"target":415},{"edgeType":"calls","source":1689,"target":814},{"edgeType":"calls","source":3338,"target":1489},{"edgeType":"calls","source":1972,"target":493},{"edgeType":"calls","source":4846,"target":191},{"edgeType":"calls","source":4027,"target":211},{"edgeType":"calls","source":4226,"target":384},{"edgeType":"calls","source":776,"target":572},{"edgeType":"calls","source":2713,"target":777},{"edgeType":"calls","source":618,"target":185},{"edgeType":"calls","source":4567,"target":384},{"edgeType":"calls","source":2323,"target":183},{"edgeType":"calls","source":978,"target":653},{"edgeType":"calls","source":1839,"target":387},{"edgeType":"calls","source":3816,"target":3580},{"edgeType":"calls","source":1972,"target":492},{"edgeType":"calls","source":3272,"target":2476},{"edgeType":"calls","source":4770,"target":1489},{"edgeType":"calls","source":3837,"target":3988},{"edgeType":"calls","source":4027,"target":212},{"edgeType":"calls","source":4226,"target":385},{"edgeType":"calls","source":4582,"target":975},{"edgeType":"calls","source":644,"target":435},{"edgeType":"calls","source":2309,"target":1675},{"edgeType":"calls","source":776,"target":571},{"edgeType":"calls","source":4567,"target":383},{"edgeType":"contains","source":1485,"target":1910},{"edgeType":"calls","source":2178,"target":451},{"edgeType":"contains","source":1636,"target":3571},{"edgeType":"calls","source":1839,"target":386},{"edgeType":"contains","source":4600,"target":4704},{"edgeType":"calls","source":1972,"target":495},{"edgeType":"calls","source":4226,"target":382},{"edgeType":"calls","source":4567,"target":382},{"edgeType":"calls","source":4654,"target":1913},{"edgeType":"calls","source":2256,"target":2258},{"edgeType":"imports","source":3643,"target":1337},{"edgeType":"imports","source":3685,"target":35},{"edgeType":"contains","source":3447,"target":3451},{"edgeType":"contains","source":1485,"target":1907},{"edgeType":"calls","source":512,"target":301},{"edgeType":"calls","source":1839,"target":389},{"edgeType":"calls","source":1972,"target":494},{"edgeType":"calls","source":4226,"target":383},{"edgeType":"imports","source":3701,"target":1654},{"edgeType":"calls","source":4634,"target":1475},{"edgeType":"calls","source":2667,"target":88},{"edgeType":"contains","source":1516,"target":2004},{"edgeType":"contains","source":1062,"target":1280},{"edgeType":"calls","source":1735,"target":441},{"edgeType":"calls","source":1839,"target":388},{"edgeType":"contains","source":1485,"target":1908},{"edgeType":"calls","source":3857,"target":194},{"edgeType":"contains","source":3447,"target":3450},{"edgeType":"contains","source":1160,"target":1384},{"edgeType":"calls","source":1973,"target":491},{"edgeType":"calls","source":4227,"target":382},{"edgeType":"calls","source":771,"target":756},{"edgeType":"contains","source":2353,"target":2455},{"edgeType":"calls","source":407,"target":413},{"edgeType":"contains","source":340,"target":378},{"edgeType":"contains","source":3710,"target":3727},{"edgeType":"calls","source":724,"target":99},{"edgeType":"contains","source":2201,"target":824},{"edgeType":"calls","source":817,"target":387},{"edgeType":"contains","source":1485,"target":1880},{"edgeType":"contains","source":3573,"target":3746},{"edgeType":"calls","source":4517,"target":906},{"edgeType":"contains","source":770,"target":789},{"edgeType":"calls","source":2323,"target":212},{"edgeType":"calls","source":308,"target":311},{"edgeType":"contains","source":1529,"target":1573},{"edgeType":"calls","source":1493,"target":572},{"edgeType":"contains","source":621,"target":1179},{"edgeType":"calls","source":3151,"target":3085},{"edgeType":"calls","source":4227,"target":383},{"edgeType":"imports","source":4234,"target":2029},{"edgeType":"contains","source":341,"target":346},{"edgeType":"calls","source":817,"target":386},{"edgeType":"calls","source":724,"target":98},{"edgeType":"calls","source":4881,"target":191},{"edgeType":"calls","source":3032,"target":1489},{"edgeType":"calls","source":3124,"target":1808},{"edgeType":"contains","source":1529,"target":1574},{"edgeType":"calls","source":1497,"target":447},{"edgeType":"calls","source":1493,"target":571},{"edgeType":"calls","source":1973,"target":493},{"edgeType":"calls","source":2692,"target":398},{"edgeType":"contains","source":341,"target":349},{"edgeType":"calls","source":1050,"target":566},{"edgeType":"calls","source":4716,"target":1077},{"edgeType":"calls","source":407,"target":415},{"edgeType":"calls","source":817,"target":389},{"edgeType":"calls","source":771,"target":758},{"edgeType":"calls","source":724,"target":101},{"edgeType":"contains","source":803,"target":825},{"edgeType":"calls","source":4466,"target":1428},{"edgeType":"contains","source":1529,"target":1571},{"edgeType":"calls","source":4540,"target":191},{"edgeType":"calls","source":3892,"target":194},{"edgeType":"calls","source":4046,"target":705},{"edgeType":"imports","source":1918,"target":886},{"edgeType":"calls","source":2748,"target":777},{"edgeType":"calls","source":1973,"target":492},{"edgeType":"calls","source":2085,"target":191},{"edgeType":"calls","source":3367,"target":1672},{"edgeType":"calls","source":407,"target":414},{"edgeType":"calls","source":1133,"target":106},{"edgeType":"contains","source":341,"target":348},{"edgeType":"contains","source":2356,"target":2361},{"edgeType":"calls","source":4716,"target":1076},{"edgeType":"calls","source":724,"target":100},{"edgeType":"calls","source":817,"target":388},{"edgeType":"calls","source":771,"target":757},{"edgeType":"contains","source":1529,"target":1572},{"edgeType":"calls","source":338,"target":439},{"edgeType":"calls","source":2323,"target":211},{"edgeType":"calls","source":3737,"target":772},{"edgeType":"calls","source":2726,"target":2513},{"edgeType":"contains","source":3115,"target":1035},{"edgeType":"calls","source":1493,"target":568},{"edgeType":"calls","source":817,"target":383},{"edgeType":"calls","source":985,"target":460},{"edgeType":"calls","source":1808,"target":316},{"edgeType":"contains","source":2976,"target":3229},{"edgeType":"imports","source":396,"target":498},{"edgeType":"contains","source":4600,"target":4681},{"edgeType":"calls","source":817,"target":382},{"edgeType":"calls","source":4304,"target":106},{"edgeType":"calls","source":3361,"target":1856},{"edgeType":"calls","source":1493,"target":567},{"edgeType":"contains","source":2353,"target":2460},{"edgeType":"calls","source":3748,"target":3600},{"edgeType":"calls","source":1808,"target":315},{"edgeType":"calls","source":1728,"target":1738},{"edgeType":"imports","source":1918,"target":1940},{"edgeType":"contains","source":2026,"target":2027},{"edgeType":"calls","source":1949,"target":1229},{"edgeType":"contains","source":4600,"target":4680},{"edgeType":"calls","source":4112,"target":772},{"edgeType":"contains","source":2647,"target":2859},{"edgeType":"calls","source":2050,"target":1273},{"edgeType":"calls","source":2813,"target":2985},{"edgeType":"calls","source":543,"target":423},{"edgeType":"calls","source":1493,"target":570},{"edgeType":"calls","source":817,"target":385},{"edgeType":"calls","source":773,"target":692},{"edgeType":"calls","source":1167,"target":106},{"edgeType":"contains","source":1918,"target":2200},{"edgeType":"contains","source":11,"target":13},{"edgeType":"imports","source":1918,"target":1939},{"edgeType":"contains","source":1529,"target":1575},{"edgeType":"calls","source":4492,"target":1675},{"edgeType":"calls","source":4059,"target":298},{"edgeType":"contains","source":2647,"target":2856},{"edgeType":"calls","source":1974,"target":457},{"edgeType":"calls","source":2887,"target":692},{"edgeType":"calls","source":4854,"target":4193},{"edgeType":"calls","source":1301,"target":179},{"edgeType":"calls","source":1493,"target":569},{"edgeType":"calls","source":4793,"target":1856},{"edgeType":"calls","source":817,"target":384},{"edgeType":"calls","source":779,"target":505},{"edgeType":"contains","source":11,"target":12},{"edgeType":"contains","source":2092,"target":2093},{"edgeType":"calls","source":1808,"target":317},{"edgeType":"contains","source":1529,"target":1576},{"edgeType":"calls","source":407,"target":410},{"edgeType":"calls","source":4714,"target":77},{"edgeType":"contains","source":2975,"target":3259},{"edgeType":"extends","source":1962,"target":1874},{"edgeType":"calls","source":2319,"target":331},{"edgeType":"calls","source":4330,"target":354},{"edgeType":"imports","source":2201,"target":564},{"edgeType":"calls","source":1974,"target":456},{"edgeType":"calls","source":921,"target":326},{"edgeType":"calls","source":747,"target":435},{"edgeType":"calls","source":2728,"target":2447},{"edgeType":"contains","source":3017,"target":3020},{"edgeType":"calls","source":3340,"target":388},{"edgeType":"calls","source":1133,"target":1153},{"edgeType":"calls","source":1728,"target":1735},{"edgeType":"contains","source":11,"target":15},{"edgeType":"calls","source":2323,"target":2318},{"edgeType":"calls","source":4452,"target":1856},{"edgeType":"contains","source":4302,"target":4410},{"edgeType":"calls","source":4210,"target":1957},{"edgeType":"calls","source":4330,"target":353},{"edgeType":"calls","source":312,"target":179},{"edgeType":"contains","source":3017,"target":3021},{"edgeType":"calls","source":2887,"target":690},{"edgeType":"calls","source":747,"target":434},{"edgeType":"imports","source":1918,"target":1952},{"edgeType":"calls","source":921,"target":325},{"edgeType":"contains","source":2951,"target":2953},{"edgeType":"calls","source":3340,"target":389},{"edgeType":"contains","source":11,"target":14},{"edgeType":"calls","source":4024,"target":325},{"edgeType":"contains","source":2092,"target":2099},{"edgeType":"contains","source":4600,"target":4684},{"edgeType":"contains","source":4302,"target":4409},{"edgeType":"calls","source":638,"target":642},{"edgeType":"calls","source":4526,"target":1675},{"edgeType":"calls","source":4307,"target":1063},{"edgeType":"calls","source":1493,"target":566},{"edgeType":"calls","source":3583,"target":3423},{"edgeType":"calls","source":1497,"target":1499},{"edgeType":"calls","source":2812,"target":1955},{"edgeType":"calls","source":2846,"target":901},{"edgeType":"contains","source":3017,"target":3018},{"edgeType":"calls","source":3839,"target":772},{"edgeType":"calls","source":1329,"target":365},{"edgeType":"calls","source":3340,"target":386},{"edgeType":"calls","source":378,"target":249},{"edgeType":"calls","source":3340,"target":385},{"edgeType":"contains","source":637,"target":694},{"edgeType":"calls","source":4677,"target":3335},{"edgeType":"calls","source":4012,"target":3865},{"edgeType":"contains","source":16,"target":919},{"edgeType":"calls","source":4841,"target":365},{"edgeType":"calls","source":4468,"target":301},{"edgeType":"calls","source":1497,"target":441},{"edgeType":"contains","source":3017,"target":3019},{"edgeType":"calls","source":789,"target":191},{"edgeType":"calls","source":2846,"target":902},{"edgeType":"calls","source":3340,"target":387},{"edgeType":"calls","source":378,"target":248},{"edgeType":"calls","source":4093,"target":298},{"edgeType":"contains","source":2092,"target":2097},{"edgeType":"calls","source":4108,"target":4061},{"edgeType":"contains","source":803,"target":832},{"edgeType":"calls","source":4642,"target":191},{"edgeType":"contains","source":2647,"target":2861},{"edgeType":"contains","source":4302,"target":4414},{"edgeType":"contains","source":2975,"target":3269},{"edgeType":"contains","source":3017,"target":3024},{"edgeType":"calls","source":1844,"target":249},{"edgeType":"calls","source":3525,"target":991},{"edgeType":"calls","source":3340,"target":383},{"edgeType":"calls","source":3292,"target":1871},{"edgeType":"imports","source":3162,"target":2495},{"edgeType":"contains","source":2092,"target":2102},{"edgeType":"calls","source":4606,"target":249},{"edgeType":"calls","source":3640,"target":1655},{"edgeType":"calls","source":3583,"target":3422},{"edgeType":"calls","source":2247,"target":1499},{"edgeType":"calls","source":2813,"target":2980},{"edgeType":"calls","source":2846,"target":900},{"edgeType":"calls","source":1844,"target":248},{"edgeType":"contains","source":3017,"target":3025},{"edgeType":"calls","source":3495,"target":865},{"edgeType":"calls","source":3340,"target":384},{"edgeType":"calls","source":3333,"target":1658},{"edgeType":"contains","source":2092,"target":2103},{"edgeType":"calls","source":4864,"target":1763},{"edgeType":"contains","source":2488,"target":2511},{"edgeType":"contains","source":4302,"target":4413},{"edgeType":"calls","source":4606,"target":248},{"edgeType":"contains","source":4234,"target":4407},{"edgeType":"contains","source":3017,"target":3022},{"edgeType":"calls","source":4335,"target":191},{"edgeType":"contains","source":2948,"target":3047},{"edgeType":"calls","source":985,"target":454},{"edgeType":"calls","source":3946,"target":622},{"edgeType":"calls","source":3674,"target":1655},{"edgeType":"calls","source":4748,"target":1130},{"edgeType":"calls","source":4028,"target":194},{"edgeType":"calls","source":1128,"target":249},{"edgeType":"calls","source":4178,"target":4000},{"edgeType":"contains","source":2092,"target":2100},{"edgeType":"calls","source":4685,"target":969},{"edgeType":"calls","source":2726,"target":389},{"edgeType":"calls","source":4520,"target":1856},{"edgeType":"contains","source":4302,"target":4412},{"edgeType":"contains","source":2948,"target":3048},{"edgeType":"contains","source":3017,"target":3023},{"edgeType":"contains","source":3643,"target":3699},{"edgeType":"calls","source":3847,"target":3692},{"edgeType":"calls","source":3786,"target":298},{"edgeType":"contains","source":3345,"target":3424},{"edgeType":"calls","source":3340,"target":382},{"edgeType":"calls","source":1128,"target":248},{"edgeType":"calls","source":4594,"target":1675},{"edgeType":"calls","source":638,"target":640},{"edgeType":"contains","source":4600,"target":4686},{"edgeType":"contains","source":4302,"target":4411}],"nodes":[{"groupName":"","id":3,"nodeType":"Repo","repoName":"mwaskom#seaborn#54cab15bdacfaa05a88fbc5502a5b322d99f148e"},{"id":6,"name":"doc/_docstrings","nodeType":"Package"},{"id":9,"name":"countplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2fdf0f63-d515-4cb8-b3e0-62cac7852b12\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"5adcc785-6643-4c55-ba38-ac9b65857932\",\n \"metadata\": {},\n \"source\": [\n \"Show the number of datapoints with each value of a categorical variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6e9d0485-870d-4841-9c84-6e0bacbde7db\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"df = sns.load_dataset(\\\"titanic\\\")\\n\",\n \"sns.countplot(x=df[\\\"class\\\"])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"c2e36b42-5453-4478-918b-3699ac1fbc0e\",\n \"metadata\": {},\n \"source\": [\n \"Group by a second variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"26f73c00-a2b3-45c3-b3cd-2babe0a81894\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.countplot(data=df, x=\\\"class\\\", hue=\\\"alive\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"eac30be1-c9d8-472c-afa9-16119afab86e\",\n \"metadata\": {},\n \"source\": [\n \"Plot horizontally to make more space for category labels:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"31758c56-106e-4a9c-bcee-ef1f93f472e8\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.countplot(data=df, y=\\\"deck\\\", hue=\\\"alive\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5c049d0c-d91b-4675-a9aa-7deea1421d68\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":10,"name":"set_context.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"thorough-equipment\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"canadian-protection\",\n \"metadata\": {},\n \"source\": [\n \"Call the function with the name of a context to set the default for all plots:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"freelance-leonard\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"notebook\\\")\\n\",\n \"sns.lineplot(x=[0, 1, 2], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"studied-adventure\",\n \"metadata\": {},\n \"source\": [\n \"You can independently scale the font elements relative to the current context:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"irish-digest\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"notebook\\\", font_scale=1.25)\\n\",\n \"sns.lineplot(x=[0, 1, 2], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"fourth-technical\",\n \"metadata\": {},\n \"source\": [\n \"It is also possible to override some of the parameters with specific values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"advance-request\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"notebook\\\", rc={\\\"lines.linewidth\\\": 3})\\n\",\n \"sns.lineplot(x=[0, 1, 2], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"compatible-string\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":11,"name":"doc/_tutorial","nodeType":"Package"},{"id":12,"name":"objects_interface.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"id\": \"35110bb9-6889-4bd5-b9d6-5a0479131433\",\n \"metadata\": {},\n \"source\": [\n \".. _objects_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn.objects\\n\",\n \"\\n\",\n \"The seaborn.objects interface\\n\",\n \"=============================\\n\",\n \"\\n\",\n \"The `seaborn.objects` namespace was introduced in version 0.12 as a completely new interface for making seaborn plots. It offers a more consistent and flexible API, comprising a collection of composable classes for transforming and plotting data. In contrast to the existing `seaborn` functions, the new interface aims to support end-to-end plot specification and customization without dropping down to matplotlib (although it will remain possible to do so if necessary).\\n\",\n \"\\n\",\n \".. note::\\n\",\n \" The objects interface is currently experimental and incomplete. It is stable enough for serious use, but there certainly are some rough edges and missing features.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"706badfa-58be-4808-9016-bd0ca3ebaf12\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"import matplotlib as mpl\\n\",\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"penguins = sns.load_dataset(\\\"penguins\\\").dropna()\\n\",\n \"diamonds = sns.load_dataset(\\\"diamonds\\\")\\n\",\n \"healthexp = sns.load_dataset(\\\"healthexp\\\").sort_values([\\\"Country\\\", \\\"Year\\\"]).query(\\\"Year <= 2020\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dd1ceae5-f930-41c2-8a18-f3cf94a161ad\",\n \"metadata\": {},\n \"source\": [\n \"Specifying a plot and mapping data\\n\",\n \"----------------------------------\\n\",\n \"\\n\",\n \"The objects interface should be imported with the following convention:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1c113156-20ad-4612-a9f5-0071d7fd35dd\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"6518484e-828b-4e7c-8529-ed6c9e61fa69\",\n \"metadata\": {},\n \"source\": [\n \"The `seaborn.objects` namespace will provide access to all of the relevant classes. The most important is :class:`Plot`. You specify plots by instantiating a :class:`Plot` object and calling its methods. Let's see a simple example:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2e7f8ad0-9831-464b-9825-60733f110f34\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \" .add(so.Dot())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"52785052-6c80-4f35-87e4-b27df499bd5c\",\n \"metadata\": {},\n \"source\": [\n \"This code, which produces a scatter plot, should look reasonably familiar. Just as when using :func:`seaborn.scatterplot`, we passed a tidy dataframe (`penguins`) and assigned two of its columns to the `x` and `y` coordinates of the plot. But instead of starting with the type of chart and then adding some data assignments, here we started with the data assignments and then added a graphical element.\\n\",\n \"\\n\",\n \"Setting properties\\n\",\n \"~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The :class:`Dot` class is an example of a :class:`Mark`: an object that graphically represents data values. Each mark will have a number of properties that can be set to change its appearance:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"310bac42-cfe4-4c45-9ddf-27c2cb200a8a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \" .add(so.Dot(color=\\\"g\\\", pointsize=4))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3f817822-dd96-4263-a42e-824f9ca4083a\",\n \"metadata\": {},\n \"source\": [\n \"Mapping properties\\n\",\n \"~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"As with seaborn's functions, it is also possible to *map* data values to various graphical properties:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6267e411-1f75-461e-a189-ead4452b2ec6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(\\n\",\n \" penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n \" color=\\\"species\\\", pointsize=\\\"body_mass_g\\\",\\n\",\n \" )\\n\",\n \" .add(so.Dot())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b6bfc0bf-cae1-44ed-9f52-e9f748c3877d\",\n \"metadata\": {},\n \"source\": [\n \"While this basic functionality is not novel, an important difference from the function API is that properties are mapped using the same parameter names that would set them directly (instead of having `hue` vs. `color`, etc.). What matters is *where* the property is defined: passing a value when you initialize :class:`Dot` will set it directly, whereas assigning a variable when you set up the :class:`Plot` will *map* the corresponding data.\\n\",\n \"\\n\",\n \"Beyond this difference, the objects interface also allows a much wider range of mark properties to be mapped:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b8637528-4e17-4a41-be1c-2cb4275a5586\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(\\n\",\n \" penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n \" edgecolor=\\\"sex\\\", edgewidth=\\\"body_mass_g\\\",\\n\",\n \" )\\n\",\n \" .add(so.Dot(color=\\\".8\\\"))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"220930c4-410c-4452-a89e-95045f325cc0\",\n \"metadata\": {},\n \"source\": [\n \"Defining groups\\n\",\n \"~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The :class:`Dot` mark represents each data point independently, so the assignment of a variable to a property only has the effect of changing each dot's appearance. For marks that group or connect observations, such as :class:`Line`, it also determines the number of distinct graphical elements:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"95f892e1-8adc-43d3-8b30-84d8c848040a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(healthexp, x=\\\"Year\\\", y=\\\"Life_Expectancy\\\", color=\\\"Country\\\")\\n\",\n \" .add(so.Line())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"6665552c-674b-405e-a3ee-237517649349\",\n \"metadata\": {},\n \"source\": [\n \"It is also possible to define a grouping without changing any visual properties, by using `group`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f9287beb-7a66-4dcb-bccf-9c5cab2790f4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(healthexp, x=\\\"Year\\\", y=\\\"Life_Expectancy\\\", group=\\\"Country\\\")\\n\",\n \" .add(so.Line())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"be097dfa-e33c-41f5-8b5a-09013cb33e6e\",\n \"metadata\": {},\n \"source\": [\n \"Transforming data before plotting\\n\",\n \"---------------------------------\\n\",\n \"\\n\",\n \"Statistical transformation\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"As with many seaborn functions, the objects interface supports statistical transformations. These are performed by :class:`Stat` objects, such as :class:`Agg`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"0964d2af-ce53-48b5-b79a-3277b05584dd\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\")\\n\",\n \" .add(so.Bar(), so.Agg())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5ac229b2-3692-4d35-8ba3-e35262f198ce\",\n \"metadata\": {},\n \"source\": [\n \"In the function interface, statistical transformations are possible with some visual representations (e.g. :func:`seaborn.barplot`) but not others (e.g. :func:`seaborn.scatterplot`). The objects interface more cleanly separates representation and transformation, allowing you to compose :class:`Mark` and :class:`Stat` objects:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5c2f917d-1cb7-4d33-b8c4-2126a4f91ccc\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\")\\n\",\n \" .add(so.Dot(pointsize=10), so.Agg())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1b9d7688-22f5-4f4a-b58e-71d8ff550b48\",\n \"metadata\": {},\n \"source\": [\n \"When forming groups by mapping properties, the :class:`Stat` transformation is applied to each group separately:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"734f9dac-4663-4e51-8070-716c0c0296c6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Dot(pointsize=10), so.Agg())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e60a8e83-c34c-4769-b34f-e0c23c80b870\",\n \"metadata\": {},\n \"source\": [\n \"Resolving overplotting\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Some seaborn functions also have mechanisms that automatically resolve overplotting, as when :func:`seaborn.barplot` \\\"dodges\\\" bars once `hue` is assigned. The objects interface has less complex default behavior. Bars representing multiple groups will overlap by default:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"96653815-7da3-4a77-877a-485b5e7578a4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Bar(), so.Agg())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"06ee3b9f-0ae9-467f-8a40-e340e6f3ce7d\",\n \"metadata\": {},\n \"source\": [\n \"Nevertheless, it is possible to compose the :class:`Bar` mark with the :class:`Agg` stat and a second transformation, implemented by :class:`Dodge`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e29792ae-c238-4538-952a-5af81adcefe0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Bar(), so.Agg(), so.Dodge())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a27dcb37-be58-427b-a722-9039b91b6503\",\n \"metadata\": {},\n \"source\": [\n \"The :class:`Dodge` class is an example of a :class:`Move` transformation, which is like a :class:`Stat` but only adjusts `x` and `y` coordinates. The :class:`Move` classes can be applied with any mark, and it's not necessary to use a :class:`Stat` first:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c4509ea7-36fe-4ffb-b784-e945d13fb93c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Dot(), so.Dodge())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a62e44ae-d6e7-4ab5-af2e-7b49a2031b1d\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to apply multiple :class:`Move` operations in sequence:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"07536818-9ddd-46d1-b10c-b034fa257335\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\", y=\\\"body_mass_g\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Dot(), so.Dodge(), so.Jitter(.3))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fd8ed5cc-6ba4-4d03-8414-57a782971d4c\",\n \"metadata\": {},\n \"source\": [\n \"Creating variables through transformation\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The :class:`Agg` stat requires both `x` and `y` to already be defined, but variables can also be *created* through statistical transformation. For example, the :class:`Hist` stat requires only one of `x` *or* `y` to be defined, and it will create the other by counting observations:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4b1f2c61-d294-4a85-a383-384d92523c36\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"species\\\")\\n\",\n \" .add(so.Bar(), so.Hist())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"9b33ea0c-f11d-48d7-be7c-13e9993906d8\",\n \"metadata\": {},\n \"source\": [\n \"The :class:`Hist` stat will also create new `x` values (by binning) when given numeric data:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"25123abd-75d4-4550-ac86-5281fdabc023\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"flipper_length_mm\\\")\\n\",\n \" .add(so.Bars(), so.Hist())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0dd84c56-eeb3-4904-b957-1677eaebd33c\",\n \"metadata\": {},\n \"source\": [\n \"Notice how we used :class:`Bars`, rather than :class:`Bar` for the plot with the continuous `x` axis. These two marks are related, but :class:`Bars` has different defaults and works better for continuous histograms. It also produces a different, more efficient matplotlib artist. You will find the pattern of singular/plural marks elsewhere. The plural version is typically optimized for cases with larger numbers of marks.\\n\",\n \"\\n\",\n \"Some transforms accept both `x` and `y`, but add *interval* data for each coordinate. This is particularly relevant for plotting error bars after aggregating:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6bc29e9d-d660-4638-80fd-8d77e15d9109\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"body_mass_g\\\", y=\\\"species\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Range(), so.Est(errorbar=\\\"sd\\\"), so.Dodge())\\n\",\n \" .add(so.Dot(), so.Agg(), so.Dodge())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3aecc891-1abb-45b2-bf15-c6944820b242\",\n \"metadata\": {},\n \"source\": [\n \"Orienting marks and transforms\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"When aggregating, dodging, and drawing a bar, the `x` and `y` variables are treated differently. Each operation has the concept of an *orientation*. The :class:`Plot` tries to determine the orientation automatically based on the data types of the variables. For instance, if we flip the assignment of `species` and `body_mass_g`, we'll get the same plot, but oriented horizontally:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1dd7ebeb-893e-4d27-aeaf-a8ff0cd2cc15\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"body_mass_g\\\", y=\\\"species\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Bar(), so.Agg(), so.Dodge())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"382603cb-9ae9-46ed-bceb-b48456781092\",\n \"metadata\": {},\n \"source\": [\n \"Sometimes, the correct orientation is ambiguous, as when both the `x` and `y` variables are numeric. In these cases, you can be explicit by passing the `orient` parameter to :meth:`Plot.add`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"75277dda-47c4-443c-9454-b8d97fc399e2\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, x=\\\"total_bill\\\", y=\\\"size\\\", color=\\\"time\\\")\\n\",\n \" .add(so.Bar(), so.Agg(), so.Dodge(), orient=\\\"y\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dc845c14-03e5-495d-9dc8-3a90f7879346\",\n \"metadata\": {},\n \"source\": [\n \"Building and displaying the plot\\n\",\n \"--------------------------------\\n\",\n \"\\n\",\n \"Each example thus far has produced a single subplot with a single kind of mark on it. But :class:`Plot` does not limit you to this.\\n\",\n \"\\n\",\n \"Adding multiple layers\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"More complex single-subplot graphics can be created by calling :meth:`Plot.add` repeatedly. Each time it is called, it defines a *layer* in the plot. For example, we may want to add a scatterplot (now using :class:`Dots`) and then a regression fit:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"922b6d3d-7a81-4921-97f2-953a1fbc69ec\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .add(so.Line(), so.PolyFit())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f0309733-a86a-4952-bc3b-533d639f0b52\",\n \"metadata\": {},\n \"source\": [\n \"Variable mappings that are defined in the :class:`Plot` constructor will be used for all layers:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"604d16b9-383b-4b88-9ed7-fdefed55039a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, x=\\\"total_bill\\\", y=\\\"tip\\\", color=\\\"time\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .add(so.Line(), so.PolyFit())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"eb56fb8d-aaa3-4b6e-b311-0354562174b5\",\n \"metadata\": {},\n \"source\": [\n \"Layer-specific mappings\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"You can also define a mapping such that it is used only in a specific layer. This is accomplished by defining the mapping within the call to :class:`Plot.add` for the relevant layer:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f69a3a38-97e8-40fb-b7d4-95a751ebdcfb\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \" .add(so.Dots(), color=\\\"time\\\")\\n\",\n \" .add(so.Line(color=\\\".2\\\"), so.PolyFit())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b3f94f01-23d4-4f7a-98f8-de93dafc230a\",\n \"metadata\": {},\n \"source\": [\n \"Alternatively, define the layer for the entire plot, but *remove* it from a specific layer by setting the variable to `None`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"45706bec-3453-4a7e-9ac7-c743baff4da6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, x=\\\"total_bill\\\", y=\\\"tip\\\", color=\\\"time\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .add(so.Line(color=\\\".2\\\"), so.PolyFit(), color=None)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"295013b3-7d91-4a59-b63b-fe50e642954c\",\n \"metadata\": {},\n \"source\": [\n \"To recap, there are three ways to specify the value of a mark property: (1) by mapping a variable in all layers, (2) by mapping a variable in a specific layer, and (3) by setting the property directy:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2341eafd-4d6f-4530-835a-a409d2057d74\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"from io import StringIO\\n\",\n \"from IPython.display import SVG\\n\",\n \"C = sns.color_palette(\\\"deep\\\")\\n\",\n \"f = mpl.figure.Figure(figsize=(7, 3))\\n\",\n \"ax = f.subplots()\\n\",\n \"fontsize = 18\\n\",\n \"ax.add_artist(mpl.patches.Rectangle((.13, .53), .45, .09, color=C[0], alpha=.3))\\n\",\n \"ax.add_artist(mpl.patches.Rectangle((.22, .43), .235, .09, color=C[1], alpha=.3))\\n\",\n \"ax.add_artist(mpl.patches.Rectangle((.49, .43), .26, .09, color=C[2], alpha=.3))\\n\",\n \"ax.text(.05, .55, \\\"Plot(data, 'x', 'y', color='var1')\\\", size=fontsize, color=\\\".2\\\")\\n\",\n \"ax.text(.05, .45, \\\".add(Dot(pointsize=10), marker='var2')\\\", size=fontsize, color=\\\".2\\\")\\n\",\n \"annots = [\\n\",\n \" (\\\"Mapped\\\\nin all layers\\\", (.35, .65), (0, 45)),\\n\",\n \" (\\\"Set directly\\\", (.35, .4), (0, -45)),\\n\",\n \" (\\\"Mapped\\\\nin this layer\\\", (.63, .4), (0, -45)),\\n\",\n \"]\\n\",\n \"for i, (text, xy, xytext) in enumerate(annots):\\n\",\n \" ax.annotate(\\n\",\n \" text, xy, xytext,\\n\",\n \" textcoords=\\\"offset points\\\", fontsize=14, ha=\\\"center\\\", va=\\\"center\\\",\\n\",\n \" arrowprops=dict(arrowstyle=\\\"->\\\", color=C[i]), color=C[i],\\n\",\n \" )\\n\",\n \"ax.set_axis_off()\\n\",\n \"f.subplots_adjust(0, 0, 1, 1)\\n\",\n \"f.savefig(s:=StringIO(), format=\\\"svg\\\")\\n\",\n \"SVG(s.getvalue())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"cf2d8e39-d332-41f4-b327-2ac352878e58\",\n \"metadata\": {},\n \"source\": [\n \"Faceting and pairing subplots\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"As with seaborn's figure-level functions (:func:`seaborn.displot`, :func:`seaborn.catplot`, etc.), the :class:`Plot` interface can also produce figures with multiple \\\"facets\\\", or subplots containing subsets of data. This is accomplished with the :meth:`Plot.facet` method:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"af737dfd-1cb2-418d-9f52-1deb93154a92\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"flipper_length_mm\\\")\\n\",\n \" .facet(\\\"species\\\")\\n\",\n \" .add(so.Bars(), so.Hist())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"81c2a445-5ae1-4272-8a6c-8bfe1f3b907f\",\n \"metadata\": {},\n \"source\": [\n \"Call :meth:`Plot.facet` with the variables that should be used to define the columns and/or rows of the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b7b3495f-9a38-4976-b718-ce3672b8c186\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"flipper_length_mm\\\")\\n\",\n \" .facet(col=\\\"species\\\", row=\\\"sex\\\")\\n\",\n \" .add(so.Bars(), so.Hist())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"8b7fe085-acd2-46d2-81f6-a806dec338d3\",\n \"metadata\": {},\n \"source\": [\n \"You can facet using a variable with a larger number of levels by \\\"wrapping\\\" across the other dimension:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d62d2310-ae33-4b42-bdea-7b7456afd640\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(healthexp, x=\\\"Year\\\", y=\\\"Life_Expectancy\\\")\\n\",\n \" .facet(col=\\\"Country\\\", wrap=3)\\n\",\n \" .add(so.Line())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"86ecbeee-3ac2-41eb-b79e-9d6ed026061d\",\n \"metadata\": {},\n \"source\": [\n \"All layers will be faceted unless you explicitly exclude them, which can be useful for providing additional context on each subplot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c38be724-8564-4fa0-861c-1d96ffbbda20\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(healthexp, x=\\\"Year\\\", y=\\\"Life_Expectancy\\\")\\n\",\n \" .facet(\\\"Country\\\", wrap=3)\\n\",\n \" .add(so.Line(alpha=.3), group=\\\"Country\\\", col=None)\\n\",\n \" .add(so.Line(linewidth=3))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f97dad75-65e6-47fd-9fc4-08a8f2cb49ee\",\n \"metadata\": {},\n \"source\": [\n \"An alternate way to produce subplots is :meth:`Plot.pair`. Like :class:`seaborn.PairGrid`, this draws all of the data on each subplot, using different variables for the x and/or y coordinates:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d6350e99-2c70-4a96-87eb-74756a0fa335\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, y=\\\"body_mass_g\\\", color=\\\"species\\\")\\n\",\n \" .pair(x=[\\\"bill_length_mm\\\", \\\"bill_depth_mm\\\"])\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4deea650-b4b9-46ea-876c-2e5a3a258649\",\n \"metadata\": {},\n \"source\": [\n \"You can combine faceting and pairing so long as the operations add subplots on opposite dimensions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9de7948c-4c43-4116-956c-cbcb84d8652c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, y=\\\"body_mass_g\\\", color=\\\"species\\\")\\n\",\n \" .pair(x=[\\\"bill_length_mm\\\", \\\"bill_depth_mm\\\"])\\n\",\n \" .facet(row=\\\"sex\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0a0febe3-9daf-4271-aef9-9637d59aaf10\",\n \"metadata\": {},\n \"source\": [\n \"Integrating with matplotlib\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"There may be cases where you want multiple subplots to appear in a figure with a more complex structure than what :meth:`Plot.facet` or :meth:`Plot.pair` can provide. The current solution is to delegate figure setup to matplotlib and to supply the matplotlib object that :class:`Plot` should use with the :meth:`Plot.on` method. This object can be either a :class:`matplotlib.axes.Axes`, :class:`matplotlib.figure.Figure`, or :class:`matplotlib.figure.SubFigure`; the latter is most useful for constructing bespoke subplot layouts:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b046466d-f6c2-43fa-9ae9-f40a292a82b7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f = mpl.figure.Figure(figsize=(8, 4))\\n\",\n \"sf1, sf2 = f.subfigures(1, 2)\\n\",\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"body_mass_g\\\", y=\\\"flipper_length_mm\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .on(sf1)\\n\",\n \" .plot()\\n\",\n \")\\n\",\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"body_mass_g\\\")\\n\",\n \" .facet(row=\\\"sex\\\")\\n\",\n \" .add(so.Bars(), so.Hist())\\n\",\n \" .on(sf2)\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"7074f599-8b9f-4b77-9e15-55349592c747\",\n \"metadata\": {},\n \"source\": [\n \"Building and displaying the plot\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"An important thing to know is that :class:`Plot` methods clone the object they are called on and return that clone instead of updating the object in place. This means that you can define a common plot spec and then produce several variations on it.\\n\",\n \"\\n\",\n \"So, take this basic specification:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b79b2148-b867-4e96-9b84-b3fc44ad0c82\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(healthexp, \\\"Year\\\", \\\"Spending_USD\\\", color=\\\"Country\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"135f89e5-c41e-4c6c-9865-5413787bdc62\",\n \"metadata\": {},\n \"source\": [\n \"We could use it to draw a line plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"10722a20-dc8c-4421-a433-8ff21fed9495\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Line())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f9db1184-f352-41b8-a45a-02ff6eb85071\",\n \"metadata\": {},\n \"source\": [\n \"Or perhaps a stacked area plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ea2ad629-c718-44a9-92af-144728094cd5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Area(), so.Stack())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"17fb2676-6199-4a2c-9f10-3d5aebb7a285\",\n \"metadata\": {},\n \"source\": [\n \"The :class:`Plot` methods are fully declarative. Calling them updates the plot spec, but it doesn't actually do any plotting. One consequence of this is that methods can be called in any order, and many of them can be called multiple times.\\n\",\n \"\\n\",\n \"When does the plot actually get rendered? :class:`Plot` is optimized for use in notebook environments. The rendering is automatically triggered when the :class:`Plot` gets displayed in the Jupyter REPL. That's why we didn't see anything in the example above, where we defined a :class:`Plot` but assigned it to `p` rather than letting it return out to the REPL.\\n\",\n \"\\n\",\n \"To see a plot in a notebook, either return it from the final line of a cell or call Jupyter's built-in `display` function on the object. The notebook integration bypasses :mod:`matplotlib.pyplot` entirely, but you can use its figure-display machinery in other contexts by calling :meth:`Plot.show`.\\n\",\n \"\\n\",\n \"You can also save the plot to a file (or buffer) by calling :meth:`Plot.save`.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"abfa0384-af88-4409-a119-912601a14f13\",\n \"metadata\": {},\n \"source\": [\n \"Customizing the appearance\\n\",\n \"--------------------------\\n\",\n \"\\n\",\n \"The new interface aims to support a deep amount of customization through :class:`Plot`, reducing the need to switch gears and use matplotlib functionality directly. (But please be patient; not all of the features needed to achieve this goal have been implemented!)\\n\",\n \"\\n\",\n \"Parameterizing scales\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"All of the data-dependent properties are controlled by the concept of a :class:`Scale` and the :meth:`Plot.scale` method. This method accepts several different types of arguments. One possibility, which is closest to the use of scales in matplotlib, is to pass the name of a function that transforms the coordinates:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5acfe6d2-144a-462d-965b-2900fb619eac\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .scale(y=\\\"log\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"ccff884b-53cb-4c15-aab2-f5d4e5551d72\",\n \"metadata\": {},\n \"source\": [\n \":meth:`Plot.scale` can also control the mappings for semantic properties like `color`. You can directly pass it any argument that you would pass to the `palette` parameter in seaborn's function interface:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4f243a31-d7da-43d2-8dc4-aad1b584ff48\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\", color=\\\"clarity\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .scale(color=\\\"flare\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4fdf291e-a008-4a8e-8ced-a24f78d9b49f\",\n \"metadata\": {},\n \"source\": [\n \"Another option is to provide a tuple of `(min, max)` values, controlling the range that the scale should map into. This works both for numeric properties and for colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4cdc12ee-83f9-4472-b198-85bfe5cf0e4f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\", color=\\\"clarity\\\", pointsize=\\\"carat\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .scale(color=(\\\"#88c\\\", \\\"#555\\\"), pointsize=(2, 10))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e326bf46-a296-4997-8e91-6531a7eef304\",\n \"metadata\": {},\n \"source\": [\n \"For additional control, you can pass a :class:`Scale` object. There are several different types of :class:`Scale`, each with appropriate parameters. For example, :class:`Continuous` lets you define the input domain (`norm`), the output range (`values`), and the function that maps between them (`trans`), while :class:`Nominal` allows you to specify an ordering:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"53682db4-2ba4-4dfd-80c2-1fef466cfab2\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\", color=\\\"carat\\\", marker=\\\"cut\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .scale(\\n\",\n \" color=so.Continuous(\\\"crest\\\", norm=(0, 3), trans=\\\"sqrt\\\"),\\n\",\n \" marker=so.Nominal([\\\"o\\\", \\\"+\\\", \\\"x\\\"], order=[\\\"Ideal\\\", \\\"Premium\\\", \\\"Good\\\"]),\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"7bf112fe-136d-4e63-a397-1e7d2ff4f543\",\n \"metadata\": {},\n \"source\": [\n \"Customizing legends and ticks\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The :class:`Scale` objects are also how you specify which values should appear as tick labels / in the legend, along with how they appear. For example, the :meth:`Continuous.tick` method lets you control the density or locations of the ticks, and the :meth:`Continuous.label` method lets you modify the format:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4f8e821f-bd19-4af1-bb66-488593b3c968\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\", color=\\\"carat\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \" .scale(\\n\",\n \" x=so.Continuous().tick(every=0.5),\\n\",\n \" y=so.Continuous().label(like=\\\"${x:.0f}\\\"),\\n\",\n \" color=so.Continuous().tick(at=[1, 2, 3, 4]),\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4f6646c9-084b-49ae-ad6f-39c0bd12fc4e\",\n \"metadata\": {},\n \"source\": [\n \"Customizing limits, labels, and titles\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \":class:`Plot` has a number of methods for simple customization, including :meth:`Plot.label`, :meth:`Plot.limit`, and :meth:`Plot.share`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e9586669-35ea-4784-9594-ea375a06aec0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"body_mass_g\\\", y=\\\"species\\\", color=\\\"island\\\")\\n\",\n \" .facet(col=\\\"sex\\\")\\n\",\n \" .add(so.Dot(), so.Jitter(.5))\\n\",\n \" .share(x=False)\\n\",\n \" .limit(y=(2.5, -.5))\\n\",\n \" .label(\\n\",\n \" x=\\\"Body mass (g)\\\", y=\\\"\\\",\\n\",\n \" color=str.capitalize,\\n\",\n \" title=\\\"{} penguins\\\".format,\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3b38607a-9b41-49c0-8031-e05bc87701c8\",\n \"metadata\": {},\n \"source\": [\n \"Theme customization\\n\",\n \"~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Finally, :class:`Plot` supports data-independent theming through the :class:`Plot.theme` method. Currently, this method accepts a dictionary of matplotlib rc parameters. You can set them directly and/or pass a package of parameters from seaborn's theming functions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2df40831-fd41-4b76-90ff-042aecd694d4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"from seaborn import axes_style\\n\",\n \"so.Plot().theme({**axes_style(\\\"whitegrid\\\"), \\\"grid.linestyle\\\": \\\":\\\"})\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"8ac5e809-e4a0-4c08-b9c0-fa78bd93eb82\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":13,"name":"distributions.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _distribution_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Visualizing distributions of data\\n\",\n \"==================================\\n\",\n \"\\n\",\n \"An early step in any effort to analyze or model data should be to understand how the variables are distributed. Techniques for distribution visualization can provide quick answers to many important questions. What range do the observations cover? What is their central tendency? Are they heavily skewed in one direction? Is there evidence for bimodality? Are there significant outliers? Do the answers to these questions vary across subsets defined by other variables?\\n\",\n \"\\n\",\n \"The :ref:`distributions module ` contains several functions designed to answer questions such as these. The axes-level functions are :func:`histplot`, :func:`kdeplot`, :func:`ecdfplot`, and :func:`rugplot`. They are grouped together within the figure-level :func:`displot`, :func:`jointplot`, and :func:`pairplot` functions.\\n\",\n \"\\n\",\n \"There are several different approaches to visualizing a distribution, and each has its relative advantages and drawbacks. It is important to understand these factors so that you can choose the best approach for your particular aim.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"%matplotlib inline\\n\",\n \"import seaborn as sns; sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _tutorial_hist:\\n\",\n \"\\n\",\n \"Plotting univariate histograms\\n\",\n \"------------------------------\\n\",\n \"\\n\",\n \"Perhaps the most common approach to visualizing a distribution is the *histogram*. This is the default approach in :func:`displot`, which uses the same underlying code as :func:`histplot`. A histogram is a bar plot where the axis representing the data variable is divided into a set of discrete bins and the count of observations falling within each bin is shown using the height of the corresponding bar:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This plot immediately affords a few insights about the ``flipper_length_mm`` variable. For instance, we can see that the most common flipper length is about 195 mm, but the distribution appears bimodal, so this one number does not represent the data well.\\n\",\n \"\\n\",\n \"Choosing the bin size\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"The size of the bins is an important parameter, and using the wrong bin size can mislead by obscuring important features of the data or by creating apparent features out of random variability. By default, :func:`displot`/:func:`histplot` choose a default bin size based on the variance of the data and the number of observations. But you should not be over-reliant on such automatic approaches, because they depend on particular assumptions about the structure of your data. It is always advisable to check that your impressions of the distribution are consistent across different bin sizes. To choose the size directly, set the `binwidth` parameter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", binwidth=3)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In other circumstances, it may make more sense to specify the *number* of bins, rather than their size:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", bins=20)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"One example of a situation where defaults fail is when the variable takes a relatively small number of integer values. In that case, the default bin width may be too small, creating awkward gaps in the distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.displot(tips, x=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"One approach would be to specify the precise bin breaks by passing an array to ``bins``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(tips, x=\\\"size\\\", bins=[1, 2, 3, 4, 5, 6, 7])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This can also be accomplished by setting ``discrete=True``, which chooses bin breaks that represent the unique values in a dataset with bars that are centered on their corresponding value.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(tips, x=\\\"size\\\", discrete=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to visualize the distribution of a categorical variable using the logic of a histogram. Discrete bins are automatically set for categorical variables, but it may also be helpful to \\\"shrink\\\" the bars slightly to emphasize the categorical nature of the axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(tips, x=\\\"day\\\", shrink=.8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Conditioning on other variables\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"Once you understand the distribution of a variable, the next step is often to ask whether features of that distribution differ across other variables in the dataset. For example, what accounts for the bimodal distribution of flipper lengths that we saw above? :func:`displot` and :func:`histplot` provide support for conditional subsetting via the ``hue`` semantic. Assigning a variable to ``hue`` will draw a separate histogram for each of its unique values and distinguish them by color:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, the different histograms are \\\"layered\\\" on top of each other and, in some cases, they may be difficult to distinguish. One option is to change the visual representation of the histogram from a bar plot to a \\\"step\\\" plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", element=\\\"step\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Alternatively, instead of layering each bar, they can be \\\"stacked\\\", or moved vertically. In this plot, the outline of the full histogram will match the plot with only a single variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The stacked histogram emphasizes the part-whole relationship between the variables, but it can obscure other features (for example, it is difficult to determine the mode of the Adelie distribution. Another option is \\\"dodge\\\" the bars, which moves them horizontally and reduces their width. This ensures that there are no overlaps and that the bars remain comparable in terms of height. But it only works well when the categorical variable has a small number of levels:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"sex\\\", multiple=\\\"dodge\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Because :func:`displot` is a figure-level function and is drawn onto a :class:`FacetGrid`, it is also possible to draw each individual distribution in a separate subplot by assigning the second variable to ``col`` or ``row`` rather than (or in addition to) ``hue``. This represents the distribution of each subset well, but it makes it more difficult to draw direct comparisons:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", col=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"None of these approaches are perfect, and we will soon see some alternatives to a histogram that are better-suited to the task of comparison.\\n\",\n \"\\n\",\n \"Normalized histogram statistics\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"Before we do, another point to note is that, when the subsets have unequal numbers of observations, comparing their distributions in terms of counts may not be ideal. One solution is to *normalize* the counts using the ``stat`` parameter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", stat=\\\"density\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, however, the normalization is applied to the entire distribution, so this simply rescales the height of the bars. By setting ``common_norm=False``, each subset will be normalized independently:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", stat=\\\"density\\\", common_norm=False)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Density normalization scales the bars so that their *areas* sum to 1. As a result, the density axis is not directly interpretable. Another option is to normalize the bars to that their *heights* sum to 1. This makes most sense when the variable is discrete, but it is an option for all histograms:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", stat=\\\"probability\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _tutorial_kde:\\n\",\n \"\\n\",\n \"Kernel density estimation\\n\",\n \"-------------------------\\n\",\n \"\\n\",\n \"A histogram aims to approximate the underlying probability density function that generated the data by binning and counting observations. Kernel density estimation (KDE) presents a different solution to the same problem. Rather than using discrete bins, a KDE plot smooths the observations with a Gaussian kernel, producing a continuous density estimate:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Choosing the smoothing bandwidth\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"Much like with the bin size in the histogram, the ability of the KDE to accurately represent the data depends on the choice of smoothing bandwidth. An over-smoothed estimate might erase meaningful features, but an under-smoothed estimate can obscure the true shape within random noise. The easiest way to check the robustness of the estimate is to adjust the default bandwidth:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", kind=\\\"kde\\\", bw_adjust=.25)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Note how the narrow bandwidth makes the bimodality much more apparent, but the curve is much less smooth. In contrast, a larger bandwidth obscures the bimodality almost completely:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", kind=\\\"kde\\\", bw_adjust=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Conditioning on other variables\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"As with histograms, if you assign a ``hue`` variable, a separate density estimate will be computed for each level of that variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In many cases, the layered KDE is easier to interpret than the layered histogram, so it is often a good choice for the task of comparison. Many of the same options for resolving multiple distributions apply to the KDE as well, however:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", kind=\\\"kde\\\", multiple=\\\"stack\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Note how the stacked plot filled in the area between each curve by default. It is also possible to fill in the curves for single or layered densities, although the default alpha value (opacity) will be different, so that the individual densities are easier to resolve.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", kind=\\\"kde\\\", fill=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Kernel density estimation pitfalls\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"KDE plots have many advantages. Important features of the data are easy to discern (central tendency, bimodality, skew), and they afford easy comparisons between subsets. But there are also situations where KDE poorly represents the underlying data. This is because the logic of KDE assumes that the underlying distribution is smooth and unbounded. One way this assumption can fail is when a variable reflects a quantity that is naturally bounded. If there are observations lying close to the bound (for example, small values of a variable that cannot be negative), the KDE curve may extend to unrealistic values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(tips, x=\\\"total_bill\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This can be partially avoided with the ``cut`` parameter, which specifies how far the curve should extend beyond the extreme datapoints. But this influences only where the curve is drawn; the density estimate will still smooth over the range where no data can exist, causing it to be artificially low at the extremes of the distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(tips, x=\\\"total_bill\\\", kind=\\\"kde\\\", cut=0)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The KDE approach also fails for discrete data or when data are naturally continuous but specific values are over-represented. The important thing to keep in mind is that the KDE will *always show you a smooth curve*, even when the data themselves are not smooth. For example, consider this distribution of diamond weights:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"diamonds = sns.load_dataset(\\\"diamonds\\\")\\n\",\n \"sns.displot(diamonds, x=\\\"carat\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"While the KDE suggests that there are peaks around specific values, the histogram reveals a much more jagged distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(diamonds, x=\\\"carat\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As a compromise, it is possible to combine these two approaches. While in histogram mode, :func:`displot` (as with :func:`histplot`) has the option of including the smoothed KDE curve (note ``kde=True``, not ``kind=\\\"kde\\\"``):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(diamonds, x=\\\"carat\\\", kde=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _tutorial_ecdf:\\n\",\n \"\\n\",\n \"Empirical cumulative distributions\\n\",\n \"----------------------------------\\n\",\n \"\\n\",\n \"A third option for visualizing distributions computes the \\\"empirical cumulative distribution function\\\" (ECDF). This plot draws a monotonically-increasing curve through each datapoint such that the height of the curve reflects the proportion of observations with a smaller value:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", kind=\\\"ecdf\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The ECDF plot has two key advantages. Unlike the histogram or KDE, it directly represents each datapoint. That means there is no bin size or smoothing parameter to consider. Additionally, because the curve is monotonically increasing, it is well-suited for comparing multiple distributions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", kind=\\\"ecdf\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The major downside to the ECDF plot is that it represents the shape of the distribution less intuitively than a histogram or density curve. Consider how the bimodality of flipper lengths is immediately apparent in the histogram, but to see it in the ECDF plot, you must look for varying slopes. Nevertheless, with practice, you can learn to answer all of the important questions about a distribution by examining the ECDF, and doing so can be a powerful approach.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Visualizing bivariate distributions\\n\",\n \"-----------------------------------\\n\",\n \"\\n\",\n \"All of the examples so far have considered *univariate* distributions: distributions of a single variable, perhaps conditional on a second variable assigned to ``hue``. Assigning a second variable to ``y``, however, will plot a *bivariate* distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A bivariate histogram bins the data within rectangles that tile the plot and then shows the count of observations within each rectangle with the fill color (analogous to a :func:`heatmap`). Similarly, a bivariate KDE plot smoothes the (x, y) observations with a 2D Gaussian. The default representation then shows the *contours* of the 2D density:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a ``hue`` variable will plot multiple heatmaps or contour sets using different colors. For bivariate histograms, this will only work well if there is minimal overlap between the conditional distributions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The contour approach of the bivariate KDE plot lends itself better to evaluating overlap, although a plot with too many contours can get busy:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Just as with univariate plots, the choice of bin size or smoothing bandwidth will determine how well the plot represents the underlying bivariate distribution. The same parameters apply, but they can be tuned for each variable by passing a pair of values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", binwidth=(2, .5))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To aid interpretation of the heatmap, add a colorbar to show the mapping between counts and color intensity:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", binwidth=(2, .5), cbar=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The meaning of the bivariate density contours is less straightforward. Because the density is not directly interpretable, the contours are drawn at *iso-proportions* of the density, meaning that each curve shows a level set such that some proportion *p* of the density lies below it. The *p* values are evenly spaced, with the lowest level contolled by the ``thresh`` parameter and the number controlled by ``levels``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", kind=\\\"kde\\\", thresh=.2, levels=4)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The ``levels`` parameter also accepts a list of values, for more control:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", kind=\\\"kde\\\", levels=[.01, .05, .1, .8])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The bivariate histogram allows one or both variables to be discrete. Plotting one discrete and one continuous variable offers another way to compare conditional univariate distributions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(diamonds, x=\\\"price\\\", y=\\\"clarity\\\", log_scale=(True, False))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In contrast, plotting two discrete variables is an easy to way show the cross-tabulation of the observations:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(diamonds, x=\\\"color\\\", y=\\\"clarity\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Distribution visualization in other settings\\n\",\n \"--------------------------------------------\\n\",\n \"\\n\",\n \"Several other figure-level plotting functions in seaborn make use of the :func:`histplot` and :func:`kdeplot` functions.\\n\",\n \"\\n\",\n \"\\n\",\n \"Plotting joint and marginal distributions\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"The first is :func:`jointplot`, which augments a bivariate relatonal or distribution plot with the marginal distributions of the two variables. By default, :func:`jointplot` represents the bivariate distribution using :func:`scatterplot` and the marginal distributions using :func:`histplot`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Similar to :func:`displot`, setting a different ``kind=\\\"kde\\\"`` in :func:`jointplot` will change both the joint and marginal plots the use :func:`kdeplot`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(\\n\",\n \" data=penguins,\\n\",\n \" x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\",\\n\",\n \" kind=\\\"kde\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \":func:`jointplot` is a convenient interface to the :class:`JointGrid` class, which offeres more flexibility when used directly:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot_joint(sns.histplot)\\n\",\n \"g.plot_marginals(sns.boxplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A less-obtrusive way to show marginal distributions uses a \\\"rug\\\" plot, which adds a small tick on the edge of the plot to represent each individual observation. This is built into :func:`displot`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.displot(\\n\",\n \" penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n \" kind=\\\"kde\\\", rug=True\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"And the axes-level :func:`rugplot` function can be used to add rugs on the side of any other kind of plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"sns.rugplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Plotting many distributions\\n\",\n \"^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n \"\\n\",\n \"The :func:`pairplot` function offers a similar blend of joint and marginal distributions. Rather than focusing on a single relationship, however, :func:`pairplot` uses a \\\"small-multiple\\\" approach to visualize the univariate distribution of all variables in a dataset along with all of their pairwise relationships:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.pairplot(penguins)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As with :func:`jointplot`/:class:`JointGrid`, using the underlying :class:`PairGrid` directly will afford more flexibility with only a bit more typing:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins)\\n\",\n \"g.map_upper(sns.histplot)\\n\",\n \"g.map_lower(sns.kdeplot, fill=True)\\n\",\n \"g.map_diag(sns.histplot, kde=True)\"\n ]\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":14,"name":"axis_grids.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _grid_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Building structured multi-plot grids\\n\",\n \"====================================\\n\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When exploring multi-dimensional data, a useful approach is to draw multiple instances of the same plot on different subsets of your dataset. This technique is sometimes called either \\\"lattice\\\" or \\\"trellis\\\" plotting, and it is related to the idea of `\\\"small multiples\\\" `_. It allows a viewer to quickly extract a large amount of information about a complex dataset. Matplotlib offers good support for making figures with multiple axes; seaborn builds on top of this to directly link the structure of the plot to the structure of your dataset.\\n\",\n \"\\n\",\n \"The :doc:`figure-level ` functions are built on top of the objects discussed in this chapter of the tutorial. In most cases, you will want to work with those functions. They take care of some important bookkeeping that synchronizes the multiple plots in each grid. This chapter explains how the underlying objects work, which may be useful for advanced applications.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"sns.set_theme(style=\\\"ticks\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"%matplotlib inline\\n\",\n \"import numpy as np\\n\",\n \"np.random.seed(sum(map(ord, \\\"axis_grids\\\")))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _facet_grid:\\n\",\n \"\\n\",\n \"Conditional small multiples\\n\",\n \"---------------------------\\n\",\n \"\\n\",\n \"The :class:`FacetGrid` class is useful when you want to visualize the distribution of a variable or the relationship between multiple variables separately within subsets of your dataset. A :class:`FacetGrid` can be drawn with up to three dimensions: ``row``, ``col``, and ``hue``. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.\\n\",\n \"\\n\",\n \"Each of :func:`relplot`, :func:`displot`, :func:`catplot`, and :func:`lmplot` use this object internally, and they return the object when they are finished so that it can be used for further tweaking.\\n\",\n \"\\n\",\n \"The class is used by initializing a :class:`FacetGrid` object with a dataframe and the names of the variables that will form the row, column, or hue dimensions of the grid. These variables should be categorical or discrete, and then the data at each level of the variable will be used for a facet along that axis. For example, say we wanted to examine differences between lunch and dinner in the ``tips`` dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"g = sns.FacetGrid(tips, col=\\\"time\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Initializing the grid like this sets up the matplotlib figure and axes, but doesn't draw anything on them.\\n\",\n \"\\n\",\n \"The main approach for visualizing data on this grid is with the :meth:`FacetGrid.map` method. Provide it with a plotting function and the name(s) of variable(s) in the dataframe to plot. Let's look at the distribution of tips in each of these subsets, using a histogram:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\")\\n\",\n \"g.map(sns.histplot, \\\"tip\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This function will draw the figure and annotate the axes, hopefully producing a finished plot in one step. To make a relational plot, just pass multiple variable names. You can also provide keyword arguments, which will be passed to the plotting function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"sex\\\", hue=\\\"smoker\\\")\\n\",\n \"g.map(sns.scatterplot, \\\"total_bill\\\", \\\"tip\\\", alpha=.7)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"There are several options for controlling the look of the grid that can be passed to the class constructor.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, row=\\\"smoker\\\", col=\\\"time\\\", margin_titles=True)\\n\",\n \"g.map(sns.regplot, \\\"size\\\", \\\"total_bill\\\", color=\\\".3\\\", fit_reg=False, x_jitter=.1)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Note that ``margin_titles`` isn't formally supported by the matplotlib API, and may not work well in all cases. In particular, it currently can't be used with a legend that lies outside of the plot.\\n\",\n \"\\n\",\n \"The size of the figure is set by providing the height of *each* facet, along with the aspect ratio:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"day\\\", height=4, aspect=.5)\\n\",\n \"g.map(sns.barplot, \\\"sex\\\", \\\"total_bill\\\", order=[\\\"Male\\\", \\\"Female\\\"])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The default ordering of the facets is derived from the information in the DataFrame. If the variable used to define facets has a categorical type, then the order of the categories is used. Otherwise, the facets will be in the order of appearance of the category levels. It is possible, however, to specify an ordering of any facet dimension with the appropriate ``*_order`` parameter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"ordered_days = tips.day.value_counts().index\\n\",\n \"g = sns.FacetGrid(tips, row=\\\"day\\\", row_order=ordered_days,\\n\",\n \" height=1.7, aspect=4,)\\n\",\n \"g.map(sns.kdeplot, \\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Any seaborn color palette (i.e., something that can be passed to :func:`color_palette()` can be provided. You can also use a dictionary that maps the names of values in the ``hue`` variable to valid matplotlib colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"pal = dict(Lunch=\\\"seagreen\\\", Dinner=\\\".7\\\")\\n\",\n \"g = sns.FacetGrid(tips, hue=\\\"time\\\", palette=pal, height=5)\\n\",\n \"g.map(sns.scatterplot, \\\"total_bill\\\", \\\"tip\\\", s=100, alpha=.5)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If you have many levels of one variable, you can plot it along the columns but \\\"wrap\\\" them so that they span multiple rows. When doing this, you cannot use a ``row`` variable.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"attend = sns.load_dataset(\\\"attention\\\").query(\\\"subject <= 12\\\")\\n\",\n \"g = sns.FacetGrid(attend, col=\\\"subject\\\", col_wrap=4, height=2, ylim=(0, 10))\\n\",\n \"g.map(sns.pointplot, \\\"solutions\\\", \\\"score\\\", order=[1, 2, 3], color=\\\".3\\\", errorbar=None)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Once you've drawn a plot using :meth:`FacetGrid.map` (which can be called multiple times), you may want to adjust some aspects of the plot. There are also a number of methods on the :class:`FacetGrid` object for manipulating the figure at a higher level of abstraction. The most general is :meth:`FacetGrid.set`, and there are other more specialized methods like :meth:`FacetGrid.set_axis_labels`, which respects the fact that interior facets do not have axis labels. For example:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"with sns.axes_style(\\\"white\\\"):\\n\",\n \" g = sns.FacetGrid(tips, row=\\\"sex\\\", col=\\\"smoker\\\", margin_titles=True, height=2.5)\\n\",\n \"g.map(sns.scatterplot, \\\"total_bill\\\", \\\"tip\\\", color=\\\"#334488\\\")\\n\",\n \"g.set_axis_labels(\\\"Total bill (US Dollars)\\\", \\\"Tip\\\")\\n\",\n \"g.set(xticks=[10, 30, 50], yticks=[2, 6, 10])\\n\",\n \"g.figure.subplots_adjust(wspace=.02, hspace=.02)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"For even more customization, you can work directly with the underling matplotlib ``Figure`` and ``Axes`` objects, which are stored as member attributes at ``figure`` and ``axes_dict``, respectively. When making a figure without row or column faceting, you can also use the ``ax`` attribute to directly access the single axes.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"smoker\\\", margin_titles=True, height=4)\\n\",\n \"g.map(plt.scatter, \\\"total_bill\\\", \\\"tip\\\", color=\\\"#338844\\\", edgecolor=\\\"white\\\", s=50, lw=1)\\n\",\n \"for ax in g.axes_dict.values():\\n\",\n \" ax.axline((0, 0), slope=.2, c=\\\".2\\\", ls=\\\"--\\\", zorder=0)\\n\",\n \"g.set(xlim=(0, 60), ylim=(0, 14))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _custom_map_func:\\n\",\n \"\\n\",\n \"Using custom functions\\n\",\n \"----------------------\\n\",\n \"\\n\",\n \"You're not limited to existing matplotlib and seaborn functions when using :class:`FacetGrid`. However, to work properly, any function you use must follow a few rules:\\n\",\n \"\\n\",\n \"1. It must plot onto the \\\"currently active\\\" matplotlib ``Axes``. This will be true of functions in the ``matplotlib.pyplot`` namespace, and you can call :func:`matplotlib.pyplot.gca` to get a reference to the current ``Axes`` if you want to work directly with its methods.\\n\",\n \"2. It must accept the data that it plots in positional arguments. Internally, :class:`FacetGrid` will pass a ``Series`` of data for each of the named positional arguments passed to :meth:`FacetGrid.map`.\\n\",\n \"3. It must be able to accept ``color`` and ``label`` keyword arguments, and, ideally, it will do something useful with them. In most cases, it's easiest to catch a generic dictionary of ``**kwargs`` and pass it along to the underlying plotting function.\\n\",\n \"\\n\",\n \"Let's look at minimal example of a function you can plot with. This function will just take a single vector of data for each facet:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"from scipy import stats\\n\",\n \"def quantile_plot(x, **kwargs):\\n\",\n \" quantiles, xr = stats.probplot(x, fit=False)\\n\",\n \" plt.scatter(xr, quantiles, **kwargs)\\n\",\n \" \\n\",\n \"g = sns.FacetGrid(tips, col=\\\"sex\\\", height=4)\\n\",\n \"g.map(quantile_plot, \\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If we want to make a bivariate plot, you should write the function so that it accepts the x-axis variable first and the y-axis variable second:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"def qqplot(x, y, **kwargs):\\n\",\n \" _, xr = stats.probplot(x, fit=False)\\n\",\n \" _, yr = stats.probplot(y, fit=False)\\n\",\n \" plt.scatter(xr, yr, **kwargs)\\n\",\n \" \\n\",\n \"g = sns.FacetGrid(tips, col=\\\"smoker\\\", height=4)\\n\",\n \"g.map(qqplot, \\\"total_bill\\\", \\\"tip\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Because :func:`matplotlib.pyplot.scatter` accepts ``color`` and ``label`` keyword arguments and does the right thing with them, we can add a hue facet without any difficulty:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, hue=\\\"time\\\", col=\\\"sex\\\", height=4)\\n\",\n \"g.map(qqplot, \\\"total_bill\\\", \\\"tip\\\")\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Sometimes, though, you'll want to map a function that doesn't work the way you expect with the ``color`` and ``label`` keyword arguments. In this case, you'll want to explicitly catch them and handle them in the logic of your custom function. For example, this approach will allow use to map :func:`matplotlib.pyplot.hexbin`, which otherwise does not play well with the :class:`FacetGrid` API:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"def hexbin(x, y, color, **kwargs):\\n\",\n \" cmap = sns.light_palette(color, as_cmap=True)\\n\",\n \" plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs)\\n\",\n \"\\n\",\n \"with sns.axes_style(\\\"dark\\\"):\\n\",\n \" g = sns.FacetGrid(tips, hue=\\\"time\\\", col=\\\"time\\\", height=4)\\n\",\n \"g.map(hexbin, \\\"total_bill\\\", \\\"tip\\\", extent=[0, 50, 0, 10]);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _pair_grid:\\n\",\n \"\\n\",\n \"Plotting pairwise data relationships\\n\",\n \"------------------------------------\\n\",\n \"\\n\",\n \":class:`PairGrid` also allows you to quickly draw a grid of small subplots using the same plot type to visualize data in each. In a :class:`PairGrid`, each row and column is assigned to a different variable, so the resulting plot shows each pairwise relationship in the dataset. This style of plot is sometimes called a \\\"scatterplot matrix\\\", as this is the most common way to show each relationship, but :class:`PairGrid` is not limited to scatterplots.\\n\",\n \"\\n\",\n \"It's important to understand the differences between a :class:`FacetGrid` and a :class:`PairGrid`. In the former, each facet shows the same relationship conditioned on different levels of other variables. In the latter, each plot shows a different relationship (although the upper and lower triangles will have mirrored plots). Using :class:`PairGrid` can give you a very quick, very high-level summary of interesting relationships in your dataset.\\n\",\n \"\\n\",\n \"The basic usage of the class is very similar to :class:`FacetGrid`. First you initialize the grid, then you pass plotting function to a ``map`` method and it will be called on each subplot. There is also a companion function, :func:`pairplot` that trades off some flexibility for faster plotting.\\n\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"iris = sns.load_dataset(\\\"iris\\\")\\n\",\n \"g = sns.PairGrid(iris)\\n\",\n \"g.map(sns.scatterplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's possible to plot a different function on the diagonal to show the univariate distribution of the variable in each column. Note that the axis ticks won't correspond to the count or density axis of this plot, though.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(iris)\\n\",\n \"g.map_diag(sns.histplot)\\n\",\n \"g.map_offdiag(sns.scatterplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A very common way to use this plot colors the observations by a separate categorical variable. For example, the iris dataset has four measurements for each of three different species of iris flowers so you can see how they differ.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(iris, hue=\\\"species\\\")\\n\",\n \"g.map_diag(sns.histplot)\\n\",\n \"g.map_offdiag(sns.scatterplot)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default every numeric column in the dataset is used, but you can focus on particular relationships if you want.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(iris, vars=[\\\"sepal_length\\\", \\\"sepal_width\\\"], hue=\\\"species\\\")\\n\",\n \"g.map(sns.scatterplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to use a different function in the upper and lower triangles to emphasize different aspects of the relationship.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(iris)\\n\",\n \"g.map_upper(sns.scatterplot)\\n\",\n \"g.map_lower(sns.kdeplot)\\n\",\n \"g.map_diag(sns.kdeplot, lw=3, legend=False)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The square grid with identity relationships on the diagonal is actually just a special case, and you can plot with different variables in the rows and columns.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(tips, y_vars=[\\\"tip\\\"], x_vars=[\\\"total_bill\\\", \\\"size\\\"], height=4)\\n\",\n \"g.map(sns.regplot, color=\\\".3\\\")\\n\",\n \"g.set(ylim=(-1, 11), yticks=[0, 5, 10])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Of course, the aesthetic attributes are configurable. For instance, you can use a different palette (say, to show an ordering of the ``hue`` variable) and pass keyword arguments into the plotting functions.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(tips, hue=\\\"size\\\", palette=\\\"GnBu_d\\\")\\n\",\n \"g.map(plt.scatter, s=50, edgecolor=\\\"white\\\")\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \":class:`PairGrid` is flexible, but to take a quick look at a dataset, it can be easier to use :func:`pairplot`. This function uses scatterplots and histograms by default, although a few other kinds will be added (currently, you can also plot regression plots on the off-diagonals and KDEs on the diagonal).\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.pairplot(iris, hue=\\\"species\\\", height=2.5)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can also control the aesthetics of the plot with keyword arguments, and it returns the :class:`PairGrid` instance for further tweaking.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.pairplot(iris, hue=\\\"species\\\", palette=\\\"Set2\\\", diag_kind=\\\"kde\\\", height=2.5)\"\n ]\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":15,"name":"Makefile","nodeType":"TextFile","path":"doc/_tutorial","text":"rst_files := $(patsubst %.ipynb,../tutorial/%.rst,$(wildcard *.ipynb))\n\ntutorial: ${rst_files}\n\n../tutorial/%.rst: %.ipynb\n\t../tools/nb_to_doc.py $*.ipynb ../tutorial\n\nclean:\n\trm -rf ../tutorial\n"},{"id":16,"name":"examples","nodeType":"Package"},{"fileName":"anscombes_quartet.py","filePath":"examples","id":17,"nodeType":"File","text":"\"\"\"\nAnscombe's quartet\n==================\n\n_thumb: .4, .4\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\n\n# Load the example dataset for Anscombe's quartet\ndf = sns.load_dataset(\"anscombe\")\n\n# Show the results of a linear regression within each dataset\nsns.lmplot(\n data=df, x=\"x\", y=\"y\", col=\"dataset\", hue=\"dataset\",\n col_wrap=2, palette=\"muted\", ci=None,\n height=4, scatter_kws={\"s\": 50, \"alpha\": 1}\n)\n"},{"fileName":"histogram_stacked.py","filePath":"examples","id":18,"nodeType":"File","text":"\"\"\"\nStacked histogram on a log scale\n================================\n\n_thumb: .5, .45\n\n\"\"\"\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"ticks\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\n\nf, ax = plt.subplots(figsize=(7, 5))\nsns.despine(f)\n\nsns.histplot(\n diamonds,\n x=\"price\", hue=\"cut\",\n multiple=\"stack\",\n palette=\"light:m_r\",\n edgecolor=\".3\",\n linewidth=.5,\n log_scale=True,\n)\nax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())\nax.set_xticks([500, 1000, 2000, 5000, 10000])\n"},{"fileName":"pointplot_anova.py","filePath":"examples","id":19,"nodeType":"File","text":"\"\"\"\nPlotting a three-way ANOVA\n==========================\n\n_thumb: .42, .5\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the example exercise dataset\nexercise = sns.load_dataset(\"exercise\")\n\n# Draw a pointplot to show pulse as a function of three categorical factors\ng = sns.catplot(\n data=exercise, x=\"time\", y=\"pulse\", hue=\"kind\", col=\"diet\",\n capsize=.2, palette=\"YlGnBu_d\", errorbar=\"se\",\n kind=\"point\", height=6, aspect=.75,\n)\ng.despine(left=True)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":20,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":21,"name":"df","nodeType":"Attribute","startLoc":11,"text":"df"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":22,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":23,"name":"exercise","nodeType":"Attribute","startLoc":11,"text":"exercise"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":24,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"null","col":21,"comment":"null","endLoc":9,"id":25,"name":"mpl","nodeType":"Attribute","startLoc":9,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":10,"id":26,"name":"plt","nodeType":"Attribute","startLoc":10,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":27,"name":"diamonds","nodeType":"Attribute","startLoc":14,"text":"diamonds"},{"id":28,"name":"seaborn","nodeType":"Package"},{"fileName":"regression.py","filePath":"seaborn","id":29,"nodeType":"File","text":"\"\"\"Plotting functions for linear models (broadly construed).\"\"\"\nimport copy\nfrom textwrap import dedent\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ntry:\n import statsmodels\n assert statsmodels\n _has_statsmodels = True\nexcept ImportError:\n _has_statsmodels = False\n\nfrom . import utils\nfrom . import algorithms as algo\nfrom .axisgrid import FacetGrid, _facet_docs\n\n\n__all__ = [\"lmplot\", \"regplot\", \"residplot\"]\n\n\nclass _LinearPlotter:\n \"\"\"Base class for plotting relational data in tidy format.\n\n To get anything useful done you'll have to inherit from this, but setup\n code that can be abstracted out should be put here.\n\n \"\"\"\n def establish_variables(self, data, **kws):\n \"\"\"Extract variables from data or use directly.\"\"\"\n self.data = data\n\n # Validate the inputs\n any_strings = any([isinstance(v, str) for v in kws.values()])\n if any_strings and data is None:\n raise ValueError(\"Must pass `data` if using named variables.\")\n\n # Set the variables\n for var, val in kws.items():\n if isinstance(val, str):\n vector = data[val]\n elif isinstance(val, list):\n vector = np.asarray(val)\n else:\n vector = val\n if vector is not None and vector.shape != (1,):\n vector = np.squeeze(vector)\n if np.ndim(vector) > 1:\n err = \"regplot inputs must be 1d\"\n raise ValueError(err)\n setattr(self, var, vector)\n\n def dropna(self, *vars):\n \"\"\"Remove observations with missing data.\"\"\"\n vals = [getattr(self, var) for var in vars]\n vals = [v for v in vals if v is not None]\n not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1)\n for var in vars:\n val = getattr(self, var)\n if val is not None:\n setattr(self, var, val[not_na])\n\n def plot(self, ax):\n raise NotImplementedError\n\n\nclass _RegressionPlotter(_LinearPlotter):\n \"\"\"Plotter for numeric independent variables with regression model.\n\n This does the computations and drawing for the `regplot` function, and\n is thus also used indirectly by `lmplot`.\n \"\"\"\n def __init__(self, x, y, data=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=False, dropna=True, x_jitter=None, y_jitter=None,\n color=None, label=None):\n\n # Set member attributes\n self.x_estimator = x_estimator\n self.ci = ci\n self.x_ci = ci if x_ci == \"ci\" else x_ci\n self.n_boot = n_boot\n self.seed = seed\n self.scatter = scatter\n self.fit_reg = fit_reg\n self.order = order\n self.logistic = logistic\n self.lowess = lowess\n self.robust = robust\n self.logx = logx\n self.truncate = truncate\n self.x_jitter = x_jitter\n self.y_jitter = y_jitter\n self.color = color\n self.label = label\n\n # Validate the regression options:\n if sum((order > 1, logistic, robust, lowess, logx)) > 1:\n raise ValueError(\"Mutually exclusive regression options.\")\n\n # Extract the data vals from the arguments or passed dataframe\n self.establish_variables(data, x=x, y=y, units=units,\n x_partial=x_partial, y_partial=y_partial)\n\n # Drop null observations\n if dropna:\n self.dropna(\"x\", \"y\", \"units\", \"x_partial\", \"y_partial\")\n\n # Regress nuisance variables out of the data\n if self.x_partial is not None:\n self.x = self.regress_out(self.x, self.x_partial)\n if self.y_partial is not None:\n self.y = self.regress_out(self.y, self.y_partial)\n\n # Possibly bin the predictor variable, which implies a point estimate\n if x_bins is not None:\n self.x_estimator = np.mean if x_estimator is None else x_estimator\n x_discrete, x_bins = self.bin_predictor(x_bins)\n self.x_discrete = x_discrete\n else:\n self.x_discrete = self.x\n\n # Disable regression in case of singleton inputs\n if len(self.x) <= 1:\n self.fit_reg = False\n\n # Save the range of the x variable for the grid later\n if self.fit_reg:\n self.x_range = self.x.min(), self.x.max()\n\n @property\n def scatter_data(self):\n \"\"\"Data where each observation is a point.\"\"\"\n x_j = self.x_jitter\n if x_j is None:\n x = self.x\n else:\n x = self.x + np.random.uniform(-x_j, x_j, len(self.x))\n\n y_j = self.y_jitter\n if y_j is None:\n y = self.y\n else:\n y = self.y + np.random.uniform(-y_j, y_j, len(self.y))\n\n return x, y\n\n @property\n def estimate_data(self):\n \"\"\"Data with a point estimate and CI for each discrete x value.\"\"\"\n x, y = self.x_discrete, self.y\n vals = sorted(np.unique(x))\n points, cis = [], []\n\n for val in vals:\n\n # Get the point estimate of the y variable\n _y = y[x == val]\n est = self.x_estimator(_y)\n points.append(est)\n\n # Compute the confidence interval for this estimate\n if self.x_ci is None:\n cis.append(None)\n else:\n units = None\n if self.x_ci == \"sd\":\n sd = np.std(_y)\n _ci = est - sd, est + sd\n else:\n if self.units is not None:\n units = self.units[x == val]\n boots = algo.bootstrap(_y,\n func=self.x_estimator,\n n_boot=self.n_boot,\n units=units,\n seed=self.seed)\n _ci = utils.ci(boots, self.x_ci)\n cis.append(_ci)\n\n return vals, points, cis\n\n def fit_regression(self, ax=None, x_range=None, grid=None):\n \"\"\"Fit the regression model.\"\"\"\n # Create the grid for the regression\n if grid is None:\n if self.truncate:\n x_min, x_max = self.x_range\n else:\n if ax is None:\n x_min, x_max = x_range\n else:\n x_min, x_max = ax.get_xlim()\n grid = np.linspace(x_min, x_max, 100)\n ci = self.ci\n\n # Fit the regression\n if self.order > 1:\n yhat, yhat_boots = self.fit_poly(grid, self.order)\n elif self.logistic:\n from statsmodels.genmod.generalized_linear_model import GLM\n from statsmodels.genmod.families import Binomial\n yhat, yhat_boots = self.fit_statsmodels(grid, GLM,\n family=Binomial())\n elif self.lowess:\n ci = None\n grid, yhat = self.fit_lowess()\n elif self.robust:\n from statsmodels.robust.robust_linear_model import RLM\n yhat, yhat_boots = self.fit_statsmodels(grid, RLM)\n elif self.logx:\n yhat, yhat_boots = self.fit_logx(grid)\n else:\n yhat, yhat_boots = self.fit_fast(grid)\n\n # Compute the confidence interval at each grid point\n if ci is None:\n err_bands = None\n else:\n err_bands = utils.ci(yhat_boots, ci, axis=0)\n\n return grid, yhat, err_bands\n\n def fit_fast(self, grid):\n \"\"\"Low-level regression and prediction using linear algebra.\"\"\"\n def reg_func(_x, _y):\n return np.linalg.pinv(_x).dot(_y)\n\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), grid]\n yhat = grid.dot(reg_func(X, y))\n if self.ci is None:\n return yhat, None\n\n beta_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed).T\n yhat_boots = grid.dot(beta_boots).T\n return yhat, yhat_boots\n\n def fit_poly(self, grid, order):\n \"\"\"Regression using numpy polyfit for higher-order trends.\"\"\"\n def reg_func(_x, _y):\n return np.polyval(np.polyfit(_x, _y, order), grid)\n\n x, y = self.x, self.y\n yhat = reg_func(x, y)\n if self.ci is None:\n return yhat, None\n\n yhat_boots = algo.bootstrap(x, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed)\n return yhat, yhat_boots\n\n def fit_statsmodels(self, grid, model, **kwargs):\n \"\"\"More general regression function using statsmodels objects.\"\"\"\n import statsmodels.genmod.generalized_linear_model as glm\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), grid]\n\n def reg_func(_x, _y):\n try:\n yhat = model(_y, _x, **kwargs).fit().predict(grid)\n except glm.PerfectSeparationError:\n yhat = np.empty(len(grid))\n yhat.fill(np.nan)\n return yhat\n\n yhat = reg_func(X, y)\n if self.ci is None:\n return yhat, None\n\n yhat_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed)\n return yhat, yhat_boots\n\n def fit_lowess(self):\n \"\"\"Fit a locally-weighted regression, which returns its own grid.\"\"\"\n from statsmodels.nonparametric.smoothers_lowess import lowess\n grid, yhat = lowess(self.y, self.x).T\n return grid, yhat\n\n def fit_logx(self, grid):\n \"\"\"Fit the model in log-space.\"\"\"\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), np.log(grid)]\n\n def reg_func(_x, _y):\n _x = np.c_[_x[:, 0], np.log(_x[:, 1])]\n return np.linalg.pinv(_x).dot(_y)\n\n yhat = grid.dot(reg_func(X, y))\n if self.ci is None:\n return yhat, None\n\n beta_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed).T\n yhat_boots = grid.dot(beta_boots).T\n return yhat, yhat_boots\n\n def bin_predictor(self, bins):\n \"\"\"Discretize a predictor by assigning value to closest bin.\"\"\"\n x = np.asarray(self.x)\n if np.isscalar(bins):\n percentiles = np.linspace(0, 100, bins + 2)[1:-1]\n bins = np.percentile(x, percentiles)\n else:\n bins = np.ravel(bins)\n\n dist = np.abs(np.subtract.outer(x, bins))\n x_binned = bins[np.argmin(dist, axis=1)].ravel()\n\n return x_binned, bins\n\n def regress_out(self, a, b):\n \"\"\"Regress b from a keeping a's original mean.\"\"\"\n a_mean = a.mean()\n a = a - a_mean\n b = b - b.mean()\n b = np.c_[b]\n a_prime = a - b.dot(np.linalg.pinv(b).dot(a))\n return np.asarray(a_prime + a_mean).reshape(a.shape)\n\n def plot(self, ax, scatter_kws, line_kws):\n \"\"\"Draw the full plot.\"\"\"\n # Insert the plot label into the correct set of keyword arguments\n if self.scatter:\n scatter_kws[\"label\"] = self.label\n else:\n line_kws[\"label\"] = self.label\n\n # Use the current color cycle state as a default\n if self.color is None:\n lines, = ax.plot([], [])\n color = lines.get_color()\n lines.remove()\n else:\n color = self.color\n\n # Ensure that color is hex to avoid matplotlib weirdness\n color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color))\n\n # Let color in keyword arguments override overall plot color\n scatter_kws.setdefault(\"color\", color)\n line_kws.setdefault(\"color\", color)\n\n # Draw the constituent plots\n if self.scatter:\n self.scatterplot(ax, scatter_kws)\n\n if self.fit_reg:\n self.lineplot(ax, line_kws)\n\n # Label the axes\n if hasattr(self.x, \"name\"):\n ax.set_xlabel(self.x.name)\n if hasattr(self.y, \"name\"):\n ax.set_ylabel(self.y.name)\n\n def scatterplot(self, ax, kws):\n \"\"\"Draw the data.\"\"\"\n # Treat the line-based markers specially, explicitly setting larger\n # linewidth than is provided by the seaborn style defaults.\n # This would ideally be handled better in matplotlib (i.e., distinguish\n # between edgewidth for solid glyphs and linewidth for line glyphs\n # but this should do for now.\n line_markers = [\"1\", \"2\", \"3\", \"4\", \"+\", \"x\", \"|\", \"_\"]\n if self.x_estimator is None:\n if \"marker\" in kws and kws[\"marker\"] in line_markers:\n lw = mpl.rcParams[\"lines.linewidth\"]\n else:\n lw = mpl.rcParams[\"lines.markeredgewidth\"]\n kws.setdefault(\"linewidths\", lw)\n\n if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4:\n kws.setdefault(\"alpha\", .8)\n\n x, y = self.scatter_data\n ax.scatter(x, y, **kws)\n else:\n # TODO abstraction\n ci_kws = {\"color\": kws[\"color\"]}\n if \"alpha\" in kws:\n ci_kws[\"alpha\"] = kws[\"alpha\"]\n ci_kws[\"linewidth\"] = mpl.rcParams[\"lines.linewidth\"] * 1.75\n kws.setdefault(\"s\", 50)\n\n xs, ys, cis = self.estimate_data\n if [ci for ci in cis if ci is not None]:\n for x, ci in zip(xs, cis):\n ax.plot([x, x], ci, **ci_kws)\n ax.scatter(xs, ys, **kws)\n\n def lineplot(self, ax, kws):\n \"\"\"Draw the model.\"\"\"\n # Fit the regression model\n grid, yhat, err_bands = self.fit_regression(ax)\n edges = grid[0], grid[-1]\n\n # Get set default aesthetics\n fill_color = kws[\"color\"]\n lw = kws.pop(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.5)\n kws.setdefault(\"linewidth\", lw)\n\n # Draw the regression line and confidence interval\n line, = ax.plot(grid, yhat, **kws)\n if not self.truncate:\n line.sticky_edges.x[:] = edges # Prevent mpl from adding margin\n if err_bands is not None:\n ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15)\n\n\n_regression_docs = dict(\n\n model_api=dedent(\"\"\"\\\n There are a number of mutually exclusive options for estimating the\n regression model. See the :ref:`tutorial ` for more\n information.\\\n \"\"\"),\n regplot_vs_lmplot=dedent(\"\"\"\\\n The :func:`regplot` and :func:`lmplot` functions are closely related, but\n the former is an axes-level function while the latter is a figure-level\n function that combines :func:`regplot` and :class:`FacetGrid`.\\\n \"\"\"),\n x_estimator=dedent(\"\"\"\\\n x_estimator : callable that maps vector -> scalar, optional\n Apply this function to each unique value of ``x`` and plot the\n resulting estimate. This is useful when ``x`` is a discrete variable.\n If ``x_ci`` is given, this estimate will be bootstrapped and a\n confidence interval will be drawn.\\\n \"\"\"),\n x_bins=dedent(\"\"\"\\\n x_bins : int or vector, optional\n Bin the ``x`` variable into discrete bins and then estimate the central\n tendency and a confidence interval. This binning only influences how\n the scatterplot is drawn; the regression is still fit to the original\n data. This parameter is interpreted either as the number of\n evenly-sized (not necessary spaced) bins or the positions of the bin\n centers. When this parameter is used, it implies that the default of\n ``x_estimator`` is ``numpy.mean``.\\\n \"\"\"),\n x_ci=dedent(\"\"\"\\\n x_ci : \"ci\", \"sd\", int in [0, 100] or None, optional\n Size of the confidence interval used when plotting a central tendency\n for discrete values of ``x``. If ``\"ci\"``, defer to the value of the\n ``ci`` parameter. If ``\"sd\"``, skip bootstrapping and show the\n standard deviation of the observations in each bin.\\\n \"\"\"),\n scatter=dedent(\"\"\"\\\n scatter : bool, optional\n If ``True``, draw a scatterplot with the underlying observations (or\n the ``x_estimator`` values).\\\n \"\"\"),\n fit_reg=dedent(\"\"\"\\\n fit_reg : bool, optional\n If ``True``, estimate and plot a regression model relating the ``x``\n and ``y`` variables.\\\n \"\"\"),\n ci=dedent(\"\"\"\\\n ci : int in [0, 100] or None, optional\n Size of the confidence interval for the regression estimate. This will\n be drawn using translucent bands around the regression line. The\n confidence interval is estimated using a bootstrap; for large\n datasets, it may be advisable to avoid that computation by setting\n this parameter to None.\\\n \"\"\"),\n n_boot=dedent(\"\"\"\\\n n_boot : int, optional\n Number of bootstrap resamples used to estimate the ``ci``. The default\n value attempts to balance time and stability; you may want to increase\n this value for \"final\" versions of plots.\\\n \"\"\"),\n units=dedent(\"\"\"\\\n units : variable name in ``data``, optional\n If the ``x`` and ``y`` observations are nested within sampling units,\n those can be specified here. This will be taken into account when\n computing the confidence intervals by performing a multilevel bootstrap\n that resamples both units and observations (within unit). This does not\n otherwise influence how the regression is estimated or drawn.\\\n \"\"\"),\n seed=dedent(\"\"\"\\\n seed : int, numpy.random.Generator, or numpy.random.RandomState, optional\n Seed or random number generator for reproducible bootstrapping.\\\n \"\"\"),\n order=dedent(\"\"\"\\\n order : int, optional\n If ``order`` is greater than 1, use ``numpy.polyfit`` to estimate a\n polynomial regression.\\\n \"\"\"),\n logistic=dedent(\"\"\"\\\n logistic : bool, optional\n If ``True``, assume that ``y`` is a binary variable and use\n ``statsmodels`` to estimate a logistic regression model. Note that this\n is substantially more computationally intensive than linear regression,\n so you may wish to decrease the number of bootstrap resamples\n (``n_boot``) or set ``ci`` to None.\\\n \"\"\"),\n lowess=dedent(\"\"\"\\\n lowess : bool, optional\n If ``True``, use ``statsmodels`` to estimate a nonparametric lowess\n model (locally weighted linear regression). Note that confidence\n intervals cannot currently be drawn for this kind of model.\\\n \"\"\"),\n robust=dedent(\"\"\"\\\n robust : bool, optional\n If ``True``, use ``statsmodels`` to estimate a robust regression. This\n will de-weight outliers. Note that this is substantially more\n computationally intensive than standard linear regression, so you may\n wish to decrease the number of bootstrap resamples (``n_boot``) or set\n ``ci`` to None.\\\n \"\"\"),\n logx=dedent(\"\"\"\\\n logx : bool, optional\n If ``True``, estimate a linear regression of the form y ~ log(x), but\n plot the scatterplot and regression model in the input space. Note that\n ``x`` must be positive for this to work.\\\n \"\"\"),\n xy_partial=dedent(\"\"\"\\\n {x,y}_partial : strings in ``data`` or matrices\n Confounding variables to regress out of the ``x`` or ``y`` variables\n before plotting.\\\n \"\"\"),\n truncate=dedent(\"\"\"\\\n truncate : bool, optional\n If ``True``, the regression line is bounded by the data limits. If\n ``False``, it extends to the ``x`` axis limits.\n \"\"\"),\n xy_jitter=dedent(\"\"\"\\\n {x,y}_jitter : floats, optional\n Add uniform random noise of this size to either the ``x`` or ``y``\n variables. The noise is added to a copy of the data after fitting the\n regression, and only influences the look of the scatterplot. This can\n be helpful when plotting variables that take discrete values.\\\n \"\"\"),\n scatter_line_kws=dedent(\"\"\"\\\n {scatter,line}_kws : dictionaries\n Additional keyword arguments to pass to ``plt.scatter`` and\n ``plt.plot``.\\\n \"\"\"),\n)\n_regression_docs.update(_facet_docs)\n\n\ndef lmplot(\n data=None, *,\n x=None, y=None, hue=None, col=None, row=None,\n palette=None, col_wrap=None, height=5, aspect=1, markers=\"o\",\n sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None,\n legend=True, legend_out=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None,\n line_kws=None, facet_kws=None,\n):\n\n if facet_kws is None:\n facet_kws = {}\n\n def facet_kw_deprecation(key, val):\n msg = (\n f\"{key} is deprecated from the `lmplot` function signature. \"\n \"Please update your code to pass it using `facet_kws`.\"\n )\n if val is not None:\n warnings.warn(msg, UserWarning)\n facet_kws[key] = val\n\n facet_kw_deprecation(\"sharex\", sharex)\n facet_kw_deprecation(\"sharey\", sharey)\n facet_kw_deprecation(\"legend_out\", legend_out)\n\n if data is None:\n raise TypeError(\"Missing required keyword argument `data`.\")\n\n # Reduce the dataframe to only needed columns\n need_cols = [x, y, hue, col, row, units, x_partial, y_partial]\n cols = np.unique([a for a in need_cols if a is not None]).tolist()\n data = data[cols]\n\n # Initialize the grid\n facets = FacetGrid(\n data, row=row, col=col, hue=hue,\n palette=palette,\n row_order=row_order, col_order=col_order, hue_order=hue_order,\n height=height, aspect=aspect, col_wrap=col_wrap,\n **facet_kws,\n )\n\n # Add the markers here as FacetGrid has figured out how many levels of the\n # hue variable are needed and we don't want to duplicate that process\n if facets.hue_names is None:\n n_markers = 1\n else:\n n_markers = len(facets.hue_names)\n if not isinstance(markers, list):\n markers = [markers] * n_markers\n if len(markers) != n_markers:\n raise ValueError(\"markers must be a singleton or a list of markers \"\n \"for each level of the hue variable\")\n facets.hue_kws = {\"marker\": markers}\n\n def update_datalim(data, x, y, ax, **kws):\n xys = data[[x, y]].to_numpy().astype(float)\n ax.update_datalim(xys, updatey=False)\n ax.autoscale_view(scaley=False)\n\n facets.map_dataframe(update_datalim, x=x, y=y)\n\n # Draw the regression plot on each facet\n regplot_kws = dict(\n x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci,\n scatter=scatter, fit_reg=fit_reg, ci=ci, n_boot=n_boot, units=units,\n seed=seed, order=order, logistic=logistic, lowess=lowess,\n robust=robust, logx=logx, x_partial=x_partial, y_partial=y_partial,\n truncate=truncate, x_jitter=x_jitter, y_jitter=y_jitter,\n scatter_kws=scatter_kws, line_kws=line_kws,\n )\n facets.map_dataframe(regplot, x=x, y=y, **regplot_kws)\n facets.set_axis_labels(x, y)\n\n # Add a legend\n if legend and (hue is not None) and (hue not in [col, row]):\n facets.add_legend()\n return facets\n\n\nlmplot.__doc__ = dedent(\"\"\"\\\n Plot data and regression model fits across a FacetGrid.\n\n This function combines :func:`regplot` and :class:`FacetGrid`. It is\n intended as a convenient interface to fit regression models across\n conditional subsets of a dataset.\n\n When thinking about how to assign variables to different facets, a general\n rule is that it makes sense to use ``hue`` for the most important\n comparison, followed by ``col`` and ``row``. However, always think about\n your particular dataset and the goals of the visualization you are\n creating.\n\n {model_api}\n\n The parameters to this function span most of the options in\n :class:`FacetGrid`, although there may be occasional cases where you will\n want to use that class and :func:`regplot` directly.\n\n Parameters\n ----------\n {data}\n x, y : strings, optional\n Input variables; these should be column names in ``data``.\n hue, col, row : strings\n Variables that define subsets of the data, which will be drawn on\n separate facets in the grid. See the ``*_order`` parameters to control\n the order of levels of this variable.\n {palette}\n {col_wrap}\n {height}\n {aspect}\n markers : matplotlib marker code or list of marker codes, optional\n Markers for the scatterplot. If a list, each marker in the list will be\n used for each level of the ``hue`` variable.\n {share_xy}\n\n .. deprecated:: 0.12.0\n Pass using the `facet_kws` dictionary.\n\n {{hue,col,row}}_order : lists, optional\n Order for the levels of the faceting variables. By default, this will\n be the order that the levels appear in ``data`` or, if the variables\n are pandas categoricals, the category order.\n legend : bool, optional\n If ``True`` and there is a ``hue`` variable, add a legend.\n {legend_out}\n\n .. deprecated:: 0.12.0\n Pass using the `facet_kws` dictionary.\n\n {x_estimator}\n {x_bins}\n {x_ci}\n {scatter}\n {fit_reg}\n {ci}\n {n_boot}\n {units}\n {seed}\n {order}\n {logistic}\n {lowess}\n {robust}\n {logx}\n {xy_partial}\n {truncate}\n {xy_jitter}\n {scatter_line_kws}\n facet_kws : dict\n Dictionary of keyword arguments for :class:`FacetGrid`.\n\n See Also\n --------\n regplot : Plot data and a conditional model fit.\n FacetGrid : Subplot grid for plotting conditional relationships.\n pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with\n ``kind=\"reg\"``).\n\n Notes\n -----\n\n {regplot_vs_lmplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/lmplot.rst\n\n \"\"\").format(**_regression_docs)\n\n\ndef regplot(\n data=None, *, x=None, y=None,\n x_estimator=None, x_bins=None, x_ci=\"ci\",\n scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None,\n seed=None, order=1, logistic=False, lowess=False, robust=False,\n logx=False, x_partial=None, y_partial=None,\n truncate=True, dropna=True, x_jitter=None, y_jitter=None,\n label=None, color=None, marker=\"o\",\n scatter_kws=None, line_kws=None, ax=None\n):\n\n plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci,\n scatter, fit_reg, ci, n_boot, units, seed,\n order, logistic, lowess, robust, logx,\n x_partial, y_partial, truncate, dropna,\n x_jitter, y_jitter, color, label)\n\n if ax is None:\n ax = plt.gca()\n\n scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws)\n scatter_kws[\"marker\"] = marker\n line_kws = {} if line_kws is None else copy.copy(line_kws)\n plotter.plot(ax, scatter_kws, line_kws)\n return ax\n\n\nregplot.__doc__ = dedent(\"\"\"\\\n Plot data and a linear regression model fit.\n\n {model_api}\n\n Parameters\n ----------\n x, y: string, series, or vector array\n Input variables. If strings, these should correspond with column names\n in ``data``. When pandas objects are used, axes will be labeled with\n the series name.\n {data}\n {x_estimator}\n {x_bins}\n {x_ci}\n {scatter}\n {fit_reg}\n {ci}\n {n_boot}\n {units}\n {seed}\n {order}\n {logistic}\n {lowess}\n {robust}\n {logx}\n {xy_partial}\n {truncate}\n {xy_jitter}\n label : string\n Label to apply to either the scatterplot or regression line (if\n ``scatter`` is ``False``) for use in a legend.\n color : matplotlib color\n Color to apply to all plot elements; will be superseded by colors\n passed in ``scatter_kws`` or ``line_kws``.\n marker : matplotlib marker code\n Marker to use for the scatterplot glyphs.\n {scatter_line_kws}\n ax : matplotlib Axes, optional\n Axes object to draw the plot onto, otherwise uses the current Axes.\n\n Returns\n -------\n ax : matplotlib Axes\n The Axes object containing the plot.\n\n See Also\n --------\n lmplot : Combine :func:`regplot` and :class:`FacetGrid` to plot multiple\n linear relationships in a dataset.\n jointplot : Combine :func:`regplot` and :class:`JointGrid` (when used with\n ``kind=\"reg\"``).\n pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with\n ``kind=\"reg\"``).\n residplot : Plot the residuals of a linear regression model.\n\n Notes\n -----\n\n {regplot_vs_lmplot}\n\n\n It's also easy to combine :func:`regplot` and :class:`JointGrid` or\n :class:`PairGrid` through the :func:`jointplot` and :func:`pairplot`\n functions, although these do not directly accept all of :func:`regplot`'s\n parameters.\n\n Examples\n --------\n\n .. include: ../docstrings/regplot.rst\n\n \"\"\").format(**_regression_docs)\n\n\ndef residplot(\n data=None, *, x=None, y=None,\n x_partial=None, y_partial=None, lowess=False,\n order=1, robust=False, dropna=True, label=None, color=None,\n scatter_kws=None, line_kws=None, ax=None\n):\n \"\"\"Plot the residuals of a linear regression.\n\n This function will regress y on x (possibly as a robust or polynomial\n regression) and then draw a scatterplot of the residuals. You can\n optionally fit a lowess smoother to the residual plot, which can\n help in determining if there is structure to the residuals.\n\n Parameters\n ----------\n data : DataFrame, optional\n DataFrame to use if `x` and `y` are column names.\n x : vector or string\n Data or column name in `data` for the predictor variable.\n y : vector or string\n Data or column name in `data` for the response variable.\n {x, y}_partial : vectors or string(s) , optional\n These variables are treated as confounding and are removed from\n the `x` or `y` variables before plotting.\n lowess : boolean, optional\n Fit a lowess smoother to the residual scatterplot.\n order : int, optional\n Order of the polynomial to fit when calculating the residuals.\n robust : boolean, optional\n Fit a robust linear regression when calculating the residuals.\n dropna : boolean, optional\n If True, ignore observations with missing data when fitting and\n plotting.\n label : string, optional\n Label that will be used in any plot legends.\n color : matplotlib color, optional\n Color to use for all elements of the plot.\n {scatter, line}_kws : dictionaries, optional\n Additional keyword arguments passed to scatter() and plot() for drawing\n the components of the plot.\n ax : matplotlib axis, optional\n Plot into this axis, otherwise grab the current axis or make a new\n one if not existing.\n\n Returns\n -------\n ax: matplotlib axes\n Axes with the regression plot.\n\n See Also\n --------\n regplot : Plot a simple linear regression model.\n jointplot : Draw a :func:`residplot` with univariate marginal distributions\n (when used with ``kind=\"resid\"``).\n\n Examples\n --------\n\n .. include:: ../docstrings/residplot.rst\n\n \"\"\"\n plotter = _RegressionPlotter(x, y, data, ci=None,\n order=order, robust=robust,\n x_partial=x_partial, y_partial=y_partial,\n dropna=dropna, color=color, label=label)\n\n if ax is None:\n ax = plt.gca()\n\n # Calculate the residual from a linear regression\n _, yhat, _ = plotter.fit_regression(grid=plotter.x)\n plotter.y = plotter.y - yhat\n\n # Set the regression option on the plotter\n if lowess:\n plotter.lowess = True\n else:\n plotter.fit_reg = False\n\n # Plot a horizontal line at 0\n ax.axhline(0, ls=\":\", c=\".2\")\n\n # Draw the scatterplot\n scatter_kws = {} if scatter_kws is None else scatter_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n plotter.plot(ax, scatter_kws, line_kws)\n return ax\n"},{"col":0,"comment":"null","endLoc":102,"header":"def dedent(text: str) -> str","id":30,"name":"dedent","nodeType":"Function","startLoc":102,"text":"def dedent(text: str) -> str: ..."},{"id":31,"name":"seaborn/_marks","nodeType":"Package"},{"fileName":"bar.py","filePath":"seaborn/_marks","id":32,"nodeType":"File","text":"from __future__ import annotations\nfrom collections import defaultdict\nfrom dataclasses import dataclass\n\nimport numpy as np\nimport matplotlib as mpl\n\nfrom seaborn._marks.base import (\n Mark,\n Mappable,\n MappableBool,\n MappableColor,\n MappableFloat,\n MappableStyle,\n resolve_properties,\n resolve_color,\n document_properties\n)\nfrom seaborn.external.version import Version\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Any\n from matplotlib.artist import Artist\n from seaborn._core.scales import Scale\n\n\nclass BarBase(Mark):\n\n def _make_patches(self, data, scales, orient):\n\n kws = self._resolve_properties(data, scales)\n if orient == \"x\":\n kws[\"x\"] = (data[\"x\"] - data[\"width\"] / 2).to_numpy()\n kws[\"y\"] = data[\"baseline\"].to_numpy()\n kws[\"w\"] = data[\"width\"].to_numpy()\n kws[\"h\"] = (data[\"y\"] - data[\"baseline\"]).to_numpy()\n else:\n kws[\"x\"] = data[\"baseline\"].to_numpy()\n kws[\"y\"] = (data[\"y\"] - data[\"width\"] / 2).to_numpy()\n kws[\"w\"] = (data[\"x\"] - data[\"baseline\"]).to_numpy()\n kws[\"h\"] = data[\"width\"].to_numpy()\n\n kws.pop(\"width\", None)\n kws.pop(\"baseline\", None)\n\n val_dim = {\"x\": \"h\", \"y\": \"w\"}[orient]\n bars, vals = [], []\n\n for i in range(len(data)):\n\n row = {k: v[i] for k, v in kws.items()}\n\n # Skip bars with no value. It's possible we'll want to make this\n # an option (i.e so you have an artist for animating or annotating),\n # but let's keep things simple for now.\n if not np.nan_to_num(row[val_dim]):\n continue\n\n bar = mpl.patches.Rectangle(\n xy=(row[\"x\"], row[\"y\"]),\n width=row[\"w\"],\n height=row[\"h\"],\n facecolor=row[\"facecolor\"],\n edgecolor=row[\"edgecolor\"],\n linestyle=row[\"edgestyle\"],\n linewidth=row[\"edgewidth\"],\n **self.artist_kws,\n )\n bars.append(bar)\n vals.append(row[val_dim])\n\n return bars, vals\n\n def _resolve_properties(self, data, scales):\n\n resolved = resolve_properties(self, data, scales)\n\n resolved[\"facecolor\"] = resolve_color(self, data, \"\", scales)\n resolved[\"edgecolor\"] = resolve_color(self, data, \"edge\", scales)\n\n fc = resolved[\"facecolor\"]\n if isinstance(fc, tuple):\n resolved[\"facecolor\"] = fc[0], fc[1], fc[2], fc[3] * resolved[\"fill\"]\n else:\n fc[:, 3] = fc[:, 3] * resolved[\"fill\"] # TODO Is inplace mod a problem?\n resolved[\"facecolor\"] = fc\n\n return resolved\n\n def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n # TODO return some sensible default?\n key = {v: value for v in variables}\n key = self._resolve_properties(key, scales)\n artist = mpl.patches.Patch(\n facecolor=key[\"facecolor\"],\n edgecolor=key[\"edgecolor\"],\n linewidth=key[\"edgewidth\"],\n linestyle=key[\"edgestyle\"],\n )\n return artist\n\n\n@document_properties\n@dataclass\nclass Bar(BarBase):\n \"\"\"\n A bar mark drawn between baseline and data values.\n\n See also\n --------\n Bars : A faster bar mark with defaults more suitable for histograms.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Bar.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(.7, grouping=False)\n fill: MappableBool = Mappable(True, grouping=False)\n edgecolor: MappableColor = Mappable(depend=\"color\", grouping=False)\n edgealpha: MappableFloat = Mappable(1, grouping=False)\n edgewidth: MappableFloat = Mappable(rc=\"patch.linewidth\", grouping=False)\n edgestyle: MappableStyle = Mappable(\"-\", grouping=False)\n # pattern: MappableString = Mappable(None) # TODO no Property yet\n\n width: MappableFloat = Mappable(.8, grouping=False)\n baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable?\n\n def _plot(self, split_gen, scales, orient):\n\n val_idx = [\"y\", \"x\"].index(orient)\n\n for _, data, ax in split_gen():\n\n bars, vals = self._make_patches(data, scales, orient)\n\n for bar in bars:\n\n # Because we are clipping the artist (see below), the edges end up\n # looking half as wide as they actually are. I don't love this clumsy\n # workaround, which is going to cause surprises if you work with the\n # artists directly. We may need to revisit after feedback.\n bar.set_linewidth(bar.get_linewidth() * 2)\n linestyle = bar.get_linestyle()\n if linestyle[1]:\n linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1]))\n bar.set_linestyle(linestyle)\n\n # This is a bit of a hack to handle the fact that the edge lines are\n # centered on the actual extents of the bar, and overlap when bars are\n # stacked or dodged. We may discover that this causes problems and needs\n # to be revisited at some point. Also it should be faster to clip with\n # a bbox than a path, but I cant't work out how to get the intersection\n # with the axes bbox.\n bar.set_clip_path(bar.get_path(), bar.get_transform() + ax.transData)\n if self.artist_kws.get(\"clip_on\", True):\n # It seems the above hack undoes the default axes clipping\n bar.set_clip_box(ax.bbox)\n bar.sticky_edges[val_idx][:] = (0, np.inf)\n ax.add_patch(bar)\n\n # Add a container which is useful for, e.g. Axes.bar_label\n if Version(mpl.__version__) >= Version(\"3.4.0\"):\n orientation = {\"x\": \"vertical\", \"y\": \"horizontal\"}[orient]\n container_kws = dict(datavalues=vals, orientation=orientation)\n else:\n container_kws = {}\n container = mpl.container.BarContainer(bars, **container_kws)\n ax.add_container(container)\n\n\n@document_properties\n@dataclass\nclass Bars(BarBase):\n \"\"\"\n A faster bar mark with defaults more suitable histograms.\n\n See also\n --------\n Bar : A bar mark drawn between baseline and data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Bars.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(.7, grouping=False)\n fill: MappableBool = Mappable(True, grouping=False)\n edgecolor: MappableColor = Mappable(rc=\"patch.edgecolor\", grouping=False)\n edgealpha: MappableFloat = Mappable(1, grouping=False)\n edgewidth: MappableFloat = Mappable(auto=True, grouping=False)\n edgestyle: MappableStyle = Mappable(\"-\", grouping=False)\n # pattern: MappableString = Mappable(None) # TODO no Property yet\n\n width: MappableFloat = Mappable(1, grouping=False)\n baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable?\n\n def _plot(self, split_gen, scales, orient):\n\n ori_idx = [\"x\", \"y\"].index(orient)\n val_idx = [\"y\", \"x\"].index(orient)\n\n patches = defaultdict(list)\n for _, data, ax in split_gen():\n bars, _ = self._make_patches(data, scales, orient)\n patches[ax].extend(bars)\n\n collections = {}\n for ax, ax_patches in patches.items():\n\n col = mpl.collections.PatchCollection(ax_patches, match_original=True)\n col.sticky_edges[val_idx][:] = (0, np.inf)\n ax.add_collection(col, autolim=False)\n collections[ax] = col\n\n # Workaround for matplotlib autoscaling bug\n # https://github.com/matplotlib/matplotlib/issues/11898\n # https://github.com/matplotlib/matplotlib/issues/23129\n xys = np.vstack([path.vertices for path in col.get_paths()])\n ax.update_datalim(xys)\n\n if \"edgewidth\" not in scales and isinstance(self.edgewidth, Mappable):\n\n for ax in collections:\n ax.autoscale_view()\n\n def get_dimensions(collection):\n edges, widths = [], []\n for verts in (path.vertices for path in collection.get_paths()):\n edges.append(min(verts[:, ori_idx]))\n widths.append(np.ptp(verts[:, ori_idx]))\n return np.array(edges), np.array(widths)\n\n min_width = np.inf\n for ax, col in collections.items():\n edges, widths = get_dimensions(col)\n points = 72 / ax.figure.dpi * abs(\n ax.transData.transform([edges + widths] * 2)\n - ax.transData.transform([edges] * 2)\n )\n min_width = min(min_width, min(points[:, ori_idx]))\n\n linewidth = min(.1 * min_width, mpl.rcParams[\"patch.linewidth\"])\n for _, col in collections.items():\n col.set_linewidth(linewidth)\n"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":20,"id":33,"name":"annotations","nodeType":"Attribute","startLoc":20,"text":"annotations"},{"fileName":"text.py","filePath":"seaborn/_marks","id":34,"nodeType":"File","text":"from __future__ import annotations\nfrom collections import defaultdict\nfrom dataclasses import dataclass\n\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib.transforms import ScaledTranslation\n\nfrom seaborn._marks.base import (\n Mark,\n Mappable,\n MappableFloat,\n MappableString,\n MappableColor,\n resolve_properties,\n resolve_color,\n document_properties,\n)\n\n\n@document_properties\n@dataclass\nclass Text(Mark):\n \"\"\"\n A textual mark to annotate or represent data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Text.rst\n\n \"\"\"\n text: MappableString = Mappable(\"\")\n color: MappableColor = Mappable(\"k\")\n alpha: MappableFloat = Mappable(1)\n fontsize: MappableFloat = Mappable(rc=\"font.size\")\n halign: MappableString = Mappable(\"center\")\n valign: MappableString = Mappable(\"center_baseline\")\n offset: MappableFloat = Mappable(4)\n\n def _plot(self, split_gen, scales, orient):\n\n ax_data = defaultdict(list)\n\n for keys, data, ax in split_gen():\n\n vals = resolve_properties(self, keys, scales)\n color = resolve_color(self, keys, \"\", scales)\n\n halign = vals[\"halign\"]\n valign = vals[\"valign\"]\n fontsize = vals[\"fontsize\"]\n offset = vals[\"offset\"] / 72\n\n offset_trans = ScaledTranslation(\n {\"right\": -offset, \"left\": +offset}.get(halign, 0),\n {\"top\": -offset, \"bottom\": +offset, \"baseline\": +offset}.get(valign, 0),\n ax.figure.dpi_scale_trans,\n )\n\n for row in data.to_dict(\"records\"):\n artist = mpl.text.Text(\n x=row[\"x\"],\n y=row[\"y\"],\n text=str(row.get(\"text\", vals[\"text\"])),\n color=color,\n fontsize=fontsize,\n horizontalalignment=halign,\n verticalalignment=valign,\n transform=ax.transData + offset_trans,\n **self.artist_kws,\n )\n ax.add_artist(artist)\n ax_data[ax].append([row[\"x\"], row[\"y\"]])\n\n for ax, ax_vals in ax_data.items():\n ax.update_datalim(np.array(ax_vals))\n"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":20,"id":35,"name":"annotations","nodeType":"Attribute","startLoc":20,"text":"annotations"},{"className":"defaultdict","col":0,"comment":"null","endLoc":446,"id":36,"nodeType":"Class","startLoc":400,"text":"class defaultdict(dict[_KT, _VT]):\n default_factory: Callable[[], _VT] | None\n @overload\n def __init__(self) -> None: ...\n @overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None: ...\n def __missing__(self, key: _KT, /) -> _VT: ...\n def __copy__(self) -> Self: ...\n def copy(self) -> Self: ...\n if sys.version_info >= (3, 9):\n @overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ...\n @overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"className":"defaultdict","col":0,"comment":"null","endLoc":446,"id":37,"nodeType":"Class","startLoc":400,"text":"class defaultdict(dict[_KT, _VT]):\n default_factory: Callable[[], _VT] | None\n @overload\n def __init__(self) -> None: ...\n @overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None: ...\n def __missing__(self, key: _KT, /) -> _VT: ...\n def __copy__(self) -> Self: ...\n def copy(self) -> Self: ...\n if sys.version_info >= (3, 9):\n @overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ...\n @overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"fileName":"line.py","filePath":"seaborn/_marks","id":38,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import ClassVar\n\nimport numpy as np\nimport matplotlib as mpl\n\nfrom seaborn._marks.base import (\n Mark,\n Mappable,\n MappableFloat,\n MappableString,\n MappableColor,\n resolve_properties,\n resolve_color,\n document_properties,\n)\nfrom seaborn.external.version import Version\n\n\n@document_properties\n@dataclass\nclass Path(Mark):\n \"\"\"\n A mark connecting data points in the order they appear.\n\n See also\n --------\n Line : A mark connecting data points with sorting along the orientation axis.\n Paths : A faster but less-flexible mark for drawing many paths.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Path.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\")\n alpha: MappableFloat = Mappable(1)\n linewidth: MappableFloat = Mappable(rc=\"lines.linewidth\")\n linestyle: MappableString = Mappable(rc=\"lines.linestyle\")\n marker: MappableString = Mappable(rc=\"lines.marker\")\n pointsize: MappableFloat = Mappable(rc=\"lines.markersize\")\n fillcolor: MappableColor = Mappable(depend=\"color\")\n edgecolor: MappableColor = Mappable(depend=\"color\")\n edgewidth: MappableFloat = Mappable(rc=\"lines.markeredgewidth\")\n\n _sort: ClassVar[bool] = False\n\n def _plot(self, split_gen, scales, orient):\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n vals[\"fillcolor\"] = resolve_color(self, keys, prefix=\"fill\", scales=scales)\n vals[\"edgecolor\"] = resolve_color(self, keys, prefix=\"edge\", scales=scales)\n\n # https://github.com/matplotlib/matplotlib/pull/16692\n if Version(mpl.__version__) < Version(\"3.3.0\"):\n vals[\"marker\"] = vals[\"marker\"]._marker\n\n if self._sort:\n data = data.sort_values(orient, kind=\"mergesort\")\n\n artist_kws = self.artist_kws.copy()\n self._handle_capstyle(artist_kws, vals)\n\n line = mpl.lines.Line2D(\n data[\"x\"].to_numpy(),\n data[\"y\"].to_numpy(),\n color=vals[\"color\"],\n linewidth=vals[\"linewidth\"],\n linestyle=vals[\"linestyle\"],\n marker=vals[\"marker\"],\n markersize=vals[\"pointsize\"],\n markerfacecolor=vals[\"fillcolor\"],\n markeredgecolor=vals[\"edgecolor\"],\n markeredgewidth=vals[\"edgewidth\"],\n **artist_kws,\n )\n ax.add_line(line)\n\n def _legend_artist(self, variables, value, scales):\n\n keys = {v: value for v in variables}\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n vals[\"fillcolor\"] = resolve_color(self, keys, prefix=\"fill\", scales=scales)\n vals[\"edgecolor\"] = resolve_color(self, keys, prefix=\"edge\", scales=scales)\n\n # https://github.com/matplotlib/matplotlib/pull/16692\n if Version(mpl.__version__) < Version(\"3.3.0\"):\n vals[\"marker\"] = vals[\"marker\"]._marker\n\n artist_kws = self.artist_kws.copy()\n self._handle_capstyle(artist_kws, vals)\n\n return mpl.lines.Line2D(\n [], [],\n color=vals[\"color\"],\n linewidth=vals[\"linewidth\"],\n linestyle=vals[\"linestyle\"],\n marker=vals[\"marker\"],\n markersize=vals[\"pointsize\"],\n markerfacecolor=vals[\"fillcolor\"],\n markeredgecolor=vals[\"edgecolor\"],\n markeredgewidth=vals[\"edgewidth\"],\n **artist_kws,\n )\n\n def _handle_capstyle(self, kws, vals):\n\n # Work around for this matplotlib issue:\n # https://github.com/matplotlib/matplotlib/issues/23437\n if vals[\"linestyle\"][1] is None:\n capstyle = kws.get(\"solid_capstyle\", mpl.rcParams[\"lines.solid_capstyle\"])\n kws[\"dash_capstyle\"] = capstyle\n\n\n@document_properties\n@dataclass\nclass Line(Path):\n \"\"\"\n A mark connecting data points with sorting along the orientation axis.\n\n See also\n --------\n Path : A mark connecting data points in the order they appear.\n Lines : A faster but less-flexible mark for drawing many lines.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Line.rst\n\n \"\"\"\n _sort: ClassVar[bool] = True\n\n\n@document_properties\n@dataclass\nclass Paths(Mark):\n \"\"\"\n A faster but less-flexible mark for drawing many paths.\n\n See also\n --------\n Path : A mark connecting data points in the order they appear.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Paths.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\")\n alpha: MappableFloat = Mappable(1)\n linewidth: MappableFloat = Mappable(rc=\"lines.linewidth\")\n linestyle: MappableString = Mappable(rc=\"lines.linestyle\")\n\n _sort: ClassVar[bool] = False\n\n def __post_init__(self):\n\n # LineCollection artists have a capstyle property but don't source its value\n # from the rc, so we do that manually here. Unfortunately, because we add\n # only one LineCollection, we have the use the same capstyle for all lines\n # even when they are dashed. It's a slight inconsistency, but looks fine IMO.\n self.artist_kws.setdefault(\"capstyle\", mpl.rcParams[\"lines.solid_capstyle\"])\n\n def _setup_lines(self, split_gen, scales, orient):\n\n line_data = {}\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n if ax not in line_data:\n line_data[ax] = {\n \"segments\": [],\n \"colors\": [],\n \"linewidths\": [],\n \"linestyles\": [],\n }\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n\n if self._sort:\n data = data.sort_values(orient, kind=\"mergesort\")\n\n # Column stack to avoid block consolidation\n xy = np.column_stack([data[\"x\"], data[\"y\"]])\n line_data[ax][\"segments\"].append(xy)\n line_data[ax][\"colors\"].append(vals[\"color\"])\n line_data[ax][\"linewidths\"].append(vals[\"linewidth\"])\n line_data[ax][\"linestyles\"].append(vals[\"linestyle\"])\n\n return line_data\n\n def _plot(self, split_gen, scales, orient):\n\n line_data = self._setup_lines(split_gen, scales, orient)\n\n for ax, ax_data in line_data.items():\n lines = mpl.collections.LineCollection(**ax_data, **self.artist_kws)\n # Handle datalim update manually\n # https://github.com/matplotlib/matplotlib/issues/23129\n ax.add_collection(lines, autolim=False)\n if ax_data[\"segments\"]:\n xy = np.concatenate(ax_data[\"segments\"])\n ax.update_datalim(xy)\n\n def _legend_artist(self, variables, value, scales):\n\n key = resolve_properties(self, {v: value for v in variables}, scales)\n\n artist_kws = self.artist_kws.copy()\n capstyle = artist_kws.pop(\"capstyle\")\n artist_kws[\"solid_capstyle\"] = capstyle\n artist_kws[\"dash_capstyle\"] = capstyle\n\n return mpl.lines.Line2D(\n [], [],\n color=key[\"color\"],\n linewidth=key[\"linewidth\"],\n linestyle=key[\"linestyle\"],\n **artist_kws,\n )\n\n\n@document_properties\n@dataclass\nclass Lines(Paths):\n \"\"\"\n A faster but less-flexible mark for drawing many lines.\n\n See also\n --------\n Line : A mark connecting data points with sorting along the orientation axis.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Lines.rst\n\n \"\"\"\n _sort: ClassVar[bool] = True\n\n\n@document_properties\n@dataclass\nclass Range(Paths):\n \"\"\"\n An oriented line mark drawn between min/max values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Range.rst\n\n \"\"\"\n def _setup_lines(self, split_gen, scales, orient):\n\n line_data = {}\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n if ax not in line_data:\n line_data[ax] = {\n \"segments\": [],\n \"colors\": [],\n \"linewidths\": [],\n \"linestyles\": [],\n }\n\n # TODO better checks on what variables we have\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n\n # TODO what if only one exist?\n if not set(data.columns) & {f\"{other}min\", f\"{other}max\"}:\n agg = {f\"{other}min\": (other, \"min\"), f\"{other}max\": (other, \"max\")}\n data = data.groupby(orient).agg(**agg).reset_index()\n\n cols = [orient, f\"{other}min\", f\"{other}max\"]\n data = data[cols].melt(orient, value_name=other)[[\"x\", \"y\"]]\n segments = [d.to_numpy() for _, d in data.groupby(orient)]\n\n line_data[ax][\"segments\"].extend(segments)\n\n n = len(segments)\n line_data[ax][\"colors\"].extend([vals[\"color\"]] * n)\n line_data[ax][\"linewidths\"].extend([vals[\"linewidth\"]] * n)\n line_data[ax][\"linestyles\"].extend([vals[\"linestyle\"]] * n)\n\n return line_data\n"},{"col":0,"comment":"null","endLoc":58,"header":"@overload\ndef dataclass(cls: None, /) -> Callable[[type[_T]], type[_T]]","id":39,"name":"dataclass","nodeType":"Function","startLoc":57,"text":"@overload\ndef dataclass(cls: None, /) -> Callable[[type[_T]], type[_T]]: ..."},{"col":0,"comment":"null","endLoc":60,"header":"@overload\ndef dataclass(cls: type[_T], /) -> type[_T]","id":40,"name":"dataclass","nodeType":"Function","startLoc":59,"text":"@overload\ndef dataclass(cls: type[_T], /) -> type[_T]: ..."},{"col":4,"comment":"null","endLoc":103,"header":"@overload\n def dataclass(\n *,\n init: bool = True,\n repr: bool = True,\n eq: bool = True,\n order: bool = False,\n unsafe_hash: bool = False,\n frozen: bool = False,\n ) -> Callable[[type[_T]], type[_T]]","id":41,"name":"dataclass","nodeType":"Function","startLoc":94,"text":"@overload\n def dataclass(\n *,\n init: bool = True,\n repr: bool = True,\n eq: bool = True,\n order: bool = False,\n unsafe_hash: bool = False,\n frozen: bool = False,\n ) -> Callable[[type[_T]], type[_T]]: ..."},{"attributeType":"_SpecialForm","col":0,"comment":"null","endLoc":207,"id":42,"name":"ClassVar","nodeType":"Attribute","startLoc":207,"text":"ClassVar"},{"id":43,"name":"seaborn/_core","nodeType":"Package"},{"fileName":"scales.py","filePath":"seaborn/_core","id":44,"nodeType":"File","text":"from __future__ import annotations\nimport re\nfrom copy import copy\nfrom collections.abc import Sequence\nfrom dataclasses import dataclass\nfrom functools import partial\nfrom typing import Any, Callable, Tuple, Optional, ClassVar\n\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib.ticker import (\n Locator,\n Formatter,\n AutoLocator,\n AutoMinorLocator,\n FixedLocator,\n LinearLocator,\n LogLocator,\n SymmetricalLogLocator,\n MaxNLocator,\n MultipleLocator,\n EngFormatter,\n FuncFormatter,\n LogFormatterSciNotation,\n ScalarFormatter,\n StrMethodFormatter,\n)\nfrom matplotlib.dates import (\n AutoDateLocator,\n AutoDateFormatter,\n ConciseDateFormatter,\n)\nfrom matplotlib.axis import Axis\nfrom matplotlib.scale import ScaleBase\nfrom pandas import Series\n\nfrom seaborn._core.rules import categorical_order\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from seaborn._core.properties import Property\n from numpy.typing import ArrayLike, NDArray\n\n TransFuncs = Tuple[\n Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]\n ]\n\n # TODO Reverting typing to Any as it was proving too complicated to\n # work out the right way to communicate the types to mypy. Revisit!\n Pipeline = Sequence[Optional[Callable[[Any], Any]]]\n\n\nclass Scale:\n \"\"\"Base class for objects that map data values to visual properties.\"\"\"\n\n values: tuple | str | list | dict | None\n\n _priority: ClassVar[int]\n _pipeline: Pipeline\n _matplotlib_scale: ScaleBase\n _spacer: staticmethod\n _legend: tuple[list[str], list[Any]] | None\n\n def __post_init__(self):\n\n self._tick_params = None\n self._label_params = None\n self._legend = None\n\n def tick(self):\n raise NotImplementedError()\n\n def label(self):\n raise NotImplementedError()\n\n def _get_locators(self):\n raise NotImplementedError()\n\n def _get_formatter(self, locator: Locator | None = None):\n raise NotImplementedError()\n\n def _get_scale(self, name: str, forward: Callable, inverse: Callable):\n\n major_locator, minor_locator = self._get_locators(**self._tick_params)\n major_formatter = self._get_formatter(major_locator, **self._label_params)\n\n class InternalScale(mpl.scale.FuncScale):\n def set_default_locators_and_formatters(self, axis):\n axis.set_major_locator(major_locator)\n if minor_locator is not None:\n axis.set_minor_locator(minor_locator)\n axis.set_major_formatter(major_formatter)\n\n return InternalScale(name, (forward, inverse))\n\n def _spacing(self, x: Series) -> float:\n return self._spacer(x)\n\n def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n raise NotImplementedError()\n\n def __call__(self, data: Series) -> ArrayLike:\n\n trans_data: Series | NDArray | list\n\n # TODO sometimes we need to handle scalars (e.g. for Line)\n # but what is the best way to do that?\n scalar_data = np.isscalar(data)\n if scalar_data:\n trans_data = np.array([data])\n else:\n trans_data = data\n\n for func in self._pipeline:\n if func is not None:\n trans_data = func(trans_data)\n\n if scalar_data:\n return trans_data[0]\n else:\n return trans_data\n\n @staticmethod\n def _identity():\n\n class Identity(Scale):\n _pipeline = []\n _spacer = None\n _legend = None\n _matplotlib_scale = None\n\n return Identity()\n\n\n@dataclass\nclass Nominal(Scale):\n \"\"\"\n A categorical scale without relative importance / magnitude.\n \"\"\"\n # Categorical (convert to strings), un-sortable\n\n values: tuple | str | list | dict | None = None\n order: list | None = None\n\n _priority: ClassVar[int] = 3\n\n def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n\n new = copy(self)\n if new._tick_params is None:\n new = new.tick()\n if new._label_params is None:\n new = new.label()\n\n # TODO flexibility over format() which isn't great for numbers / dates\n stringify = np.vectorize(format)\n\n units_seed = categorical_order(data, new.order)\n\n # TODO move to Nominal._get_scale?\n # TODO this needs some more complicated rethinking about how to pass\n # a unit dictionary down to these methods, along with how much we want\n # to invest in their API. What is it useful for tick() to do here?\n # (Ordinal may be different if we draw that contrast).\n # Any customization we do to allow, e.g., label wrapping will probably\n # require defining our own Formatter subclass.\n # We could also potentially implement auto-wrapping in an Axis subclass\n # (see Axis.draw ... it already is computing the bboxes).\n # major_locator, minor_locator = new._get_locators(**new._tick_params)\n # major_formatter = new._get_formatter(major_locator, **new._label_params)\n\n class CatScale(mpl.scale.LinearScale):\n name = None # To work around mpl<3.4 compat issues\n\n def set_default_locators_and_formatters(self, axis):\n ...\n # axis.set_major_locator(major_locator)\n # if minor_locator is not None:\n # axis.set_minor_locator(minor_locator)\n # axis.set_major_formatter(major_formatter)\n\n mpl_scale = CatScale(data.name)\n if axis is None:\n axis = PseudoAxis(mpl_scale)\n\n # TODO Currently just used in non-Coordinate contexts, but should\n # we use this to (A) set the padding we want for categorial plots\n # and (B) allow the values parameter for a Coordinate to set xlim/ylim\n axis.set_view_interval(0, len(units_seed) - 1)\n\n new._matplotlib_scale = mpl_scale\n\n # TODO array cast necessary to handle float/int mixture, which we need\n # to solve in a more systematic way probably\n # (i.e. if we have [1, 2.5], do we want [1.0, 2.5]? Unclear)\n axis.update_units(stringify(np.array(units_seed)))\n\n # TODO define this more centrally\n def convert_units(x):\n # TODO only do this with explicit order?\n # (But also category dtype?)\n # TODO isin fails when units_seed mixes numbers and strings (numpy error?)\n # but np.isin also does not seem any faster? (Maybe not broadcasting in C)\n # keep = x.isin(units_seed)\n keep = np.array([x_ in units_seed for x_ in x], bool)\n out = np.full(len(x), np.nan)\n out[keep] = axis.convert_units(stringify(x[keep]))\n return out\n\n new._pipeline = [\n convert_units,\n prop.get_mapping(new, data),\n # TODO how to handle color representation consistency?\n ]\n\n def spacer(x):\n return 1\n\n new._spacer = spacer\n\n if prop.legend:\n new._legend = units_seed, list(stringify(units_seed))\n\n return new\n\n def tick(self, locator: Locator | None = None):\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n\n Returns\n -------\n Copy of self with new tick configuration.\n\n \"\"\"\n new = copy(self)\n new._tick_params = {\n \"locator\": locator,\n }\n return new\n\n def label(self, formatter: Formatter | None = None):\n \"\"\"\n Configure the selection of labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured matplotlib formatter; other parameters will not be used.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n new = copy(self)\n new._label_params = {\n \"formatter\": formatter,\n }\n return new\n\n def _get_locators(self, locator):\n\n if locator is not None:\n return locator, None\n\n locator = mpl.category.StrCategoryLocator({})\n\n return locator, None\n\n def _get_formatter(self, locator, formatter):\n\n if formatter is not None:\n return formatter\n\n formatter = mpl.category.StrCategoryFormatter({})\n\n return formatter\n\n\n@dataclass\nclass Ordinal(Scale):\n # Categorical (convert to strings), sortable, can skip ticklabels\n ...\n\n\n@dataclass\nclass Discrete(Scale):\n # Numeric, integral, can skip ticks/ticklabels\n ...\n\n\n@dataclass\nclass ContinuousBase(Scale):\n\n values: tuple | str | None = None\n norm: tuple | None = None\n\n def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n\n new = copy(self)\n if new._tick_params is None:\n new = new.tick()\n if new._label_params is None:\n new = new.label()\n\n forward, inverse = new._get_transform()\n\n mpl_scale = new._get_scale(str(data.name), forward, inverse)\n\n if axis is None:\n axis = PseudoAxis(mpl_scale)\n axis.update_units(data)\n\n mpl_scale.set_default_locators_and_formatters(axis)\n new._matplotlib_scale = mpl_scale\n\n normalize: Optional[Callable[[ArrayLike], ArrayLike]]\n if prop.normed:\n if new.norm is None:\n vmin, vmax = data.min(), data.max()\n else:\n vmin, vmax = new.norm\n vmin, vmax = axis.convert_units((vmin, vmax))\n a = forward(vmin)\n b = forward(vmax) - forward(vmin)\n\n def normalize(x):\n return (x - a) / b\n\n else:\n normalize = vmin = vmax = None\n\n new._pipeline = [\n axis.convert_units,\n forward,\n normalize,\n prop.get_mapping(new, data)\n ]\n\n def spacer(x):\n x = x.dropna().unique()\n if len(x) < 2:\n return np.nan\n return np.min(np.diff(np.sort(x)))\n new._spacer = spacer\n\n # TODO How to allow disabling of legend for all uses of property?\n # Could add a Scale parameter, or perhaps Scale.suppress()?\n # Are there other useful parameters that would be in Scale.legend()\n # besides allowing Scale.legend(False)?\n if prop.legend:\n axis.set_view_interval(vmin, vmax)\n locs = axis.major.locator()\n locs = locs[(vmin <= locs) & (locs <= vmax)]\n labels = axis.major.formatter.format_ticks(locs)\n new._legend = list(locs), list(labels)\n\n return new\n\n def _get_transform(self):\n\n arg = self.trans\n\n def get_param(method, default):\n if arg == method:\n return default\n return float(arg[len(method):])\n\n if arg is None:\n return _make_identity_transforms()\n elif isinstance(arg, tuple):\n return arg\n elif isinstance(arg, str):\n if arg == \"ln\":\n return _make_log_transforms()\n elif arg == \"logit\":\n base = get_param(\"logit\", 10)\n return _make_logit_transforms(base)\n elif arg.startswith(\"log\"):\n base = get_param(\"log\", 10)\n return _make_log_transforms(base)\n elif arg.startswith(\"symlog\"):\n c = get_param(\"symlog\", 1)\n return _make_symlog_transforms(c)\n elif arg.startswith(\"pow\"):\n exp = get_param(\"pow\", 2)\n return _make_power_transforms(exp)\n elif arg == \"sqrt\":\n return _make_sqrt_transforms()\n else:\n raise ValueError(f\"Unknown value provided for trans: {arg!r}\")\n\n\n@dataclass\nclass Continuous(ContinuousBase):\n \"\"\"\n A numeric scale supporting norms and functional transforms.\n \"\"\"\n values: tuple | str | None = None\n trans: str | TransFuncs | None = None\n\n # TODO Add this to deal with outliers?\n # outside: Literal[\"keep\", \"drop\", \"clip\"] = \"keep\"\n\n _priority: ClassVar[int] = 1\n\n def tick(\n self,\n locator: Locator | None = None, *,\n at: Sequence[float] = None,\n upto: int | None = None,\n count: int | None = None,\n every: float | None = None,\n between: tuple[float, float] | None = None,\n minor: int | None = None,\n ) -> Continuous:\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n at : sequence of floats\n Place ticks at these specific locations (in data units).\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n count : int\n Choose exactly this number of ticks, bounded by `between` or axis limits.\n every : float\n Choose locations at this interval of separation (in data units).\n between : pair of floats\n Bound upper / lower ticks when using `every` or `count`.\n minor : int\n Number of unlabeled ticks to draw between labeled \"major\" ticks.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n # Input checks\n if locator is not None and not isinstance(locator, Locator):\n raise TypeError(\n f\"Tick locator must be an instance of {Locator!r}, \"\n f\"not {type(locator)!r}.\"\n )\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n if log_base or symlog_thresh:\n if count is not None and between is None:\n raise RuntimeError(\"`count` requires `between` with log transform.\")\n if every is not None:\n raise RuntimeError(\"`every` not supported with log transform.\")\n\n new = copy(self)\n new._tick_params = {\n \"locator\": locator,\n \"at\": at,\n \"upto\": upto,\n \"count\": count,\n \"every\": every,\n \"between\": between,\n \"minor\": minor,\n }\n return new\n\n def label(\n self,\n formatter: Formatter | None = None, *,\n like: str | Callable | None = None,\n base: int | None = None,\n unit: str | None = None,\n ) -> Continuous:\n \"\"\"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n like : str or callable\n Either a format pattern (e.g., `\".2f\"`), a format string with fields named\n `x` and/or `pos` (e.g., `\"${x:.2f}\"`), or a callable that consumes a number\n and returns a string.\n base : number\n Use log formatter (with scientific notation) having this value as the base.\n unit : str or (str, str) tuple\n Use SI prefixes with these units (e.g., with `unit=\"g\"`, a tick value\n of 5000 will appear as `5 kg`). When a tuple, the first element gives the\n separator between the number and unit.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n \"\"\"\n # Input checks\n if formatter is not None and not isinstance(formatter, Formatter):\n raise TypeError(\n f\"Label formatter must be an instance of {Formatter!r}, \"\n f\"not {type(formatter)!r}\"\n )\n if like is not None and not (isinstance(like, str) or callable(like)):\n msg = f\"`like` must be a string or callable, not {type(like).__name__}.\"\n raise TypeError(msg)\n\n new = copy(self)\n new._label_params = {\n \"formatter\": formatter,\n \"like\": like,\n \"base\": base,\n \"unit\": unit,\n }\n return new\n\n def _parse_for_log_params(\n self, trans: str | TransFuncs | None\n ) -> tuple[float | None, float | None]:\n\n log_base = symlog_thresh = None\n if isinstance(trans, str):\n m = re.match(r\"^log(\\d*)\", trans)\n if m is not None:\n log_base = float(m[1] or 10)\n m = re.match(r\"symlog(\\d*)\", trans)\n if m is not None:\n symlog_thresh = float(m[1] or 1)\n return log_base, symlog_thresh\n\n def _get_locators(self, locator, at, upto, count, every, between, minor):\n\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n\n if locator is not None:\n major_locator = locator\n\n elif upto is not None:\n if log_base:\n major_locator = LogLocator(base=log_base, numticks=upto)\n else:\n major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10])\n\n elif count is not None:\n if between is None:\n # This is rarely useful (unless you are setting limits)\n major_locator = LinearLocator(count)\n else:\n if log_base or symlog_thresh:\n forward, inverse = self._get_transform()\n lo, hi = forward(between)\n ticks = inverse(np.linspace(lo, hi, num=count))\n else:\n ticks = np.linspace(*between, num=count)\n major_locator = FixedLocator(ticks)\n\n elif every is not None:\n if between is None:\n major_locator = MultipleLocator(every)\n else:\n lo, hi = between\n ticks = np.arange(lo, hi + every, every)\n major_locator = FixedLocator(ticks)\n\n elif at is not None:\n major_locator = FixedLocator(at)\n\n else:\n if log_base:\n major_locator = LogLocator(log_base)\n elif symlog_thresh:\n major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10)\n else:\n major_locator = AutoLocator()\n\n if minor is None:\n minor_locator = LogLocator(log_base, subs=None) if log_base else None\n else:\n if log_base:\n subs = np.linspace(0, log_base, minor + 2)[1:-1]\n minor_locator = LogLocator(log_base, subs=subs)\n else:\n minor_locator = AutoMinorLocator(minor + 1)\n\n return major_locator, minor_locator\n\n def _get_formatter(self, locator, formatter, like, base, unit):\n\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n if base is None:\n if symlog_thresh:\n log_base = 10\n base = log_base\n\n if formatter is not None:\n return formatter\n\n if like is not None:\n if isinstance(like, str):\n if \"{x\" in like or \"{pos\" in like:\n fmt = like\n else:\n fmt = f\"{{x:{like}}}\"\n formatter = StrMethodFormatter(fmt)\n else:\n formatter = FuncFormatter(like)\n\n elif base is not None:\n # We could add other log options if necessary\n formatter = LogFormatterSciNotation(base)\n\n elif unit is not None:\n if isinstance(unit, tuple):\n sep, unit = unit\n elif not unit:\n sep = \"\"\n else:\n sep = \" \"\n formatter = EngFormatter(unit, sep=sep)\n\n else:\n formatter = ScalarFormatter()\n\n return formatter\n\n\n@dataclass\nclass Temporal(ContinuousBase):\n \"\"\"\n A scale for date/time data.\n \"\"\"\n # TODO date: bool?\n # For when we only care about the time component, would affect\n # default formatter and norm conversion. Should also happen in\n # Property.default_scale. The alternative was having distinct\n # Calendric / Temporal scales, but that feels a bit fussy, and it\n # would get in the way of using first-letter shorthands because\n # Calendric and Continuous would collide. Still, we haven't implemented\n # those yet, and having a clear distinction betewen date(time) / time\n # may be more useful.\n\n trans = None\n\n _priority: ClassVar[int] = 2\n\n def tick(\n self, locator: Locator | None = None, *,\n upto: int | None = None,\n ) -> Temporal:\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n if locator is not None and not isinstance(locator, Locator):\n err = (\n f\"Tick locator must be an instance of {Locator!r}, \"\n f\"not {type(locator)!r}.\"\n )\n raise TypeError(err)\n\n new = copy(self)\n new._tick_params = {\"locator\": locator, \"upto\": upto}\n return new\n\n def label(\n self,\n formatter: Formatter | None = None, *,\n concise: bool = False,\n ) -> Temporal:\n \"\"\"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n concise : bool\n If True, use :class:`matplotlib.dates.ConciseDateFormatter` to make\n the tick labels as compact as possible.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n \"\"\"\n new = copy(self)\n new._label_params = {\"formatter\": formatter, \"concise\": concise}\n return new\n\n def _get_locators(self, locator, upto):\n\n if locator is not None:\n major_locator = locator\n elif upto is not None:\n major_locator = AutoDateLocator(minticks=2, maxticks=upto)\n\n else:\n major_locator = AutoDateLocator(minticks=2, maxticks=6)\n minor_locator = None\n\n return major_locator, minor_locator\n\n def _get_formatter(self, locator, formatter, concise):\n\n if formatter is not None:\n return formatter\n\n if concise:\n # TODO ideally we would have concise coordinate ticks,\n # but full semantic ticks. Is that possible?\n formatter = ConciseDateFormatter(locator)\n else:\n formatter = AutoDateFormatter(locator)\n\n return formatter\n\n\n# ----------------------------------------------------------------------------------- #\n\n\n# TODO Have this separate from Temporal or have Temporal(date=True) or similar?\n# class Calendric(Scale):\n\n# TODO Needed? Or handle this at layer (in stat or as param, eg binning=)\n# class Binned(Scale):\n\n# TODO any need for color-specific scales?\n# class Sequential(Continuous):\n# class Diverging(Continuous):\n# class Qualitative(Nominal):\n\n\n# ----------------------------------------------------------------------------------- #\n\n\nclass PseudoAxis:\n \"\"\"\n Internal class implementing minimal interface equivalent to matplotlib Axis.\n\n Coordinate variables are typically scaled by attaching the Axis object from\n the figure where the plot will end up. Matplotlib has no similar concept of\n and axis for the other mappable variables (color, etc.), but to simplify the\n code, this object acts like an Axis and can be used to scale other variables.\n\n \"\"\"\n axis_name = \"\" # Matplotlib requirement but not actually used\n\n def __init__(self, scale):\n\n self.converter = None\n self.units = None\n self.scale = scale\n self.major = mpl.axis.Ticker()\n self.minor = mpl.axis.Ticker()\n\n # It appears that this needs to be initialized this way on matplotlib 3.1,\n # but not later versions. It is unclear whether there are any issues with it.\n self._data_interval = None, None\n\n scale.set_default_locators_and_formatters(self)\n # self.set_default_intervals() Is this ever needed?\n\n def set_view_interval(self, vmin, vmax):\n self._view_interval = vmin, vmax\n\n def get_view_interval(self):\n return self._view_interval\n\n # TODO do we want to distinguish view/data intervals? e.g. for a legend\n # we probably want to represent the full range of the data values, but\n # still norm the colormap. If so, we'll need to track data range separately\n # from the norm, which we currently don't do.\n\n def set_data_interval(self, vmin, vmax):\n self._data_interval = vmin, vmax\n\n def get_data_interval(self):\n return self._data_interval\n\n def get_tick_space(self):\n # TODO how to do this in a configurable / auto way?\n # Would be cool to have legend density adapt to figure size, etc.\n return 5\n\n def set_major_locator(self, locator):\n self.major.locator = locator\n locator.set_axis(self)\n\n def set_major_formatter(self, formatter):\n self.major.formatter = formatter\n formatter.set_axis(self)\n\n def set_minor_locator(self, locator):\n self.minor.locator = locator\n locator.set_axis(self)\n\n def set_minor_formatter(self, formatter):\n self.minor.formatter = formatter\n formatter.set_axis(self)\n\n def set_units(self, units):\n self.units = units\n\n def update_units(self, x):\n \"\"\"Pass units to the internal converter, potentially updating its mapping.\"\"\"\n self.converter = mpl.units.registry.get_converter(x)\n if self.converter is not None:\n self.converter.default_units(x, self)\n\n info = self.converter.axisinfo(self.units, self)\n\n if info is None:\n return\n if info.majloc is not None:\n self.set_major_locator(info.majloc)\n if info.majfmt is not None:\n self.set_major_formatter(info.majfmt)\n\n # This is in matplotlib method; do we need this?\n # self.set_default_intervals()\n\n def convert_units(self, x):\n \"\"\"Return a numeric representation of the input data.\"\"\"\n if np.issubdtype(np.asarray(x).dtype, np.number):\n return x\n elif self.converter is None:\n return x\n return self.converter.convert(x, self.units, self)\n\n def get_scale(self):\n # Note that matplotlib actually returns a string here!\n # (e.g., with a log scale, axis.get_scale() returns \"log\")\n # Currently we just hit it with minor ticks where it checks for\n # scale == \"log\". I'm not sure how you'd actually use log-scale\n # minor \"ticks\" in a legend context, so this is fine....\n return self.scale\n\n def get_majorticklocs(self):\n return self.major.locator()\n\n\n# ------------------------------------------------------------------------------------ #\n# Transform function creation\n\n\ndef _make_identity_transforms() -> TransFuncs:\n\n def identity(x):\n return x\n\n return identity, identity\n\n\ndef _make_logit_transforms(base: float = None) -> TransFuncs:\n\n log, exp = _make_log_transforms(base)\n\n def logit(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return log(x) - log(1 - x)\n\n def expit(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return exp(x) / (1 + exp(x))\n\n return logit, expit\n\n\ndef _make_log_transforms(base: float | None = None) -> TransFuncs:\n\n fs: TransFuncs\n if base is None:\n fs = np.log, np.exp\n elif base == 2:\n fs = np.log2, partial(np.power, 2)\n elif base == 10:\n fs = np.log10, partial(np.power, 10)\n else:\n def forward(x):\n return np.log(x) / np.log(base)\n fs = forward, partial(np.power, base)\n\n def log(x: ArrayLike) -> ArrayLike:\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return fs[0](x)\n\n def exp(x: ArrayLike) -> ArrayLike:\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return fs[1](x)\n\n return log, exp\n\n\ndef _make_symlog_transforms(c: float = 1, base: float = 10) -> TransFuncs:\n\n # From https://iopscience.iop.org/article/10.1088/0957-0233/24/2/027001\n\n # Note: currently not using base because we only get\n # one parameter from the string, and are using c (this is consistent with d3)\n\n log, exp = _make_log_transforms(base)\n\n def symlog(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return np.sign(x) * log(1 + np.abs(np.divide(x, c)))\n\n def symexp(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return np.sign(x) * c * (exp(np.abs(x)) - 1)\n\n return symlog, symexp\n\n\ndef _make_sqrt_transforms() -> TransFuncs:\n\n def sqrt(x):\n return np.sign(x) * np.sqrt(np.abs(x))\n\n def square(x):\n return np.sign(x) * np.square(x)\n\n return sqrt, square\n\n\ndef _make_power_transforms(exp: float) -> TransFuncs:\n\n def forward(x):\n return np.sign(x) * np.power(np.abs(x), exp)\n\n def inverse(x):\n return np.sign(x) * np.power(np.abs(x), 1 / exp)\n\n return forward, inverse\n"},{"col":0,"comment":"null","endLoc":20,"header":"def copy(x: _T) -> _T","id":45,"name":"copy","nodeType":"Function","startLoc":20,"text":"def copy(x: _T) -> _T: ..."},{"className":"Sequence","col":0,"comment":"null","endLoc":577,"id":46,"nodeType":"Class","startLoc":565,"text":"class Sequence(Collection[_T_co], Reversible[_T_co]):\n @overload\n @abstractmethod\n def __getitem__(self, index: int) -> _T_co: ...\n @overload\n @abstractmethod\n def __getitem__(self, index: slice) -> Sequence[_T_co]: ...\n # Mixin methods\n def index(self, value: Any, start: int = 0, stop: int = ...) -> int: ...\n def count(self, value: Any) -> int: ...\n def __contains__(self, value: object) -> bool: ...\n def __iter__(self) -> Iterator[_T_co]: ...\n def __reversed__(self) -> Iterator[_T_co]: ..."},{"col":4,"comment":"null","endLoc":403,"header":"@overload\n def __init__(self) -> None","id":47,"name":"__init__","nodeType":"Function","startLoc":402,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":405,"header":"@overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None","id":48,"name":"__init__","nodeType":"Function","startLoc":404,"text":"@overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780"},{"col":4,"comment":"null","endLoc":407,"header":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None","id":49,"name":"__init__","nodeType":"Function","startLoc":406,"text":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ..."},{"col":4,"comment":"null","endLoc":414,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None","id":50,"name":"__init__","nodeType":"Function","startLoc":408,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":416,"header":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None","id":51,"name":"__init__","nodeType":"Function","startLoc":415,"text":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ..."},{"col":4,"comment":"null","endLoc":424,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None","id":52,"name":"__init__","nodeType":"Function","startLoc":417,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":426,"header":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None","id":53,"name":"__init__","nodeType":"Function","startLoc":425,"text":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ..."},{"col":4,"comment":"null","endLoc":434,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None","id":54,"name":"__init__","nodeType":"Function","startLoc":427,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":435,"header":"def __missing__(self, key: _KT, /) -> _VT","id":55,"name":"__missing__","nodeType":"Function","startLoc":435,"text":"def __missing__(self, key: _KT, /) -> _VT: ..."},{"col":4,"comment":"null","endLoc":436,"header":"def __copy__(self) -> Self","id":56,"name":"__copy__","nodeType":"Function","startLoc":436,"text":"def __copy__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":437,"header":"def copy(self) -> Self","id":57,"name":"copy","nodeType":"Function","startLoc":437,"text":"def copy(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":440,"header":"@overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self","id":58,"name":"__or__","nodeType":"Function","startLoc":439,"text":"@overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ..."},{"col":8,"comment":"null","endLoc":442,"header":"@overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]","id":59,"name":"__or__","nodeType":"Function","startLoc":441,"text":"@overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":444,"header":"@overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self","id":60,"name":"__ror__","nodeType":"Function","startLoc":443,"text":"@overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ..."},{"col":8,"comment":"null","endLoc":446,"header":"@overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]","id":61,"name":"__ror__","nodeType":"Function","startLoc":445,"text":"@overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"attributeType":"() -> _VT | None","col":4,"comment":"null","endLoc":401,"id":62,"name":"default_factory","nodeType":"Attribute","startLoc":401,"text":"default_factory"},{"className":"Mark","col":0,"comment":"Base class for objects that visually represent data.","endLoc":221,"id":63,"nodeType":"Class","startLoc":102,"text":"@dataclass\nclass Mark:\n \"\"\"Base class for objects that visually represent data.\"\"\"\n\n artist_kws: dict = field(default_factory=dict)\n\n @property\n def _mappable_props(self):\n return {\n f.name: getattr(self, f.name) for f in fields(self)\n if isinstance(f.default, Mappable)\n }\n\n @property\n def _grouping_props(self):\n # TODO does it make sense to have variation within a Mark's\n # properties about whether they are grouping?\n return [\n f.name for f in fields(self)\n if isinstance(f.default, Mappable) and f.default.grouping\n ]\n\n # TODO make this method private? Would extender every need to call directly?\n def _resolve(\n self,\n data: DataFrame | dict[str, Any],\n name: str,\n scales: dict[str, Scale] | None = None,\n ) -> Any:\n \"\"\"Obtain default, specified, or mapped value for a named feature.\n\n Parameters\n ----------\n data : DataFrame or dict with scalar values\n Container with data values for features that will be semantically mapped.\n name : string\n Identity of the feature / semantic.\n scales: dict\n Mapping from variable to corresponding scale object.\n\n Returns\n -------\n value or array of values\n Outer return type depends on whether `data` is a dict (implying that\n we want a single value) or DataFrame (implying that we want an array\n of values with matching length).\n\n \"\"\"\n feature = self._mappable_props[name]\n prop = PROPERTIES.get(name, Property(name))\n directly_specified = not isinstance(feature, Mappable)\n return_multiple = isinstance(data, pd.DataFrame)\n return_array = return_multiple and not name.endswith(\"style\")\n\n # Special case width because it needs to be resolved and added to the dataframe\n # during layer prep (so the Move operations use it properly).\n # TODO how does width *scaling* work, e.g. for violin width by count?\n if name == \"width\":\n directly_specified = directly_specified and name not in data\n\n if directly_specified:\n feature = prop.standardize(feature)\n if return_multiple:\n feature = [feature] * len(data)\n if return_array:\n feature = np.array(feature)\n return feature\n\n if name in data:\n if scales is None or name not in scales:\n # TODO Might this obviate the identity scale? Just don't add a scale?\n feature = data[name]\n else:\n feature = scales[name](data[name])\n if return_array:\n feature = np.asarray(feature)\n return feature\n\n if feature.depend is not None:\n # TODO add source_func or similar to transform the source value?\n # e.g. set linewidth as a proportion of pointsize?\n return self._resolve(data, feature.depend, scales)\n\n default = prop.standardize(feature.default)\n if return_multiple:\n default = [default] * len(data)\n if return_array:\n default = np.array(default)\n return default\n\n def _infer_orient(self, scales: dict) -> str: # TODO type scales\n\n # TODO The original version of this (in seaborn._oldcore) did more checking.\n # Paring that down here for the prototype to see what restrictions make sense.\n\n # TODO rethink this to map from scale type to \"DV priority\" and use that?\n # e.g. Nominal > Discrete > Continuous\n\n x = 0 if \"x\" not in scales else scales[\"x\"]._priority\n y = 0 if \"y\" not in scales else scales[\"y\"]._priority\n\n if y > x:\n return \"y\"\n else:\n return \"x\"\n\n def _plot(\n self,\n split_generator: Callable[[], Generator],\n scales: dict[str, Scale],\n orient: str,\n ) -> None:\n \"\"\"Main interface for creating a plot.\"\"\"\n raise NotImplementedError()\n\n def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n\n return None"},{"col":4,"comment":"null","endLoc":113,"header":"@property\n def _mappable_props(self)","id":64,"name":"_mappable_props","nodeType":"Function","startLoc":108,"text":"@property\n def _mappable_props(self):\n return {\n f.name: getattr(self, f.name) for f in fields(self)\n if isinstance(f.default, Mappable)\n }"},{"className":"Mappable","col":0,"comment":"null","endLoc":90,"id":65,"nodeType":"Class","startLoc":25,"text":"class Mappable:\n def __init__(\n self,\n val: Any = None,\n depend: str | None = None,\n rc: str | None = None,\n auto: bool = False,\n grouping: bool = True,\n ):\n \"\"\"\n Property that can be mapped from data or set directly, with flexible defaults.\n\n Parameters\n ----------\n val : Any\n Use this value as the default.\n depend : str\n Use the value of this feature as the default.\n rc : str\n Use the value of this rcParam as the default.\n auto : bool\n The default value will depend on other parameters at compile time.\n grouping : bool\n If True, use the mapped variable to define groups.\n\n \"\"\"\n if depend is not None:\n assert depend in PROPERTIES\n if rc is not None:\n assert rc in mpl.rcParams\n\n self._val = val\n self._rc = rc\n self._depend = depend\n self._auto = auto\n self._grouping = grouping\n\n def __repr__(self):\n \"\"\"Nice formatting for when object appears in Mark init signature.\"\"\"\n if self._val is not None:\n s = f\"<{repr(self._val)}>\"\n elif self._depend is not None:\n s = f\"\"\n elif self._rc is not None:\n s = f\"\"\n elif self._auto:\n s = \"\"\n else:\n s = \"\"\n return s\n\n @property\n def depend(self) -> Any:\n \"\"\"Return the name of the feature to source a default value from.\"\"\"\n return self._depend\n\n @property\n def grouping(self) -> bool:\n return self._grouping\n\n @property\n def default(self) -> Any:\n \"\"\"Get the default value for this feature, or access the relevant rcParam.\"\"\"\n if self._val is not None:\n return self._val\n return mpl.rcParams.get(self._rc)"},{"col":4,"comment":"\n Property that can be mapped from data or set directly, with flexible defaults.\n\n Parameters\n ----------\n val : Any\n Use this value as the default.\n depend : str\n Use the value of this feature as the default.\n rc : str\n Use the value of this rcParam as the default.\n auto : bool\n The default value will depend on other parameters at compile time.\n grouping : bool\n If True, use the mapped variable to define groups.\n\n ","endLoc":60,"header":"def __init__(\n self,\n val: Any = None,\n depend: str | None = None,\n rc: str | None = None,\n auto: bool = False,\n grouping: bool = True,\n )","id":66,"name":"__init__","nodeType":"Function","startLoc":26,"text":"def __init__(\n self,\n val: Any = None,\n depend: str | None = None,\n rc: str | None = None,\n auto: bool = False,\n grouping: bool = True,\n ):\n \"\"\"\n Property that can be mapped from data or set directly, with flexible defaults.\n\n Parameters\n ----------\n val : Any\n Use this value as the default.\n depend : str\n Use the value of this feature as the default.\n rc : str\n Use the value of this rcParam as the default.\n auto : bool\n The default value will depend on other parameters at compile time.\n grouping : bool\n If True, use the mapped variable to define groups.\n\n \"\"\"\n if depend is not None:\n assert depend in PROPERTIES\n if rc is not None:\n assert rc in mpl.rcParams\n\n self._val = val\n self._rc = rc\n self._depend = depend\n self._auto = auto\n self._grouping = grouping"},{"col":4,"comment":"Nice formatting for when object appears in Mark init signature.","endLoc":74,"header":"def __repr__(self)","id":67,"name":"__repr__","nodeType":"Function","startLoc":62,"text":"def __repr__(self):\n \"\"\"Nice formatting for when object appears in Mark init signature.\"\"\"\n if self._val is not None:\n s = f\"<{repr(self._val)}>\"\n elif self._depend is not None:\n s = f\"\"\n elif self._rc is not None:\n s = f\"\"\n elif self._auto:\n s = \"\"\n else:\n s = \"\"\n return s"},{"col":4,"comment":"null","endLoc":568,"header":"@overload\n @abstractmethod\n def __getitem__(self, index: int) -> _T_co","id":69,"name":"__getitem__","nodeType":"Function","startLoc":566,"text":"@overload\n @abstractmethod\n def __getitem__(self, index: int) -> _T_co: ..."},{"col":4,"comment":"null","endLoc":571,"header":"@overload\n @abstractmethod\n def __getitem__(self, index: slice) -> Sequence[_T_co]","id":70,"name":"__getitem__","nodeType":"Function","startLoc":569,"text":"@overload\n @abstractmethod\n def __getitem__(self, index: slice) -> Sequence[_T_co]: ..."},{"col":4,"comment":"null","endLoc":573,"header":"def index(self, value: Any, start: int = 0, stop: int = ...) -> int","id":71,"name":"index","nodeType":"Function","startLoc":573,"text":"def index(self, value: Any, start: int = 0, stop: int = ...) -> int: ..."},{"col":4,"comment":"null","endLoc":574,"header":"def count(self, value: Any) -> int","id":72,"name":"count","nodeType":"Function","startLoc":574,"text":"def count(self, value: Any) -> int: ..."},{"col":4,"comment":"null","endLoc":575,"header":"def __contains__(self, value: object) -> bool","id":73,"name":"__contains__","nodeType":"Function","startLoc":575,"text":"def __contains__(self, value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":576,"header":"def __iter__(self) -> Iterator[_T_co]","id":74,"name":"__iter__","nodeType":"Function","startLoc":576,"text":"def __iter__(self) -> Iterator[_T_co]: ..."},{"col":4,"comment":"null","endLoc":577,"header":"def __reversed__(self) -> Iterator[_T_co]","id":75,"name":"__reversed__","nodeType":"Function","startLoc":577,"text":"def __reversed__(self) -> Iterator[_T_co]: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":95,"id":76,"name":"MappableBool","nodeType":"Attribute","startLoc":95,"text":"MappableBool"},{"className":"partial","col":0,"comment":"null","endLoc":135,"id":78,"nodeType":"Class","startLoc":125,"text":"class partial(Generic[_T]):\n @property\n def func(self) -> Callable[..., _T]: ...\n @property\n def args(self) -> tuple[Any, ...]: ...\n @property\n def keywords(self) -> dict[str, Any]: ...\n def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ...\n def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ...\n if sys.version_info >= (3, 9):\n def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":98,"id":79,"name":"MappableColor","nodeType":"Attribute","startLoc":98,"text":"MappableColor"},{"attributeType":"null","col":0,"comment":"null","endLoc":97,"id":80,"name":"MappableFloat","nodeType":"Attribute","startLoc":97,"text":"MappableFloat"},{"attributeType":"null","col":0,"comment":"null","endLoc":99,"id":81,"name":"MappableStyle","nodeType":"Attribute","startLoc":99,"text":"MappableStyle"},{"col":0,"comment":"null","endLoc":231,"header":"def resolve_properties(\n mark: Mark, data: DataFrame, scales: dict[str, Scale]\n) -> dict[str, Any]","id":82,"name":"resolve_properties","nodeType":"Function","startLoc":224,"text":"def resolve_properties(\n mark: Mark, data: DataFrame, scales: dict[str, Scale]\n) -> dict[str, Any]:\n\n props = {\n name: mark._resolve(data, name, scales) for name in mark._mappable_props\n }\n return props"},{"col":4,"comment":"Obtain default, specified, or mapped value for a named feature.\n\n Parameters\n ----------\n data : DataFrame or dict with scalar values\n Container with data values for features that will be semantically mapped.\n name : string\n Identity of the feature / semantic.\n scales: dict\n Mapping from variable to corresponding scale object.\n\n Returns\n -------\n value or array of values\n Outer return type depends on whether `data` is a dict (implying that\n we want a single value) or DataFrame (implying that we want an array\n of values with matching length).\n\n ","endLoc":190,"header":"def _resolve(\n self,\n data: DataFrame | dict[str, Any],\n name: str,\n scales: dict[str, Scale] | None = None,\n ) -> Any","id":83,"name":"_resolve","nodeType":"Function","startLoc":125,"text":"def _resolve(\n self,\n data: DataFrame | dict[str, Any],\n name: str,\n scales: dict[str, Scale] | None = None,\n ) -> Any:\n \"\"\"Obtain default, specified, or mapped value for a named feature.\n\n Parameters\n ----------\n data : DataFrame or dict with scalar values\n Container with data values for features that will be semantically mapped.\n name : string\n Identity of the feature / semantic.\n scales: dict\n Mapping from variable to corresponding scale object.\n\n Returns\n -------\n value or array of values\n Outer return type depends on whether `data` is a dict (implying that\n we want a single value) or DataFrame (implying that we want an array\n of values with matching length).\n\n \"\"\"\n feature = self._mappable_props[name]\n prop = PROPERTIES.get(name, Property(name))\n directly_specified = not isinstance(feature, Mappable)\n return_multiple = isinstance(data, pd.DataFrame)\n return_array = return_multiple and not name.endswith(\"style\")\n\n # Special case width because it needs to be resolved and added to the dataframe\n # during layer prep (so the Move operations use it properly).\n # TODO how does width *scaling* work, e.g. for violin width by count?\n if name == \"width\":\n directly_specified = directly_specified and name not in data\n\n if directly_specified:\n feature = prop.standardize(feature)\n if return_multiple:\n feature = [feature] * len(data)\n if return_array:\n feature = np.array(feature)\n return feature\n\n if name in data:\n if scales is None or name not in scales:\n # TODO Might this obviate the identity scale? Just don't add a scale?\n feature = data[name]\n else:\n feature = scales[name](data[name])\n if return_array:\n feature = np.asarray(feature)\n return feature\n\n if feature.depend is not None:\n # TODO add source_func or similar to transform the source value?\n # e.g. set linewidth as a proportion of pointsize?\n return self._resolve(data, feature.depend, scales)\n\n default = prop.standardize(feature.default)\n if return_multiple:\n default = [default] * len(data)\n if return_array:\n default = np.array(default)\n return default"},{"col":4,"comment":"null","endLoc":127,"header":"@property\n def func(self) -> Callable[..., _T]","id":84,"name":"func","nodeType":"Function","startLoc":126,"text":"@property\n def func(self) -> Callable[..., _T]: ..."},{"col":4,"comment":"null","endLoc":129,"header":"@property\n def args(self) -> tuple[Any, ...]","id":85,"name":"args","nodeType":"Function","startLoc":128,"text":"@property\n def args(self) -> tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":131,"header":"@property\n def keywords(self) -> dict[str, Any]","id":86,"name":"keywords","nodeType":"Function","startLoc":130,"text":"@property\n def keywords(self) -> dict[str, Any]: ..."},{"col":4,"comment":"null","endLoc":132,"header":"def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self","id":87,"name":"__new__","nodeType":"Function","startLoc":132,"text":"def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":133,"header":"def __call__(self, /, *args: Any, **kwargs: Any) -> _T","id":88,"name":"__call__","nodeType":"Function","startLoc":133,"text":"def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ..."},{"col":8,"comment":"null","endLoc":135,"header":"def __class_getitem__(cls, item: Any, /) -> GenericAlias","id":89,"name":"__class_getitem__","nodeType":"Function","startLoc":135,"text":"def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":134,"id":90,"name":"Any","nodeType":"Attribute","startLoc":134,"text":"Any"},{"attributeType":"Callable","col":0,"comment":"null","endLoc":204,"id":91,"name":"Callable","nodeType":"Attribute","startLoc":204,"text":"Callable"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":210,"id":92,"name":"Tuple","nodeType":"Attribute","startLoc":210,"text":"Tuple"},{"attributeType":"_SpecialForm","col":0,"comment":"null","endLoc":209,"id":93,"name":"Optional","nodeType":"Attribute","startLoc":209,"text":"Optional"},{"col":4,"comment":"Return the name of the feature to source a default value from.","endLoc":79,"header":"@property\n def depend(self) -> Any","id":94,"name":"depend","nodeType":"Function","startLoc":76,"text":"@property\n def depend(self) -> Any:\n \"\"\"Return the name of the feature to source a default value from.\"\"\"\n return self._depend"},{"col":4,"comment":"null","endLoc":83,"header":"@property\n def grouping(self) -> bool","id":95,"name":"grouping","nodeType":"Function","startLoc":81,"text":"@property\n def grouping(self) -> bool:\n return self._grouping"},{"col":4,"comment":"Get the default value for this feature, or access the relevant rcParam.","endLoc":90,"header":"@property\n def default(self) -> Any","id":96,"name":"default","nodeType":"Function","startLoc":85,"text":"@property\n def default(self) -> Any:\n \"\"\"Get the default value for this feature, or access the relevant rcParam.\"\"\"\n if self._val is not None:\n return self._val\n return mpl.rcParams.get(self._rc)"},{"fileName":"_oldcore.py","filePath":"seaborn","id":97,"nodeType":"File","text":"import warnings\nimport itertools\nfrom copy import copy\nfrom functools import partial\nfrom collections import UserString\nfrom collections.abc import Iterable, Sequence, Mapping\nfrom numbers import Number\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\n\nfrom ._decorators import (\n share_init_params_with_map,\n)\nfrom .external.version import Version\nfrom .palettes import (\n QUAL_PALETTES,\n color_palette,\n)\nfrom .utils import (\n _check_argument,\n get_color_cycle,\n remove_na,\n)\n\n\nclass SemanticMapping:\n \"\"\"Base class for mapping data values to plot attributes.\"\"\"\n\n # -- Default attributes that all SemanticMapping subclasses must set\n\n # Whether the mapping is numeric, categorical, or datetime\n map_type = None\n\n # Ordered list of unique values in the input data\n levels = None\n\n # A mapping from the data values to corresponding plot attributes\n lookup_table = None\n\n def __init__(self, plotter):\n\n # TODO Putting this here so we can continue to use a lot of the\n # logic that's built into the library, but the idea of this class\n # is to move towards semantic mappings that are agnostic about the\n # kind of plot they're going to be used to draw.\n # Fully achieving that is going to take some thinking.\n self.plotter = plotter\n\n def map(cls, plotter, *args, **kwargs):\n # This method is assigned the __init__ docstring\n method_name = f\"_{cls.__name__[:-7].lower()}_map\"\n setattr(plotter, method_name, cls(plotter, *args, **kwargs))\n return plotter\n\n def _check_list_length(self, levels, values, variable):\n \"\"\"Input check when values are provided as a list.\"\"\"\n # Copied from _core/properties; eventually will be replaced for that.\n message = \"\"\n if len(levels) > len(values):\n message = \" \".join([\n f\"\\nThe {variable} list has fewer values ({len(values)})\",\n f\"than needed ({len(levels)}) and will cycle, which may\",\n \"produce an uninterpretable plot.\"\n ])\n values = [x for _, x in zip(levels, itertools.cycle(values))]\n\n elif len(values) > len(levels):\n message = \" \".join([\n f\"The {variable} list has more values ({len(values)})\",\n f\"than needed ({len(levels)}), which may not be intended.\",\n ])\n values = values[:len(levels)]\n\n if message:\n warnings.warn(message, UserWarning, stacklevel=6)\n\n return values\n\n def _lookup_single(self, key):\n \"\"\"Apply the mapping to a single data value.\"\"\"\n return self.lookup_table[key]\n\n def __call__(self, key, *args, **kwargs):\n \"\"\"Get the attribute(s) values for the data key.\"\"\"\n if isinstance(key, (list, np.ndarray, pd.Series)):\n return [self._lookup_single(k, *args, **kwargs) for k in key]\n else:\n return self._lookup_single(key, *args, **kwargs)\n\n\n@share_init_params_with_map\nclass HueMapping(SemanticMapping):\n \"\"\"Mapping that sets artist colors according to data values.\"\"\"\n # A specification of the colors that should appear in the plot\n palette = None\n\n # An object that normalizes data values to [0, 1] range for color mapping\n norm = None\n\n # A continuous colormap object for interpolating in a numeric context\n cmap = None\n\n def __init__(\n self, plotter, palette=None, order=None, norm=None,\n ):\n \"\"\"Map the levels of the `hue` variable to distinct colors.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"hue\", pd.Series(dtype=float))\n\n if data.isna().all():\n if palette is not None:\n msg = \"Ignoring `palette` because no `hue` variable has been assigned.\"\n warnings.warn(msg, stacklevel=4)\n else:\n\n map_type = self.infer_map_type(\n palette, norm, plotter.input_format, plotter.var_types[\"hue\"]\n )\n\n # Our goal is to end up with a dictionary mapping every unique\n # value in `data` to a color. We will also keep track of the\n # metadata about this mapping we will need for, e.g., a legend\n\n # --- Option 1: numeric mapping with a matplotlib colormap\n\n if map_type == \"numeric\":\n\n data = pd.to_numeric(data)\n levels, lookup_table, norm, cmap = self.numeric_mapping(\n data, palette, norm,\n )\n\n # --- Option 2: categorical mapping using seaborn palette\n\n elif map_type == \"categorical\":\n\n cmap = norm = None\n levels, lookup_table = self.categorical_mapping(\n data, palette, order,\n )\n\n # --- Option 3: datetime mapping\n\n else:\n # TODO this needs actual implementation\n cmap = norm = None\n levels, lookup_table = self.categorical_mapping(\n # Casting data to list to handle differences in the way\n # pandas and numpy represent datetime64 data\n list(data), palette, order,\n )\n\n self.map_type = map_type\n self.lookup_table = lookup_table\n self.palette = palette\n self.levels = levels\n self.norm = norm\n self.cmap = cmap\n\n def _lookup_single(self, key):\n \"\"\"Get the color for a single value, using colormap to interpolate.\"\"\"\n try:\n # Use a value that's in the original data vector\n value = self.lookup_table[key]\n except KeyError:\n\n if self.norm is None:\n # Currently we only get here in scatterplot with hue_order,\n # because scatterplot does not consider hue a grouping variable\n # So unused hue levels are in the data, but not the lookup table\n return (0, 0, 0, 0)\n\n # Use the colormap to interpolate between existing datapoints\n # (e.g. in the context of making a continuous legend)\n try:\n normed = self.norm(key)\n except TypeError as err:\n if np.isnan(key):\n value = (0, 0, 0, 0)\n else:\n raise err\n else:\n if np.ma.is_masked(normed):\n normed = np.nan\n value = self.cmap(normed)\n return value\n\n def infer_map_type(self, palette, norm, input_format, var_type):\n \"\"\"Determine how to implement the mapping.\"\"\"\n if palette in QUAL_PALETTES:\n map_type = \"categorical\"\n elif norm is not None:\n map_type = \"numeric\"\n elif isinstance(palette, (dict, list)):\n map_type = \"categorical\"\n elif input_format == \"wide\":\n map_type = \"categorical\"\n else:\n map_type = var_type\n\n return map_type\n\n def categorical_mapping(self, data, palette, order):\n \"\"\"Determine colors when the hue mapping is categorical.\"\"\"\n # -- Identify the order and name of the levels\n\n levels = categorical_order(data, order)\n n_colors = len(levels)\n\n # -- Identify the set of colors to use\n\n if isinstance(palette, dict):\n\n missing = set(levels) - set(palette)\n if any(missing):\n err = \"The palette dictionary is missing keys: {}\"\n raise ValueError(err.format(missing))\n\n lookup_table = palette\n\n else:\n\n if palette is None:\n if n_colors <= len(get_color_cycle()):\n colors = color_palette(None, n_colors)\n else:\n colors = color_palette(\"husl\", n_colors)\n elif isinstance(palette, list):\n colors = self._check_list_length(levels, palette, \"palette\")\n else:\n colors = color_palette(palette, n_colors)\n\n lookup_table = dict(zip(levels, colors))\n\n return levels, lookup_table\n\n def numeric_mapping(self, data, palette, norm):\n \"\"\"Determine colors when the hue variable is quantitative.\"\"\"\n if isinstance(palette, dict):\n\n # The presence of a norm object overrides a dictionary of hues\n # in specifying a numeric mapping, so we need to process it here.\n levels = list(sorted(palette))\n colors = [palette[k] for k in sorted(palette)]\n cmap = mpl.colors.ListedColormap(colors)\n lookup_table = palette.copy()\n\n else:\n\n # The levels are the sorted unique values in the data\n levels = list(np.sort(remove_na(data.unique())))\n\n # --- Sort out the colormap to use from the palette argument\n\n # Default numeric palette is our default cubehelix palette\n # TODO do we want to do something complicated to ensure contrast?\n palette = \"ch:\" if palette is None else palette\n\n if isinstance(palette, mpl.colors.Colormap):\n cmap = palette\n else:\n cmap = color_palette(palette, as_cmap=True)\n\n # Now sort out the data normalization\n if norm is None:\n norm = mpl.colors.Normalize()\n elif isinstance(norm, tuple):\n norm = mpl.colors.Normalize(*norm)\n elif not isinstance(norm, mpl.colors.Normalize):\n err = \"``hue_norm`` must be None, tuple, or Normalize object.\"\n raise ValueError(err)\n\n if not norm.scaled():\n norm(np.asarray(data.dropna()))\n\n lookup_table = dict(zip(levels, cmap(norm(levels))))\n\n return levels, lookup_table, norm, cmap\n\n\n@share_init_params_with_map\nclass SizeMapping(SemanticMapping):\n \"\"\"Mapping that sets artist sizes according to data values.\"\"\"\n # An object that normalizes data values to [0, 1] range\n norm = None\n\n def __init__(\n self, plotter, sizes=None, order=None, norm=None,\n ):\n \"\"\"Map the levels of the `size` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"size\", pd.Series(dtype=float))\n\n if data.notna().any():\n\n map_type = self.infer_map_type(\n norm, sizes, plotter.var_types[\"size\"]\n )\n\n # --- Option 1: numeric mapping\n\n if map_type == \"numeric\":\n\n levels, lookup_table, norm, size_range = self.numeric_mapping(\n data, sizes, norm,\n )\n\n # --- Option 2: categorical mapping\n\n elif map_type == \"categorical\":\n\n levels, lookup_table = self.categorical_mapping(\n data, sizes, order,\n )\n size_range = None\n\n # --- Option 3: datetime mapping\n\n # TODO this needs an actual implementation\n else:\n\n levels, lookup_table = self.categorical_mapping(\n # Casting data to list to handle differences in the way\n # pandas and numpy represent datetime64 data\n list(data), sizes, order,\n )\n size_range = None\n\n self.map_type = map_type\n self.levels = levels\n self.norm = norm\n self.sizes = sizes\n self.size_range = size_range\n self.lookup_table = lookup_table\n\n def infer_map_type(self, norm, sizes, var_type):\n\n if norm is not None:\n map_type = \"numeric\"\n elif isinstance(sizes, (dict, list)):\n map_type = \"categorical\"\n else:\n map_type = var_type\n\n return map_type\n\n def _lookup_single(self, key):\n\n try:\n value = self.lookup_table[key]\n except KeyError:\n normed = self.norm(key)\n if np.ma.is_masked(normed):\n normed = np.nan\n value = self.size_range[0] + normed * np.ptp(self.size_range)\n return value\n\n def categorical_mapping(self, data, sizes, order):\n\n levels = categorical_order(data, order)\n\n if isinstance(sizes, dict):\n\n # Dict inputs map existing data values to the size attribute\n missing = set(levels) - set(sizes)\n if any(missing):\n err = f\"Missing sizes for the following levels: {missing}\"\n raise ValueError(err)\n lookup_table = sizes.copy()\n\n elif isinstance(sizes, list):\n\n # List inputs give size values in the same order as the levels\n sizes = self._check_list_length(levels, sizes, \"sizes\")\n lookup_table = dict(zip(levels, sizes))\n\n else:\n\n if isinstance(sizes, tuple):\n\n # Tuple input sets the min, max size values\n if len(sizes) != 2:\n err = \"A `sizes` tuple must have only 2 values\"\n raise ValueError(err)\n\n elif sizes is not None:\n\n err = f\"Value for `sizes` not understood: {sizes}\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, we need to get the min, max size values from\n # the plotter object we are attached to.\n\n # TODO this is going to cause us trouble later, because we\n # want to restructure things so that the plotter is generic\n # across the visual representation of the data. But at this\n # point, we don't know the visual representation. Likely we\n # want to change the logic of this Mapping so that it gives\n # points on a normalized range that then gets un-normalized\n # when we know what we're drawing. But given the way the\n # package works now, this way is cleanest.\n sizes = self.plotter._default_size_range\n\n # For categorical sizes, use regularly-spaced linear steps\n # between the minimum and maximum sizes. Then reverse the\n # ramp so that the largest value is used for the first entry\n # in size_order, etc. This is because \"ordered\" categories\n # are often though to go in decreasing priority.\n sizes = np.linspace(*sizes, len(levels))[::-1]\n lookup_table = dict(zip(levels, sizes))\n\n return levels, lookup_table\n\n def numeric_mapping(self, data, sizes, norm):\n\n if isinstance(sizes, dict):\n # The presence of a norm object overrides a dictionary of sizes\n # in specifying a numeric mapping, so we need to process it\n # dictionary here\n levels = list(np.sort(list(sizes)))\n size_values = sizes.values()\n size_range = min(size_values), max(size_values)\n\n else:\n\n # The levels here will be the unique values in the data\n levels = list(np.sort(remove_na(data.unique())))\n\n if isinstance(sizes, tuple):\n\n # For numeric inputs, the size can be parametrized by\n # the minimum and maximum artist values to map to. The\n # norm object that gets set up next specifies how to\n # do the mapping.\n\n if len(sizes) != 2:\n err = \"A `sizes` tuple must have only 2 values\"\n raise ValueError(err)\n\n size_range = sizes\n\n elif sizes is not None:\n\n err = f\"Value for `sizes` not understood: {sizes}\"\n raise ValueError(err)\n\n else:\n\n # When not provided, we get the size range from the plotter\n # object we are attached to. See the note in the categorical\n # method about how this is suboptimal for future development.\n size_range = self.plotter._default_size_range\n\n # Now that we know the minimum and maximum sizes that will get drawn,\n # we need to map the data values that we have into that range. We will\n # use a matplotlib Normalize class, which is typically used for numeric\n # color mapping but works fine here too. It takes data values and maps\n # them into a [0, 1] interval, potentially nonlinear-ly.\n\n if norm is None:\n # Default is a linear function between the min and max data values\n norm = mpl.colors.Normalize()\n elif isinstance(norm, tuple):\n # It is also possible to give different limits in data space\n norm = mpl.colors.Normalize(*norm)\n elif not isinstance(norm, mpl.colors.Normalize):\n err = f\"Value for size `norm` parameter not understood: {norm}\"\n raise ValueError(err)\n else:\n # If provided with Normalize object, copy it so we can modify\n norm = copy(norm)\n\n # Set the mapping so all output values are in [0, 1]\n norm.clip = True\n\n # If the input range is not set, use the full range of the data\n if not norm.scaled():\n norm(levels)\n\n # Map from data values to [0, 1] range\n sizes_scaled = norm(levels)\n\n # Now map from the scaled range into the artist units\n if isinstance(sizes, dict):\n lookup_table = sizes\n else:\n lo, hi = size_range\n sizes = lo + sizes_scaled * (hi - lo)\n lookup_table = dict(zip(levels, sizes))\n\n return levels, lookup_table, norm, size_range\n\n\n@share_init_params_with_map\nclass StyleMapping(SemanticMapping):\n \"\"\"Mapping that sets artist style according to data values.\"\"\"\n\n # Style mapping is always treated as categorical\n map_type = \"categorical\"\n\n def __init__(\n self, plotter, markers=None, dashes=None, order=None,\n ):\n \"\"\"Map the levels of the `style` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"style\", pd.Series(dtype=float))\n\n if data.notna().any():\n\n # Cast to list to handle numpy/pandas datetime quirks\n if variable_type(data) == \"datetime\":\n data = list(data)\n\n # Find ordered unique values\n levels = categorical_order(data, order)\n\n markers = self._map_attributes(\n markers, levels, unique_markers(len(levels)), \"markers\",\n )\n dashes = self._map_attributes(\n dashes, levels, unique_dashes(len(levels)), \"dashes\",\n )\n\n # Build the paths matplotlib will use to draw the markers\n paths = {}\n filled_markers = []\n for k, m in markers.items():\n if not isinstance(m, mpl.markers.MarkerStyle):\n m = mpl.markers.MarkerStyle(m)\n paths[k] = m.get_path().transformed(m.get_transform())\n filled_markers.append(m.is_filled())\n\n # Mixture of filled and unfilled markers will show line art markers\n # in the edge color, which defaults to white. This can be handled,\n # but there would be additional complexity with specifying the\n # weight of the line art markers without overwhelming the filled\n # ones with the edges. So for now, we will disallow mixtures.\n if any(filled_markers) and not all(filled_markers):\n err = \"Filled and line art markers cannot be mixed\"\n raise ValueError(err)\n\n lookup_table = {}\n for key in levels:\n lookup_table[key] = {}\n if markers:\n lookup_table[key][\"marker\"] = markers[key]\n lookup_table[key][\"path\"] = paths[key]\n if dashes:\n lookup_table[key][\"dashes\"] = dashes[key]\n\n self.levels = levels\n self.lookup_table = lookup_table\n\n def _lookup_single(self, key, attr=None):\n \"\"\"Get attribute(s) for a given data point.\"\"\"\n if attr is None:\n value = self.lookup_table[key]\n else:\n value = self.lookup_table[key][attr]\n return value\n\n def _map_attributes(self, arg, levels, defaults, attr):\n \"\"\"Handle the specification for a given style attribute.\"\"\"\n if arg is True:\n lookup_table = dict(zip(levels, defaults))\n elif isinstance(arg, dict):\n missing = set(levels) - set(arg)\n if missing:\n err = f\"These `{attr}` levels are missing values: {missing}\"\n raise ValueError(err)\n lookup_table = arg\n elif isinstance(arg, Sequence):\n arg = self._check_list_length(levels, arg, attr)\n lookup_table = dict(zip(levels, arg))\n elif arg:\n err = f\"This `{attr}` argument was not understood: {arg}\"\n raise ValueError(err)\n else:\n lookup_table = {}\n\n return lookup_table\n\n\n# =========================================================================== #\n\n\nclass VectorPlotter:\n \"\"\"Base class for objects underlying *plot functions.\"\"\"\n\n _semantic_mappings = {\n \"hue\": HueMapping,\n \"size\": SizeMapping,\n \"style\": StyleMapping,\n }\n\n # TODO units is another example of a non-mapping \"semantic\"\n # we need a general name for this and separate handling\n semantics = \"x\", \"y\", \"hue\", \"size\", \"style\", \"units\"\n wide_structure = {\n \"x\": \"@index\", \"y\": \"@values\", \"hue\": \"@columns\", \"style\": \"@columns\",\n }\n flat_structure = {\"x\": \"@index\", \"y\": \"@values\"}\n\n _default_size_range = 1, 2 # Unused but needed in tests, ugh\n\n def __init__(self, data=None, variables={}):\n\n self._var_levels = {}\n # var_ordered is relevant only for categorical axis variables, and may\n # be better handled by an internal axis information object that tracks\n # such information and is set up by the scale_* methods. The analogous\n # information for numeric axes would be information about log scales.\n self._var_ordered = {\"x\": False, \"y\": False} # alt., used DefaultDict\n self.assign_variables(data, variables)\n\n for var, cls in self._semantic_mappings.items():\n\n # Create the mapping function\n map_func = partial(cls.map, plotter=self)\n setattr(self, f\"map_{var}\", map_func)\n\n # Call the mapping function to initialize with default values\n getattr(self, f\"map_{var}\")()\n\n @classmethod\n def get_semantics(cls, kwargs, semantics=None):\n \"\"\"Subset a dictionary arguments with known semantic variables.\"\"\"\n # TODO this should be get_variables since we have included x and y\n if semantics is None:\n semantics = cls.semantics\n variables = {}\n for key, val in kwargs.items():\n if key in semantics and val is not None:\n variables[key] = val\n return variables\n\n @property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n return bool({\"x\", \"y\"} & set(self.variables))\n\n @property\n def var_levels(self):\n \"\"\"Property interface to ordered list of variables levels.\n\n Each time it's accessed, it updates the var_levels dictionary with the\n list of levels in the current semantic mappers. But it also allows the\n dictionary to persist, so it can be used to set levels by a key. This is\n used to track the list of col/row levels using an attached FacetGrid\n object, but it's kind of messy and ideally fixed by improving the\n faceting logic so it interfaces better with the modern approach to\n tracking plot variables.\n\n \"\"\"\n for var in self.variables:\n try:\n map_obj = getattr(self, f\"_{var}_map\")\n self._var_levels[var] = map_obj.levels\n except AttributeError:\n pass\n return self._var_levels\n\n def assign_variables(self, data=None, variables={}):\n \"\"\"Define plot variables, optionally using lookup from `data`.\"\"\"\n x = variables.get(\"x\", None)\n y = variables.get(\"y\", None)\n\n if x is None and y is None:\n self.input_format = \"wide\"\n plot_data, variables = self._assign_variables_wideform(\n data, **variables,\n )\n else:\n self.input_format = \"long\"\n plot_data, variables = self._assign_variables_longform(\n data, **variables,\n )\n\n self.plot_data = plot_data\n self.variables = variables\n self.var_types = {\n v: variable_type(\n plot_data[v],\n boolean_type=\"numeric\" if v in \"xy\" else \"categorical\"\n )\n for v in variables\n }\n\n return self\n\n def _assign_variables_wideform(self, data=None, **kwargs):\n \"\"\"Define plot variables given wide-form data.\n\n Parameters\n ----------\n data : flat vector or collection of vectors\n Data can be a vector or mapping that is coerceable to a Series\n or a sequence- or mapping-based collection of such vectors, or a\n rectangular numpy array, or a Pandas DataFrame.\n kwargs : variable -> data mappings\n Behavior with keyword arguments is currently undefined.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n \"\"\"\n # Raise if semantic or other variables are assigned in wide-form mode\n assigned = [k for k, v in kwargs.items() if v is not None]\n if any(assigned):\n s = \"s\" if len(assigned) > 1 else \"\"\n err = f\"The following variable{s} cannot be assigned with wide-form data: \"\n err += \", \".join(f\"`{v}`\" for v in assigned)\n raise ValueError(err)\n\n # Determine if the data object actually has any data in it\n empty = data is None or not len(data)\n\n # Then, determine if we have \"flat\" data (a single vector)\n if isinstance(data, dict):\n values = data.values()\n else:\n values = np.atleast_1d(np.asarray(data, dtype=object))\n flat = not any(\n isinstance(v, Iterable) and not isinstance(v, (str, bytes))\n for v in values\n )\n\n if empty:\n\n # Make an object with the structure of plot_data, but empty\n plot_data = pd.DataFrame()\n variables = {}\n\n elif flat:\n\n # Handle flat data by converting to pandas Series and using the\n # index and/or values to define x and/or y\n # (Could be accomplished with a more general to_series() interface)\n flat_data = pd.Series(data).copy()\n names = {\n \"@values\": flat_data.name,\n \"@index\": flat_data.index.name\n }\n\n plot_data = {}\n variables = {}\n\n for var in [\"x\", \"y\"]:\n if var in self.flat_structure:\n attr = self.flat_structure[var]\n plot_data[var] = getattr(flat_data, attr[1:])\n variables[var] = names[self.flat_structure[var]]\n\n plot_data = pd.DataFrame(plot_data)\n\n else:\n\n # Otherwise assume we have some collection of vectors.\n\n # Handle Python sequences such that entries end up in the columns,\n # not in the rows, of the intermediate wide DataFrame.\n # One way to accomplish this is to convert to a dict of Series.\n if isinstance(data, Sequence):\n data_dict = {}\n for i, var in enumerate(data):\n key = getattr(var, \"name\", i)\n # TODO is there a safer/more generic way to ensure Series?\n # sort of like np.asarray, but for pandas?\n data_dict[key] = pd.Series(var)\n\n data = data_dict\n\n # Pandas requires that dict values either be Series objects\n # or all have the same length, but we want to allow \"ragged\" inputs\n if isinstance(data, Mapping):\n data = {key: pd.Series(val) for key, val in data.items()}\n\n # Otherwise, delegate to the pandas DataFrame constructor\n # This is where we'd prefer to use a general interface that says\n # \"give me this data as a pandas DataFrame\", so we can accept\n # DataFrame objects from other libraries\n wide_data = pd.DataFrame(data, copy=True)\n\n # At this point we should reduce the dataframe to numeric cols\n numeric_cols = [\n k for k, v in wide_data.items() if variable_type(v) == \"numeric\"\n ]\n wide_data = wide_data[numeric_cols]\n\n # Now melt the data to long form\n melt_kws = {\"var_name\": \"@columns\", \"value_name\": \"@values\"}\n use_index = \"@index\" in self.wide_structure.values()\n if use_index:\n melt_kws[\"id_vars\"] = \"@index\"\n try:\n orig_categories = wide_data.columns.categories\n orig_ordered = wide_data.columns.ordered\n wide_data.columns = wide_data.columns.add_categories(\"@index\")\n except AttributeError:\n category_columns = False\n else:\n category_columns = True\n wide_data[\"@index\"] = wide_data.index.to_series()\n\n plot_data = wide_data.melt(**melt_kws)\n\n if use_index and category_columns:\n plot_data[\"@columns\"] = pd.Categorical(plot_data[\"@columns\"],\n orig_categories,\n orig_ordered)\n\n # Assign names corresponding to plot semantics\n for var, attr in self.wide_structure.items():\n plot_data[var] = plot_data[attr]\n\n # Define the variable names\n variables = {}\n for var, attr in self.wide_structure.items():\n obj = getattr(wide_data, attr[1:])\n variables[var] = getattr(obj, \"name\", None)\n\n # Remove redundant columns from plot_data\n plot_data = plot_data[list(variables)]\n\n return plot_data, variables\n\n def _assign_variables_longform(self, data=None, **kwargs):\n \"\"\"Define plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data : dict-like collection of vectors\n Input data where variable names map to vector values.\n kwargs : variable -> data mappings\n Keys are seaborn variables (x, y, hue, ...) and values are vectors\n in any format that can construct a :class:`pandas.DataFrame` or\n names of columns or index levels in ``data``.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in ``data``.\n\n \"\"\"\n plot_data = {}\n variables = {}\n\n # Data is optional; all variables can be defined as vectors\n if data is None:\n data = {}\n\n # TODO should we try a data.to_dict() or similar here to more\n # generally accept objects with that interface?\n # Note that dict(df) also works for pandas, and gives us what we\n # want, whereas DataFrame.to_dict() gives a nested dict instead of\n # a dict of series.\n\n # Variables can also be extracted from the index attribute\n # TODO is this the most general way to enable it?\n # There is no index.to_dict on multiindex, unfortunately\n try:\n index = data.index.to_frame()\n except AttributeError:\n index = {}\n\n # The caller will determine the order of variables in plot_data\n for key, val in kwargs.items():\n\n # First try to treat the argument as a key for the data collection.\n # But be flexible about what can be used as a key.\n # Usually it will be a string, but allow numbers or tuples too when\n # taking from the main data object. Only allow strings to reference\n # fields in the index, because otherwise there is too much ambiguity.\n try:\n val_as_data_key = (\n val in data\n or (isinstance(val, (str, bytes)) and val in index)\n )\n except (KeyError, TypeError):\n val_as_data_key = False\n\n if val_as_data_key:\n\n # We know that __getitem__ will work\n\n if val in data:\n plot_data[key] = data[val]\n elif val in index:\n plot_data[key] = index[val]\n variables[key] = val\n\n elif isinstance(val, (str, bytes)):\n\n # This looks like a column name but we don't know what it means!\n\n err = f\"Could not interpret value `{val}` for parameter `{key}`\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, assume the value is itself data\n\n # Raise when data object is present and a vector can't matched\n if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series):\n if np.ndim(val) and len(data) != len(val):\n val_cls = val.__class__.__name__\n err = (\n f\"Length of {val_cls} vectors must match length of `data`\"\n f\" when both are used, but `data` has length {len(data)}\"\n f\" and the vector passed to `{key}` has length {len(val)}.\"\n )\n raise ValueError(err)\n\n plot_data[key] = val\n\n # Try to infer the name of the variable\n variables[key] = getattr(val, \"name\", None)\n\n # Construct a tidy plot DataFrame. This will convert a number of\n # types automatically, aligning on index in case of pandas objects\n plot_data = pd.DataFrame(plot_data)\n\n # Reduce the variables dictionary to fields with valid data\n variables = {\n var: name\n for var, name in variables.items()\n if plot_data[var].notnull().any()\n }\n\n return plot_data, variables\n\n def iter_data(\n self, grouping_vars=None, *,\n reverse=False, from_comp_data=False,\n by_facet=True, allow_empty=False, dropna=True,\n ):\n \"\"\"Generator for getting subsets of data defined by semantic variables.\n\n Also injects \"col\" and \"row\" into grouping semantics.\n\n Parameters\n ----------\n grouping_vars : string or list of strings\n Semantic variables that define the subsets of data.\n reverse : bool\n If True, reverse the order of iteration.\n from_comp_data : bool\n If True, use self.comp_data rather than self.plot_data\n by_facet : bool\n If True, add faceting variables to the set of grouping variables.\n allow_empty : bool\n If True, yield an empty dataframe when no observations exist for\n combinations of grouping variables.\n dropna : bool\n If True, remove rows with missing data.\n\n Yields\n ------\n sub_vars : dict\n Keys are semantic names, values are the level of that semantic.\n sub_data : :class:`pandas.DataFrame`\n Subset of ``plot_data`` for this combination of semantic values.\n\n \"\"\"\n # TODO should this default to using all (non x/y?) semantics?\n # or define grouping vars somewhere?\n if grouping_vars is None:\n grouping_vars = []\n elif isinstance(grouping_vars, str):\n grouping_vars = [grouping_vars]\n elif isinstance(grouping_vars, tuple):\n grouping_vars = list(grouping_vars)\n\n # Always insert faceting variables\n if by_facet:\n facet_vars = {\"col\", \"row\"}\n grouping_vars.extend(\n facet_vars & set(self.variables) - set(grouping_vars)\n )\n\n # Reduce to the semantics used in this plot\n grouping_vars = [\n var for var in grouping_vars if var in self.variables\n ]\n\n if from_comp_data:\n data = self.comp_data\n else:\n data = self.plot_data\n\n if dropna:\n data = data.dropna()\n\n levels = self.var_levels.copy()\n if from_comp_data:\n for axis in {\"x\", \"y\"} & set(grouping_vars):\n if self.var_types[axis] == \"categorical\":\n if self._var_ordered[axis]:\n # If the axis is ordered, then the axes in a possible\n # facet grid are by definition \"shared\", or there is a\n # single axis with a unique cat -> idx mapping.\n # So we can just take the first converter object.\n converter = self.converters[axis].iloc[0]\n levels[axis] = converter.convert_units(levels[axis])\n else:\n # Otherwise, the mappings may not be unique, but we can\n # use the unique set of index values in comp_data.\n levels[axis] = np.sort(data[axis].unique())\n elif self.var_types[axis] == \"datetime\":\n levels[axis] = mpl.dates.date2num(levels[axis])\n elif self.var_types[axis] == \"numeric\" and self._log_scaled(axis):\n levels[axis] = np.log10(levels[axis])\n\n if grouping_vars:\n\n grouped_data = data.groupby(\n grouping_vars, sort=False, as_index=False\n )\n\n grouping_keys = []\n for var in grouping_vars:\n grouping_keys.append(levels.get(var, []))\n\n iter_keys = itertools.product(*grouping_keys)\n if reverse:\n iter_keys = reversed(list(iter_keys))\n\n for key in iter_keys:\n\n # Pandas fails with singleton tuple inputs\n pd_key = key[0] if len(key) == 1 else key\n\n try:\n data_subset = grouped_data.get_group(pd_key)\n except KeyError:\n # XXX we are adding this to allow backwards compatibility\n # with the empty artists that old categorical plots would\n # add (before 0.12), which we may decide to break, in which\n # case this option could be removed\n data_subset = data.loc[[]]\n\n if data_subset.empty and not allow_empty:\n continue\n\n sub_vars = dict(zip(grouping_vars, key))\n\n yield sub_vars, data_subset.copy()\n\n else:\n\n yield {}, data.copy()\n\n @property\n def comp_data(self):\n \"\"\"Dataframe with numeric x and y, after unit conversion and log scaling.\"\"\"\n if not hasattr(self, \"ax\"):\n # Probably a good idea, but will need a bunch of tests updated\n # Most of these tests should just use the external interface\n # Then this can be re-enabled.\n # raise AttributeError(\"No Axes attached to plotter\")\n return self.plot_data\n\n if not hasattr(self, \"_comp_data\"):\n\n comp_data = (\n self.plot_data\n .copy(deep=False)\n .drop([\"x\", \"y\"], axis=1, errors=\"ignore\")\n )\n\n for var in \"yx\":\n if var not in self.variables:\n continue\n\n parts = []\n grouped = self.plot_data[var].groupby(self.converters[var], sort=False)\n for converter, orig in grouped:\n with pd.option_context('mode.use_inf_as_null', True):\n orig = orig.dropna()\n if var in self.var_levels:\n # TODO this should happen in some centralized location\n # it is similar to GH2419, but more complicated because\n # supporting `order` in categorical plots is tricky\n orig = orig[orig.isin(self.var_levels[var])]\n comp = pd.to_numeric(converter.convert_units(orig))\n if converter.get_scale() == \"log\":\n comp = np.log10(comp)\n parts.append(pd.Series(comp, orig.index, name=orig.name))\n if parts:\n comp_col = pd.concat(parts)\n else:\n comp_col = pd.Series(dtype=float, name=var)\n comp_data.insert(0, var, comp_col)\n\n self._comp_data = comp_data\n\n return self._comp_data\n\n def _get_axes(self, sub_vars):\n \"\"\"Return an Axes object based on existence of row/col variables.\"\"\"\n row = sub_vars.get(\"row\", None)\n col = sub_vars.get(\"col\", None)\n if row is not None and col is not None:\n return self.facets.axes_dict[(row, col)]\n elif row is not None:\n return self.facets.axes_dict[row]\n elif col is not None:\n return self.facets.axes_dict[col]\n elif self.ax is None:\n return self.facets.ax\n else:\n return self.ax\n\n def _attach(\n self,\n obj,\n allowed_types=None,\n log_scale=None,\n ):\n \"\"\"Associate the plotter with an Axes manager and initialize its units.\n\n Parameters\n ----------\n obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid`\n Structural object that we will eventually plot onto.\n allowed_types : str or list of str\n If provided, raise when either the x or y variable does not have\n one of the declared seaborn types.\n log_scale : bool, number, or pair of bools or numbers\n If not False, set the axes to use log scaling, with the given\n base or defaulting to 10. If a tuple, interpreted as separate\n arguments for the x and y axes.\n\n \"\"\"\n from .axisgrid import FacetGrid\n if isinstance(obj, FacetGrid):\n self.ax = None\n self.facets = obj\n ax_list = obj.axes.flatten()\n if obj.col_names is not None:\n self.var_levels[\"col\"] = obj.col_names\n if obj.row_names is not None:\n self.var_levels[\"row\"] = obj.row_names\n else:\n self.ax = obj\n self.facets = None\n ax_list = [obj]\n\n # Identify which \"axis\" variables we have defined\n axis_variables = set(\"xy\").intersection(self.variables)\n\n # -- Verify the types of our x and y variables here.\n # This doesn't really make complete sense being here here, but it's a fine\n # place for it, given the current system.\n # (Note that for some plots, there might be more complicated restrictions)\n # e.g. the categorical plots have their own check that as specific to the\n # non-categorical axis.\n if allowed_types is None:\n allowed_types = [\"numeric\", \"datetime\", \"categorical\"]\n elif isinstance(allowed_types, str):\n allowed_types = [allowed_types]\n\n for var in axis_variables:\n var_type = self.var_types[var]\n if var_type not in allowed_types:\n err = (\n f\"The {var} variable is {var_type}, but one of \"\n f\"{allowed_types} is required\"\n )\n raise TypeError(err)\n\n # -- Get axis objects for each row in plot_data for type conversions and scaling\n\n facet_dim = {\"x\": \"col\", \"y\": \"row\"}\n\n self.converters = {}\n for var in axis_variables:\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n\n converter = pd.Series(index=self.plot_data.index, name=var, dtype=object)\n share_state = getattr(self.facets, f\"_share{var}\", True)\n\n # Simplest cases are that we have a single axes, all axes are shared,\n # or sharing is only on the orthogonal facet dimension. In these cases,\n # all datapoints get converted the same way, so use the first axis\n if share_state is True or share_state == facet_dim[other_var]:\n converter.loc[:] = getattr(ax_list[0], f\"{var}axis\")\n\n else:\n\n # Next simplest case is when no axes are shared, and we can\n # use the axis objects within each facet\n if share_state is False:\n for axes_vars, axes_data in self.iter_data():\n ax = self._get_axes(axes_vars)\n converter.loc[axes_data.index] = getattr(ax, f\"{var}axis\")\n\n # In the more complicated case, the axes are shared within each\n # \"file\" of the facetgrid. In that case, we need to subset the data\n # for that file and assign it the first axis in the slice of the grid\n else:\n\n names = getattr(self.facets, f\"{share_state}_names\")\n for i, level in enumerate(names):\n idx = (i, 0) if share_state == \"row\" else (0, i)\n axis = getattr(self.facets.axes[idx], f\"{var}axis\")\n converter.loc[self.plot_data[share_state] == level] = axis\n\n # Store the converter vector, which we use elsewhere (e.g comp_data)\n self.converters[var] = converter\n\n # Now actually update the matplotlib objects to do the conversion we want\n grouped = self.plot_data[var].groupby(self.converters[var], sort=False)\n for converter, seed_data in grouped:\n if self.var_types[var] == \"categorical\":\n if self._var_ordered[var]:\n order = self.var_levels[var]\n else:\n order = None\n seed_data = categorical_order(seed_data, order)\n converter.update_units(seed_data)\n\n # -- Set numerical axis scales\n\n # First unpack the log_scale argument\n if log_scale is None:\n scalex = scaley = False\n else:\n # Allow single value or x, y tuple\n try:\n scalex, scaley = log_scale\n except TypeError:\n scalex = log_scale if \"x\" in self.variables else False\n scaley = log_scale if \"y\" in self.variables else False\n\n # Now use it\n for axis, scale in zip(\"xy\", (scalex, scaley)):\n if scale:\n for ax in ax_list:\n set_scale = getattr(ax, f\"set_{axis}scale\")\n if scale is True:\n set_scale(\"log\")\n else:\n if Version(mpl.__version__) >= Version(\"3.3\"):\n set_scale(\"log\", base=scale)\n else:\n set_scale(\"log\", **{f\"base{axis}\": scale})\n\n # For categorical y, we want the \"first\" level to be at the top of the axis\n if self.var_types.get(\"y\", None) == \"categorical\":\n for ax in ax_list:\n try:\n ax.yaxis.set_inverted(True)\n except AttributeError: # mpl < 3.1\n if not ax.yaxis_inverted():\n ax.invert_yaxis()\n\n # TODO -- Add axes labels\n\n def _log_scaled(self, axis):\n \"\"\"Return True if specified axis is log scaled on all attached axes.\"\"\"\n if not hasattr(self, \"ax\"):\n return False\n\n if self.ax is None:\n axes_list = self.facets.axes.flatten()\n else:\n axes_list = [self.ax]\n\n log_scaled = []\n for ax in axes_list:\n data_axis = getattr(ax, f\"{axis}axis\")\n log_scaled.append(data_axis.get_scale() == \"log\")\n\n if any(log_scaled) and not all(log_scaled):\n raise RuntimeError(\"Axis scaling is not consistent\")\n\n return any(log_scaled)\n\n def _add_axis_labels(self, ax, default_x=\"\", default_y=\"\"):\n \"\"\"Add axis labels if not present, set visibility to match ticklabels.\"\"\"\n # TODO ax could default to None and use attached axes if present\n # but what to do about the case of facets? Currently using FacetGrid's\n # set_axis_labels method, which doesn't add labels to the interior even\n # when the axes are not shared. Maybe that makes sense?\n if not ax.get_xlabel():\n x_visible = any(t.get_visible() for t in ax.get_xticklabels())\n ax.set_xlabel(self.variables.get(\"x\", default_x), visible=x_visible)\n if not ax.get_ylabel():\n y_visible = any(t.get_visible() for t in ax.get_yticklabels())\n ax.set_ylabel(self.variables.get(\"y\", default_y), visible=y_visible)\n\n # XXX If the scale_* methods are going to modify the plot_data structure, they\n # can't be called twice. That means that if they are called twice, they should\n # raise. Alternatively, we could store an original version of plot_data and each\n # time they are called they operate on the store, not the current state.\n\n def scale_native(self, axis, *args, **kwargs):\n\n # Default, defer to matplotlib\n\n raise NotImplementedError\n\n def scale_numeric(self, axis, *args, **kwargs):\n\n # Feels needed to completeness, what should it do?\n # Perhaps handle log scaling? Set the ticker/formatter/limits?\n\n raise NotImplementedError\n\n def scale_datetime(self, axis, *args, **kwargs):\n\n # Use pd.to_datetime to convert strings or numbers to datetime objects\n # Note, use day-resolution for numeric->datetime to match matplotlib\n\n raise NotImplementedError\n\n def scale_categorical(self, axis, order=None, formatter=None):\n \"\"\"\n Enforce categorical (fixed-scale) rules for the data on given axis.\n\n Parameters\n ----------\n axis : \"x\" or \"y\"\n Axis of the plot to operate on.\n order : list\n Order that unique values should appear in.\n formatter : callable\n Function mapping values to a string representation.\n\n Returns\n -------\n self\n\n \"\"\"\n # This method both modifies the internal representation of the data\n # (converting it to string) and sets some attributes on self. It might be\n # a good idea to have a separate object attached to self that contains the\n # information in those attributes (i.e. whether to enforce variable order\n # across facets, the order to use) similar to the SemanticMapping objects\n # we have for semantic variables. That object could also hold the converter\n # objects that get used, if we can decouple those from an existing axis\n # (cf. https://github.com/matplotlib/matplotlib/issues/19229).\n # There are some interactions with faceting information that would need\n # to be thought through, since the converts to use depend on facets.\n # If we go that route, these methods could become \"borrowed\" methods similar\n # to what happens with the alternate semantic mapper constructors, although\n # that approach is kind of fussy and confusing.\n\n # TODO this method could also set the grid state? Since we like to have no\n # grid on the categorical axis by default. Again, a case where we'll need to\n # store information until we use it, so best to have a way to collect the\n # attributes that this method sets.\n\n # TODO if we are going to set visual properties of the axes with these methods,\n # then we could do the steps currently in CategoricalPlotter._adjust_cat_axis\n\n # TODO another, and distinct idea, is to expose a cut= param here\n\n _check_argument(\"axis\", [\"x\", \"y\"], axis)\n\n # Categorical plots can be \"univariate\" in which case they get an anonymous\n # category label on the opposite axis.\n if axis not in self.variables:\n self.variables[axis] = None\n self.var_types[axis] = \"categorical\"\n self.plot_data[axis] = \"\"\n\n # If the \"categorical\" variable has a numeric type, sort the rows so that\n # the default result from categorical_order has those values sorted after\n # they have been coerced to strings. The reason for this is so that later\n # we can get facet-wise orders that are correct.\n # XXX Should this also sort datetimes?\n # It feels more consistent, but technically will be a default change\n # If so, should also change categorical_order to behave that way\n if self.var_types[axis] == \"numeric\":\n self.plot_data = self.plot_data.sort_values(axis, kind=\"mergesort\")\n\n # Now get a reference to the categorical data vector\n cat_data = self.plot_data[axis]\n\n # Get the initial categorical order, which we do before string\n # conversion to respect the original types of the order list.\n # Track whether the order is given explicitly so that we can know\n # whether or not to use the order constructed here downstream\n self._var_ordered[axis] = order is not None or cat_data.dtype.name == \"category\"\n order = pd.Index(categorical_order(cat_data, order))\n\n # Then convert data to strings. This is because in matplotlib,\n # \"categorical\" data really mean \"string\" data, so doing this artists\n # will be drawn on the categorical axis with a fixed scale.\n # TODO implement formatter here; check that it returns strings?\n if formatter is not None:\n cat_data = cat_data.map(formatter)\n order = order.map(formatter)\n else:\n cat_data = cat_data.astype(str)\n order = order.astype(str)\n\n # Update the levels list with the type-converted order variable\n self.var_levels[axis] = order\n\n # Now ensure that seaborn will use categorical rules internally\n self.var_types[axis] = \"categorical\"\n\n # Put the string-typed categorical vector back into the plot_data structure\n self.plot_data[axis] = cat_data\n\n return self\n\n\nclass VariableType(UserString):\n \"\"\"\n Prevent comparisons elsewhere in the library from using the wrong name.\n\n Errors are simple assertions because users should not be able to trigger\n them. If that changes, they should be more verbose.\n\n \"\"\"\n # TODO we can replace this with typing.Literal on Python 3.8+\n allowed = \"numeric\", \"datetime\", \"categorical\"\n\n def __init__(self, data):\n assert data in self.allowed, data\n super().__init__(data)\n\n def __eq__(self, other):\n assert other in self.allowed, other\n return self.data == other\n\n\ndef variable_type(vector, boolean_type=\"numeric\"):\n \"\"\"\n Determine whether a vector contains numeric, categorical, or datetime data.\n\n This function differs from the pandas typing API in two ways:\n\n - Python sequences or object-typed PyData objects are considered numeric if\n all of their entries are numeric.\n - String or mixed-type data are considered categorical even if not\n explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.\n\n Parameters\n ----------\n vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence\n Input data to test.\n boolean_type : 'numeric' or 'categorical'\n Type to use for vectors containing only 0s and 1s (and NAs).\n\n Returns\n -------\n var_type : 'numeric', 'categorical', or 'datetime'\n Name identifying the type of data in the vector.\n \"\"\"\n\n # If a categorical dtype is set, infer categorical\n if pd.api.types.is_categorical_dtype(vector):\n return VariableType(\"categorical\")\n\n # Special-case all-na data, which is always \"numeric\"\n if pd.isna(vector).all():\n return VariableType(\"numeric\")\n\n # Special-case binary/boolean data, allow caller to determine\n # This triggers a numpy warning when vector has strings/objects\n # https://github.com/numpy/numpy/issues/6784\n # Because we reduce with .all(), we are agnostic about whether the\n # comparison returns a scalar or vector, so we will ignore the warning.\n # It triggers a separate DeprecationWarning when the vector has datetimes:\n # https://github.com/numpy/numpy/issues/13548\n # This is considered a bug by numpy and will likely go away.\n with warnings.catch_warnings():\n warnings.simplefilter(\n action='ignore', category=(FutureWarning, DeprecationWarning)\n )\n if np.isin(vector, [0, 1, np.nan]).all():\n return VariableType(boolean_type)\n\n # Defer to positive pandas tests\n if pd.api.types.is_numeric_dtype(vector):\n return VariableType(\"numeric\")\n\n if pd.api.types.is_datetime64_dtype(vector):\n return VariableType(\"datetime\")\n\n # --- If we get to here, we need to check the entries\n\n # Check for a collection where everything is a number\n\n def all_numeric(x):\n for x_i in x:\n if not isinstance(x_i, Number):\n return False\n return True\n\n if all_numeric(vector):\n return VariableType(\"numeric\")\n\n # Check for a collection where everything is a datetime\n\n def all_datetime(x):\n for x_i in x:\n if not isinstance(x_i, (datetime, np.datetime64)):\n return False\n return True\n\n if all_datetime(vector):\n return VariableType(\"datetime\")\n\n # Otherwise, our final fallback is to consider things categorical\n\n return VariableType(\"categorical\")\n\n\ndef infer_orient(x=None, y=None, orient=None, require_numeric=True):\n \"\"\"Determine how the plot should be oriented based on the data.\n\n For historical reasons, the convention is to call a plot \"horizontally\"\n or \"vertically\" oriented based on the axis representing its dependent\n variable. Practically, this is used when determining the axis for\n numerical aggregation.\n\n Parameters\n ----------\n x, y : Vector data or None\n Positional data vectors for the plot.\n orient : string or None\n Specified orientation, which must start with \"v\" or \"h\" if not None.\n require_numeric : bool\n If set, raise when the implied dependent variable is not numeric.\n\n Returns\n -------\n orient : \"v\" or \"h\"\n\n Raises\n ------\n ValueError: When `orient` is not None and does not start with \"h\" or \"v\"\n TypeError: When dependent variable is not numeric, with `require_numeric`\n\n \"\"\"\n\n x_type = None if x is None else variable_type(x)\n y_type = None if y is None else variable_type(y)\n\n nonnumeric_dv_error = \"{} orientation requires numeric `{}` variable.\"\n single_var_warning = \"{} orientation ignored with only `{}` specified.\"\n\n if x is None:\n if str(orient).startswith(\"h\"):\n warnings.warn(single_var_warning.format(\"Horizontal\", \"y\"))\n if require_numeric and y_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Vertical\", \"y\"))\n return \"v\"\n\n elif y is None:\n if str(orient).startswith(\"v\"):\n warnings.warn(single_var_warning.format(\"Vertical\", \"x\"))\n if require_numeric and x_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Horizontal\", \"x\"))\n return \"h\"\n\n elif str(orient).startswith(\"v\"):\n if require_numeric and y_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Vertical\", \"y\"))\n return \"v\"\n\n elif str(orient).startswith(\"h\"):\n if require_numeric and x_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Horizontal\", \"x\"))\n return \"h\"\n\n elif orient is not None:\n err = (\n \"`orient` must start with 'v' or 'h' or be None, \"\n f\"but `{repr(orient)}` was passed.\"\n )\n raise ValueError(err)\n\n elif x_type != \"categorical\" and y_type == \"categorical\":\n return \"h\"\n\n elif x_type != \"numeric\" and y_type == \"numeric\":\n return \"v\"\n\n elif x_type == \"numeric\" and y_type != \"numeric\":\n return \"h\"\n\n elif require_numeric and \"numeric\" not in (x_type, y_type):\n err = \"Neither the `x` nor `y` variable appears to be numeric.\"\n raise TypeError(err)\n\n else:\n return \"v\"\n\n\ndef unique_dashes(n):\n \"\"\"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n \"\"\"\n # Start with dash specs that are well distinguishable\n dashes = [\n \"\",\n (4, 1.5),\n (1, 1),\n (3, 1.25, 1.5, 1.25),\n (5, 1, 1, 1),\n ]\n\n # Now programmatically build as many as we need\n p = 3\n while len(dashes) < n:\n\n # Take combinations of long and short dashes\n a = itertools.combinations_with_replacement([3, 1.25], p)\n b = itertools.combinations_with_replacement([4, 1], p)\n\n # Interleave the combinations, reversing one of the streams\n segment_list = itertools.chain(*zip(\n list(a)[1:-1][::-1],\n list(b)[1:-1]\n ))\n\n # Now insert the gaps\n for segments in segment_list:\n gap = min(segments)\n spec = tuple(itertools.chain(*((seg, gap) for seg in segments)))\n dashes.append(spec)\n\n p += 1\n\n return dashes[:n]\n\n\ndef unique_markers(n):\n \"\"\"Build an arbitrarily long list of unique marker styles for points.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n \"\"\"\n # Start with marker specs that are well distinguishable\n markers = [\n \"o\",\n \"X\",\n (4, 0, 45),\n \"P\",\n (4, 0, 0),\n (4, 1, 0),\n \"^\",\n (4, 1, 45),\n \"v\",\n ]\n\n # Now generate more from regular polygons of increasing order\n s = 5\n while len(markers) < n:\n a = 360 / (s + 1) / 2\n markers.extend([\n (s + 1, 1, a),\n (s + 1, 0, a),\n (s, 1, 0),\n (s, 0, 0),\n ])\n s += 1\n\n # Convert to MarkerStyle object, using only exactly what we need\n # markers = [mpl.markers.MarkerStyle(m) for m in markers[:n]]\n\n return markers[:n]\n\n\ndef categorical_order(vector, order=None):\n \"\"\"Return a list of unique data values.\n\n Determine an ordered list of levels in ``values``.\n\n Parameters\n ----------\n vector : list, array, Categorical, or Series\n Vector of \"categorical\" values\n order : list-like, optional\n Desired order of category levels to override the order determined\n from the ``values`` object.\n\n Returns\n -------\n order : list\n Ordered list of category levels not including null values.\n\n \"\"\"\n if order is None:\n if hasattr(vector, \"categories\"):\n order = vector.categories\n else:\n try:\n order = vector.cat.categories\n except (TypeError, AttributeError):\n\n try:\n order = vector.unique()\n except AttributeError:\n order = pd.unique(vector)\n\n if variable_type(vector) == \"numeric\":\n order = np.sort(order)\n\n order = filter(pd.notnull, order)\n return list(order)\n"},{"className":"UserString","col":0,"comment":"null","endLoc":236,"id":103,"nodeType":"Class","startLoc":164,"text":"class UserString(Sequence[UserString]):\n data: str\n def __init__(self, seq: object) -> None: ...\n def __int__(self) -> int: ...\n def __float__(self) -> float: ...\n def __complex__(self) -> complex: ...\n def __getnewargs__(self) -> tuple[str]: ...\n def __lt__(self, string: str | UserString) -> bool: ...\n def __le__(self, string: str | UserString) -> bool: ...\n def __gt__(self, string: str | UserString) -> bool: ...\n def __ge__(self, string: str | UserString) -> bool: ...\n def __eq__(self, string: object) -> bool: ...\n def __hash__(self) -> int: ...\n def __contains__(self, char: object) -> bool: ...\n def __len__(self) -> int: ...\n def __getitem__(self, index: SupportsIndex | slice) -> Self: ...\n def __iter__(self) -> Iterator[Self]: ...\n def __reversed__(self) -> Iterator[Self]: ...\n def __add__(self, other: object) -> Self: ...\n def __radd__(self, other: object) -> Self: ...\n def __mul__(self, n: int) -> Self: ...\n def __rmul__(self, n: int) -> Self: ...\n def __mod__(self, args: Any) -> Self: ...\n def __rmod__(self, template: object) -> Self: ...\n def capitalize(self) -> Self: ...\n def casefold(self) -> Self: ...\n def center(self, width: int, *args: Any) -> Self: ...\n def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n def encode(self: UserString, encoding: str | None = \"utf-8\", errors: str | None = \"strict\") -> bytes: ...\n def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ...\n def expandtabs(self, tabsize: int = 8) -> Self: ...\n def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n def format(self, *args: Any, **kwds: Any) -> str: ...\n def format_map(self, mapping: Mapping[str, Any]) -> str: ...\n def index(self, sub: str, start: int = 0, end: int = sys.maxsize) -> int: ...\n def isalpha(self) -> bool: ...\n def isalnum(self) -> bool: ...\n def isdecimal(self) -> bool: ...\n def isdigit(self) -> bool: ...\n def isidentifier(self) -> bool: ...\n def islower(self) -> bool: ...\n def isnumeric(self) -> bool: ...\n def isprintable(self) -> bool: ...\n def isspace(self) -> bool: ...\n def istitle(self) -> bool: ...\n def isupper(self) -> bool: ...\n def isascii(self) -> bool: ...\n def join(self, seq: Iterable[str]) -> str: ...\n def ljust(self, width: int, *args: Any) -> Self: ...\n def lower(self) -> Self: ...\n def lstrip(self, chars: str | None = None) -> Self: ...\n maketrans = str.maketrans\n def partition(self, sep: str) -> tuple[str, str, str]: ...\n if sys.version_info >= (3, 9):\n def removeprefix(self, prefix: str | UserString, /) -> Self: ...\n def removesuffix(self, suffix: str | UserString, /) -> Self: ...\n\n def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self: ...\n def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n def rindex(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n def rjust(self, width: int, *args: Any) -> Self: ...\n def rpartition(self, sep: str) -> tuple[str, str, str]: ...\n def rstrip(self, chars: str | None = None) -> Self: ...\n def split(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ...\n def rsplit(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ...\n def splitlines(self, keepends: bool = False) -> list[str]: ...\n def startswith(self, prefix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ...\n def strip(self, chars: str | None = None) -> Self: ...\n def swapcase(self) -> Self: ...\n def title(self) -> Self: ...\n def translate(self, *args: Any) -> Self: ...\n def upper(self) -> Self: ...\n def zfill(self, width: int) -> Self: ..."},{"attributeType":"str | None","col":8,"comment":"null","endLoc":57,"id":104,"name":"_rc","nodeType":"Attribute","startLoc":57,"text":"self._rc"},{"col":0,"comment":"null","endLoc":215,"header":"def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]","id":105,"name":"fields","nodeType":"Function","startLoc":215,"text":"def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ..."},{"col":4,"comment":"null","endLoc":122,"header":"@property\n def _grouping_props(self)","id":107,"name":"_grouping_props","nodeType":"Function","startLoc":115,"text":"@property\n def _grouping_props(self):\n # TODO does it make sense to have variation within a Mark's\n # properties about whether they are grouping?\n return [\n f.name for f in fields(self)\n if isinstance(f.default, Mappable) and f.default.grouping\n ]"},{"col":4,"comment":"null","endLoc":206,"header":"def _infer_orient(self, scales: dict) -> str","id":108,"name":"_infer_orient","nodeType":"Function","startLoc":192,"text":"def _infer_orient(self, scales: dict) -> str: # TODO type scales\n\n # TODO The original version of this (in seaborn._oldcore) did more checking.\n # Paring that down here for the prototype to see what restrictions make sense.\n\n # TODO rethink this to map from scale type to \"DV priority\" and use that?\n # e.g. Nominal > Discrete > Continuous\n\n x = 0 if \"x\" not in scales else scales[\"x\"]._priority\n y = 0 if \"y\" not in scales else scales[\"y\"]._priority\n\n if y > x:\n return \"y\"\n else:\n return \"x\""},{"col":4,"comment":"Main interface for creating a plot.","endLoc":215,"header":"def _plot(\n self,\n split_generator: Callable[[], Generator],\n scales: dict[str, Scale],\n orient: str,\n ) -> None","id":109,"name":"_plot","nodeType":"Function","startLoc":208,"text":"def _plot(\n self,\n split_generator: Callable[[], Generator],\n scales: dict[str, Scale],\n orient: str,\n ) -> None:\n \"\"\"Main interface for creating a plot.\"\"\"\n raise NotImplementedError()"},{"col":4,"comment":"null","endLoc":166,"header":"def __init__(self, seq: object) -> None","id":110,"name":"__init__","nodeType":"Function","startLoc":166,"text":"def __init__(self, seq: object) -> None: ..."},{"col":4,"comment":"null","endLoc":167,"header":"def __int__(self) -> int","id":111,"name":"__int__","nodeType":"Function","startLoc":167,"text":"def __int__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":168,"header":"def __float__(self) -> float","id":112,"name":"__float__","nodeType":"Function","startLoc":168,"text":"def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":169,"header":"def __complex__(self) -> complex","id":113,"name":"__complex__","nodeType":"Function","startLoc":169,"text":"def __complex__(self) -> complex: ..."},{"col":4,"comment":"null","endLoc":170,"header":"def __getnewargs__(self) -> tuple[str]","id":114,"name":"__getnewargs__","nodeType":"Function","startLoc":170,"text":"def __getnewargs__(self) -> tuple[str]: ..."},{"col":4,"comment":"null","endLoc":171,"header":"def __lt__(self, string: str | UserString) -> bool","id":115,"name":"__lt__","nodeType":"Function","startLoc":171,"text":"def __lt__(self, string: str | UserString) -> bool: ..."},{"col":4,"comment":"null","endLoc":172,"header":"def __le__(self, string: str | UserString) -> bool","id":116,"name":"__le__","nodeType":"Function","startLoc":172,"text":"def __le__(self, string: str | UserString) -> bool: ..."},{"col":4,"comment":"null","endLoc":173,"header":"def __gt__(self, string: str | UserString) -> bool","id":117,"name":"__gt__","nodeType":"Function","startLoc":173,"text":"def __gt__(self, string: str | UserString) -> bool: ..."},{"col":4,"comment":"null","endLoc":174,"header":"def __ge__(self, string: str | UserString) -> bool","id":118,"name":"__ge__","nodeType":"Function","startLoc":174,"text":"def __ge__(self, string: str | UserString) -> bool: ..."},{"col":4,"comment":"null","endLoc":175,"header":"def __eq__(self, string: object) -> bool","id":119,"name":"__eq__","nodeType":"Function","startLoc":175,"text":"def __eq__(self, string: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":176,"header":"def __hash__(self) -> int","id":120,"name":"__hash__","nodeType":"Function","startLoc":176,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":177,"header":"def __contains__(self, char: object) -> bool","id":121,"name":"__contains__","nodeType":"Function","startLoc":177,"text":"def __contains__(self, char: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":178,"header":"def __len__(self) -> int","id":122,"name":"__len__","nodeType":"Function","startLoc":178,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":179,"header":"def __getitem__(self, index: SupportsIndex | slice) -> Self","id":123,"name":"__getitem__","nodeType":"Function","startLoc":179,"text":"def __getitem__(self, index: SupportsIndex | slice) -> Self: ..."},{"col":4,"comment":"null","endLoc":180,"header":"def __iter__(self) -> Iterator[Self]","id":124,"name":"__iter__","nodeType":"Function","startLoc":180,"text":"def __iter__(self) -> Iterator[Self]: ..."},{"col":4,"comment":"null","endLoc":181,"header":"def __reversed__(self) -> Iterator[Self]","id":125,"name":"__reversed__","nodeType":"Function","startLoc":181,"text":"def __reversed__(self) -> Iterator[Self]: ..."},{"col":4,"comment":"null","endLoc":182,"header":"def __add__(self, other: object) -> Self","id":126,"name":"__add__","nodeType":"Function","startLoc":182,"text":"def __add__(self, other: object) -> Self: ..."},{"col":4,"comment":"null","endLoc":183,"header":"def __radd__(self, other: object) -> Self","id":127,"name":"__radd__","nodeType":"Function","startLoc":183,"text":"def __radd__(self, other: object) -> Self: ..."},{"col":4,"comment":"null","endLoc":184,"header":"def __mul__(self, n: int) -> Self","id":128,"name":"__mul__","nodeType":"Function","startLoc":184,"text":"def __mul__(self, n: int) -> Self: ..."},{"col":4,"comment":"null","endLoc":185,"header":"def __rmul__(self, n: int) -> Self","id":129,"name":"__rmul__","nodeType":"Function","startLoc":185,"text":"def __rmul__(self, n: int) -> Self: ..."},{"col":4,"comment":"null","endLoc":186,"header":"def __mod__(self, args: Any) -> Self","id":130,"name":"__mod__","nodeType":"Function","startLoc":186,"text":"def __mod__(self, args: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":187,"header":"def __rmod__(self, template: object) -> Self","id":131,"name":"__rmod__","nodeType":"Function","startLoc":187,"text":"def __rmod__(self, template: object) -> Self: ..."},{"col":4,"comment":"null","endLoc":188,"header":"def capitalize(self) -> Self","id":132,"name":"capitalize","nodeType":"Function","startLoc":188,"text":"def capitalize(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":189,"header":"def casefold(self) -> Self","id":133,"name":"casefold","nodeType":"Function","startLoc":189,"text":"def casefold(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":190,"header":"def center(self, width: int, *args: Any) -> Self","id":134,"name":"center","nodeType":"Function","startLoc":190,"text":"def center(self, width: int, *args: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":191,"header":"def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int","id":135,"name":"count","nodeType":"Function","startLoc":191,"text":"def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ..."},{"col":4,"comment":"null","endLoc":192,"header":"def encode(self: UserString, encoding: str | None = \"utf-8\", errors: str | None = \"strict\") -> bytes","id":136,"name":"encode","nodeType":"Function","startLoc":192,"text":"def encode(self: UserString, encoding: str | None = \"utf-8\", errors: str | None = \"strict\") -> bytes: ..."},{"col":4,"comment":"null","endLoc":193,"header":"def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool","id":137,"name":"endswith","nodeType":"Function","startLoc":193,"text":"def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ..."},{"col":4,"comment":"null","endLoc":194,"header":"def expandtabs(self, tabsize: int = 8) -> Self","id":138,"name":"expandtabs","nodeType":"Function","startLoc":194,"text":"def expandtabs(self, tabsize: int = 8) -> Self: ..."},{"col":4,"comment":"null","endLoc":195,"header":"def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int","id":139,"name":"find","nodeType":"Function","startLoc":195,"text":"def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ..."},{"col":4,"comment":"null","endLoc":196,"header":"def format(self, *args: Any, **kwds: Any) -> str","id":140,"name":"format","nodeType":"Function","startLoc":196,"text":"def format(self, *args: Any, **kwds: Any) -> str: ..."},{"col":4,"comment":"null","endLoc":197,"header":"def format_map(self, mapping: Mapping[str, Any]) -> str","id":141,"name":"format_map","nodeType":"Function","startLoc":197,"text":"def format_map(self, mapping: Mapping[str, Any]) -> str: ..."},{"col":4,"comment":"null","endLoc":198,"header":"def index(self, sub: str, start: int = 0, end: int = sys.maxsize) -> int","id":142,"name":"index","nodeType":"Function","startLoc":198,"text":"def index(self, sub: str, start: int = 0, end: int = sys.maxsize) -> int: ..."},{"col":4,"comment":"null","endLoc":199,"header":"def isalpha(self) -> bool","id":143,"name":"isalpha","nodeType":"Function","startLoc":199,"text":"def isalpha(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":200,"header":"def isalnum(self) -> bool","id":144,"name":"isalnum","nodeType":"Function","startLoc":200,"text":"def isalnum(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":201,"header":"def isdecimal(self) -> bool","id":145,"name":"isdecimal","nodeType":"Function","startLoc":201,"text":"def isdecimal(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":202,"header":"def isdigit(self) -> bool","id":146,"name":"isdigit","nodeType":"Function","startLoc":202,"text":"def isdigit(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":203,"header":"def isidentifier(self) -> bool","id":147,"name":"isidentifier","nodeType":"Function","startLoc":203,"text":"def isidentifier(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":204,"header":"def islower(self) -> bool","id":148,"name":"islower","nodeType":"Function","startLoc":204,"text":"def islower(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":205,"header":"def isnumeric(self) -> bool","id":149,"name":"isnumeric","nodeType":"Function","startLoc":205,"text":"def isnumeric(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":206,"header":"def isprintable(self) -> bool","id":150,"name":"isprintable","nodeType":"Function","startLoc":206,"text":"def isprintable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":207,"header":"def isspace(self) -> bool","id":151,"name":"isspace","nodeType":"Function","startLoc":207,"text":"def isspace(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":208,"header":"def istitle(self) -> bool","id":152,"name":"istitle","nodeType":"Function","startLoc":208,"text":"def istitle(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":209,"header":"def isupper(self) -> bool","id":153,"name":"isupper","nodeType":"Function","startLoc":209,"text":"def isupper(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":210,"header":"def isascii(self) -> bool","id":154,"name":"isascii","nodeType":"Function","startLoc":210,"text":"def isascii(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":211,"header":"def join(self, seq: Iterable[str]) -> str","id":155,"name":"join","nodeType":"Function","startLoc":211,"text":"def join(self, seq: Iterable[str]) -> str: ..."},{"col":4,"comment":"null","endLoc":212,"header":"def ljust(self, width: int, *args: Any) -> Self","id":156,"name":"ljust","nodeType":"Function","startLoc":212,"text":"def ljust(self, width: int, *args: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":213,"header":"def lower(self) -> Self","id":157,"name":"lower","nodeType":"Function","startLoc":213,"text":"def lower(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":214,"header":"def lstrip(self, chars: str | None = None) -> Self","id":158,"name":"lstrip","nodeType":"Function","startLoc":214,"text":"def lstrip(self, chars: str | None = None) -> Self: ..."},{"col":4,"comment":"null","endLoc":216,"header":"def partition(self, sep: str) -> tuple[str, str, str]","id":159,"name":"partition","nodeType":"Function","startLoc":216,"text":"def partition(self, sep: str) -> tuple[str, str, str]: ..."},{"col":8,"comment":"null","endLoc":218,"header":"def removeprefix(self, prefix: str | UserString, /) -> Self","id":160,"name":"removeprefix","nodeType":"Function","startLoc":218,"text":"def removeprefix(self, prefix: str | UserString, /) -> Self: ..."},{"col":8,"comment":"null","endLoc":219,"header":"def removesuffix(self, suffix: str | UserString, /) -> Self","id":161,"name":"removesuffix","nodeType":"Function","startLoc":219,"text":"def removesuffix(self, suffix: str | UserString, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":221,"header":"def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self","id":162,"name":"replace","nodeType":"Function","startLoc":221,"text":"def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self: ..."},{"col":4,"comment":"null","endLoc":222,"header":"def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int","id":163,"name":"rfind","nodeType":"Function","startLoc":222,"text":"def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ..."},{"col":4,"comment":"null","endLoc":223,"header":"def rindex(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int","id":164,"name":"rindex","nodeType":"Function","startLoc":223,"text":"def rindex(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ..."},{"col":4,"comment":"null","endLoc":224,"header":"def rjust(self, width: int, *args: Any) -> Self","id":165,"name":"rjust","nodeType":"Function","startLoc":224,"text":"def rjust(self, width: int, *args: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":225,"header":"def rpartition(self, sep: str) -> tuple[str, str, str]","id":166,"name":"rpartition","nodeType":"Function","startLoc":225,"text":"def rpartition(self, sep: str) -> tuple[str, str, str]: ..."},{"col":4,"comment":"null","endLoc":226,"header":"def rstrip(self, chars: str | None = None) -> Self","id":167,"name":"rstrip","nodeType":"Function","startLoc":226,"text":"def rstrip(self, chars: str | None = None) -> Self: ..."},{"col":4,"comment":"null","endLoc":227,"header":"def split(self, sep: str | None = None, maxsplit: int = -1) -> list[str]","id":168,"name":"split","nodeType":"Function","startLoc":227,"text":"def split(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":228,"header":"def rsplit(self, sep: str | None = None, maxsplit: int = -1) -> list[str]","id":169,"name":"rsplit","nodeType":"Function","startLoc":228,"text":"def rsplit(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":229,"header":"def splitlines(self, keepends: bool = False) -> list[str]","id":170,"name":"splitlines","nodeType":"Function","startLoc":229,"text":"def splitlines(self, keepends: bool = False) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":230,"header":"def startswith(self, prefix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool","id":171,"name":"startswith","nodeType":"Function","startLoc":230,"text":"def startswith(self, prefix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ..."},{"col":4,"comment":"null","endLoc":231,"header":"def strip(self, chars: str | None = None) -> Self","id":172,"name":"strip","nodeType":"Function","startLoc":231,"text":"def strip(self, chars: str | None = None) -> Self: ..."},{"col":4,"comment":"null","endLoc":232,"header":"def swapcase(self) -> Self","id":173,"name":"swapcase","nodeType":"Function","startLoc":232,"text":"def swapcase(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":233,"header":"def title(self) -> Self","id":174,"name":"title","nodeType":"Function","startLoc":233,"text":"def title(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":234,"header":"def translate(self, *args: Any) -> Self","id":175,"name":"translate","nodeType":"Function","startLoc":234,"text":"def translate(self, *args: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":235,"header":"def upper(self) -> Self","id":176,"name":"upper","nodeType":"Function","startLoc":235,"text":"def upper(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":236,"header":"def zfill(self, width: int) -> Self","id":177,"name":"zfill","nodeType":"Function","startLoc":236,"text":"def zfill(self, width: int) -> Self: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":165,"id":178,"name":"data","nodeType":"Attribute","startLoc":165,"text":"data"},{"col":4,"comment":"null","endLoc":1933,"header":"def __init__(self, *args: object) -> None","id":179,"name":"__init__","nodeType":"Function","startLoc":1933,"text":"def __init__(self, *args: object) -> None: ..."},{"col":4,"comment":"null","endLoc":221,"header":"def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist","id":180,"name":"_legend_artist","nodeType":"Function","startLoc":217,"text":"def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n\n return None"},{"attributeType":"dict","col":4,"comment":"null","endLoc":106,"id":181,"name":"artist_kws","nodeType":"Attribute","startLoc":106,"text":"artist_kws"},{"attributeType":"function | function | function","col":4,"comment":"null","endLoc":215,"id":182,"name":"maketrans","nodeType":"Attribute","startLoc":215,"text":"maketrans"},{"col":0,"comment":"\n Return a list of unique data values using seaborn's ordering rules.\n\n Parameters\n ----------\n vector : Series\n Vector of \"categorical\" values\n order : list\n Desired order of category levels to override the order determined\n from the `data` object.\n\n Returns\n -------\n order : list\n Ordered list of category levels not including null values.\n\n ","endLoc":153,"header":"def categorical_order(vector: Series, order: list | None = None) -> list","id":183,"name":"categorical_order","nodeType":"Function","startLoc":125,"text":"def categorical_order(vector: Series, order: list | None = None) -> list:\n \"\"\"\n Return a list of unique data values using seaborn's ordering rules.\n\n Parameters\n ----------\n vector : Series\n Vector of \"categorical\" values\n order : list\n Desired order of category levels to override the order determined\n from the `data` object.\n\n Returns\n -------\n order : list\n Ordered list of category levels not including null values.\n\n \"\"\"\n if order is not None:\n return order\n\n if vector.dtype.name == \"category\":\n order = list(vector.cat.categories)\n else:\n order = list(filter(pd.notnull, vector.unique()))\n if variable_type(pd.Series(order)) == \"numeric\":\n order.sort()\n\n return order"},{"attributeType":"null","col":0,"comment":"null","endLoc":96,"id":184,"name":"MappableString","nodeType":"Attribute","startLoc":96,"text":"MappableString"},{"col":0,"comment":"\n Obtain a default, specified, or mapped value for a color feature.\n\n This method exists separately to support the relationship between a\n color and its corresponding alpha. We want to respect alpha values that\n are passed in specified (or mapped) color values but also make use of a\n separate `alpha` variable, which can be mapped. This approach may also\n be extended to support mapping of specific color channels (i.e.\n luminance, chroma) in the future.\n\n Parameters\n ----------\n mark :\n Mark with the color property.\n data :\n Container with data values for features that will be semantically mapped.\n prefix :\n Support \"color\", \"fillcolor\", etc.\n\n ","endLoc":287,"header":"def resolve_color(\n mark: Mark,\n data: DataFrame | dict,\n prefix: str = \"\",\n scales: dict[str, Scale] | None = None,\n) -> RGBATuple | ndarray","id":185,"name":"resolve_color","nodeType":"Function","startLoc":234,"text":"def resolve_color(\n mark: Mark,\n data: DataFrame | dict,\n prefix: str = \"\",\n scales: dict[str, Scale] | None = None,\n) -> RGBATuple | ndarray:\n \"\"\"\n Obtain a default, specified, or mapped value for a color feature.\n\n This method exists separately to support the relationship between a\n color and its corresponding alpha. We want to respect alpha values that\n are passed in specified (or mapped) color values but also make use of a\n separate `alpha` variable, which can be mapped. This approach may also\n be extended to support mapping of specific color channels (i.e.\n luminance, chroma) in the future.\n\n Parameters\n ----------\n mark :\n Mark with the color property.\n data :\n Container with data values for features that will be semantically mapped.\n prefix :\n Support \"color\", \"fillcolor\", etc.\n\n \"\"\"\n color = mark._resolve(data, f\"{prefix}color\", scales)\n\n if f\"{prefix}alpha\" in mark._mappable_props:\n alpha = mark._resolve(data, f\"{prefix}alpha\", scales)\n else:\n alpha = mark._resolve(data, \"alpha\", scales)\n\n def visible(x, axis=None):\n \"\"\"Detect \"invisible\" colors to set alpha appropriately.\"\"\"\n # TODO First clause only needed to handle non-rgba arrays,\n # which we are trying to handle upstream\n return np.array(x).dtype.kind != \"f\" or np.isfinite(x).all(axis)\n\n # Second check here catches vectors of strings with identity scale\n # It could probably be handled better upstream. This is a tricky problem\n if np.ndim(color) < 2 and all(isinstance(x, float) for x in color):\n if len(color) == 4:\n return mpl.colors.to_rgba(color)\n alpha = alpha if visible(color) else np.nan\n return mpl.colors.to_rgba(color, alpha)\n else:\n if np.ndim(color) == 2 and color.shape[1] == 4:\n return mpl.colors.to_rgba_array(color)\n alpha = np.where(visible(color, axis=1), alpha, np.nan)\n return mpl.colors.to_rgba_array(color, alpha)\n\n # TODO should we be implementing fill here too?\n # (i.e. set fillalpha to 0 when fill=False)"},{"className":"Iterable","col":0,"comment":"null","endLoc":423,"id":186,"nodeType":"Class","startLoc":420,"text":"@runtime_checkable\nclass Iterable(Protocol[_T_co]):\n @abstractmethod\n def __iter__(self) -> Iterator[_T_co]: ..."},{"attributeType":"bool | function","col":8,"comment":"null","endLoc":60,"id":187,"name":"_grouping","nodeType":"Attribute","startLoc":60,"text":"self._grouping"},{"col":4,"comment":"null","endLoc":423,"header":"@abstractmethod\n def __iter__(self) -> Iterator[_T_co]","id":188,"name":"__iter__","nodeType":"Function","startLoc":422,"text":"@abstractmethod\n def __iter__(self) -> Iterator[_T_co]: ..."},{"className":"Mapping","col":0,"comment":"null","endLoc":691,"id":190,"nodeType":"Class","startLoc":677,"text":"class Mapping(Collection[_KT], Generic[_KT, _VT_co]):\n # TODO: We wish the key type could also be covariant, but that doesn't work,\n # see discussion in https://github.com/python/typing/pull/273.\n @abstractmethod\n def __getitem__(self, key: _KT, /) -> _VT_co: ...\n # Mixin methods\n @overload\n def get(self, key: _KT, /) -> _VT_co | None: ...\n @overload\n def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T: ...\n def items(self) -> ItemsView[_KT, _VT_co]: ...\n def keys(self) -> KeysView[_KT]: ...\n def values(self) -> ValuesView[_VT_co]: ...\n def __contains__(self, key: object, /) -> bool: ...\n def __eq__(self, other: object, /) -> bool: ..."},{"col":0,"comment":"null","endLoc":1470,"header":"def len(__obj: Sized) -> int","id":191,"name":"len","nodeType":"Function","startLoc":1470,"text":"def len(__obj: Sized) -> int: ..."},{"attributeType":"str | None | function","col":8,"comment":"null","endLoc":58,"id":193,"name":"_depend","nodeType":"Attribute","startLoc":58,"text":"self._depend"},{"col":4,"comment":"Initialize the property with the name of the corresponding plot variable.","endLoc":60,"header":"def __init__(self, variable: str | None = None)","id":194,"name":"__init__","nodeType":"Function","startLoc":56,"text":"def __init__(self, variable: str | None = None):\n \"\"\"Initialize the property with the name of the corresponding plot variable.\"\"\"\n if not variable:\n variable = self.__class__.__name__.lower()\n self.variable = variable"},{"col":4,"comment":"null","endLoc":681,"header":"@abstractmethod\n def __getitem__(self, key: _KT, /) -> _VT_co","id":195,"name":"__getitem__","nodeType":"Function","startLoc":680,"text":"@abstractmethod\n def __getitem__(self, key: _KT, /) -> _VT_co: ..."},{"col":0,"comment":"null","endLoc":309,"header":"def document_properties(mark)","id":196,"name":"document_properties","nodeType":"Function","startLoc":290,"text":"def document_properties(mark):\n\n properties = [f.name for f in fields(mark) if isinstance(f.default, Mappable)]\n text = [\n \"\",\n \" This mark defines the following properties:\",\n textwrap.fill(\n \", \".join([f\"|{p}|\" for p in properties]),\n width=78, initial_indent=\" \" * 8, subsequent_indent=\" \" * 8,\n ),\n ]\n\n docstring_lines = mark.__doc__.split(\"\\n\")\n new_docstring = \"\\n\".join([\n *docstring_lines[:2],\n *text,\n *docstring_lines[2:],\n ])\n mark.__doc__ = new_docstring\n return mark"},{"col":4,"comment":"null","endLoc":684,"header":"@overload\n def get(self, key: _KT, /) -> _VT_co | None","id":197,"name":"get","nodeType":"Function","startLoc":683,"text":"@overload\n def get(self, key: _KT, /) -> _VT_co | None: ..."},{"col":4,"comment":"null","endLoc":686,"header":"@overload\n def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T","id":198,"name":"get","nodeType":"Function","startLoc":685,"text":"@overload\n def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T: ..."},{"col":4,"comment":"null","endLoc":687,"header":"def items(self) -> ItemsView[_KT, _VT_co]","id":199,"name":"items","nodeType":"Function","startLoc":687,"text":"def items(self) -> ItemsView[_KT, _VT_co]: ..."},{"col":4,"comment":"null","endLoc":688,"header":"def keys(self) -> KeysView[_KT]","id":200,"name":"keys","nodeType":"Function","startLoc":688,"text":"def keys(self) -> KeysView[_KT]: ..."},{"col":4,"comment":"null","endLoc":689,"header":"def values(self) -> ValuesView[_VT_co]","id":201,"name":"values","nodeType":"Function","startLoc":689,"text":"def values(self) -> ValuesView[_VT_co]: ..."},{"col":4,"comment":"null","endLoc":690,"header":"def __contains__(self, key: object, /) -> bool","id":202,"name":"__contains__","nodeType":"Function","startLoc":690,"text":"def __contains__(self, key: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":691,"header":"def __eq__(self, other: object, /) -> bool","id":203,"name":"__eq__","nodeType":"Function","startLoc":691,"text":"def __eq__(self, other: object, /) -> bool: ..."},{"attributeType":"bool","col":8,"comment":"null","endLoc":59,"id":204,"name":"_auto","nodeType":"Attribute","startLoc":59,"text":"self._auto"},{"attributeType":"None","col":8,"comment":"null","endLoc":56,"id":205,"name":"_val","nodeType":"Attribute","startLoc":56,"text":"self._val"},{"className":"Number","col":0,"comment":"null","endLoc":63,"id":206,"nodeType":"Class","startLoc":61,"text":"class Number(metaclass=ABCMeta):\n @abstractmethod\n def __hash__(self) -> int: ..."},{"className":"Text","col":0,"comment":"\n A textual mark to annotate or represent data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Text.rst\n\n ","endLoc":76,"id":207,"nodeType":"Class","startLoc":21,"text":"@document_properties\n@dataclass\nclass Text(Mark):\n \"\"\"\n A textual mark to annotate or represent data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Text.rst\n\n \"\"\"\n text: MappableString = Mappable(\"\")\n color: MappableColor = Mappable(\"k\")\n alpha: MappableFloat = Mappable(1)\n fontsize: MappableFloat = Mappable(rc=\"font.size\")\n halign: MappableString = Mappable(\"center\")\n valign: MappableString = Mappable(\"center_baseline\")\n offset: MappableFloat = Mappable(4)\n\n def _plot(self, split_gen, scales, orient):\n\n ax_data = defaultdict(list)\n\n for keys, data, ax in split_gen():\n\n vals = resolve_properties(self, keys, scales)\n color = resolve_color(self, keys, \"\", scales)\n\n halign = vals[\"halign\"]\n valign = vals[\"valign\"]\n fontsize = vals[\"fontsize\"]\n offset = vals[\"offset\"] / 72\n\n offset_trans = ScaledTranslation(\n {\"right\": -offset, \"left\": +offset}.get(halign, 0),\n {\"top\": -offset, \"bottom\": +offset, \"baseline\": +offset}.get(valign, 0),\n ax.figure.dpi_scale_trans,\n )\n\n for row in data.to_dict(\"records\"):\n artist = mpl.text.Text(\n x=row[\"x\"],\n y=row[\"y\"],\n text=str(row.get(\"text\", vals[\"text\"])),\n color=color,\n fontsize=fontsize,\n horizontalalignment=halign,\n verticalalignment=valign,\n transform=ax.transData + offset_trans,\n **self.artist_kws,\n )\n ax.add_artist(artist)\n ax_data[ax].append([row[\"x\"], row[\"y\"]])\n\n for ax, ax_vals in ax_data.items():\n ax.update_datalim(np.array(ax_vals))"},{"col":4,"comment":"null","endLoc":76,"header":"def _plot(self, split_gen, scales, orient)","id":208,"name":"_plot","nodeType":"Function","startLoc":40,"text":"def _plot(self, split_gen, scales, orient):\n\n ax_data = defaultdict(list)\n\n for keys, data, ax in split_gen():\n\n vals = resolve_properties(self, keys, scales)\n color = resolve_color(self, keys, \"\", scales)\n\n halign = vals[\"halign\"]\n valign = vals[\"valign\"]\n fontsize = vals[\"fontsize\"]\n offset = vals[\"offset\"] / 72\n\n offset_trans = ScaledTranslation(\n {\"right\": -offset, \"left\": +offset}.get(halign, 0),\n {\"top\": -offset, \"bottom\": +offset, \"baseline\": +offset}.get(valign, 0),\n ax.figure.dpi_scale_trans,\n )\n\n for row in data.to_dict(\"records\"):\n artist = mpl.text.Text(\n x=row[\"x\"],\n y=row[\"y\"],\n text=str(row.get(\"text\", vals[\"text\"])),\n color=color,\n fontsize=fontsize,\n horizontalalignment=halign,\n verticalalignment=valign,\n transform=ax.transData + offset_trans,\n **self.artist_kws,\n )\n ax.add_artist(artist)\n ax_data[ax].append([row[\"x\"], row[\"y\"]])\n\n for ax, ax_vals in ax_data.items():\n ax.update_datalim(np.array(ax_vals))"},{"col":4,"comment":"null","endLoc":63,"header":"@abstractmethod\n def __hash__(self) -> int","id":209,"name":"__hash__","nodeType":"Function","startLoc":62,"text":"@abstractmethod\n def __hash__(self) -> int: ..."},{"className":"datetime","col":0,"comment":"null","endLoc":327,"id":210,"nodeType":"Class","startLoc":229,"text":"class datetime(date):\n min: ClassVar[datetime]\n max: ClassVar[datetime]\n def __new__(\n cls,\n year: SupportsIndex,\n month: SupportsIndex,\n day: SupportsIndex,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ...\n @property\n def hour(self) -> int: ...\n @property\n def minute(self) -> int: ...\n @property\n def second(self) -> int: ...\n @property\n def microsecond(self) -> int: ...\n @property\n def tzinfo(self) -> _TzInfo | None: ...\n @property\n def fold(self) -> int: ...\n # On <3.12, the name of the first parameter in the pure-Python implementation\n # didn't match the name in the C implementation,\n # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n if sys.version_info >= (3, 12):\n @classmethod\n def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self: ...\n else:\n @classmethod\n def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = ...) -> Self: ...\n\n @classmethod\n @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)\")\n def utcfromtimestamp(cls, t: float, /) -> Self: ...\n @classmethod\n def now(cls, tz: _TzInfo | None = None) -> Self: ...\n @classmethod\n @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)\")\n def utcnow(cls) -> Self: ...\n @classmethod\n def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ...\n def timestamp(self) -> float: ...\n def utctimetuple(self) -> struct_time: ...\n def date(self) -> _Date: ...\n def time(self) -> _Time: ...\n def timetz(self) -> _Time: ...\n if sys.version_info >= (3, 13):\n def __replace__(\n self,\n /,\n *,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n fold: int = ...,\n ) -> Self: ...\n\n def replace(\n self,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ...\n def astimezone(self, tz: _TzInfo | None = ...) -> Self: ...\n def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ...\n @classmethod\n def strptime(cls, date_string: str, format: str, /) -> Self: ...\n def utcoffset(self) -> timedelta | None: ...\n def tzname(self) -> str | None: ...\n def dst(self) -> timedelta | None: ...\n def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override]\n def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override]\n def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override]\n def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override]\n def __eq__(self, value: object, /) -> bool: ...\n def __hash__(self) -> int: ...\n @overload # type: ignore[override]\n def __sub__(self, value: Self, /) -> timedelta: ...\n @overload\n def __sub__(self, value: timedelta, /) -> Self: ..."},{"className":"date","col":0,"comment":"null","endLoc":105,"id":213,"nodeType":"Class","startLoc":48,"text":"class date:\n min: ClassVar[date]\n max: ClassVar[date]\n resolution: ClassVar[timedelta]\n def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ...\n @classmethod\n def fromtimestamp(cls, timestamp: float, /) -> Self: ...\n @classmethod\n def today(cls) -> Self: ...\n @classmethod\n def fromordinal(cls, n: int, /) -> Self: ...\n @classmethod\n def fromisoformat(cls, date_string: str, /) -> Self: ...\n @classmethod\n def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ...\n @property\n def year(self) -> int: ...\n @property\n def month(self) -> int: ...\n @property\n def day(self) -> int: ...\n def ctime(self) -> str: ...\n # On <3.12, the name of the parameter in the pure-Python implementation\n # didn't match the name in the C implementation,\n # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n if sys.version_info >= (3, 12):\n def strftime(self, format: str) -> str: ...\n else:\n def strftime(self, format: str, /) -> str: ...\n\n def __format__(self, fmt: str, /) -> str: ...\n def isoformat(self) -> str: ...\n def timetuple(self) -> struct_time: ...\n def toordinal(self) -> int: ...\n if sys.version_info >= (3, 13):\n def __replace__(self, /, *, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ...\n\n def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ...\n def __le__(self, value: date, /) -> bool: ...\n def __lt__(self, value: date, /) -> bool: ...\n def __ge__(self, value: date, /) -> bool: ...\n def __gt__(self, value: date, /) -> bool: ...\n def __eq__(self, value: object, /) -> bool: ...\n def __add__(self, value: timedelta, /) -> Self: ...\n def __radd__(self, value: timedelta, /) -> Self: ...\n @overload\n def __sub__(self, value: datetime, /) -> NoReturn: ...\n @overload\n def __sub__(self, value: Self, /) -> timedelta: ...\n @overload\n def __sub__(self, value: timedelta, /) -> Self: ...\n def __hash__(self) -> int: ...\n def weekday(self) -> int: ...\n def isoweekday(self) -> int: ...\n if sys.version_info >= (3, 9):\n def isocalendar(self) -> _IsoCalendarDate: ...\n else:\n def isocalendar(self) -> tuple[int, int, int]: ..."},{"col":4,"comment":"null","endLoc":52,"header":"def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self","id":214,"name":"__new__","nodeType":"Function","startLoc":52,"text":"def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ..."},{"col":4,"comment":"null","endLoc":54,"header":"@classmethod\n def fromtimestamp(cls, timestamp: float, /) -> Self","id":215,"name":"fromtimestamp","nodeType":"Function","startLoc":53,"text":"@classmethod\n def fromtimestamp(cls, timestamp: float, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":56,"header":"@classmethod\n def today(cls) -> Self","id":216,"name":"today","nodeType":"Function","startLoc":55,"text":"@classmethod\n def today(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":58,"header":"@classmethod\n def fromordinal(cls, n: int, /) -> Self","id":217,"name":"fromordinal","nodeType":"Function","startLoc":57,"text":"@classmethod\n def fromordinal(cls, n: int, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":60,"header":"@classmethod\n def fromisoformat(cls, date_string: str, /) -> Self","id":218,"name":"fromisoformat","nodeType":"Function","startLoc":59,"text":"@classmethod\n def fromisoformat(cls, date_string: str, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":62,"header":"@classmethod\n def fromisocalendar(cls, year: int, week: int, day: int) -> Self","id":219,"name":"fromisocalendar","nodeType":"Function","startLoc":61,"text":"@classmethod\n def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ..."},{"col":4,"comment":"null","endLoc":64,"header":"@property\n def year(self) -> int","id":220,"name":"year","nodeType":"Function","startLoc":63,"text":"@property\n def year(self) -> int: ..."},{"col":4,"comment":"null","endLoc":66,"header":"@property\n def month(self) -> int","id":221,"name":"month","nodeType":"Function","startLoc":65,"text":"@property\n def month(self) -> int: ..."},{"col":4,"comment":"null","endLoc":68,"header":"@property\n def day(self) -> int","id":223,"name":"day","nodeType":"Function","startLoc":67,"text":"@property\n def day(self) -> int: ..."},{"col":4,"comment":"null","endLoc":69,"header":"def ctime(self) -> str","id":224,"name":"ctime","nodeType":"Function","startLoc":69,"text":"def ctime(self) -> str: ..."},{"col":8,"comment":"null","endLoc":76,"header":"def strftime(self, format: str, /) -> str","id":225,"name":"strftime","nodeType":"Function","startLoc":76,"text":"def strftime(self, format: str, /) -> str: ..."},{"col":4,"comment":"null","endLoc":78,"header":"def __format__(self, fmt: str, /) -> str","id":226,"name":"__format__","nodeType":"Function","startLoc":78,"text":"def __format__(self, fmt: str, /) -> str: ..."},{"col":4,"comment":"null","endLoc":79,"header":"def isoformat(self) -> str","id":227,"name":"isoformat","nodeType":"Function","startLoc":79,"text":"def isoformat(self) -> str: ..."},{"col":4,"comment":"null","endLoc":80,"header":"def timetuple(self) -> struct_time","id":228,"name":"timetuple","nodeType":"Function","startLoc":80,"text":"def timetuple(self) -> struct_time: ..."},{"col":4,"comment":"null","endLoc":81,"header":"def toordinal(self) -> int","id":229,"name":"toordinal","nodeType":"Function","startLoc":81,"text":"def toordinal(self) -> int: ..."},{"col":4,"comment":"null","endLoc":85,"header":"def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self","id":230,"name":"replace","nodeType":"Function","startLoc":85,"text":"def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":86,"header":"def __le__(self, value: date, /) -> bool","id":231,"name":"__le__","nodeType":"Function","startLoc":86,"text":"def __le__(self, value: date, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":87,"header":"def __lt__(self, value: date, /) -> bool","id":232,"name":"__lt__","nodeType":"Function","startLoc":87,"text":"def __lt__(self, value: date, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":88,"header":"def __ge__(self, value: date, /) -> bool","id":233,"name":"__ge__","nodeType":"Function","startLoc":88,"text":"def __ge__(self, value: date, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":89,"header":"def __gt__(self, value: date, /) -> bool","id":234,"name":"__gt__","nodeType":"Function","startLoc":89,"text":"def __gt__(self, value: date, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":90,"header":"def __eq__(self, value: object, /) -> bool","id":235,"name":"__eq__","nodeType":"Function","startLoc":90,"text":"def __eq__(self, value: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":91,"header":"def __add__(self, value: timedelta, /) -> Self","id":236,"name":"__add__","nodeType":"Function","startLoc":91,"text":"def __add__(self, value: timedelta, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":92,"header":"def __radd__(self, value: timedelta, /) -> Self","id":237,"name":"__radd__","nodeType":"Function","startLoc":92,"text":"def __radd__(self, value: timedelta, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":94,"header":"@overload\n def __sub__(self, value: datetime, /) -> NoReturn","id":238,"name":"__sub__","nodeType":"Function","startLoc":93,"text":"@overload\n def __sub__(self, value: datetime, /) -> NoReturn: ..."},{"col":4,"comment":"null","endLoc":96,"header":"@overload\n def __sub__(self, value: Self, /) -> timedelta","id":239,"name":"__sub__","nodeType":"Function","startLoc":95,"text":"@overload\n def __sub__(self, value: Self, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":98,"header":"@overload\n def __sub__(self, value: timedelta, /) -> Self","id":240,"name":"__sub__","nodeType":"Function","startLoc":97,"text":"@overload\n def __sub__(self, value: timedelta, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":99,"header":"def __hash__(self) -> int","id":241,"name":"__hash__","nodeType":"Function","startLoc":99,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":100,"header":"def weekday(self) -> int","id":242,"name":"weekday","nodeType":"Function","startLoc":100,"text":"def weekday(self) -> int: ..."},{"col":4,"comment":"null","endLoc":101,"header":"def isoweekday(self) -> int","id":243,"name":"isoweekday","nodeType":"Function","startLoc":101,"text":"def isoweekday(self) -> int: ..."},{"col":8,"comment":"null","endLoc":103,"header":"def isocalendar(self) -> _IsoCalendarDate","id":244,"name":"isocalendar","nodeType":"Function","startLoc":103,"text":"def isocalendar(self) -> _IsoCalendarDate: ..."},{"attributeType":"date","col":4,"comment":"null","endLoc":49,"id":245,"name":"min","nodeType":"Attribute","startLoc":49,"text":"min"},{"attributeType":"date","col":4,"comment":"null","endLoc":50,"id":246,"name":"max","nodeType":"Attribute","startLoc":50,"text":"max"},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":51,"id":247,"name":"resolution","nodeType":"Attribute","startLoc":51,"text":"resolution"},{"col":4,"comment":"null","endLoc":1010,"header":"@overload\n def __init__(self) -> None","id":248,"name":"__init__","nodeType":"Function","startLoc":1009,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":1012,"header":"@overload\n def __init__(self, __iterable: Iterable[_T]) -> None","id":249,"name":"__init__","nodeType":"Function","startLoc":1011,"text":"@overload\n def __init__(self, __iterable: Iterable[_T]) -> None: ..."},{"col":4,"comment":"null","endLoc":244,"header":"def __new__(\n cls,\n year: SupportsIndex,\n month: SupportsIndex,\n day: SupportsIndex,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self","id":250,"name":"__new__","nodeType":"Function","startLoc":232,"text":"def __new__(\n cls,\n year: SupportsIndex,\n month: SupportsIndex,\n day: SupportsIndex,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ..."},{"col":4,"comment":"null","endLoc":246,"header":"@property\n def hour(self) -> int","id":251,"name":"hour","nodeType":"Function","startLoc":245,"text":"@property\n def hour(self) -> int: ..."},{"col":4,"comment":"null","endLoc":248,"header":"@property\n def minute(self) -> int","id":252,"name":"minute","nodeType":"Function","startLoc":247,"text":"@property\n def minute(self) -> int: ..."},{"col":4,"comment":"null","endLoc":250,"header":"@property\n def second(self) -> int","id":253,"name":"second","nodeType":"Function","startLoc":249,"text":"@property\n def second(self) -> int: ..."},{"col":4,"comment":"null","endLoc":252,"header":"@property\n def microsecond(self) -> int","id":254,"name":"microsecond","nodeType":"Function","startLoc":251,"text":"@property\n def microsecond(self) -> int: ..."},{"col":4,"comment":"null","endLoc":254,"header":"@property\n def tzinfo(self) -> _TzInfo | None","id":255,"name":"tzinfo","nodeType":"Function","startLoc":253,"text":"@property\n def tzinfo(self) -> _TzInfo | None: ..."},{"col":4,"comment":"null","endLoc":256,"header":"@property\n def fold(self) -> int","id":256,"name":"fold","nodeType":"Function","startLoc":255,"text":"@property\n def fold(self) -> int: ..."},{"col":8,"comment":"null","endLoc":265,"header":"@classmethod\n def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = ...) -> Self","id":257,"name":"fromtimestamp","nodeType":"Function","startLoc":264,"text":"@classmethod\n def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":269,"header":"@classmethod\n @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)\")\n def utcfromtimestamp(cls, t","id":258,"name":"utcfromtimestamp","nodeType":"Function","startLoc":267,"text":"@classmethod\n @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)\")\n def utcfromtimestamp(cls, t: float, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":271,"header":"@classmethod\n def now(cls, tz: _TzInfo | None = None) -> Self","id":261,"name":"now","nodeType":"Function","startLoc":270,"text":"@classmethod\n def now(cls, tz: _TzInfo | None = None) -> Self: ..."},{"col":4,"comment":"null","endLoc":274,"header":"@classmethod\n @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)\")\n def utcnow(cls) -> Self","id":262,"name":"utcnow","nodeType":"Function","startLoc":272,"text":"@classmethod\n @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)\")\n def utcnow(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":276,"header":"@classmethod\n def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self","id":263,"name":"combine","nodeType":"Function","startLoc":275,"text":"@classmethod\n def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":277,"header":"def timestamp(self) -> float","id":264,"name":"timestamp","nodeType":"Function","startLoc":277,"text":"def timestamp(self) -> float: ..."},{"col":4,"comment":"null","endLoc":278,"header":"def utctimetuple(self) -> struct_time","id":265,"name":"utctimetuple","nodeType":"Function","startLoc":278,"text":"def utctimetuple(self) -> struct_time: ..."},{"col":4,"comment":"null","endLoc":279,"header":"def date(self) -> _Date","id":266,"name":"date","nodeType":"Function","startLoc":279,"text":"def date(self) -> _Date: ..."},{"col":4,"comment":"null","endLoc":280,"header":"def time(self) -> _Time","id":267,"name":"time","nodeType":"Function","startLoc":280,"text":"def time(self) -> _Time: ..."},{"col":4,"comment":"null","endLoc":281,"header":"def timetz(self) -> _Time","id":268,"name":"timetz","nodeType":"Function","startLoc":281,"text":"def timetz(self) -> _Time: ..."},{"col":4,"comment":"null","endLoc":310,"header":"def replace(\n self,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self","id":269,"name":"replace","nodeType":"Function","startLoc":298,"text":"def replace(\n self,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ..."},{"col":4,"comment":"null","endLoc":311,"header":"def astimezone(self, tz: _TzInfo | None = ...) -> Self","id":270,"name":"astimezone","nodeType":"Function","startLoc":311,"text":"def astimezone(self, tz: _TzInfo | None = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":312,"header":"def isoformat(self, sep: str = ..., timespec: str = ...) -> str","id":271,"name":"isoformat","nodeType":"Function","startLoc":312,"text":"def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ..."},{"col":4,"comment":"null","endLoc":314,"header":"@classmethod\n def strptime(cls, date_string: str, format: str, /) -> Self","id":272,"name":"strptime","nodeType":"Function","startLoc":313,"text":"@classmethod\n def strptime(cls, date_string: str, format: str, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":315,"header":"def utcoffset(self) -> timedelta | None","id":273,"name":"utcoffset","nodeType":"Function","startLoc":315,"text":"def utcoffset(self) -> timedelta | None: ..."},{"col":4,"comment":"null","endLoc":316,"header":"def tzname(self) -> str | None","id":274,"name":"tzname","nodeType":"Function","startLoc":316,"text":"def tzname(self) -> str | None: ..."},{"col":4,"comment":"null","endLoc":317,"header":"def dst(self) -> timedelta | None","id":275,"name":"dst","nodeType":"Function","startLoc":317,"text":"def dst(self) -> timedelta | None: ..."},{"col":4,"comment":"null","endLoc":318,"header":"def __le__(self, value: datetime, /) -> bool","id":276,"name":"__le__","nodeType":"Function","startLoc":318,"text":"def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":319,"header":"def __lt__(self, value: datetime, /) -> bool","id":277,"name":"__lt__","nodeType":"Function","startLoc":319,"text":"def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":320,"header":"def __ge__(self, value: datetime, /) -> bool","id":278,"name":"__ge__","nodeType":"Function","startLoc":320,"text":"def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":321,"header":"def __gt__(self, value: datetime, /) -> bool","id":279,"name":"__gt__","nodeType":"Function","startLoc":321,"text":"def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":322,"header":"def __eq__(self, value: object, /) -> bool","id":280,"name":"__eq__","nodeType":"Function","startLoc":322,"text":"def __eq__(self, value: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":323,"header":"def __hash__(self) -> int","id":281,"name":"__hash__","nodeType":"Function","startLoc":323,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":325,"header":"@overload # type: ignore[override]\n def __sub__(self, value: Self, /) -> timedelta","id":282,"name":"__sub__","nodeType":"Function","startLoc":324,"text":"@overload # type: ignore[override]\n def __sub__(self, value: Self, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":327,"header":"@overload\n def __sub__(self, value: timedelta, /) -> Self","id":283,"name":"__sub__","nodeType":"Function","startLoc":326,"text":"@overload\n def __sub__(self, value: timedelta, /) -> Self: ..."},{"attributeType":"datetime","col":4,"comment":"null","endLoc":230,"id":284,"name":"min","nodeType":"Attribute","startLoc":230,"text":"min"},{"className":"Version","col":0,"comment":"null","endLoc":347,"id":285,"nodeType":"Class","startLoc":214,"text":"class Version(_BaseVersion):\n\n _regex = re.compile(r\"^\\s*\" + VERSION_PATTERN + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n def __init__(self, version: str) -> None:\n\n # Validate the version and parse it into pieces\n match = self._regex.search(version)\n if not match:\n raise InvalidVersion(f\"Invalid version: '{version}'\")\n\n # Store the parsed out pieces of the version\n self._version = _Version(\n epoch=int(match.group(\"epoch\")) if match.group(\"epoch\") else 0,\n release=tuple(int(i) for i in match.group(\"release\").split(\".\")),\n pre=_parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\")),\n post=_parse_letter_version(\n match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n ),\n dev=_parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\")),\n local=_parse_local_version(match.group(\"local\")),\n )\n\n # Generate a key which will be used for sorting\n self._key = _cmpkey(\n self._version.epoch,\n self._version.release,\n self._version.pre,\n self._version.post,\n self._version.dev,\n self._version.local,\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __str__(self) -> str:\n parts = []\n\n # Epoch\n if self.epoch != 0:\n parts.append(f\"{self.epoch}!\")\n\n # Release segment\n parts.append(\".\".join(str(x) for x in self.release))\n\n # Pre-release\n if self.pre is not None:\n parts.append(\"\".join(str(x) for x in self.pre))\n\n # Post-release\n if self.post is not None:\n parts.append(f\".post{self.post}\")\n\n # Development release\n if self.dev is not None:\n parts.append(f\".dev{self.dev}\")\n\n # Local version segment\n if self.local is not None:\n parts.append(f\"+{self.local}\")\n\n return \"\".join(parts)\n\n @property\n def epoch(self) -> int:\n _epoch: int = self._version.epoch\n return _epoch\n\n @property\n def release(self) -> Tuple[int, ...]:\n _release: Tuple[int, ...] = self._version.release\n return _release\n\n @property\n def pre(self) -> Optional[Tuple[str, int]]:\n _pre: Optional[Tuple[str, int]] = self._version.pre\n return _pre\n\n @property\n def post(self) -> Optional[int]:\n return self._version.post[1] if self._version.post else None\n\n @property\n def dev(self) -> Optional[int]:\n return self._version.dev[1] if self._version.dev else None\n\n @property\n def local(self) -> Optional[str]:\n if self._version.local:\n return \".\".join(str(x) for x in self._version.local)\n else:\n return None\n\n @property\n def public(self) -> str:\n return str(self).split(\"+\", 1)[0]\n\n @property\n def base_version(self) -> str:\n parts = []\n\n # Epoch\n if self.epoch != 0:\n parts.append(f\"{self.epoch}!\")\n\n # Release segment\n parts.append(\".\".join(str(x) for x in self.release))\n\n return \"\".join(parts)\n\n @property\n def is_prerelease(self) -> bool:\n return self.dev is not None or self.pre is not None\n\n @property\n def is_postrelease(self) -> bool:\n return self.post is not None\n\n @property\n def is_devrelease(self) -> bool:\n return self.dev is not None\n\n @property\n def major(self) -> int:\n return self.release[0] if len(self.release) >= 1 else 0\n\n @property\n def minor(self) -> int:\n return self.release[1] if len(self.release) >= 2 else 0\n\n @property\n def micro(self) -> int:\n return self.release[2] if len(self.release) >= 3 else 0"},{"attributeType":"datetime","col":4,"comment":"null","endLoc":231,"id":286,"name":"max","nodeType":"Attribute","startLoc":231,"text":"max"},{"className":"_BaseVersion","col":0,"comment":"null","endLoc":177,"id":287,"nodeType":"Class","startLoc":134,"text":"class _BaseVersion:\n _key: Union[CmpKey, LegacyCmpKey]\n\n def __hash__(self) -> int:\n return hash(self._key)\n\n # Please keep the duplicated `isinstance` check\n # in the six comparisons hereunder\n # unless you find a way to avoid adding overhead function calls.\n def __lt__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key < other._key\n\n def __le__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key <= other._key\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key == other._key\n\n def __ge__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key >= other._key\n\n def __gt__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key > other._key\n\n def __ne__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key != other._key"},{"col":4,"comment":"null","endLoc":138,"header":"def __hash__(self) -> int","id":288,"name":"__hash__","nodeType":"Function","startLoc":137,"text":"def __hash__(self) -> int:\n return hash(self._key)"},{"col":4,"comment":"null","endLoc":147,"header":"def __lt__(self, other: \"_BaseVersion\") -> bool","id":290,"name":"__lt__","nodeType":"Function","startLoc":143,"text":"def __lt__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key < other._key"},{"col":4,"comment":"null","endLoc":153,"header":"def __le__(self, other: \"_BaseVersion\") -> bool","id":291,"name":"__le__","nodeType":"Function","startLoc":149,"text":"def __le__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key <= other._key"},{"col":4,"comment":"null","endLoc":159,"header":"def __eq__(self, other: object) -> bool","id":292,"name":"__eq__","nodeType":"Function","startLoc":155,"text":"def __eq__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key == other._key"},{"col":4,"comment":"null","endLoc":165,"header":"def __ge__(self, other: \"_BaseVersion\") -> bool","id":293,"name":"__ge__","nodeType":"Function","startLoc":161,"text":"def __ge__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key >= other._key"},{"col":4,"comment":"null","endLoc":171,"header":"def __gt__(self, other: \"_BaseVersion\") -> bool","id":294,"name":"__gt__","nodeType":"Function","startLoc":167,"text":"def __gt__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key > other._key"},{"col":4,"comment":"null","endLoc":177,"header":"def __ne__(self, other: object) -> bool","id":295,"name":"__ne__","nodeType":"Function","startLoc":173,"text":"def __ne__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key != other._key"},{"col":0,"comment":"Make cls.map a classmethod with same signature as cls.__init__.","endLoc":16,"header":"def share_init_params_with_map(cls)","id":296,"name":"share_init_params_with_map","nodeType":"Function","startLoc":4,"text":"def share_init_params_with_map(cls):\n \"\"\"Make cls.map a classmethod with same signature as cls.__init__.\"\"\"\n map_sig = signature(cls.map)\n init_sig = signature(cls.__init__)\n\n new = [v for k, v in init_sig.parameters.items() if k != \"self\"]\n new.insert(0, map_sig.parameters[\"cls\"])\n cls.map.__signature__ = map_sig.replace(parameters=new)\n cls.map.__doc__ = cls.__init__.__doc__\n\n cls.map = classmethod(cls.map)\n\n return cls"},{"attributeType":"(int, (int, ...), InfinityType | NegativeInfinityType | (str, int), InfinityType | NegativeInfinityType | (str, int), InfinityType | NegativeInfinityType | (str, int), NegativeInfinityType | (InfinityType | NegativeInfinityType | int | str | (InfinityType | NegativeInfinityType | int | str, str) | (NegativeInfinityType, InfinityType | NegativeInfinityType | int | str), ...)) | (int, (str, ...))","col":4,"comment":"null","endLoc":135,"id":297,"name":"_key","nodeType":"Attribute","startLoc":135,"text":"_key"},{"col":4,"comment":"null","endLoc":123,"header":"def __call__(self, data: Series) -> ArrayLike","id":298,"name":"__call__","nodeType":"Function","startLoc":104,"text":"def __call__(self, data: Series) -> ArrayLike:\n\n trans_data: Series | NDArray | list\n\n # TODO sometimes we need to handle scalars (e.g. for Line)\n # but what is the best way to do that?\n scalar_data = np.isscalar(data)\n if scalar_data:\n trans_data = np.array([data])\n else:\n trans_data = data\n\n for func in self._pipeline:\n if func is not None:\n trans_data = func(trans_data)\n\n if scalar_data:\n return trans_data[0]\n else:\n return trans_data"},{"col":4,"comment":"null","endLoc":308,"header":"def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature","id":299,"name":"signature","nodeType":"Function","startLoc":308,"text":"def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature: ..."},{"attributeType":"bool","col":0,"comment":"null","endLoc":745,"id":300,"name":"TYPE_CHECKING","nodeType":"Attribute","startLoc":745,"text":"TYPE_CHECKING"},{"col":4,"comment":"null","endLoc":245,"header":"def __init__(self, version: str) -> None","id":301,"name":"__init__","nodeType":"Function","startLoc":218,"text":"def __init__(self, version: str) -> None:\n\n # Validate the version and parse it into pieces\n match = self._regex.search(version)\n if not match:\n raise InvalidVersion(f\"Invalid version: '{version}'\")\n\n # Store the parsed out pieces of the version\n self._version = _Version(\n epoch=int(match.group(\"epoch\")) if match.group(\"epoch\") else 0,\n release=tuple(int(i) for i in match.group(\"release\").split(\".\")),\n pre=_parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\")),\n post=_parse_letter_version(\n match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n ),\n dev=_parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\")),\n local=_parse_local_version(match.group(\"local\")),\n )\n\n # Generate a key which will be used for sorting\n self._key = _cmpkey(\n self._version.epoch,\n self._version.release,\n self._version.pre,\n self._version.post,\n self._version.dev,\n self._version.local,\n )"},{"className":"Scale","col":0,"comment":"Base class for objects that map data values to visual properties.","endLoc":134,"id":302,"nodeType":"Class","startLoc":53,"text":"class Scale:\n \"\"\"Base class for objects that map data values to visual properties.\"\"\"\n\n values: tuple | str | list | dict | None\n\n _priority: ClassVar[int]\n _pipeline: Pipeline\n _matplotlib_scale: ScaleBase\n _spacer: staticmethod\n _legend: tuple[list[str], list[Any]] | None\n\n def __post_init__(self):\n\n self._tick_params = None\n self._label_params = None\n self._legend = None\n\n def tick(self):\n raise NotImplementedError()\n\n def label(self):\n raise NotImplementedError()\n\n def _get_locators(self):\n raise NotImplementedError()\n\n def _get_formatter(self, locator: Locator | None = None):\n raise NotImplementedError()\n\n def _get_scale(self, name: str, forward: Callable, inverse: Callable):\n\n major_locator, minor_locator = self._get_locators(**self._tick_params)\n major_formatter = self._get_formatter(major_locator, **self._label_params)\n\n class InternalScale(mpl.scale.FuncScale):\n def set_default_locators_and_formatters(self, axis):\n axis.set_major_locator(major_locator)\n if minor_locator is not None:\n axis.set_minor_locator(minor_locator)\n axis.set_major_formatter(major_formatter)\n\n return InternalScale(name, (forward, inverse))\n\n def _spacing(self, x: Series) -> float:\n return self._spacer(x)\n\n def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n raise NotImplementedError()\n\n def __call__(self, data: Series) -> ArrayLike:\n\n trans_data: Series | NDArray | list\n\n # TODO sometimes we need to handle scalars (e.g. for Line)\n # but what is the best way to do that?\n scalar_data = np.isscalar(data)\n if scalar_data:\n trans_data = np.array([data])\n else:\n trans_data = data\n\n for func in self._pipeline:\n if func is not None:\n trans_data = func(trans_data)\n\n if scalar_data:\n return trans_data[0]\n else:\n return trans_data\n\n @staticmethod\n def _identity():\n\n class Identity(Scale):\n _pipeline = []\n _spacer = None\n _legend = None\n _matplotlib_scale = None\n\n return Identity()"},{"col":4,"comment":"null","endLoc":68,"header":"def __post_init__(self)","id":303,"name":"__post_init__","nodeType":"Function","startLoc":64,"text":"def __post_init__(self):\n\n self._tick_params = None\n self._label_params = None\n self._legend = None"},{"col":4,"comment":"null","endLoc":71,"header":"def tick(self)","id":304,"name":"tick","nodeType":"Function","startLoc":70,"text":"def tick(self):\n raise NotImplementedError()"},{"col":0,"comment":"\n Determine whether a vector contains numeric, categorical, or datetime data.\n\n This function differs from the pandas typing API in two ways:\n\n - Python sequences or object-typed PyData objects are considered numeric if\n all of their entries are numeric.\n - String or mixed-type data are considered categorical even if not\n explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.\n\n Parameters\n ----------\n vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence\n Input data to test.\n boolean_type : 'numeric' or 'categorical'\n Type to use for vectors containing only 0s and 1s (and NAs).\n\n Returns\n -------\n var_type : 'numeric', 'categorical', or 'datetime'\n Name identifying the type of data in the vector.\n ","endLoc":122,"header":"def variable_type(\n vector: Series,\n boolean_type: Literal[\"numeric\", \"categorical\"] = \"numeric\",\n) -> VarType","id":308,"name":"variable_type","nodeType":"Function","startLoc":38,"text":"def variable_type(\n vector: Series,\n boolean_type: Literal[\"numeric\", \"categorical\"] = \"numeric\",\n) -> VarType:\n \"\"\"\n Determine whether a vector contains numeric, categorical, or datetime data.\n\n This function differs from the pandas typing API in two ways:\n\n - Python sequences or object-typed PyData objects are considered numeric if\n all of their entries are numeric.\n - String or mixed-type data are considered categorical even if not\n explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.\n\n Parameters\n ----------\n vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence\n Input data to test.\n boolean_type : 'numeric' or 'categorical'\n Type to use for vectors containing only 0s and 1s (and NAs).\n\n Returns\n -------\n var_type : 'numeric', 'categorical', or 'datetime'\n Name identifying the type of data in the vector.\n \"\"\"\n\n # If a categorical dtype is set, infer categorical\n if pd.api.types.is_categorical_dtype(vector):\n return VarType(\"categorical\")\n\n # Special-case all-na data, which is always \"numeric\"\n if pd.isna(vector).all():\n return VarType(\"numeric\")\n\n # Special-case binary/boolean data, allow caller to determine\n # This triggers a numpy warning when vector has strings/objects\n # https://github.com/numpy/numpy/issues/6784\n # Because we reduce with .all(), we are agnostic about whether the\n # comparison returns a scalar or vector, so we will ignore the warning.\n # It triggers a separate DeprecationWarning when the vector has datetimes:\n # https://github.com/numpy/numpy/issues/13548\n # This is considered a bug by numpy and will likely go away.\n with warnings.catch_warnings():\n warnings.simplefilter(\n action='ignore',\n category=(FutureWarning, DeprecationWarning) # type: ignore # mypy bug?\n )\n if np.isin(vector, [0, 1, np.nan]).all():\n return VarType(boolean_type)\n\n # Defer to positive pandas tests\n if pd.api.types.is_numeric_dtype(vector):\n return VarType(\"numeric\")\n\n if pd.api.types.is_datetime64_dtype(vector):\n return VarType(\"datetime\")\n\n # --- If we get to here, we need to check the entries\n\n # Check for a collection where everything is a number\n\n def all_numeric(x):\n for x_i in x:\n if not isinstance(x_i, Number):\n return False\n return True\n\n if all_numeric(vector):\n return VarType(\"numeric\")\n\n # Check for a collection where everything is a datetime\n\n def all_datetime(x):\n for x_i in x:\n if not isinstance(x_i, (datetime, np.datetime64)):\n return False\n return True\n\n if all_datetime(vector):\n return VarType(\"datetime\")\n\n # Otherwise, our final fallback is to consider things categorical\n\n return VarType(\"categorical\")"},{"col":4,"comment":"null","endLoc":74,"header":"def label(self)","id":309,"name":"label","nodeType":"Function","startLoc":73,"text":"def label(self):\n raise NotImplementedError()"},{"col":4,"comment":"null","endLoc":77,"header":"def _get_locators(self)","id":310,"name":"_get_locators","nodeType":"Function","startLoc":76,"text":"def _get_locators(self):\n raise NotImplementedError()"},{"col":4,"comment":"null","endLoc":31,"header":"def __init__(self, data)","id":311,"name":"__init__","nodeType":"Function","startLoc":29,"text":"def __init__(self, data):\n assert data in self.allowed, data\n super().__init__(data)"},{"col":4,"comment":"null","endLoc":80,"header":"def _get_formatter(self, locator: Locator | None = None)","id":312,"name":"_get_formatter","nodeType":"Function","startLoc":79,"text":"def _get_formatter(self, locator: Locator | None = None):\n raise NotImplementedError()"},{"col":4,"comment":"null","endLoc":94,"header":"def _get_scale(self, name: str, forward: Callable, inverse: Callable)","id":313,"name":"_get_scale","nodeType":"Function","startLoc":82,"text":"def _get_scale(self, name: str, forward: Callable, inverse: Callable):\n\n major_locator, minor_locator = self._get_locators(**self._tick_params)\n major_formatter = self._get_formatter(major_locator, **self._label_params)\n\n class InternalScale(mpl.scale.FuncScale):\n def set_default_locators_and_formatters(self, axis):\n axis.set_major_locator(major_locator)\n if minor_locator is not None:\n axis.set_minor_locator(minor_locator)\n axis.set_major_formatter(major_formatter)\n\n return InternalScale(name, (forward, inverse))"},{"col":4,"comment":"null","endLoc":97,"header":"def _spacing(self, x: Series) -> float","id":314,"name":"_spacing","nodeType":"Function","startLoc":96,"text":"def _spacing(self, x: Series) -> float:\n return self._spacer(x)"},{"attributeType":"null","col":0,"comment":"null","endLoc":58,"id":319,"name":"QUAL_PALETTES","nodeType":"Attribute","startLoc":58,"text":"QUAL_PALETTES"},{"className":"FacetGrid","col":0,"comment":"Multi-plot grid for plotting conditional relationships.","endLoc":1169,"id":320,"nodeType":"Class","startLoc":363,"text":"class FacetGrid(Grid):\n \"\"\"Multi-plot grid for plotting conditional relationships.\"\"\"\n\n def __init__(\n self, data, *,\n row=None, col=None, hue=None, col_wrap=None,\n sharex=True, sharey=True, height=3, aspect=1, palette=None,\n row_order=None, col_order=None, hue_order=None, hue_kws=None,\n dropna=False, legend_out=True, despine=True,\n margin_titles=False, xlim=None, ylim=None, subplot_kws=None,\n gridspec_kws=None,\n ):\n\n super().__init__()\n\n # Determine the hue facet layer information\n hue_var = hue\n if hue is None:\n hue_names = None\n else:\n hue_names = categorical_order(data[hue], hue_order)\n\n colors = self._get_palette(data, hue, hue_order, palette)\n\n # Set up the lists of names for the row and column facet variables\n if row is None:\n row_names = []\n else:\n row_names = categorical_order(data[row], row_order)\n\n if col is None:\n col_names = []\n else:\n col_names = categorical_order(data[col], col_order)\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n hue_kws = hue_kws if hue_kws is not None else {}\n\n # Make a boolean mask that is True anywhere there is an NA\n # value in one of the faceting variables, but only if dropna is True\n none_na = np.zeros(len(data), bool)\n if dropna:\n row_na = none_na if row is None else data[row].isnull()\n col_na = none_na if col is None else data[col].isnull()\n hue_na = none_na if hue is None else data[hue].isnull()\n not_na = ~(row_na | col_na | hue_na)\n else:\n not_na = ~none_na\n\n # Compute the grid shape\n ncol = 1 if col is None else len(col_names)\n nrow = 1 if row is None else len(row_names)\n self._n_facets = ncol * nrow\n\n self._col_wrap = col_wrap\n if col_wrap is not None:\n if row is not None:\n err = \"Cannot use `row` and `col_wrap` together.\"\n raise ValueError(err)\n ncol = col_wrap\n nrow = int(np.ceil(len(col_names) / col_wrap))\n self._ncol = ncol\n self._nrow = nrow\n\n # Calculate the base figure size\n # This can get stretched later by a legend\n # TODO this doesn't account for axis labels\n figsize = (ncol * height * aspect, nrow * height)\n\n # Validate some inputs\n if col_wrap is not None:\n margin_titles = False\n\n # Build the subplot keyword dictionary\n subplot_kws = {} if subplot_kws is None else subplot_kws.copy()\n gridspec_kws = {} if gridspec_kws is None else gridspec_kws.copy()\n if xlim is not None:\n subplot_kws[\"xlim\"] = xlim\n if ylim is not None:\n subplot_kws[\"ylim\"] = ylim\n\n # --- Initialize the subplot grid\n\n with _disable_autolayout():\n fig = plt.figure(figsize=figsize)\n\n if col_wrap is None:\n\n kwargs = dict(squeeze=False,\n sharex=sharex, sharey=sharey,\n subplot_kw=subplot_kws,\n gridspec_kw=gridspec_kws)\n\n axes = fig.subplots(nrow, ncol, **kwargs)\n\n if col is None and row is None:\n axes_dict = {}\n elif col is None:\n axes_dict = dict(zip(row_names, axes.flat))\n elif row is None:\n axes_dict = dict(zip(col_names, axes.flat))\n else:\n facet_product = product(row_names, col_names)\n axes_dict = dict(zip(facet_product, axes.flat))\n\n else:\n\n # If wrapping the col variable we need to make the grid ourselves\n if gridspec_kws:\n warnings.warn(\"`gridspec_kws` ignored when using `col_wrap`\")\n\n n_axes = len(col_names)\n axes = np.empty(n_axes, object)\n axes[0] = fig.add_subplot(nrow, ncol, 1, **subplot_kws)\n if sharex:\n subplot_kws[\"sharex\"] = axes[0]\n if sharey:\n subplot_kws[\"sharey\"] = axes[0]\n for i in range(1, n_axes):\n axes[i] = fig.add_subplot(nrow, ncol, i + 1, **subplot_kws)\n\n axes_dict = dict(zip(col_names, axes))\n\n # --- Set up the class attributes\n\n # Attributes that are part of the public API but accessed through\n # a property so that Sphinx adds them to the auto class doc\n self._figure = fig\n self._axes = axes\n self._axes_dict = axes_dict\n self._legend = None\n\n # Public attributes that aren't explicitly documented\n # (It's not obvious that having them be public was a good idea)\n self.data = data\n self.row_names = row_names\n self.col_names = col_names\n self.hue_names = hue_names\n self.hue_kws = hue_kws\n\n # Next the private variables\n self._nrow = nrow\n self._row_var = row\n self._ncol = ncol\n self._col_var = col\n\n self._margin_titles = margin_titles\n self._margin_titles_texts = []\n self._col_wrap = col_wrap\n self._hue_var = hue_var\n self._colors = colors\n self._legend_out = legend_out\n self._legend_data = {}\n self._x_var = None\n self._y_var = None\n self._sharex = sharex\n self._sharey = sharey\n self._dropna = dropna\n self._not_na = not_na\n\n # --- Make the axes look good\n\n self.set_titles()\n self.tight_layout()\n\n if despine:\n self.despine()\n\n if sharex in [True, 'col']:\n for ax in self._not_bottom_axes:\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n ax.xaxis.label.set_visible(False)\n\n if sharey in [True, 'row']:\n for ax in self._not_left_axes:\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n ax.yaxis.label.set_visible(False)\n\n __init__.__doc__ = dedent(\"\"\"\\\n Initialize the matplotlib figure and FacetGrid object.\n\n This class maps a dataset onto multiple axes arrayed in a grid of rows\n and columns that correspond to *levels* of variables in the dataset.\n The plots it produces are often called \"lattice\", \"trellis\", or\n \"small-multiple\" graphics.\n\n It can also represent levels of a third variable with the ``hue``\n parameter, which plots different subsets of data in different colors.\n This uses color to resolve elements on a third dimension, but only\n draws subsets on top of each other and will not tailor the ``hue``\n parameter for the specific visualization the way that axes-level\n functions that accept ``hue`` will.\n\n The basic workflow is to initialize the :class:`FacetGrid` object with\n the dataset and the variables that are used to structure the grid. Then\n one or more plotting functions can be applied to each subset by calling\n :meth:`FacetGrid.map` or :meth:`FacetGrid.map_dataframe`. Finally, the\n plot can be tweaked with other methods to do things like change the\n axis labels, use different ticks, or add a legend. See the detailed\n code examples below for more information.\n\n .. warning::\n\n When using seaborn functions that infer semantic mappings from a\n dataset, care must be taken to synchronize those mappings across\n facets (e.g., by defining the ``hue`` mapping with a palette dict or\n setting the data type of the variables to ``category``). In most cases,\n it will be better to use a figure-level function (e.g. :func:`relplot`\n or :func:`catplot`) than to use :class:`FacetGrid` directly.\n\n See the :ref:`tutorial ` for more information.\n\n Parameters\n ----------\n {data}\n row, col, hue : strings\n Variables that define subsets of the data, which will be drawn on\n separate facets in the grid. See the ``{{var}}_order`` parameters to\n control the order of levels of this variable.\n {col_wrap}\n {share_xy}\n {height}\n {aspect}\n {palette}\n {{row,col,hue}}_order : lists\n Order for the levels of the faceting variables. By default, this\n will be the order that the levels appear in ``data`` or, if the\n variables are pandas categoricals, the category order.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n {legend_out}\n despine : boolean\n Remove the top and right spines from the plots.\n {margin_titles}\n {{x, y}}lim: tuples\n Limits for each of the axes on each facet (only relevant when\n share{{x, y}} is True).\n subplot_kws : dict\n Dictionary of keyword arguments passed to matplotlib subplot(s)\n methods.\n gridspec_kws : dict\n Dictionary of keyword arguments passed to\n :class:`matplotlib.gridspec.GridSpec`\n (via :meth:`matplotlib.figure.Figure.subplots`).\n Ignored if ``col_wrap`` is not ``None``.\n\n See Also\n --------\n PairGrid : Subplot grid for plotting pairwise relationships\n relplot : Combine a relational plot and a :class:`FacetGrid`\n displot : Combine a distribution plot and a :class:`FacetGrid`\n catplot : Combine a categorical plot and a :class:`FacetGrid`\n lmplot : Combine a regression plot and a :class:`FacetGrid`\n\n Examples\n --------\n\n .. note::\n\n These examples use seaborn functions to demonstrate some of the\n advanced features of the class, but in most cases you will want\n to use figue-level functions (e.g. :func:`displot`, :func:`relplot`)\n to make the plots shown here.\n\n .. include:: ../docstrings/FacetGrid.rst\n\n \"\"\").format(**_facet_docs)\n\n def facet_data(self):\n \"\"\"Generator for name indices and data subsets for each facet.\n\n Yields\n ------\n (i, j, k), data_ijk : tuple of ints, DataFrame\n The ints provide an index into the {row, col, hue}_names attribute,\n and the dataframe contains a subset of the full data corresponding\n to each facet. The generator yields subsets that correspond with\n the self.axes.flat iterator, or self.axes[i, j] when `col_wrap`\n is None.\n\n \"\"\"\n data = self.data\n\n # Construct masks for the row variable\n if self.row_names:\n row_masks = [data[self._row_var] == n for n in self.row_names]\n else:\n row_masks = [np.repeat(True, len(self.data))]\n\n # Construct masks for the column variable\n if self.col_names:\n col_masks = [data[self._col_var] == n for n in self.col_names]\n else:\n col_masks = [np.repeat(True, len(self.data))]\n\n # Construct masks for the hue variable\n if self.hue_names:\n hue_masks = [data[self._hue_var] == n for n in self.hue_names]\n else:\n hue_masks = [np.repeat(True, len(self.data))]\n\n # Here is the main generator loop\n for (i, row), (j, col), (k, hue) in product(enumerate(row_masks),\n enumerate(col_masks),\n enumerate(hue_masks)):\n data_ijk = data[row & col & hue & self._not_na]\n yield (i, j, k), data_ijk\n\n def map(self, func, *args, **kwargs):\n \"\"\"Apply a plotting function to each facet's subset of the data.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. It\n must plot to the currently active matplotlib Axes and take a\n `color` keyword argument. If faceting on the `hue` dimension,\n it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # How we use the function depends on where it comes from\n func_module = str(getattr(func, \"__module__\", \"\"))\n\n # Check for categorical plots without order information\n if func_module == \"seaborn.categorical\":\n if \"order\" not in kwargs:\n warning = (\"Using the {} function without specifying \"\n \"`order` is likely to produce an incorrect \"\n \"plot.\".format(func.__name__))\n warnings.warn(warning)\n if len(args) == 3 and \"hue_order\" not in kwargs:\n warning = (\"Using the {} function without specifying \"\n \"`hue_order` is likely to produce an incorrect \"\n \"plot.\".format(func.__name__))\n warnings.warn(warning)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.size:\n continue\n\n # Get the current axis\n modify_state = not func_module.startswith(\"seaborn\")\n ax = self.facet_axis(row_i, col_j, modify_state)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = utils.to_utf8(self.hue_names[hue_k])\n\n # Get the actual data we are going to plot with\n plot_data = data_ijk[list(args)]\n if self._dropna:\n plot_data = plot_data.dropna()\n plot_args = [v for k, v in plot_data.items()]\n\n # Some matplotlib functions don't handle pandas objects correctly\n if func_module.startswith(\"matplotlib\"):\n plot_args = [v.values for v in plot_args]\n\n # Draw the plot\n self._facet_plot(func, ax, plot_args, kwargs)\n\n # Finalize the annotations and layout\n self._finalize_grid(args[:2])\n\n return self\n\n def map_dataframe(self, func, *args, **kwargs):\n \"\"\"Like ``.map`` but passes args as strings and inserts data in kwargs.\n\n This method is suitable for plotting with functions that accept a\n long-form DataFrame as a `data` keyword argument and access the\n data in that DataFrame using string variable names.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. Unlike\n the `map` method, a function used here must \"understand\" Pandas\n objects. It also must plot to the currently active matplotlib Axes\n and take a `color` keyword argument. If faceting on the `hue`\n dimension, it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.size:\n continue\n\n # Get the current axis\n modify_state = not str(func.__module__).startswith(\"seaborn\")\n ax = self.facet_axis(row_i, col_j, modify_state)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = self.hue_names[hue_k]\n\n # Stick the facet dataframe into the kwargs\n if self._dropna:\n data_ijk = data_ijk.dropna()\n kwargs[\"data\"] = data_ijk\n\n # Draw the plot\n self._facet_plot(func, ax, args, kwargs)\n\n # For axis labels, prefer to use positional args for backcompat\n # but also extract the x/y kwargs and use if no corresponding arg\n axis_labels = [kwargs.get(\"x\", None), kwargs.get(\"y\", None)]\n for i, val in enumerate(args[:2]):\n axis_labels[i] = val\n self._finalize_grid(axis_labels)\n\n return self\n\n def _facet_color(self, hue_index, kw_color):\n\n color = self._colors[hue_index]\n if kw_color is not None:\n return kw_color\n elif color is not None:\n return color\n\n def _facet_plot(self, func, ax, plot_args, plot_kwargs):\n\n # Draw the plot\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs = plot_kwargs.copy()\n semantics = [\"x\", \"y\", \"hue\", \"size\", \"style\"]\n for key, val in zip(semantics, plot_args):\n plot_kwargs[key] = val\n plot_args = []\n plot_kwargs[\"ax\"] = ax\n func(*plot_args, **plot_kwargs)\n\n # Sort out the supporting information\n self._update_legend_data(ax)\n\n def _finalize_grid(self, axlabels):\n \"\"\"Finalize the annotations and layout.\"\"\"\n self.set_axis_labels(*axlabels)\n self.tight_layout()\n\n def facet_axis(self, row_i, col_j, modify_state=True):\n \"\"\"Make the axis identified by these indices active and return it.\"\"\"\n\n # Calculate the actual indices of the axes to plot on\n if self._col_wrap is not None:\n ax = self.axes.flat[col_j]\n else:\n ax = self.axes[row_i, col_j]\n\n # Get a reference to the axes object we want, and make it active\n if modify_state:\n plt.sca(ax)\n return ax\n\n def despine(self, **kwargs):\n \"\"\"Remove axis spines from the facets.\"\"\"\n utils.despine(self._figure, **kwargs)\n return self\n\n def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs):\n \"\"\"Set axis labels on the left column and bottom row of the grid.\"\"\"\n if x_var is not None:\n self._x_var = x_var\n self.set_xlabels(x_var, clear_inner=clear_inner, **kwargs)\n if y_var is not None:\n self._y_var = y_var\n self.set_ylabels(y_var, clear_inner=clear_inner, **kwargs)\n\n return self\n\n def set_xlabels(self, label=None, clear_inner=True, **kwargs):\n \"\"\"Label the x axis on the bottom row of the grid.\"\"\"\n if label is None:\n label = self._x_var\n for ax in self._bottom_axes:\n ax.set_xlabel(label, **kwargs)\n if clear_inner:\n for ax in self._not_bottom_axes:\n ax.set_xlabel(\"\")\n return self\n\n def set_ylabels(self, label=None, clear_inner=True, **kwargs):\n \"\"\"Label the y axis on the left column of the grid.\"\"\"\n if label is None:\n label = self._y_var\n for ax in self._left_axes:\n ax.set_ylabel(label, **kwargs)\n if clear_inner:\n for ax in self._not_left_axes:\n ax.set_ylabel(\"\")\n return self\n\n def set_xticklabels(self, labels=None, step=None, **kwargs):\n \"\"\"Set x axis tick labels of the grid.\"\"\"\n for ax in self.axes.flat:\n curr_ticks = ax.get_xticks()\n ax.set_xticks(curr_ticks)\n if labels is None:\n curr_labels = [l.get_text() for l in ax.get_xticklabels()]\n if step is not None:\n xticks = ax.get_xticks()[::step]\n curr_labels = curr_labels[::step]\n ax.set_xticks(xticks)\n ax.set_xticklabels(curr_labels, **kwargs)\n else:\n ax.set_xticklabels(labels, **kwargs)\n return self\n\n def set_yticklabels(self, labels=None, **kwargs):\n \"\"\"Set y axis tick labels on the left column of the grid.\"\"\"\n for ax in self.axes.flat:\n curr_ticks = ax.get_yticks()\n ax.set_yticks(curr_ticks)\n if labels is None:\n curr_labels = [l.get_text() for l in ax.get_yticklabels()]\n ax.set_yticklabels(curr_labels, **kwargs)\n else:\n ax.set_yticklabels(labels, **kwargs)\n return self\n\n def set_titles(self, template=None, row_template=None, col_template=None,\n **kwargs):\n \"\"\"Draw titles either above each facet or on the grid margins.\n\n Parameters\n ----------\n template : string\n Template for all titles with the formatting keys {col_var} and\n {col_name} (if using a `col` faceting variable) and/or {row_var}\n and {row_name} (if using a `row` faceting variable).\n row_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {row_var} and {row_name} formatting keys.\n col_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {col_var} and {col_name} formatting keys.\n\n Returns\n -------\n self: object\n Returns self.\n\n \"\"\"\n args = dict(row_var=self._row_var, col_var=self._col_var)\n kwargs[\"size\"] = kwargs.pop(\"size\", mpl.rcParams[\"axes.labelsize\"])\n\n # Establish default templates\n if row_template is None:\n row_template = \"{row_var} = {row_name}\"\n if col_template is None:\n col_template = \"{col_var} = {col_name}\"\n if template is None:\n if self._row_var is None:\n template = col_template\n elif self._col_var is None:\n template = row_template\n else:\n template = \" | \".join([row_template, col_template])\n\n row_template = utils.to_utf8(row_template)\n col_template = utils.to_utf8(col_template)\n template = utils.to_utf8(template)\n\n if self._margin_titles:\n\n # Remove any existing title texts\n for text in self._margin_titles_texts:\n text.remove()\n self._margin_titles_texts = []\n\n if self.row_names is not None:\n # Draw the row titles on the right edge of the grid\n for i, row_name in enumerate(self.row_names):\n ax = self.axes[i, -1]\n args.update(dict(row_name=row_name))\n title = row_template.format(**args)\n text = ax.annotate(\n title, xy=(1.02, .5), xycoords=\"axes fraction\",\n rotation=270, ha=\"left\", va=\"center\",\n **kwargs\n )\n self._margin_titles_texts.append(text)\n\n if self.col_names is not None:\n # Draw the column titles as normal titles\n for j, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = col_template.format(**args)\n self.axes[0, j].set_title(title, **kwargs)\n\n return self\n\n # Otherwise title each facet with all the necessary information\n if (self._row_var is not None) and (self._col_var is not None):\n for i, row_name in enumerate(self.row_names):\n for j, col_name in enumerate(self.col_names):\n args.update(dict(row_name=row_name, col_name=col_name))\n title = template.format(**args)\n self.axes[i, j].set_title(title, **kwargs)\n elif self.row_names is not None and len(self.row_names):\n for i, row_name in enumerate(self.row_names):\n args.update(dict(row_name=row_name))\n title = template.format(**args)\n self.axes[i, 0].set_title(title, **kwargs)\n elif self.col_names is not None and len(self.col_names):\n for i, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = template.format(**args)\n # Index the flat array so col_wrap works\n self.axes.flat[i].set_title(title, **kwargs)\n return self\n\n def refline(self, *, x=None, y=None, color='.5', linestyle='--', **line_kws):\n \"\"\"Add a reference line(s) to each facet.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s). Pass ``color=None`` to\n use ``hue`` mapping.\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`FacetGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n line_kws['color'] = color\n line_kws['linestyle'] = linestyle\n\n if x is not None:\n self.map(plt.axvline, x=x, **line_kws)\n\n if y is not None:\n self.map(plt.axhline, y=y, **line_kws)\n\n return self\n\n # ------ Properties that are part of the public API and documented by Sphinx\n\n @property\n def axes(self):\n \"\"\"An array of the :class:`matplotlib.axes.Axes` objects in the grid.\"\"\"\n return self._axes\n\n @property\n def ax(self):\n \"\"\"The :class:`matplotlib.axes.Axes` when no faceting variables are assigned.\"\"\"\n if self.axes.shape == (1, 1):\n return self.axes[0, 0]\n else:\n err = (\n \"Use the `.axes` attribute when facet variables are assigned.\"\n )\n raise AttributeError(err)\n\n @property\n def axes_dict(self):\n \"\"\"A mapping of facet names to corresponding :class:`matplotlib.axes.Axes`.\n\n If only one of ``row`` or ``col`` is assigned, each key is a string\n representing a level of that variable. If both facet dimensions are\n assigned, each key is a ``({row_level}, {col_level})`` tuple.\n\n \"\"\"\n return self._axes_dict\n\n # ------ Private properties, that require some computation to get\n\n @property\n def _inner_axes(self):\n \"\"\"Return a flat array of the inner axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, 1:].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i % self._ncol\n and i < (self._ncol * (self._nrow - 1))\n and i < (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _left_axes(self):\n \"\"\"Return a flat array of the left column of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 0].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if not i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _not_left_axes(self):\n \"\"\"Return a flat array of axes that aren't on the left column.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 1:].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _bottom_axes(self):\n \"\"\"Return a flat array of the bottom row of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i >= (self._ncol * (self._nrow - 1))\n or i >= (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _not_bottom_axes(self):\n \"\"\"Return a flat array of axes that aren't on the bottom row.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i < (self._ncol * (self._nrow - 1))\n and i < (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":321,"name":"g","nodeType":"Attribute","startLoc":14,"text":"g"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":322,"name":"f","nodeType":"Attribute","startLoc":16,"text":"f"},{"col":0,"comment":"","endLoc":6,"header":"anscombes_quartet.py#","id":323,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nAnscombe's quartet\n==================\n\n_thumb: .4, .4\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\ndf = sns.load_dataset(\"anscombe\")\n\nsns.lmplot(\n data=df, x=\"x\", y=\"y\", col=\"dataset\", hue=\"dataset\",\n col_wrap=2, palette=\"muted\", ci=None,\n height=4, scatter_kws={\"s\": 50, \"alpha\": 1}\n)"},{"col":0,"comment":"\n Set aspects of the visual theme for all matplotlib and seaborn plots.\n\n This function changes the global defaults for all plots using the\n matplotlib rcParams system. The themeing is decomposed into several distinct\n sets of parameter values.\n\n The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`\n and :doc:`color palette <../tutorial/color_palettes>` tutorials.\n\n Parameters\n ----------\n context : string or dict\n Scaling parameters, see :func:`plotting_context`.\n style : string or dict\n Axes style parameters, see :func:`axes_style`.\n palette : string or sequence\n Color palette, see :func:`color_palette`.\n font : string\n Font family, see matplotlib font manager.\n font_scale : float, optional\n Separate scaling factor to independently scale the size of the\n font elements.\n color_codes : bool\n If ``True`` and ``palette`` is a seaborn palette, remap the shorthand\n color codes (e.g. \"b\", \"g\", \"r\", etc.) to the colors from this palette.\n rc : dict or None\n Dictionary of rc parameter mappings to override the above.\n\n Examples\n --------\n\n .. include:: ../docstrings/set_theme.rst\n\n ","endLoc":123,"header":"def set_theme(context=\"notebook\", style=\"darkgrid\", palette=\"deep\",\n font=\"sans-serif\", font_scale=1, color_codes=True, rc=None)","id":324,"name":"set_theme","nodeType":"Function","startLoc":82,"text":"def set_theme(context=\"notebook\", style=\"darkgrid\", palette=\"deep\",\n font=\"sans-serif\", font_scale=1, color_codes=True, rc=None):\n \"\"\"\n Set aspects of the visual theme for all matplotlib and seaborn plots.\n\n This function changes the global defaults for all plots using the\n matplotlib rcParams system. The themeing is decomposed into several distinct\n sets of parameter values.\n\n The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`\n and :doc:`color palette <../tutorial/color_palettes>` tutorials.\n\n Parameters\n ----------\n context : string or dict\n Scaling parameters, see :func:`plotting_context`.\n style : string or dict\n Axes style parameters, see :func:`axes_style`.\n palette : string or sequence\n Color palette, see :func:`color_palette`.\n font : string\n Font family, see matplotlib font manager.\n font_scale : float, optional\n Separate scaling factor to independently scale the size of the\n font elements.\n color_codes : bool\n If ``True`` and ``palette`` is a seaborn palette, remap the shorthand\n color codes (e.g. \"b\", \"g\", \"r\", etc.) to the colors from this palette.\n rc : dict or None\n Dictionary of rc parameter mappings to override the above.\n\n Examples\n --------\n\n .. include:: ../docstrings/set_theme.rst\n\n \"\"\"\n set_context(context, font_scale)\n set_style(style, rc={\"font.family\": font})\n set_palette(palette, color_codes=color_codes)\n if rc is not None:\n mpl.rcParams.update(rc)"},{"col":0,"comment":"Return a list of colors or continuous colormap defining a palette.\n\n Possible ``palette`` values include:\n - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)\n - Name of matplotlib colormap\n - 'husl' or 'hls'\n - 'ch:'\n - 'light:', 'dark:', 'blend:,',\n - A sequence of colors in any format matplotlib accepts\n\n Calling this function with ``palette=None`` will return the current\n matplotlib color cycle.\n\n This function can also be used in a ``with`` statement to temporarily\n set the color cycle for a plot or set of plots.\n\n See the :ref:`tutorial ` for more information.\n\n Parameters\n ----------\n palette : None, string, or sequence, optional\n Name of palette or None to return current palette. If a sequence, input\n colors are used but possibly cycled and desaturated.\n n_colors : int, optional\n Number of colors in the palette. If ``None``, the default will depend\n on how ``palette`` is specified. Named palettes default to 6 colors,\n but grabbing the current palette or passing in a list of colors will\n not change the number of colors unless this is specified. Asking for\n more colors than exist in the palette will cause it to cycle. Ignored\n when ``as_cmap`` is True.\n desat : float, optional\n Proportion to desaturate each color by.\n as_cmap : bool\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n set_palette : Set the default color cycle for all plots.\n set_color_codes : Reassign color codes like ``\"b\"``, ``\"g\"``, etc. to\n colors from one of the seaborn palettes.\n\n Examples\n --------\n\n .. include:: ../docstrings/color_palette.rst\n\n ","endLoc":255,"header":"def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False)","id":325,"name":"color_palette","nodeType":"Function","startLoc":122,"text":"def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False):\n \"\"\"Return a list of colors or continuous colormap defining a palette.\n\n Possible ``palette`` values include:\n - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)\n - Name of matplotlib colormap\n - 'husl' or 'hls'\n - 'ch:'\n - 'light:', 'dark:', 'blend:,',\n - A sequence of colors in any format matplotlib accepts\n\n Calling this function with ``palette=None`` will return the current\n matplotlib color cycle.\n\n This function can also be used in a ``with`` statement to temporarily\n set the color cycle for a plot or set of plots.\n\n See the :ref:`tutorial ` for more information.\n\n Parameters\n ----------\n palette : None, string, or sequence, optional\n Name of palette or None to return current palette. If a sequence, input\n colors are used but possibly cycled and desaturated.\n n_colors : int, optional\n Number of colors in the palette. If ``None``, the default will depend\n on how ``palette`` is specified. Named palettes default to 6 colors,\n but grabbing the current palette or passing in a list of colors will\n not change the number of colors unless this is specified. Asking for\n more colors than exist in the palette will cause it to cycle. Ignored\n when ``as_cmap`` is True.\n desat : float, optional\n Proportion to desaturate each color by.\n as_cmap : bool\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n set_palette : Set the default color cycle for all plots.\n set_color_codes : Reassign color codes like ``\"b\"``, ``\"g\"``, etc. to\n colors from one of the seaborn palettes.\n\n Examples\n --------\n\n .. include:: ../docstrings/color_palette.rst\n\n \"\"\"\n if palette is None:\n palette = get_color_cycle()\n if n_colors is None:\n n_colors = len(palette)\n\n elif not isinstance(palette, str):\n palette = palette\n if n_colors is None:\n n_colors = len(palette)\n else:\n\n if n_colors is None:\n # Use all colors in a qualitative palette or 6 of another kind\n n_colors = QUAL_PALETTE_SIZES.get(palette, 6)\n\n if palette in SEABORN_PALETTES:\n # Named \"seaborn variant\" of matplotlib default color cycle\n palette = SEABORN_PALETTES[palette]\n\n elif palette == \"hls\":\n # Evenly spaced colors in cylindrical RGB space\n palette = hls_palette(n_colors, as_cmap=as_cmap)\n\n elif palette == \"husl\":\n # Evenly spaced colors in cylindrical Lab space\n palette = husl_palette(n_colors, as_cmap=as_cmap)\n\n elif palette.lower() == \"jet\":\n # Paternalism\n raise ValueError(\"No.\")\n\n elif palette.startswith(\"ch:\"):\n # Cubehelix palette with params specified in string\n args, kwargs = _parse_cubehelix_args(palette)\n palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap)\n\n elif palette.startswith(\"light:\"):\n # light palette to color specified in string\n _, color = palette.split(\":\")\n reverse = color.endswith(\"_r\")\n if reverse:\n color = color[:-2]\n palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)\n\n elif palette.startswith(\"dark:\"):\n # light palette to color specified in string\n _, color = palette.split(\":\")\n reverse = color.endswith(\"_r\")\n if reverse:\n color = color[:-2]\n palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)\n\n elif palette.startswith(\"blend:\"):\n # blend palette between colors specified in string\n _, colors = palette.split(\":\")\n colors = colors.split(\",\")\n palette = blend_palette(colors, n_colors, as_cmap=as_cmap)\n\n else:\n try:\n # Perhaps a named matplotlib colormap?\n palette = mpl_palette(palette, n_colors, as_cmap=as_cmap)\n except (ValueError, KeyError): # Error class changed in mpl36\n raise ValueError(f\"{palette} is not a valid palette name\")\n\n if desat is not None:\n palette = [desaturate(c, desat) for c in palette]\n\n if not as_cmap:\n\n # Always return as many colors as we asked for\n pal_cycle = cycle(palette)\n palette = [next(pal_cycle) for _ in range(n_colors)]\n\n # Always return in r, g, b tuple format\n try:\n palette = map(mpl.colors.colorConverter.to_rgb, palette)\n palette = _ColorPalette(palette)\n except ValueError:\n raise ValueError(f\"Could not generate a palette for {palette}\")\n\n return palette"},{"col":0,"comment":"Return the list of colors in the current matplotlib color cycle\n\n Parameters\n ----------\n None\n\n Returns\n -------\n colors : list\n List of matplotlib colors in the current cycle, or dark gray if\n the current color cycle is empty.\n ","endLoc":291,"header":"def get_color_cycle()","id":326,"name":"get_color_cycle","nodeType":"Function","startLoc":277,"text":"def get_color_cycle():\n \"\"\"Return the list of colors in the current matplotlib color cycle\n\n Parameters\n ----------\n None\n\n Returns\n -------\n colors : list\n List of matplotlib colors in the current cycle, or dark gray if\n the current color cycle is empty.\n \"\"\"\n cycler = mpl.rcParams['axes.prop_cycle']\n return cycler.by_key()['color'] if 'color' in cycler.keys else [\".15\"]"},{"attributeType":"null","col":3,"comment":"null","endLoc":16,"id":327,"name":"ax","nodeType":"Attribute","startLoc":16,"text":"ax"},{"col":0,"comment":"\n Set the parameters that control the scaling of plot elements.\n\n This affects things like the size of the labels, lines, and other elements\n of the plot, but not the overall style. This is accomplished using the\n matplotlib rcParams system.\n\n The base context is \"notebook\", and the other contexts are \"paper\", \"talk\",\n and \"poster\", which are version of the notebook parameters scaled by different\n values. Font elements can also be scaled independently of (but relative to)\n the other values.\n\n See :func:`plotting_context` to get the parameter values.\n\n Parameters\n ----------\n context : dict, or one of {paper, notebook, talk, poster}\n A dictionary of parameters or the name of a preconfigured set.\n font_scale : float, optional\n Separate scaling factor to independently scale the size of the\n font elements.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n context dictionaries. This only updates parameters that are\n considered part of the context definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/set_context.rst\n\n ","endLoc":470,"header":"def set_context(context=None, font_scale=1, rc=None)","id":328,"name":"set_context","nodeType":"Function","startLoc":436,"text":"def set_context(context=None, font_scale=1, rc=None):\n \"\"\"\n Set the parameters that control the scaling of plot elements.\n\n This affects things like the size of the labels, lines, and other elements\n of the plot, but not the overall style. This is accomplished using the\n matplotlib rcParams system.\n\n The base context is \"notebook\", and the other contexts are \"paper\", \"talk\",\n and \"poster\", which are version of the notebook parameters scaled by different\n values. Font elements can also be scaled independently of (but relative to)\n the other values.\n\n See :func:`plotting_context` to get the parameter values.\n\n Parameters\n ----------\n context : dict, or one of {paper, notebook, talk, poster}\n A dictionary of parameters or the name of a preconfigured set.\n font_scale : float, optional\n Separate scaling factor to independently scale the size of the\n font elements.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n context dictionaries. This only updates parameters that are\n considered part of the context definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/set_context.rst\n\n \"\"\"\n context_object = plotting_context(context, font_scale, rc)\n mpl.rcParams.update(context_object)"},{"col":0,"comment":"","endLoc":6,"header":"pointplot_anova.py#","id":329,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPlotting a three-way ANOVA\n==========================\n\n_thumb: .42, .5\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\nexercise = sns.load_dataset(\"exercise\")\n\ng = sns.catplot(\n data=exercise, x=\"time\", y=\"pulse\", hue=\"kind\", col=\"diet\",\n capsize=.2, palette=\"YlGnBu_d\", errorbar=\"se\",\n kind=\"point\", height=6, aspect=.75,\n)\n\ng.despine(left=True)"},{"col":0,"comment":"\n Get the parameters that control the scaling of plot elements.\n\n This affects things like the size of the labels, lines, and other elements\n of the plot, but not the overall style. This is accomplished using the\n matplotlib rcParams system.\n\n The base context is \"notebook\", and the other contexts are \"paper\", \"talk\",\n and \"poster\", which are version of the notebook parameters scaled by different\n values. Font elements can also be scaled independently of (but relative to)\n the other values.\n\n This function can also be used as a context manager to temporarily\n alter the global defaults. See :func:`set_theme` or :func:`set_context`\n to modify the global defaults for all plots.\n\n Parameters\n ----------\n context : None, dict, or one of {paper, notebook, talk, poster}\n A dictionary of parameters or the name of a preconfigured set.\n font_scale : float, optional\n Separate scaling factor to independently scale the size of the\n font elements.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n context dictionaries. This only updates parameters that are\n considered part of the context definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/plotting_context.rst\n\n ","endLoc":433,"header":"def plotting_context(context=None, font_scale=1, rc=None)","id":330,"name":"plotting_context","nodeType":"Function","startLoc":335,"text":"def plotting_context(context=None, font_scale=1, rc=None):\n \"\"\"\n Get the parameters that control the scaling of plot elements.\n\n This affects things like the size of the labels, lines, and other elements\n of the plot, but not the overall style. This is accomplished using the\n matplotlib rcParams system.\n\n The base context is \"notebook\", and the other contexts are \"paper\", \"talk\",\n and \"poster\", which are version of the notebook parameters scaled by different\n values. Font elements can also be scaled independently of (but relative to)\n the other values.\n\n This function can also be used as a context manager to temporarily\n alter the global defaults. See :func:`set_theme` or :func:`set_context`\n to modify the global defaults for all plots.\n\n Parameters\n ----------\n context : None, dict, or one of {paper, notebook, talk, poster}\n A dictionary of parameters or the name of a preconfigured set.\n font_scale : float, optional\n Separate scaling factor to independently scale the size of the\n font elements.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n context dictionaries. This only updates parameters that are\n considered part of the context definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/plotting_context.rst\n\n \"\"\"\n if context is None:\n context_dict = {k: mpl.rcParams[k] for k in _context_keys}\n\n elif isinstance(context, dict):\n context_dict = context\n\n else:\n\n contexts = [\"paper\", \"notebook\", \"talk\", \"poster\"]\n if context not in contexts:\n raise ValueError(f\"context must be in {', '.join(contexts)}\")\n\n # Set up dictionary of default parameters\n texts_base_context = {\n\n \"font.size\": 12,\n \"axes.labelsize\": 12,\n \"axes.titlesize\": 12,\n \"xtick.labelsize\": 11,\n \"ytick.labelsize\": 11,\n \"legend.fontsize\": 11,\n \"legend.title_fontsize\": 12,\n\n }\n\n base_context = {\n\n \"axes.linewidth\": 1.25,\n \"grid.linewidth\": 1,\n \"lines.linewidth\": 1.5,\n \"lines.markersize\": 6,\n \"patch.linewidth\": 1,\n\n \"xtick.major.width\": 1.25,\n \"ytick.major.width\": 1.25,\n \"xtick.minor.width\": 1,\n \"ytick.minor.width\": 1,\n\n \"xtick.major.size\": 6,\n \"ytick.major.size\": 6,\n \"xtick.minor.size\": 4,\n \"ytick.minor.size\": 4,\n\n }\n base_context.update(texts_base_context)\n\n # Scale all the parameters by the same factor depending on the context\n scaling = dict(paper=.8, notebook=1, talk=1.5, poster=2)[context]\n context_dict = {k: v * scaling for k, v in base_context.items()}\n\n # Now independently scale the fonts\n font_keys = texts_base_context.keys()\n font_dict = {k: context_dict[k] * font_scale for k in font_keys}\n context_dict.update(font_dict)\n\n # Override these settings with the provided rc dictionary\n if rc is not None:\n rc = {k: v for k, v in rc.items() if k in _context_keys}\n context_dict.update(rc)\n\n # Wrap in a _PlottingContext object so this can be used in a with statement\n context_object = _PlottingContext(context_dict)\n\n return context_object"},{"col":0,"comment":"Load an example dataset from the online repository (requires internet).\n\n This function provides quick access to a small number of example datasets\n that are useful for documenting seaborn or generating reproducible examples\n for bug reports. It is not necessary for normal usage.\n\n Note that some of the datasets have a small amount of preprocessing applied\n to define a proper ordering for categorical variables.\n\n Use :func:`get_dataset_names` to see a list of available datasets.\n\n Parameters\n ----------\n name : str\n Name of the dataset (``{name}.csv`` on\n https://github.com/mwaskom/seaborn-data).\n cache : boolean, optional\n If True, try to load from the local cache first, and save to the cache\n if a download is required.\n data_home : string, optional\n The directory in which to cache data; see :func:`get_data_home`.\n kws : keys and values, optional\n Additional keyword arguments are passed to passed through to\n :func:`pandas.read_csv`.\n\n Returns\n -------\n df : :class:`pandas.DataFrame`\n Tabular data, possibly with some preprocessing applied.\n\n ","endLoc":639,"header":"def load_dataset(name, cache=True, data_home=None, **kws)","id":331,"name":"load_dataset","nodeType":"Function","startLoc":534,"text":"def load_dataset(name, cache=True, data_home=None, **kws):\n \"\"\"Load an example dataset from the online repository (requires internet).\n\n This function provides quick access to a small number of example datasets\n that are useful for documenting seaborn or generating reproducible examples\n for bug reports. It is not necessary for normal usage.\n\n Note that some of the datasets have a small amount of preprocessing applied\n to define a proper ordering for categorical variables.\n\n Use :func:`get_dataset_names` to see a list of available datasets.\n\n Parameters\n ----------\n name : str\n Name of the dataset (``{name}.csv`` on\n https://github.com/mwaskom/seaborn-data).\n cache : boolean, optional\n If True, try to load from the local cache first, and save to the cache\n if a download is required.\n data_home : string, optional\n The directory in which to cache data; see :func:`get_data_home`.\n kws : keys and values, optional\n Additional keyword arguments are passed to passed through to\n :func:`pandas.read_csv`.\n\n Returns\n -------\n df : :class:`pandas.DataFrame`\n Tabular data, possibly with some preprocessing applied.\n\n \"\"\"\n # A common beginner mistake is to assume that one's personal data needs\n # to be passed through this function to be usable with seaborn.\n # Let's provide a more helpful error than you would otherwise get.\n if isinstance(name, pd.DataFrame):\n err = (\n \"This function accepts only strings (the name of an example dataset). \"\n \"You passed a pandas DataFrame. If you have your own dataset, \"\n \"it is not necessary to use this function before plotting.\"\n )\n raise TypeError(err)\n\n url = f\"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/{name}.csv\"\n\n if cache:\n cache_path = os.path.join(get_data_home(data_home), os.path.basename(url))\n if not os.path.exists(cache_path):\n if name not in get_dataset_names():\n raise ValueError(f\"'{name}' is not one of the example datasets.\")\n urlretrieve(url, cache_path)\n full_path = cache_path\n else:\n full_path = url\n\n df = pd.read_csv(full_path, **kws)\n\n if df.iloc[-1].isnull().all():\n df = df.iloc[:-1]\n\n # Set some columns as a categorical type with ordered levels\n\n if name == \"tips\":\n df[\"day\"] = pd.Categorical(df[\"day\"], [\"Thur\", \"Fri\", \"Sat\", \"Sun\"])\n df[\"sex\"] = pd.Categorical(df[\"sex\"], [\"Male\", \"Female\"])\n df[\"time\"] = pd.Categorical(df[\"time\"], [\"Lunch\", \"Dinner\"])\n df[\"smoker\"] = pd.Categorical(df[\"smoker\"], [\"Yes\", \"No\"])\n\n elif name == \"flights\":\n months = df[\"month\"].str[:3]\n df[\"month\"] = pd.Categorical(months, months.unique())\n\n elif name == \"exercise\":\n df[\"time\"] = pd.Categorical(df[\"time\"], [\"1 min\", \"15 min\", \"30 min\"])\n df[\"kind\"] = pd.Categorical(df[\"kind\"], [\"rest\", \"walking\", \"running\"])\n df[\"diet\"] = pd.Categorical(df[\"diet\"], [\"no fat\", \"low fat\"])\n\n elif name == \"titanic\":\n df[\"class\"] = pd.Categorical(df[\"class\"], [\"First\", \"Second\", \"Third\"])\n df[\"deck\"] = pd.Categorical(df[\"deck\"], list(\"ABCDEFG\"))\n\n elif name == \"penguins\":\n df[\"sex\"] = df[\"sex\"].str.title()\n\n elif name == \"diamonds\":\n df[\"color\"] = pd.Categorical(\n df[\"color\"], [\"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"],\n )\n df[\"clarity\"] = pd.Categorical(\n df[\"clarity\"], [\"IF\", \"VVS1\", \"VVS2\", \"VS1\", \"VS2\", \"SI1\", \"SI2\", \"I1\"],\n )\n df[\"cut\"] = pd.Categorical(\n df[\"cut\"], [\"Ideal\", \"Premium\", \"Very Good\", \"Good\", \"Fair\"],\n )\n\n elif name == \"taxis\":\n df[\"pickup\"] = pd.to_datetime(df[\"pickup\"])\n df[\"dropoff\"] = pd.to_datetime(df[\"dropoff\"])\n\n elif name == \"seaice\":\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\n\n elif name == \"dowjones\":\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\n\n return df"},{"col":0,"comment":"","endLoc":7,"header":"histogram_stacked.py#","id":332,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nStacked histogram on a log scale\n================================\n\n_thumb: .5, .45\n\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\n\nf, ax = plt.subplots(figsize=(7, 5))\n\nsns.despine(f)\n\nsns.histplot(\n diamonds,\n x=\"price\", hue=\"cut\",\n multiple=\"stack\",\n palette=\"light:m_r\",\n edgecolor=\".3\",\n linewidth=.5,\n log_scale=True,\n)\n\nax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())\n\nax.set_xticks([500, 1000, 2000, 5000, 10000])"},{"col":4,"comment":"null","endLoc":102,"header":"def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale","id":334,"name":"_setup","nodeType":"Function","startLoc":99,"text":"def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n raise NotImplementedError()"},{"col":4,"comment":"null","endLoc":134,"header":"@staticmethod\n def _identity()","id":335,"name":"_identity","nodeType":"Function","startLoc":125,"text":"@staticmethod\n def _identity():\n\n class Identity(Scale):\n _pipeline = []\n _spacer = None\n _legend = None\n _matplotlib_scale = None\n\n return Identity()"},{"col":4,"comment":"null","endLoc":100,"header":"def __init__(self) -> None","id":336,"name":"__init__","nodeType":"Function","startLoc":100,"text":"def __init__(self) -> None: ..."},{"attributeType":"tuple | str | list | dict | None","col":4,"comment":"null","endLoc":56,"id":337,"name":"values","nodeType":"Attribute","startLoc":56,"text":"values"},{"col":0,"comment":"Return a path to the cache directory for example datasets.\n\n This directory is used by :func:`load_dataset`.\n\n If the ``data_home`` argument is not provided, it will use a directory\n specified by the `SEABORN_DATA` environment variable (if it exists)\n or otherwise default to an OS-appropriate user cache location.\n\n ","endLoc":531,"header":"def get_data_home(data_home=None)","id":338,"name":"get_data_home","nodeType":"Function","startLoc":516,"text":"def get_data_home(data_home=None):\n \"\"\"Return a path to the cache directory for example datasets.\n\n This directory is used by :func:`load_dataset`.\n\n If the ``data_home`` argument is not provided, it will use a directory\n specified by the `SEABORN_DATA` environment variable (if it exists)\n or otherwise default to an OS-appropriate user cache location.\n\n \"\"\"\n if data_home is None:\n data_home = os.environ.get(\"SEABORN_DATA\", user_cache_dir(\"seaborn\"))\n data_home = os.path.expanduser(data_home)\n if not os.path.exists(data_home):\n os.makedirs(data_home)\n return data_home"},{"col":0,"comment":"\n Return hues with constant lightness and saturation in the HLS system.\n\n The hues are evenly sampled along a circular path. The resulting palette will be\n appropriate for categorical or cyclical data.\n\n The `h`, `l`, and `s` values should be between 0 and 1.\n\n .. note::\n While the separation of the resulting colors will be mathematically\n constant, the HLS system does not construct a perceptually-uniform space,\n so their apparent intensity will vary.\n\n Parameters\n ----------\n n_colors : int\n Number of colors in the palette.\n h : float\n The value of the first hue.\n l : float\n The lightness value.\n s : float\n The saturation intensity.\n as_cmap : bool\n If True, return a matplotlib colormap object.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n husl_palette : Make a palette using evenly spaced hues in the HUSL system.\n\n Examples\n --------\n .. include:: ../docstrings/hls_palette.rst\n\n ","endLoc":309,"header":"def hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False)","id":339,"name":"hls_palette","nodeType":"Function","startLoc":258,"text":"def hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False): # noqa\n \"\"\"\n Return hues with constant lightness and saturation in the HLS system.\n\n The hues are evenly sampled along a circular path. The resulting palette will be\n appropriate for categorical or cyclical data.\n\n The `h`, `l`, and `s` values should be between 0 and 1.\n\n .. note::\n While the separation of the resulting colors will be mathematically\n constant, the HLS system does not construct a perceptually-uniform space,\n so their apparent intensity will vary.\n\n Parameters\n ----------\n n_colors : int\n Number of colors in the palette.\n h : float\n The value of the first hue.\n l : float\n The lightness value.\n s : float\n The saturation intensity.\n as_cmap : bool\n If True, return a matplotlib colormap object.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n husl_palette : Make a palette using evenly spaced hues in the HUSL system.\n\n Examples\n --------\n .. include:: ../docstrings/hls_palette.rst\n\n \"\"\"\n if as_cmap:\n n_colors = 256\n hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]\n hues += h\n hues %= 1\n hues -= hues.astype(int)\n palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]\n if as_cmap:\n return mpl.colors.ListedColormap(palette, \"hls\")\n else:\n return _ColorPalette(palette)"},{"className":"Grid","col":0,"comment":"A grid that can have multiple subplots and an external legend.","endLoc":301,"id":340,"nodeType":"Class","startLoc":98,"text":"class Grid(_BaseGrid):\n \"\"\"A grid that can have multiple subplots and an external legend.\"\"\"\n _margin_titles = False\n _legend_out = True\n\n def __init__(self):\n\n self._tight_layout_rect = [0, 0, 1, 1]\n self._tight_layout_pad = None\n\n # This attribute is set externally and is a hack to handle newer functions that\n # don't add proxy artists onto the Axes. We need an overall cleaner approach.\n self._extract_legend_handles = False\n\n def tight_layout(self, *args, **kwargs):\n \"\"\"Call fig.tight_layout within rect that exclude the legend.\"\"\"\n kwargs = kwargs.copy()\n kwargs.setdefault(\"rect\", self._tight_layout_rect)\n if self._tight_layout_pad is not None:\n kwargs.setdefault(\"pad\", self._tight_layout_pad)\n self._figure.tight_layout(*args, **kwargs)\n return self\n\n def add_legend(self, legend_data=None, title=None, label_order=None,\n adjust_subtitles=False, **kwargs):\n \"\"\"Draw a legend, maybe placing it outside axes and resizing the figure.\n\n Parameters\n ----------\n legend_data : dict\n Dictionary mapping label names (or two-element tuples where the\n second element is a label name) to matplotlib artist handles. The\n default reads from ``self._legend_data``.\n title : string\n Title for the legend. The default reads from ``self._hue_var``.\n label_order : list of labels\n The order that the legend entries should appear in. The default\n reads from ``self.hue_names``.\n adjust_subtitles : bool\n If True, modify entries with invisible artists to left-align\n the labels and set the font size to that of a title.\n kwargs : key, value pairings\n Other keyword arguments are passed to the underlying legend methods\n on the Figure or Axes object.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n \"\"\"\n # Find the data for the legend\n if legend_data is None:\n legend_data = self._legend_data\n if label_order is None:\n if self.hue_names is None:\n label_order = list(legend_data.keys())\n else:\n label_order = list(map(utils.to_utf8, self.hue_names))\n\n blank_handle = mpl.patches.Patch(alpha=0, linewidth=0)\n handles = [legend_data.get(l, blank_handle) for l in label_order]\n title = self._hue_var if title is None else title\n title_size = mpl.rcParams[\"legend.title_fontsize\"]\n\n # Unpack nested labels from a hierarchical legend\n labels = []\n for entry in label_order:\n if isinstance(entry, tuple):\n _, label = entry\n else:\n label = entry\n labels.append(label)\n\n # Set default legend kwargs\n kwargs.setdefault(\"scatterpoints\", 1)\n\n if self._legend_out:\n\n kwargs.setdefault(\"frameon\", False)\n kwargs.setdefault(\"loc\", \"center right\")\n\n # Draw a full-figure legend outside the grid\n figlegend = self._figure.legend(handles, labels, **kwargs)\n\n self._legend = figlegend\n figlegend.set_title(title, prop={\"size\": title_size})\n\n if adjust_subtitles:\n adjust_legend_subtitles(figlegend)\n\n # Draw the plot to set the bounding boxes correctly\n _draw_figure(self._figure)\n\n # Calculate and set the new width of the figure so the legend fits\n legend_width = figlegend.get_window_extent().width / self._figure.dpi\n fig_width, fig_height = self._figure.get_size_inches()\n self._figure.set_size_inches(fig_width + legend_width, fig_height)\n\n # Draw the plot again to get the new transformations\n _draw_figure(self._figure)\n\n # Now calculate how much space we need on the right side\n legend_width = figlegend.get_window_extent().width / self._figure.dpi\n space_needed = legend_width / (fig_width + legend_width)\n margin = .04 if self._margin_titles else .01\n self._space_needed = margin + space_needed\n right = 1 - self._space_needed\n\n # Place the subplot axes to give space for the legend\n self._figure.subplots_adjust(right=right)\n self._tight_layout_rect[2] = right\n\n else:\n # Draw a legend in the first axis\n ax = self.axes.flat[0]\n kwargs.setdefault(\"loc\", \"best\")\n\n leg = ax.legend(handles, labels, **kwargs)\n leg.set_title(title, prop={\"size\": title_size})\n self._legend = leg\n\n if adjust_subtitles:\n adjust_legend_subtitles(leg)\n\n return self\n\n def _update_legend_data(self, ax):\n \"\"\"Extract the legend data from an axes object and save it.\"\"\"\n data = {}\n\n # Get data directly from the legend, which is necessary\n # for newer functions that don't add labeled proxy artists\n if ax.legend_ is not None and self._extract_legend_handles:\n handles = ax.legend_.legendHandles\n labels = [t.get_text() for t in ax.legend_.texts]\n data.update({l: h for h, l in zip(handles, labels)})\n\n handles, labels = ax.get_legend_handles_labels()\n data.update({l: h for h, l in zip(handles, labels)})\n\n self._legend_data.update(data)\n\n # Now clear the legend\n ax.legend_ = None\n\n def _get_palette(self, data, hue, hue_order, palette):\n \"\"\"Get a list of colors for the hue variable.\"\"\"\n if hue is None:\n palette = color_palette(n_colors=1)\n\n else:\n hue_names = categorical_order(data[hue], hue_order)\n n_colors = len(hue_names)\n\n # By default use either the current color palette or HUSL\n if palette is None:\n current_palette = utils.get_color_cycle()\n if n_colors > len(current_palette):\n colors = color_palette(\"husl\", n_colors)\n else:\n colors = color_palette(n_colors=n_colors)\n\n # Allow for palette to map from hue variable names\n elif isinstance(palette, dict):\n color_names = [palette[h] for h in hue_names]\n colors = color_palette(color_names, n_colors)\n\n # Otherwise act as if we just got a list of colors\n else:\n colors = color_palette(palette, n_colors)\n\n palette = color_palette(colors, n_colors)\n\n return palette\n\n @property\n def legend(self):\n \"\"\"The :class:`matplotlib.legend.Legend` object, if present.\"\"\"\n try:\n return self._legend\n except AttributeError:\n return None\n\n def tick_params(self, axis='both', **kwargs):\n \"\"\"Modify the ticks, tick labels, and gridlines.\n\n Parameters\n ----------\n axis : {'x', 'y', 'both'}\n The axis on which to apply the formatting.\n kwargs : keyword arguments\n Additional keyword arguments to pass to\n :meth:`matplotlib.axes.Axes.tick_params`.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n \"\"\"\n for ax in self.figure.axes:\n ax.tick_params(axis=axis, **kwargs)\n return self"},{"className":"_BaseGrid","col":0,"comment":"Base class for grids of subplots.","endLoc":95,"id":341,"nodeType":"Class","startLoc":32,"text":"class _BaseGrid:\n \"\"\"Base class for grids of subplots.\"\"\"\n\n def set(self, **kwargs):\n \"\"\"Set attributes on each subplot Axes.\"\"\"\n for ax in self.axes.flat:\n if ax is not None: # Handle removed axes\n ax.set(**kwargs)\n return self\n\n @property\n def fig(self):\n \"\"\"DEPRECATED: prefer the `figure` property.\"\"\"\n # Grid.figure is preferred because it matches the Axes attribute name.\n # But as the maintanace burden on having this property is minimal,\n # let's be slow about formally deprecating it. For now just note its deprecation\n # in the docstring; add a warning in version 0.13, and eventually remove it.\n return self._figure\n\n @property\n def figure(self):\n \"\"\"Access the :class:`matplotlib.figure.Figure` object underlying the grid.\"\"\"\n return self._figure\n\n def apply(self, func, *args, **kwargs):\n \"\"\"\n Pass the grid to a user-supplied function and return self.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` is ignored; this method returns self.\n See the `pipe` method if you want the return value.\n\n Added in v0.12.0.\n\n \"\"\"\n func(self, *args, **kwargs)\n return self\n\n def pipe(self, func, *args, **kwargs):\n \"\"\"\n Pass the grid to a user-supplied function and return its value.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` becomes the return value of this method.\n See the `apply` method if you want to return self instead.\n\n Added in v0.12.0.\n\n \"\"\"\n return func(self, *args, **kwargs)\n\n def savefig(self, *args, **kwargs):\n \"\"\"\n Save an image of the plot.\n\n This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches=\"tight\"\n by default. Parameters are passed through to the matplotlib function.\n\n \"\"\"\n kwargs = kwargs.copy()\n kwargs.setdefault(\"bbox_inches\", \"tight\")\n self.figure.savefig(*args, **kwargs)"},{"col":4,"comment":"Set attributes on each subplot Axes.","endLoc":40,"header":"def set(self, **kwargs)","id":342,"name":"set","nodeType":"Function","startLoc":35,"text":"def set(self, **kwargs):\n \"\"\"Set attributes on each subplot Axes.\"\"\"\n for ax in self.axes.flat:\n if ax is not None: # Handle removed axes\n ax.set(**kwargs)\n return self"},{"col":4,"comment":"DEPRECATED: prefer the `figure` property.","endLoc":49,"header":"@property\n def fig(self)","id":343,"name":"fig","nodeType":"Function","startLoc":42,"text":"@property\n def fig(self):\n \"\"\"DEPRECATED: prefer the `figure` property.\"\"\"\n # Grid.figure is preferred because it matches the Axes attribute name.\n # But as the maintanace burden on having this property is minimal,\n # let's be slow about formally deprecating it. For now just note its deprecation\n # in the docstring; add a warning in version 0.13, and eventually remove it.\n return self._figure"},{"col":0,"comment":"Return full path to the user-specific cache dir for this application.\n\n \"appname\" is the name of application.\n If None, just the system directory is returned.\n \"appauthor\" (only used on Windows) is the name of the\n appauthor or distributing body for this application. Typically\n it is the owning company name. This falls back to appname. You may\n pass False to disable it.\n \"version\" is an optional version path element to append to the\n path. You might want to use this if you want multiple versions\n of your app to be able to run independently. If used, this\n would typically be \".\".\n Only applied when appname is present.\n \"opinion\" (boolean) can be False to disable the appending of\n \"Cache\" to the base app data dir for Windows. See\n discussion below.\n\n Typical user cache directories are:\n Mac OS X: ~/Library/Caches/\n Unix: ~/.cache/ (XDG default)\n Win XP: C:\\Documents and Settings\\\\Local Settings\\Application Data\\\\\\Cache\n Vista: C:\\Users\\\\AppData\\Local\\\\\\Cache\n\n On Windows the only suggestion in the MSDN docs is that local settings go in\n the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming\n app data dir (the default returned by `user_data_dir` above). Apps typically\n put cache data somewhere *under* the given dir here. Some examples:\n ...\\Mozilla\\Firefox\\Profiles\\\\Cache\n ...\\Acme\\SuperApp\\Cache\\1.0\n OPINION: This function appends \"Cache\" to the `CSIDL_LOCAL_APPDATA` value.\n This can be disabled with the `opinion=False` option.\n ","endLoc":127,"header":"def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True)","id":344,"name":"user_cache_dir","nodeType":"Function","startLoc":73,"text":"def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):\n r\"\"\"Return full path to the user-specific cache dir for this application.\n\n \"appname\" is the name of application.\n If None, just the system directory is returned.\n \"appauthor\" (only used on Windows) is the name of the\n appauthor or distributing body for this application. Typically\n it is the owning company name. This falls back to appname. You may\n pass False to disable it.\n \"version\" is an optional version path element to append to the\n path. You might want to use this if you want multiple versions\n of your app to be able to run independently. If used, this\n would typically be \".\".\n Only applied when appname is present.\n \"opinion\" (boolean) can be False to disable the appending of\n \"Cache\" to the base app data dir for Windows. See\n discussion below.\n\n Typical user cache directories are:\n Mac OS X: ~/Library/Caches/\n Unix: ~/.cache/ (XDG default)\n Win XP: C:\\Documents and Settings\\\\Local Settings\\Application Data\\\\\\Cache\n Vista: C:\\Users\\\\AppData\\Local\\\\\\Cache\n\n On Windows the only suggestion in the MSDN docs is that local settings go in\n the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming\n app data dir (the default returned by `user_data_dir` above). Apps typically\n put cache data somewhere *under* the given dir here. Some examples:\n ...\\Mozilla\\Firefox\\Profiles\\\\Cache\n ...\\Acme\\SuperApp\\Cache\\1.0\n OPINION: This function appends \"Cache\" to the `CSIDL_LOCAL_APPDATA` value.\n This can be disabled with the `opinion=False` option.\n \"\"\"\n if system == \"win32\":\n if appauthor is None:\n appauthor = appname\n path = os.path.normpath(_get_win_folder(\"CSIDL_LOCAL_APPDATA\"))\n if appname:\n if appauthor is not False:\n path = os.path.join(path, appauthor, appname)\n else:\n path = os.path.join(path, appname)\n if opinion:\n path = os.path.join(path, \"Cache\")\n elif system == 'darwin':\n path = os.path.expanduser('~/Library/Caches')\n if appname:\n path = os.path.join(path, appname)\n else:\n path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))\n if appname:\n path = os.path.join(path, appname)\n if appname and version:\n path = os.path.join(path, version)\n return path"},{"col":4,"comment":"Access the :class:`matplotlib.figure.Figure` object underlying the grid.","endLoc":54,"header":"@property\n def figure(self)","id":345,"name":"figure","nodeType":"Function","startLoc":51,"text":"@property\n def figure(self):\n \"\"\"Access the :class:`matplotlib.figure.Figure` object underlying the grid.\"\"\"\n return self._figure"},{"col":4,"comment":"\n Pass the grid to a user-supplied function and return self.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` is ignored; this method returns self.\n See the `pipe` method if you want the return value.\n\n Added in v0.12.0.\n\n ","endLoc":69,"header":"def apply(self, func, *args, **kwargs)","id":346,"name":"apply","nodeType":"Function","startLoc":56,"text":"def apply(self, func, *args, **kwargs):\n \"\"\"\n Pass the grid to a user-supplied function and return self.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` is ignored; this method returns self.\n See the `pipe` method if you want the return value.\n\n Added in v0.12.0.\n\n \"\"\"\n func(self, *args, **kwargs)\n return self"},{"attributeType":"int","col":4,"comment":"null","endLoc":58,"id":347,"name":"_priority","nodeType":"Attribute","startLoc":58,"text":"_priority"},{"col":4,"comment":"\n Pass the grid to a user-supplied function and return its value.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` becomes the return value of this method.\n See the `apply` method if you want to return self instead.\n\n Added in v0.12.0.\n\n ","endLoc":83,"header":"def pipe(self, func, *args, **kwargs)","id":348,"name":"pipe","nodeType":"Function","startLoc":71,"text":"def pipe(self, func, *args, **kwargs):\n \"\"\"\n Pass the grid to a user-supplied function and return its value.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` becomes the return value of this method.\n See the `apply` method if you want to return self instead.\n\n Added in v0.12.0.\n\n \"\"\"\n return func(self, *args, **kwargs)"},{"col":4,"comment":"\n Save an image of the plot.\n\n This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches=\"tight\"\n by default. Parameters are passed through to the matplotlib function.\n\n ","endLoc":95,"header":"def savefig(self, *args, **kwargs)","id":349,"name":"savefig","nodeType":"Function","startLoc":85,"text":"def savefig(self, *args, **kwargs):\n \"\"\"\n Save an image of the plot.\n\n This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches=\"tight\"\n by default. Parameters are passed through to the matplotlib function.\n\n \"\"\"\n kwargs = kwargs.copy()\n kwargs.setdefault(\"bbox_inches\", \"tight\")\n self.figure.savefig(*args, **kwargs)"},{"attributeType":"Sequence","col":4,"comment":"null","endLoc":59,"id":351,"name":"_pipeline","nodeType":"Attribute","startLoc":59,"text":"_pipeline"},{"col":0,"comment":"null","endLoc":177,"header":"def _get_win_folder_with_pywin32(csidl_name)","id":359,"name":"_get_win_folder_with_pywin32","nodeType":"Function","startLoc":153,"text":"def _get_win_folder_with_pywin32(csidl_name):\n from win32com.shell import shellcon, shell\n dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)\n # Try to make this a unicode path because SHGetFolderPath does\n # not return unicode strings when there is unicode data in the\n # path.\n try:\n dir = unicode(dir)\n\n # Downgrade to short path name if have highbit chars. See\n # .\n has_high_char = False\n for c in dir:\n if ord(c) > 255:\n has_high_char = True\n break\n if has_high_char:\n try:\n import win32api\n dir = win32api.GetShortPathName(dir)\n except ImportError:\n pass\n except UnicodeError:\n pass\n return dir"},{"attributeType":"null","col":4,"comment":"null","endLoc":60,"id":360,"name":"_matplotlib_scale","nodeType":"Attribute","startLoc":60,"text":"_matplotlib_scale"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":61,"id":363,"name":"_spacer","nodeType":"Attribute","startLoc":61,"text":"_spacer"},{"attributeType":"(list, list) | None","col":4,"comment":"null","endLoc":62,"id":364,"name":"_legend","nodeType":"Attribute","startLoc":62,"text":"_legend"},{"col":4,"comment":"null","endLoc":1085,"header":"def copy(self) -> dict[_KT, _VT]","id":365,"name":"copy","nodeType":"Function","startLoc":1085,"text":"def copy(self) -> dict[_KT, _VT]: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":66,"id":367,"name":"_tick_params","nodeType":"Attribute","startLoc":66,"text":"self._tick_params"},{"attributeType":"(list, list) | None","col":8,"comment":"null","endLoc":68,"id":368,"name":"_legend","nodeType":"Attribute","startLoc":68,"text":"self._legend"},{"col":0,"comment":"Report available example datasets, useful for reporting issues.\n\n Requires an internet connection.\n\n ","endLoc":513,"header":"def get_dataset_names()","id":369,"name":"get_dataset_names","nodeType":"Function","startLoc":501,"text":"def get_dataset_names():\n \"\"\"Report available example datasets, useful for reporting issues.\n\n Requires an internet connection.\n\n \"\"\"\n url = \"https://github.com/mwaskom/seaborn-data\"\n with urlopen(url) as resp:\n html = resp.read()\n\n pat = r\"/mwaskom/seaborn-data/blob/master/(\\w*).csv\"\n datasets = re.findall(pat, html.decode())\n return datasets"},{"col":4,"comment":"null","endLoc":110,"header":"def __init__(self)","id":370,"name":"__init__","nodeType":"Function","startLoc":103,"text":"def __init__(self):\n\n self._tight_layout_rect = [0, 0, 1, 1]\n self._tight_layout_pad = None\n\n # This attribute is set externally and is a hack to handle newer functions that\n # don't add proxy artists onto the Axes. We need an overall cleaner approach.\n self._extract_legend_handles = False"},{"col":4,"comment":"Call fig.tight_layout within rect that exclude the legend.","endLoc":119,"header":"def tight_layout(self, *args, **kwargs)","id":371,"name":"tight_layout","nodeType":"Function","startLoc":112,"text":"def tight_layout(self, *args, **kwargs):\n \"\"\"Call fig.tight_layout within rect that exclude the legend.\"\"\"\n kwargs = kwargs.copy()\n kwargs.setdefault(\"rect\", self._tight_layout_rect)\n if self._tight_layout_pad is not None:\n kwargs.setdefault(\"pad\", self._tight_layout_pad)\n self._figure.tight_layout(*args, **kwargs)\n return self"},{"attributeType":"null","col":8,"comment":"null","endLoc":67,"id":372,"name":"_label_params","nodeType":"Attribute","startLoc":67,"text":"self._label_params"},{"className":"BarBase","col":0,"comment":"null","endLoc":103,"id":373,"nodeType":"Class","startLoc":28,"text":"class BarBase(Mark):\n\n def _make_patches(self, data, scales, orient):\n\n kws = self._resolve_properties(data, scales)\n if orient == \"x\":\n kws[\"x\"] = (data[\"x\"] - data[\"width\"] / 2).to_numpy()\n kws[\"y\"] = data[\"baseline\"].to_numpy()\n kws[\"w\"] = data[\"width\"].to_numpy()\n kws[\"h\"] = (data[\"y\"] - data[\"baseline\"]).to_numpy()\n else:\n kws[\"x\"] = data[\"baseline\"].to_numpy()\n kws[\"y\"] = (data[\"y\"] - data[\"width\"] / 2).to_numpy()\n kws[\"w\"] = (data[\"x\"] - data[\"baseline\"]).to_numpy()\n kws[\"h\"] = data[\"width\"].to_numpy()\n\n kws.pop(\"width\", None)\n kws.pop(\"baseline\", None)\n\n val_dim = {\"x\": \"h\", \"y\": \"w\"}[orient]\n bars, vals = [], []\n\n for i in range(len(data)):\n\n row = {k: v[i] for k, v in kws.items()}\n\n # Skip bars with no value. It's possible we'll want to make this\n # an option (i.e so you have an artist for animating or annotating),\n # but let's keep things simple for now.\n if not np.nan_to_num(row[val_dim]):\n continue\n\n bar = mpl.patches.Rectangle(\n xy=(row[\"x\"], row[\"y\"]),\n width=row[\"w\"],\n height=row[\"h\"],\n facecolor=row[\"facecolor\"],\n edgecolor=row[\"edgecolor\"],\n linestyle=row[\"edgestyle\"],\n linewidth=row[\"edgewidth\"],\n **self.artist_kws,\n )\n bars.append(bar)\n vals.append(row[val_dim])\n\n return bars, vals\n\n def _resolve_properties(self, data, scales):\n\n resolved = resolve_properties(self, data, scales)\n\n resolved[\"facecolor\"] = resolve_color(self, data, \"\", scales)\n resolved[\"edgecolor\"] = resolve_color(self, data, \"edge\", scales)\n\n fc = resolved[\"facecolor\"]\n if isinstance(fc, tuple):\n resolved[\"facecolor\"] = fc[0], fc[1], fc[2], fc[3] * resolved[\"fill\"]\n else:\n fc[:, 3] = fc[:, 3] * resolved[\"fill\"] # TODO Is inplace mod a problem?\n resolved[\"facecolor\"] = fc\n\n return resolved\n\n def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n # TODO return some sensible default?\n key = {v: value for v in variables}\n key = self._resolve_properties(key, scales)\n artist = mpl.patches.Patch(\n facecolor=key[\"facecolor\"],\n edgecolor=key[\"edgecolor\"],\n linewidth=key[\"edgewidth\"],\n linestyle=key[\"edgestyle\"],\n )\n return artist"},{"col":4,"comment":"null","endLoc":73,"header":"def _make_patches(self, data, scales, orient)","id":374,"name":"_make_patches","nodeType":"Function","startLoc":30,"text":"def _make_patches(self, data, scales, orient):\n\n kws = self._resolve_properties(data, scales)\n if orient == \"x\":\n kws[\"x\"] = (data[\"x\"] - data[\"width\"] / 2).to_numpy()\n kws[\"y\"] = data[\"baseline\"].to_numpy()\n kws[\"w\"] = data[\"width\"].to_numpy()\n kws[\"h\"] = (data[\"y\"] - data[\"baseline\"]).to_numpy()\n else:\n kws[\"x\"] = data[\"baseline\"].to_numpy()\n kws[\"y\"] = (data[\"y\"] - data[\"width\"] / 2).to_numpy()\n kws[\"w\"] = (data[\"x\"] - data[\"baseline\"]).to_numpy()\n kws[\"h\"] = data[\"width\"].to_numpy()\n\n kws.pop(\"width\", None)\n kws.pop(\"baseline\", None)\n\n val_dim = {\"x\": \"h\", \"y\": \"w\"}[orient]\n bars, vals = [], []\n\n for i in range(len(data)):\n\n row = {k: v[i] for k, v in kws.items()}\n\n # Skip bars with no value. It's possible we'll want to make this\n # an option (i.e so you have an artist for animating or annotating),\n # but let's keep things simple for now.\n if not np.nan_to_num(row[val_dim]):\n continue\n\n bar = mpl.patches.Rectangle(\n xy=(row[\"x\"], row[\"y\"]),\n width=row[\"w\"],\n height=row[\"h\"],\n facecolor=row[\"facecolor\"],\n edgecolor=row[\"edgecolor\"],\n linestyle=row[\"edgestyle\"],\n linewidth=row[\"edgewidth\"],\n **self.artist_kws,\n )\n bars.append(bar)\n vals.append(row[val_dim])\n\n return bars, vals"},{"col":4,"comment":"null","endLoc":70,"header":"def urlopen(\n url: str | Request,\n data: _DataType | None = None,\n timeout: float | None = ...,\n *,\n cafile: str | None = None,\n capath: str | None = None,\n cadefault: bool = False,\n context: ssl.SSLContext | None = None,\n ) -> _UrlopenRet","id":375,"name":"urlopen","nodeType":"Function","startLoc":61,"text":"def urlopen(\n url: str | Request,\n data: _DataType | None = None,\n timeout: float | None = ...,\n *,\n cafile: str | None = None,\n capath: str | None = None,\n cadefault: bool = False,\n context: ssl.SSLContext | None = None,\n ) -> _UrlopenRet: ..."},{"col":0,"comment":"null","endLoc":383,"header":"def _parse_letter_version(\n letter: str, number: Union[str, bytes, SupportsInt]\n) -> Optional[Tuple[str, int]]","id":377,"name":"_parse_letter_version","nodeType":"Function","startLoc":350,"text":"def _parse_letter_version(\n letter: str, number: Union[str, bytes, SupportsInt]\n) -> Optional[Tuple[str, int]]:\n\n if letter:\n # We consider there to be an implicit 0 in a pre-release if there is\n # not a numeral associated with it.\n if number is None:\n number = 0\n\n # We normalize any letters to their lower case form\n letter = letter.lower()\n\n # We consider some words to be alternate spellings of other words and\n # in those cases we want to normalize the spellings to our preferred\n # spelling.\n if letter == \"alpha\":\n letter = \"a\"\n elif letter == \"beta\":\n letter = \"b\"\n elif letter in [\"c\", \"pre\", \"preview\"]:\n letter = \"rc\"\n elif letter in [\"rev\", \"r\"]:\n letter = \"post\"\n\n return letter, int(number)\n if not letter and number:\n # We assume if we are given a number, but we are not given a letter\n # then this is using the implicit post release syntax (e.g. 1.0-1)\n letter = \"post\"\n\n return letter, int(number)\n\n return None"},{"col":4,"comment":"Draw a legend, maybe placing it outside axes and resizing the figure.\n\n Parameters\n ----------\n legend_data : dict\n Dictionary mapping label names (or two-element tuples where the\n second element is a label name) to matplotlib artist handles. The\n default reads from ``self._legend_data``.\n title : string\n Title for the legend. The default reads from ``self._hue_var``.\n label_order : list of labels\n The order that the legend entries should appear in. The default\n reads from ``self.hue_names``.\n adjust_subtitles : bool\n If True, modify entries with invisible artists to left-align\n the labels and set the font size to that of a title.\n kwargs : key, value pairings\n Other keyword arguments are passed to the underlying legend methods\n on the Figure or Axes object.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n ","endLoc":223,"header":"def add_legend(self, legend_data=None, title=None, label_order=None,\n adjust_subtitles=False, **kwargs)","id":378,"name":"add_legend","nodeType":"Function","startLoc":121,"text":"def add_legend(self, legend_data=None, title=None, label_order=None,\n adjust_subtitles=False, **kwargs):\n \"\"\"Draw a legend, maybe placing it outside axes and resizing the figure.\n\n Parameters\n ----------\n legend_data : dict\n Dictionary mapping label names (or two-element tuples where the\n second element is a label name) to matplotlib artist handles. The\n default reads from ``self._legend_data``.\n title : string\n Title for the legend. The default reads from ``self._hue_var``.\n label_order : list of labels\n The order that the legend entries should appear in. The default\n reads from ``self.hue_names``.\n adjust_subtitles : bool\n If True, modify entries with invisible artists to left-align\n the labels and set the font size to that of a title.\n kwargs : key, value pairings\n Other keyword arguments are passed to the underlying legend methods\n on the Figure or Axes object.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n \"\"\"\n # Find the data for the legend\n if legend_data is None:\n legend_data = self._legend_data\n if label_order is None:\n if self.hue_names is None:\n label_order = list(legend_data.keys())\n else:\n label_order = list(map(utils.to_utf8, self.hue_names))\n\n blank_handle = mpl.patches.Patch(alpha=0, linewidth=0)\n handles = [legend_data.get(l, blank_handle) for l in label_order]\n title = self._hue_var if title is None else title\n title_size = mpl.rcParams[\"legend.title_fontsize\"]\n\n # Unpack nested labels from a hierarchical legend\n labels = []\n for entry in label_order:\n if isinstance(entry, tuple):\n _, label = entry\n else:\n label = entry\n labels.append(label)\n\n # Set default legend kwargs\n kwargs.setdefault(\"scatterpoints\", 1)\n\n if self._legend_out:\n\n kwargs.setdefault(\"frameon\", False)\n kwargs.setdefault(\"loc\", \"center right\")\n\n # Draw a full-figure legend outside the grid\n figlegend = self._figure.legend(handles, labels, **kwargs)\n\n self._legend = figlegend\n figlegend.set_title(title, prop={\"size\": title_size})\n\n if adjust_subtitles:\n adjust_legend_subtitles(figlegend)\n\n # Draw the plot to set the bounding boxes correctly\n _draw_figure(self._figure)\n\n # Calculate and set the new width of the figure so the legend fits\n legend_width = figlegend.get_window_extent().width / self._figure.dpi\n fig_width, fig_height = self._figure.get_size_inches()\n self._figure.set_size_inches(fig_width + legend_width, fig_height)\n\n # Draw the plot again to get the new transformations\n _draw_figure(self._figure)\n\n # Now calculate how much space we need on the right side\n legend_width = figlegend.get_window_extent().width / self._figure.dpi\n space_needed = legend_width / (fig_width + legend_width)\n margin = .04 if self._margin_titles else .01\n self._space_needed = margin + space_needed\n right = 1 - self._space_needed\n\n # Place the subplot axes to give space for the legend\n self._figure.subplots_adjust(right=right)\n self._tight_layout_rect[2] = right\n\n else:\n # Draw a legend in the first axis\n ax = self.axes.flat[0]\n kwargs.setdefault(\"loc\", \"best\")\n\n leg = ax.legend(handles, labels, **kwargs)\n leg.set_title(title, prop={\"size\": title_size})\n self._legend = leg\n\n if adjust_subtitles:\n adjust_legend_subtitles(leg)\n\n return self"},{"col":4,"comment":"null","endLoc":1086,"header":"def keys(self) -> dict_keys[_KT, _VT]","id":381,"name":"keys","nodeType":"Function","startLoc":1086,"text":"def keys(self) -> dict_keys[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":1067,"header":"@overload\n def __init__(self) -> None","id":382,"name":"__init__","nodeType":"Function","startLoc":1066,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":1069,"header":"@overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None","id":383,"name":"__init__","nodeType":"Function","startLoc":1068,"text":"@overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1071,"header":"@overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None","id":384,"name":"__init__","nodeType":"Function","startLoc":1070,"text":"@overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ..."},{"col":4,"comment":"null","endLoc":1073,"header":"@overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None","id":385,"name":"__init__","nodeType":"Function","startLoc":1072,"text":"@overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1075,"header":"@overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None","id":386,"name":"__init__","nodeType":"Function","startLoc":1074,"text":"@overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ..."},{"col":4,"comment":"null","endLoc":1077,"header":"@overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None","id":387,"name":"__init__","nodeType":"Function","startLoc":1076,"text":"@overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1081,"header":"@overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None","id":388,"name":"__init__","nodeType":"Function","startLoc":1080,"text":"@overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ..."},{"col":4,"comment":"null","endLoc":1083,"header":"@overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None","id":389,"name":"__init__","nodeType":"Function","startLoc":1082,"text":"@overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ..."},{"col":0,"comment":"null","endLoc":317,"header":"def urlretrieve(\n url: str,\n filename: StrOrBytesPath | None = None,\n reporthook: Callable[[int, int, int], object] | None = None,\n data: _DataType = None,\n) -> tuple[str, HTTPMessage]","id":393,"name":"urlretrieve","nodeType":"Function","startLoc":312,"text":"def urlretrieve(\n url: str,\n filename: StrOrBytesPath | None = None,\n reporthook: Callable[[int, int, int], object] | None = None,\n data: _DataType = None,\n) -> tuple[str, HTTPMessage]: ..."},{"col":0,"comment":"\n Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n ","endLoc":398,"header":"def _parse_local_version(local: str) -> Optional[LocalType]","id":394,"name":"_parse_local_version","nodeType":"Function","startLoc":389,"text":"def _parse_local_version(local: str) -> Optional[LocalType]:\n \"\"\"\n Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n \"\"\"\n if local is not None:\n return tuple(\n part.lower() if not part.isdigit() else int(part)\n for part in _local_version_separators.split(local)\n )\n return None"},{"id":395,"name":"tests","nodeType":"Package"},{"fileName":"test_distributions.py","filePath":"tests","id":396,"nodeType":"File","text":"import itertools\nimport warnings\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import to_rgb, to_rgba\n\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom seaborn import distributions as dist\nfrom seaborn.palettes import (\n color_palette,\n light_palette,\n)\nfrom seaborn._oldcore import (\n categorical_order,\n)\nfrom seaborn._statistics import (\n KDE,\n Histogram,\n _no_scipy,\n)\nfrom seaborn.distributions import (\n _DistributionPlotter,\n displot,\n distplot,\n histplot,\n ecdfplot,\n kdeplot,\n rugplot,\n)\nfrom seaborn.external.version import Version\nfrom seaborn.axisgrid import FacetGrid\nfrom seaborn._testing import (\n assert_plots_equal,\n assert_legends_equal,\n assert_colors_equal,\n)\n\n\ndef get_contour_coords(c):\n \"\"\"Provide compatability for change in contour artist type in mpl3.5.\"\"\"\n # See https://github.com/matplotlib/matplotlib/issues/20906\n if isinstance(c, mpl.collections.LineCollection):\n return c.get_segments()\n elif isinstance(c, mpl.collections.PathCollection):\n return [p.vertices[:np.argmax(p.codes) + 1] for p in c.get_paths()]\n\n\ndef get_contour_color(c):\n \"\"\"Provide compatability for change in contour artist type in mpl3.5.\"\"\"\n # See https://github.com/matplotlib/matplotlib/issues/20906\n if isinstance(c, mpl.collections.LineCollection):\n return c.get_color()\n elif isinstance(c, mpl.collections.PathCollection):\n if c.get_facecolor().size:\n return c.get_facecolor()\n else:\n return c.get_edgecolor()\n\n\nclass TestDistPlot:\n\n rs = np.random.RandomState(0)\n x = rs.randn(100)\n\n def test_hist_bins(self):\n\n fd_edges = np.histogram_bin_edges(self.x, \"fd\")\n with pytest.warns(UserWarning):\n ax = distplot(self.x)\n for edge, bar in zip(fd_edges, ax.patches):\n assert pytest.approx(edge) == bar.get_x()\n\n plt.close(ax.figure)\n n = 25\n n_edges = np.histogram_bin_edges(self.x, n)\n with pytest.warns(UserWarning):\n ax = distplot(self.x, bins=n)\n for edge, bar in zip(n_edges, ax.patches):\n assert pytest.approx(edge) == bar.get_x()\n\n def test_elements(self):\n\n with pytest.warns(UserWarning):\n\n n = 10\n ax = distplot(self.x, bins=n,\n hist=True, kde=False, rug=False, fit=None)\n assert len(ax.patches) == 10\n assert len(ax.lines) == 0\n assert len(ax.collections) == 0\n\n plt.close(ax.figure)\n ax = distplot(self.x,\n hist=False, kde=True, rug=False, fit=None)\n assert len(ax.patches) == 0\n assert len(ax.lines) == 1\n assert len(ax.collections) == 0\n\n plt.close(ax.figure)\n ax = distplot(self.x,\n hist=False, kde=False, rug=True, fit=None)\n assert len(ax.patches) == 0\n assert len(ax.lines) == 0\n assert len(ax.collections) == 1\n\n class Norm:\n \"\"\"Dummy object that looks like a scipy RV\"\"\"\n def fit(self, x):\n return ()\n\n def pdf(self, x, *params):\n return np.zeros_like(x)\n\n plt.close(ax.figure)\n ax = distplot(\n self.x, hist=False, kde=False, rug=False, fit=Norm())\n assert len(ax.patches) == 0\n assert len(ax.lines) == 1\n assert len(ax.collections) == 0\n\n def test_distplot_with_nans(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n x_null = np.append(self.x, [np.nan])\n\n with pytest.warns(UserWarning):\n distplot(self.x, ax=ax1)\n distplot(x_null, ax=ax2)\n\n line1 = ax1.lines[0]\n line2 = ax2.lines[0]\n assert np.array_equal(line1.get_xydata(), line2.get_xydata())\n\n for bar1, bar2 in zip(ax1.patches, ax2.patches):\n assert bar1.get_xy() == bar2.get_xy()\n assert bar1.get_height() == bar2.get_height()\n\n\nclass SharedAxesLevelTests:\n\n def test_color(self, long_df, **kwargs):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C0\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C1\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", color=\"C2\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C2\", check_alpha=False)\n\n\nclass TestRugPlot(SharedAxesLevelTests):\n\n func = staticmethod(rugplot)\n\n def get_last_color(self, ax, **kwargs):\n\n return ax.collections[-1].get_color()\n\n def assert_rug_equal(self, a, b):\n\n assert_array_equal(a.get_segments(), b.get_segments())\n\n @pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_data(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, np.asarray(vector), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n rugplot(data=long_df, **{variable: vector})\n\n for a, b in itertools.product(ax.collections, ax.collections):\n self.assert_rug_equal(a, b)\n\n def test_bivariate_data(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n rugplot(data=long_df, x=\"x\", y=\"y\", ax=ax1)\n rugplot(data=long_df, x=\"x\", ax=ax2)\n rugplot(data=long_df, y=\"y\", ax=ax2)\n\n self.assert_rug_equal(ax1.collections[0], ax2.collections[0])\n self.assert_rug_equal(ax1.collections[1], ax2.collections[1])\n\n def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n rugplot(data=wide_df, ax=ax1)\n for col in wide_df:\n rugplot(data=wide_df, x=col, ax=ax2)\n\n wide_segments = np.sort(\n np.array(ax1.collections[0].get_segments())\n )\n long_segments = np.sort(\n np.concatenate([c.get_segments() for c in ax2.collections])\n )\n\n assert_array_equal(wide_segments, long_segments)\n\n def test_flat_vector(self, long_df):\n\n f, ax = plt.subplots()\n rugplot(data=long_df[\"x\"])\n rugplot(x=long_df[\"x\"])\n self.assert_rug_equal(*ax.collections)\n\n def test_datetime_data(self, long_df):\n\n ax = rugplot(data=long_df[\"t\"])\n vals = np.stack(ax.collections[0].get_segments())[:, 0, 0]\n assert_array_equal(vals, mpl.dates.date2num(long_df[\"t\"]))\n\n def test_empty_data(self):\n\n ax = rugplot(x=[])\n assert not ax.collections\n\n def test_a_deprecation(self, flat_series):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(a=flat_series)\n rugplot(x=flat_series)\n\n self.assert_rug_equal(*ax.collections)\n\n @pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_axis_deprecation(self, flat_series, variable):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(flat_series, axis=variable)\n rugplot(**{variable: flat_series})\n\n self.assert_rug_equal(*ax.collections)\n\n def test_vertical_deprecation(self, flat_series):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(flat_series, vertical=True)\n rugplot(y=flat_series)\n\n self.assert_rug_equal(*ax.collections)\n\n def test_rug_data(self, flat_array):\n\n height = .05\n ax = rugplot(x=flat_array, height=height)\n segments = np.stack(ax.collections[0].get_segments())\n\n n = flat_array.size\n assert_array_equal(segments[:, 0, 1], np.zeros(n))\n assert_array_equal(segments[:, 1, 1], np.full(n, height))\n assert_array_equal(segments[:, 1, 0], flat_array)\n\n def test_rug_colors(self, long_df):\n\n ax = rugplot(data=long_df, x=\"x\", hue=\"a\")\n\n order = categorical_order(long_df[\"a\"])\n palette = color_palette()\n\n expected_colors = np.ones((len(long_df), 4))\n for i, val in enumerate(long_df[\"a\"]):\n expected_colors[i, :3] = palette[order.index(val)]\n\n assert_array_equal(ax.collections[0].get_color(), expected_colors)\n\n def test_expand_margins(self, flat_array):\n\n f, ax = plt.subplots()\n x1, y1 = ax.margins()\n rugplot(x=flat_array, expand_margins=False)\n x2, y2 = ax.margins()\n assert x1 == x2\n assert y1 == y2\n\n f, ax = plt.subplots()\n x1, y1 = ax.margins()\n height = .05\n rugplot(x=flat_array, height=height)\n x2, y2 = ax.margins()\n assert x1 == x2\n assert y1 + height * 2 == pytest.approx(y2)\n\n def test_multiple_rugs(self):\n\n values = np.linspace(start=0, stop=1, num=5)\n ax = rugplot(x=values)\n ylim = ax.get_ylim()\n\n rugplot(x=values, ax=ax, expand_margins=False)\n\n assert ylim == ax.get_ylim()\n\n def test_matplotlib_kwargs(self, flat_series):\n\n lw = 2\n alpha = .2\n ax = rugplot(y=flat_series, linewidth=lw, alpha=alpha)\n rug = ax.collections[0]\n assert np.all(rug.get_alpha() == alpha)\n assert np.all(rug.get_linewidth() == lw)\n\n def test_axis_labels(self, flat_series):\n\n ax = rugplot(x=flat_series)\n assert ax.get_xlabel() == flat_series.name\n assert not ax.get_ylabel()\n\n def test_log_scale(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n\n ax2.set_xscale(\"log\")\n\n rugplot(data=long_df, x=\"z\", ax=ax1)\n rugplot(data=long_df, x=\"z\", ax=ax2)\n\n rug1 = np.stack(ax1.collections[0].get_segments())\n rug2 = np.stack(ax2.collections[0].get_segments())\n\n assert_array_almost_equal(rug1, rug2)\n\n\nclass TestKDEPlotUnivariate(SharedAxesLevelTests):\n\n func = staticmethod(kdeplot)\n\n def get_last_color(self, ax, fill=True):\n\n if fill:\n return ax.collections[-1].get_facecolor()\n else:\n return ax.lines[-1].get_color()\n\n @pytest.mark.parametrize(\"fill\", [True, False])\n def test_color(self, long_df, fill):\n\n super().test_color(long_df, fill=fill)\n\n if fill:\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", facecolor=\"C3\", fill=True, ax=ax)\n assert_colors_equal(self.get_last_color(ax), \"C3\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", fc=\"C4\", fill=True, ax=ax)\n assert_colors_equal(self.get_last_color(ax), \"C4\", check_alpha=False)\n\n @pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n kdeplot(data=long_df, **{variable: vector})\n\n xdata = [l.get_xdata() for l in ax.lines]\n for a, b in itertools.product(xdata, xdata):\n assert_array_equal(a, b)\n\n ydata = [l.get_ydata() for l in ax.lines]\n for a, b in itertools.product(ydata, ydata):\n assert_array_equal(a, b)\n\n def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(data=wide_df, ax=ax1, common_norm=False, common_grid=False)\n for col in wide_df:\n kdeplot(data=wide_df, x=col, ax=ax2)\n\n for l1, l2 in zip(ax1.lines[::-1], ax2.lines):\n assert_array_equal(l1.get_xydata(), l2.get_xydata())\n\n def test_flat_vector(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df[\"x\"])\n kdeplot(x=long_df[\"x\"])\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_empty_data(self):\n\n ax = kdeplot(x=[])\n assert not ax.lines\n\n def test_singular_data(self):\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=np.ones(10))\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=[5])\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n # https://github.com/mwaskom/seaborn/issues/2762\n ax = kdeplot(x=[1929245168.06679] * 18)\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\", UserWarning)\n ax = kdeplot(x=[5], warn_singular=False)\n assert not ax.lines\n\n def test_variable_assignment(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", fill=True)\n kdeplot(data=long_df, y=\"x\", fill=True)\n\n v0 = ax.collections[0].get_paths()[0].vertices\n v1 = ax.collections[1].get_paths()[0].vertices[:, [1, 0]]\n\n assert_array_equal(v0, v1)\n\n def test_vertical_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, y=\"x\")\n\n with pytest.warns(UserWarning):\n kdeplot(data=long_df, x=\"x\", vertical=True)\n\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_bw_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", bw_method=\"silverman\")\n\n with pytest.warns(UserWarning):\n kdeplot(data=long_df, x=\"x\", bw=\"silverman\")\n\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_kernel_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\")\n\n with pytest.warns(UserWarning):\n kdeplot(data=long_df, x=\"x\", kernel=\"epi\")\n\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_shade_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n with pytest.warns(FutureWarning):\n kdeplot(data=long_df, x=\"x\", shade=True)\n kdeplot(data=long_df, x=\"x\", fill=True)\n fill1, fill2 = ax.collections\n assert_array_equal(\n fill1.get_paths()[0].vertices, fill2.get_paths()[0].vertices\n )\n\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"stack\", \"fill\"])\n def test_hue_colors(self, long_df, multiple):\n\n ax = kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=multiple,\n fill=True, legend=False\n )\n\n # Note that hue order is reversed in the plot\n lines = ax.lines[::-1]\n fills = ax.collections[::-1]\n\n palette = color_palette()\n\n for line, fill, color in zip(lines, fills, palette):\n assert_colors_equal(line.get_color(), color)\n assert_colors_equal(fill.get_facecolor(), to_rgba(color, .25))\n\n def test_hue_stacking(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"layer\", common_grid=True,\n legend=False, ax=ax1,\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"stack\", fill=False,\n legend=False, ax=ax2,\n )\n\n layered_densities = np.stack([\n l.get_ydata() for l in ax1.lines\n ])\n stacked_densities = np.stack([\n l.get_ydata() for l in ax2.lines\n ])\n\n assert_array_equal(layered_densities.cumsum(axis=0), stacked_densities)\n\n def test_hue_filling(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"layer\", common_grid=True,\n legend=False, ax=ax1,\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"fill\", fill=False,\n legend=False, ax=ax2,\n )\n\n layered = np.stack([l.get_ydata() for l in ax1.lines])\n filled = np.stack([l.get_ydata() for l in ax2.lines])\n\n assert_array_almost_equal(\n (layered / layered.sum(axis=0)).cumsum(axis=0),\n filled,\n )\n\n @pytest.mark.parametrize(\"multiple\", [\"stack\", \"fill\"])\n def test_fill_default(self, long_df, multiple):\n\n ax = kdeplot(\n data=long_df, x=\"x\", hue=\"a\", multiple=multiple, fill=None\n )\n\n assert len(ax.collections) > 0\n\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"stack\", \"fill\"])\n def test_fill_nondefault(self, long_df, multiple):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\")\n kdeplot(**kws, multiple=multiple, fill=False, ax=ax1)\n kdeplot(**kws, multiple=multiple, fill=True, ax=ax2)\n\n assert len(ax1.collections) == 0\n assert len(ax2.collections) > 0\n\n def test_color_cycle_interaction(self, flat_series):\n\n color = (.2, 1, .6)\n\n f, ax = plt.subplots()\n kdeplot(flat_series)\n kdeplot(flat_series)\n assert_colors_equal(ax.lines[0].get_color(), \"C0\")\n assert_colors_equal(ax.lines[1].get_color(), \"C1\")\n plt.close(f)\n\n f, ax = plt.subplots()\n kdeplot(flat_series, color=color)\n kdeplot(flat_series)\n assert_colors_equal(ax.lines[0].get_color(), color)\n assert_colors_equal(ax.lines[1].get_color(), \"C0\")\n plt.close(f)\n\n f, ax = plt.subplots()\n kdeplot(flat_series, fill=True)\n kdeplot(flat_series, fill=True)\n assert_colors_equal(ax.collections[0].get_facecolor(), to_rgba(\"C0\", .25))\n assert_colors_equal(ax.collections[1].get_facecolor(), to_rgba(\"C1\", .25))\n plt.close(f)\n\n @pytest.mark.parametrize(\"fill\", [True, False])\n def test_artist_color(self, long_df, fill):\n\n color = (.2, 1, .6)\n alpha = .5\n\n f, ax = plt.subplots()\n\n kdeplot(long_df[\"x\"], fill=fill, color=color)\n if fill:\n artist_color = ax.collections[-1].get_facecolor().squeeze()\n else:\n artist_color = ax.lines[-1].get_color()\n default_alpha = .25 if fill else 1\n assert_colors_equal(artist_color, to_rgba(color, default_alpha))\n\n kdeplot(long_df[\"x\"], fill=fill, color=color, alpha=alpha)\n if fill:\n artist_color = ax.collections[-1].get_facecolor().squeeze()\n else:\n artist_color = ax.lines[-1].get_color()\n assert_colors_equal(artist_color, to_rgba(color, alpha))\n\n def test_datetime_scale(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n kdeplot(x=long_df[\"t\"], fill=True, ax=ax1)\n kdeplot(x=long_df[\"t\"], fill=False, ax=ax2)\n assert ax1.get_xlim() == ax2.get_xlim()\n\n def test_multiple_argument_check(self, long_df):\n\n with pytest.raises(ValueError, match=\"`multiple` must be\"):\n kdeplot(data=long_df, x=\"x\", hue=\"a\", multiple=\"bad_input\")\n\n def test_cut(self, rng):\n\n x = rng.normal(0, 3, 1000)\n\n f, ax = plt.subplots()\n kdeplot(x=x, cut=0, legend=False)\n\n xdata_0 = ax.lines[0].get_xdata()\n assert xdata_0.min() == x.min()\n assert xdata_0.max() == x.max()\n\n kdeplot(x=x, cut=2, legend=False)\n\n xdata_2 = ax.lines[1].get_xdata()\n assert xdata_2.min() < xdata_0.min()\n assert xdata_2.max() > xdata_0.max()\n\n assert len(xdata_0) == len(xdata_2)\n\n def test_clip(self, rng):\n\n x = rng.normal(0, 3, 1000)\n\n clip = -1, 1\n ax = kdeplot(x=x, clip=clip)\n\n xdata = ax.lines[0].get_xdata()\n\n assert xdata.min() >= clip[0]\n assert xdata.max() <= clip[1]\n\n def test_line_is_density(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", cut=5)\n x, y = ax.lines[0].get_xydata().T\n assert integrate(y, x) == pytest.approx(1)\n\n @pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n def test_cumulative(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", cut=5, cumulative=True)\n y = ax.lines[0].get_ydata()\n assert y[0] == pytest.approx(0)\n assert y[-1] == pytest.approx(1)\n\n @pytest.mark.skipif(not _no_scipy, reason=\"Test requires scipy's absence\")\n def test_cumulative_requires_scipy(self, long_df):\n\n with pytest.raises(RuntimeError):\n kdeplot(data=long_df, x=\"x\", cut=5, cumulative=True)\n\n def test_common_norm(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"c\", common_norm=True, cut=10, ax=ax1\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"c\", common_norm=False, cut=10, ax=ax2\n )\n\n total_area = 0\n for line in ax1.lines:\n xdata, ydata = line.get_xydata().T\n total_area += integrate(ydata, xdata)\n assert total_area == pytest.approx(1)\n\n for line in ax2.lines:\n xdata, ydata = line.get_xydata().T\n assert integrate(ydata, xdata) == pytest.approx(1)\n\n def test_common_grid(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n order = \"a\", \"b\", \"c\"\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\", hue_order=order,\n common_grid=False, cut=0, ax=ax1,\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\", hue_order=order,\n common_grid=True, cut=0, ax=ax2,\n )\n\n for line, level in zip(ax1.lines[::-1], order):\n xdata = line.get_xdata()\n assert xdata.min() == long_df.loc[long_df[\"a\"] == level, \"x\"].min()\n assert xdata.max() == long_df.loc[long_df[\"a\"] == level, \"x\"].max()\n\n for line in ax2.lines:\n xdata = line.get_xdata().T\n assert xdata.min() == long_df[\"x\"].min()\n assert xdata.max() == long_df[\"x\"].max()\n\n def test_bw_method(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", bw_method=0.2, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_method=1.0, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_method=3.0, legend=False)\n\n l1, l2, l3 = ax.lines\n\n assert (\n np.abs(np.diff(l1.get_ydata())).mean()\n > np.abs(np.diff(l2.get_ydata())).mean()\n )\n\n assert (\n np.abs(np.diff(l2.get_ydata())).mean()\n > np.abs(np.diff(l3.get_ydata())).mean()\n )\n\n def test_bw_adjust(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", bw_adjust=0.2, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_adjust=1.0, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_adjust=3.0, legend=False)\n\n l1, l2, l3 = ax.lines\n\n assert (\n np.abs(np.diff(l1.get_ydata())).mean()\n > np.abs(np.diff(l2.get_ydata())).mean()\n )\n\n assert (\n np.abs(np.diff(l2.get_ydata())).mean()\n > np.abs(np.diff(l3.get_ydata())).mean()\n )\n\n def test_log_scale_implicit(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n ax1.set_xscale(\"log\")\n\n kdeplot(x=x, ax=ax1)\n kdeplot(x=x, ax=ax1)\n\n xdata_log = ax1.lines[0].get_xdata()\n assert (xdata_log > 0).all()\n assert (np.diff(xdata_log, 2) > 0).all()\n assert np.allclose(np.diff(np.log(xdata_log), 2), 0)\n\n f, ax = plt.subplots()\n ax.set_yscale(\"log\")\n kdeplot(y=x, ax=ax)\n assert_array_equal(ax.lines[0].get_xdata(), ax1.lines[0].get_ydata())\n\n def test_log_scale_explicit(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n\n f, (ax1, ax2, ax3) = plt.subplots(ncols=3)\n\n ax1.set_xscale(\"log\")\n kdeplot(x=x, ax=ax1)\n kdeplot(x=x, log_scale=True, ax=ax2)\n kdeplot(x=x, log_scale=10, ax=ax3)\n\n for ax in f.axes:\n assert ax.get_xscale() == \"log\"\n\n supports = [ax.lines[0].get_xdata() for ax in f.axes]\n for a, b in itertools.product(supports, supports):\n assert_array_equal(a, b)\n\n densities = [ax.lines[0].get_ydata() for ax in f.axes]\n for a, b in itertools.product(densities, densities):\n assert_array_equal(a, b)\n\n f, ax = plt.subplots()\n kdeplot(y=x, log_scale=True, ax=ax)\n assert ax.get_yscale() == \"log\"\n\n def test_log_scale_with_hue(self, rng):\n\n data = rng.lognormal(0, 1, 50), rng.lognormal(0, 2, 100)\n ax = kdeplot(data=data, log_scale=True, common_grid=True)\n assert_array_equal(ax.lines[0].get_xdata(), ax.lines[1].get_xdata())\n\n def test_log_scale_normalization(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n ax = kdeplot(x=x, log_scale=True, cut=10)\n xdata, ydata = ax.lines[0].get_xydata().T\n integral = integrate(ydata, np.log10(xdata))\n assert integral == pytest.approx(1)\n\n def test_weights(self):\n\n x = [1, 2]\n weights = [2, 1]\n\n ax = kdeplot(x=x, weights=weights, bw_method=.1)\n\n xdata, ydata = ax.lines[0].get_xydata().T\n\n y1 = ydata[np.abs(xdata - 1).argmin()]\n y2 = ydata[np.abs(xdata - 2).argmin()]\n\n assert y1 == pytest.approx(2 * y2)\n\n def test_weight_norm(self, rng):\n\n vals = rng.normal(0, 1, 50)\n x = np.concatenate([vals, vals])\n w = np.repeat([1, 2], 50)\n ax = kdeplot(x=x, weights=w, hue=w, common_norm=True)\n\n # Recall that artists are added in reverse of hue order\n x1, y1 = ax.lines[0].get_xydata().T\n x2, y2 = ax.lines[1].get_xydata().T\n\n assert integrate(y1, x1) == pytest.approx(2 * integrate(y2, x2))\n\n def test_sticky_edges(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(data=long_df, x=\"x\", fill=True, ax=ax1)\n assert ax1.collections[0].sticky_edges.y[:] == [0, np.inf]\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\", multiple=\"fill\", fill=True, ax=ax2\n )\n assert ax2.collections[0].sticky_edges.y[:] == [0, 1]\n\n def test_line_kws(self, flat_array):\n\n lw = 3\n color = (.2, .5, .8)\n ax = kdeplot(x=flat_array, linewidth=lw, color=color)\n line, = ax.lines\n assert line.get_linewidth() == lw\n assert_colors_equal(line.get_color(), color)\n\n def test_input_checking(self, long_df):\n\n err = \"The x variable is categorical,\"\n with pytest.raises(TypeError, match=err):\n kdeplot(data=long_df, x=\"a\")\n\n def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(data=long_df, x=\"x\", ax=ax1)\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"Density\"\n\n kdeplot(data=long_df, y=\"y\", ax=ax2)\n assert ax2.get_xlabel() == \"Density\"\n assert ax2.get_ylabel() == \"y\"\n\n def test_legend(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", hue=\"a\")\n\n assert ax.legend_.get_title().get_text() == \"a\"\n\n legend_labels = ax.legend_.get_texts()\n order = categorical_order(long_df[\"a\"])\n for label, level in zip(legend_labels, order):\n assert label.get_text() == level\n\n legend_artists = ax.legend_.findobj(mpl.lines.Line2D)\n if Version(mpl.__version__) < Version(\"3.5.0b0\"):\n # https://github.com/matplotlib/matplotlib/pull/20699\n legend_artists = legend_artists[::2]\n palette = color_palette()\n for artist, color in zip(legend_artists, palette):\n assert_colors_equal(artist.get_color(), color)\n\n ax.clear()\n\n kdeplot(data=long_df, x=\"x\", hue=\"a\", legend=False)\n\n assert ax.legend_ is None\n\n\nclass TestKDEPlotBivariate:\n\n def test_long_vectors(self, long_df):\n\n ax1 = kdeplot(data=long_df, x=\"x\", y=\"y\")\n\n x = long_df[\"x\"]\n x_values = [x, x.to_numpy(), x.to_list()]\n\n y = long_df[\"y\"]\n y_values = [y, y.to_numpy(), y.to_list()]\n\n for x, y in zip(x_values, y_values):\n f, ax2 = plt.subplots()\n kdeplot(x=x, y=y, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(c1.get_offsets(), c2.get_offsets())\n\n def test_singular_data(self):\n\n with pytest.warns(UserWarning):\n ax = dist.kdeplot(x=np.ones(10), y=np.arange(10))\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = dist.kdeplot(x=[5], y=[6])\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=[1929245168.06679] * 18, y=np.arange(18))\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\", UserWarning)\n ax = kdeplot(x=[5], y=[7], warn_singular=False)\n assert not ax.lines\n\n def test_fill_artists(self, long_df):\n\n for fill in [True, False]:\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"c\", fill=fill)\n for c in ax.collections:\n if fill or Version(mpl.__version__) >= Version(\"3.5.0b0\"):\n assert isinstance(c, mpl.collections.PathCollection)\n else:\n assert isinstance(c, mpl.collections.LineCollection)\n\n def test_common_norm(self, rng):\n\n hue = np.repeat([\"a\", \"a\", \"a\", \"b\"], 40)\n x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], len(hue)).T\n x[hue == \"a\"] -= 2\n x[hue == \"b\"] += 2\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, hue=hue, common_norm=True, ax=ax1)\n kdeplot(x=x, y=y, hue=hue, common_norm=False, ax=ax2)\n\n n_seg_1 = sum(len(get_contour_coords(c)) > 0 for c in ax1.collections)\n n_seg_2 = sum(len(get_contour_coords(c)) > 0 for c in ax2.collections)\n assert n_seg_2 > n_seg_1\n\n def test_log_scale(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n y = rng.uniform(0, 1, 100)\n\n levels = .2, .5, 1\n\n f, ax = plt.subplots()\n kdeplot(x=x, y=y, log_scale=True, levels=levels, ax=ax)\n assert ax.get_xscale() == \"log\"\n assert ax.get_yscale() == \"log\"\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, log_scale=(10, False), levels=levels, ax=ax1)\n assert ax1.get_xscale() == \"log\"\n assert ax1.get_yscale() == \"linear\"\n\n p = _DistributionPlotter()\n kde = KDE()\n density, (xx, yy) = kde(np.log10(x), y)\n levels = p._quantile_to_level(density, levels)\n ax2.contour(10 ** xx, yy, density, levels=levels)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n\n def test_bandwidth(self, rng):\n\n n = 100\n x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], n).T\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(x=x, y=y, ax=ax1)\n kdeplot(x=x, y=y, bw_adjust=2, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n seg1, seg2 = get_contour_coords(c1), get_contour_coords(c2)\n if seg1 + seg2:\n x1 = seg1[0][:, 0]\n x2 = seg2[0][:, 0]\n assert np.abs(x2).max() > np.abs(x1).max()\n\n def test_weights(self, rng):\n\n import warnings\n warnings.simplefilter(\"error\", np.VisibleDeprecationWarning)\n\n n = 100\n x, y = rng.multivariate_normal([1, 3], [(.2, .5), (.5, 2)], n).T\n hue = np.repeat([0, 1], n // 2)\n weights = rng.uniform(0, 1, n)\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, hue=hue, ax=ax1)\n kdeplot(x=x, y=y, hue=hue, weights=weights, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n if get_contour_coords(c1) and get_contour_coords(c2):\n seg1 = np.concatenate(get_contour_coords(c1), axis=0)\n seg2 = np.concatenate(get_contour_coords(c2), axis=0)\n assert not np.array_equal(seg1, seg2)\n\n def test_hue_ignores_cmap(self, long_df):\n\n with pytest.warns(UserWarning, match=\"cmap parameter ignored\"):\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"c\", cmap=\"viridis\")\n\n assert_colors_equal(get_contour_color(ax.collections[0]), \"C0\")\n\n def test_contour_line_colors(self, long_df):\n\n color = (.2, .9, .8, 1)\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", color=color)\n\n for c in ax.collections:\n assert_colors_equal(get_contour_color(c), color)\n\n def test_contour_line_cmap(self, long_df):\n\n color_list = color_palette(\"Blues\", 12)\n cmap = mpl.colors.ListedColormap(color_list)\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", cmap=cmap)\n for c in ax.collections:\n color = to_rgb(get_contour_color(c).squeeze())\n assert color in color_list\n\n def test_contour_fill_colors(self, long_df):\n\n n = 6\n color = (.2, .9, .8, 1)\n ax = kdeplot(\n data=long_df, x=\"x\", y=\"y\", fill=True, color=color, levels=n,\n )\n\n cmap = light_palette(color, reverse=True, as_cmap=True)\n lut = cmap(np.linspace(0, 1, 256))\n for c in ax.collections:\n color = c.get_facecolor().squeeze()\n assert color in lut\n\n def test_colorbar(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", fill=True, cbar=True)\n assert len(ax.figure.axes) == 2\n\n def test_levels_and_thresh(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n n = 8\n thresh = .1\n plot_kws = dict(data=long_df, x=\"x\", y=\"y\")\n kdeplot(**plot_kws, levels=n, thresh=thresh, ax=ax1)\n kdeplot(**plot_kws, levels=np.linspace(thresh, 1, n), ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n\n with pytest.raises(ValueError):\n kdeplot(**plot_kws, levels=[0, 1, 2])\n\n ax1.clear()\n ax2.clear()\n\n kdeplot(**plot_kws, levels=n, thresh=None, ax=ax1)\n kdeplot(**plot_kws, levels=n, thresh=0, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(c1.get_facecolors(), c2.get_facecolors())\n\n def test_quantile_to_level(self, rng):\n\n x = rng.uniform(0, 1, 100000)\n isoprop = np.linspace(.1, 1, 6)\n\n levels = _DistributionPlotter()._quantile_to_level(x, isoprop)\n for h, p in zip(levels, isoprop):\n assert (x[x <= h].sum() / x.sum()) == pytest.approx(p, abs=1e-4)\n\n def test_input_checking(self, long_df):\n\n with pytest.raises(TypeError, match=\"The x variable is categorical,\"):\n kdeplot(data=long_df, x=\"a\", y=\"y\")\n\n\nclass TestHistPlotUnivariate(SharedAxesLevelTests):\n\n func = staticmethod(histplot)\n\n def get_last_color(self, ax, element=\"bars\", fill=True):\n\n if element == \"bars\":\n if fill:\n return ax.patches[-1].get_facecolor()\n else:\n return ax.patches[-1].get_edgecolor()\n else:\n if fill:\n artist = ax.collections[-1]\n facecolor = artist.get_facecolor()\n edgecolor = artist.get_edgecolor()\n assert_colors_equal(facecolor, edgecolor, check_alpha=False)\n return facecolor\n else:\n return ax.lines[-1].get_color()\n\n @pytest.mark.parametrize(\n \"element,fill\",\n itertools.product([\"bars\", \"step\", \"poly\"], [True, False]),\n )\n def test_color(self, long_df, element, fill):\n\n super().test_color(long_df, element=element, fill=fill)\n\n @pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, axs = plt.subplots(3)\n for vector, ax in zip(vectors, axs):\n histplot(data=long_df, ax=ax, **{variable: vector})\n\n bars = [ax.patches for ax in axs]\n for a_bars, b_bars in itertools.product(bars, bars):\n for a, b in zip(a_bars, b_bars):\n assert_array_equal(a.get_height(), b.get_height())\n assert_array_equal(a.get_xy(), b.get_xy())\n\n def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=wide_df, ax=ax1, common_bins=False)\n\n for col in wide_df.columns[::-1]:\n histplot(data=wide_df, x=col, ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_height()\n assert a.get_xy() == b.get_xy()\n\n def test_flat_vector(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=long_df[\"x\"], ax=ax1)\n histplot(data=long_df, x=\"x\", ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_height()\n assert a.get_xy() == b.get_xy()\n\n def test_empty_data(self):\n\n ax = histplot(x=[])\n assert not ax.patches\n\n def test_variable_assignment(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=long_df, x=\"x\", ax=ax1)\n histplot(data=long_df, y=\"x\", ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_width()\n\n @pytest.mark.parametrize(\"element\", [\"bars\", \"step\", \"poly\"])\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\", \"stack\", \"fill\"])\n def test_hue_fill_colors(self, long_df, multiple, element):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=multiple, bins=1,\n fill=True, element=element, legend=False,\n )\n\n palette = color_palette()\n\n if multiple == \"layer\":\n if element == \"bars\":\n a = .5\n else:\n a = .25\n else:\n a = .75\n\n for bar, color in zip(ax.patches[::-1], palette):\n assert_colors_equal(bar.get_facecolor(), to_rgba(color, a))\n\n for poly, color in zip(ax.collections[::-1], palette):\n assert_colors_equal(poly.get_facecolor(), to_rgba(color, a))\n\n def test_hue_stack(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\", bins=n, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"stack\", ax=ax2)\n\n layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))\n stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))\n assert_array_equal(layer_heights, stack_heights)\n\n stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))\n assert_array_equal(\n stack_xys[..., 1] + stack_heights,\n stack_heights.cumsum(axis=0),\n )\n\n def test_hue_fill(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\", bins=n, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"fill\", ax=ax2)\n\n layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))\n stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))\n assert_array_almost_equal(\n layer_heights / layer_heights.sum(axis=0), stack_heights\n )\n\n stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))\n assert_array_almost_equal(\n (stack_xys[..., 1] + stack_heights) / stack_heights.sum(axis=0),\n stack_heights.cumsum(axis=0),\n )\n\n def test_hue_dodge(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n bw = 2\n\n kws = dict(data=long_df, x=\"x\", hue=\"c\", binwidth=bw, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"dodge\", ax=ax2)\n\n layer_heights = [b.get_height() for b in ax1.patches]\n dodge_heights = [b.get_height() for b in ax2.patches]\n assert_array_equal(layer_heights, dodge_heights)\n\n layer_xs = np.reshape([b.get_x() for b in ax1.patches], (2, -1))\n dodge_xs = np.reshape([b.get_x() for b in ax2.patches], (2, -1))\n assert_array_almost_equal(layer_xs[1], dodge_xs[1])\n assert_array_almost_equal(layer_xs[0], dodge_xs[0] - bw / 2)\n\n def test_hue_as_numpy_dodged(self, long_df):\n # https://github.com/mwaskom/seaborn/issues/2452\n\n ax = histplot(\n long_df,\n x=\"y\", hue=long_df[\"a\"].to_numpy(),\n multiple=\"dodge\", bins=1,\n )\n # Note hue order reversal\n assert ax.patches[1].get_x() < ax.patches[0].get_x()\n\n def test_multiple_input_check(self, flat_series):\n\n with pytest.raises(ValueError, match=\"`multiple` must be\"):\n histplot(flat_series, multiple=\"invalid\")\n\n def test_element_input_check(self, flat_series):\n\n with pytest.raises(ValueError, match=\"`element` must be\"):\n histplot(flat_series, element=\"invalid\")\n\n def test_count_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"count\")\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == len(flat_series)\n\n def test_density_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"density\")\n bar_heights = [b.get_height() for b in ax.patches]\n bar_widths = [b.get_width() for b in ax.patches]\n assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)\n\n def test_density_stat_common_norm(self, long_df):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=\"density\", common_norm=True, element=\"bars\",\n )\n bar_heights = [b.get_height() for b in ax.patches]\n bar_widths = [b.get_width() for b in ax.patches]\n assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)\n\n def test_density_stat_unique_norm(self, long_df):\n\n n = 10\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=\"density\", bins=n, common_norm=False, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for bars in bar_groups:\n bar_heights = [b.get_height() for b in bars]\n bar_widths = [b.get_width() for b in bars]\n bar_areas = np.multiply(bar_heights, bar_widths)\n assert bar_areas.sum() == pytest.approx(1)\n\n @pytest.fixture(params=[\"probability\", \"proportion\"])\n def height_norm_arg(self, request):\n return request.param\n\n def test_probability_stat(self, flat_series, height_norm_arg):\n\n ax = histplot(flat_series, stat=height_norm_arg)\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == pytest.approx(1)\n\n def test_probability_stat_common_norm(self, long_df, height_norm_arg):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=height_norm_arg, common_norm=True, element=\"bars\",\n )\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == pytest.approx(1)\n\n def test_probability_stat_unique_norm(self, long_df, height_norm_arg):\n\n n = 10\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=height_norm_arg, bins=n, common_norm=False, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for bars in bar_groups:\n bar_heights = [b.get_height() for b in bars]\n assert sum(bar_heights) == pytest.approx(1)\n\n def test_percent_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"percent\")\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == 100\n\n def test_common_bins(self, long_df):\n\n n = 10\n ax = histplot(\n long_df, x=\"x\", hue=\"a\", common_bins=True, bins=n, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n assert_array_equal(\n [b.get_xy() for b in bar_groups[0]],\n [b.get_xy() for b in bar_groups[1]]\n )\n\n def test_unique_bins(self, wide_df):\n\n ax = histplot(wide_df, common_bins=False, bins=10, element=\"bars\")\n\n bar_groups = np.split(np.array(ax.patches), len(wide_df.columns))\n\n for i, col in enumerate(wide_df.columns[::-1]):\n bars = bar_groups[i]\n start = bars[0].get_x()\n stop = bars[-1].get_x() + bars[-1].get_width()\n assert_array_almost_equal(start, wide_df[col].min())\n assert_array_almost_equal(stop, wide_df[col].max())\n\n def test_weights_with_missing(self, missing_df):\n\n ax = histplot(missing_df, x=\"x\", weights=\"s\", bins=5)\n\n bar_heights = [bar.get_height() for bar in ax.patches]\n total_weight = missing_df[[\"x\", \"s\"]].dropna()[\"s\"].sum()\n assert sum(bar_heights) == pytest.approx(total_weight)\n\n def test_weight_norm(self, rng):\n\n vals = rng.normal(0, 1, 50)\n x = np.concatenate([vals, vals])\n w = np.repeat([1, 2], 50)\n ax = histplot(\n x=x, weights=w, hue=w, common_norm=True, stat=\"density\", bins=5\n )\n\n # Recall that artists are added in reverse of hue order\n y1 = [bar.get_height() for bar in ax.patches[:5]]\n y2 = [bar.get_height() for bar in ax.patches[5:]]\n\n assert sum(y1) == 2 * sum(y2)\n\n def test_discrete(self, long_df):\n\n ax = histplot(long_df, x=\"s\", discrete=True)\n\n data_min = long_df[\"s\"].min()\n data_max = long_df[\"s\"].max()\n assert len(ax.patches) == (data_max - data_min + 1)\n\n for i, bar in enumerate(ax.patches):\n assert bar.get_width() == 1\n assert bar.get_x() == (data_min + i - .5)\n\n def test_discrete_categorical_default(self, long_df):\n\n ax = histplot(long_df, x=\"a\")\n for i, bar in enumerate(ax.patches):\n assert bar.get_width() == 1\n\n def test_categorical_yaxis_inversion(self, long_df):\n\n ax = histplot(long_df, y=\"a\")\n ymax, ymin = ax.get_ylim()\n assert ymax > ymin\n\n @pytest.mark.skipif(\n Version(np.__version__) < Version(\"1.17\"),\n reason=\"Histogram over datetime64 requires numpy >= 1.17\",\n )\n def test_datetime_scale(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(x=long_df[\"t\"], fill=True, ax=ax1)\n histplot(x=long_df[\"t\"], fill=False, ax=ax2)\n assert ax1.get_xlim() == ax2.get_xlim()\n\n @pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde(self, flat_series, stat):\n\n ax = histplot(\n flat_series, kde=True, stat=stat, kde_kws={\"cut\": 10}\n )\n\n bar_widths = [b.get_width() for b in ax.patches]\n bar_heights = [b.get_height() for b in ax.patches]\n hist_area = np.multiply(bar_widths, bar_heights).sum()\n\n density, = ax.lines\n kde_area = integrate(density.get_ydata(), density.get_xdata())\n\n assert kde_area == pytest.approx(hist_area)\n\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\"])\n @pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde_with_hue(self, long_df, stat, multiple):\n\n n = 10\n ax = histplot(\n long_df, x=\"x\", hue=\"c\", multiple=multiple,\n kde=True, stat=stat, element=\"bars\",\n kde_kws={\"cut\": 10}, bins=n,\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for i, bars in enumerate(bar_groups):\n bar_widths = [b.get_width() for b in bars]\n bar_heights = [b.get_height() for b in bars]\n hist_area = np.multiply(bar_widths, bar_heights).sum()\n\n x, y = ax.lines[i].get_xydata().T\n kde_area = integrate(y, x)\n\n if multiple == \"layer\":\n assert kde_area == pytest.approx(hist_area)\n elif multiple == \"dodge\":\n assert kde_area == pytest.approx(hist_area * 2)\n\n def test_kde_default_cut(self, flat_series):\n\n ax = histplot(flat_series, kde=True)\n support = ax.lines[0].get_xdata()\n assert support.min() == flat_series.min()\n assert support.max() == flat_series.max()\n\n def test_kde_hue(self, long_df):\n\n n = 10\n ax = histplot(data=long_df, x=\"x\", hue=\"a\", kde=True, bins=n)\n\n for bar, line in zip(ax.patches[::n], ax.lines):\n assert_colors_equal(\n bar.get_facecolor(), line.get_color(), check_alpha=False\n )\n\n def test_kde_yaxis(self, flat_series):\n\n f, ax = plt.subplots()\n histplot(x=flat_series, kde=True)\n histplot(y=flat_series, kde=True)\n\n x, y = ax.lines\n assert_array_equal(x.get_xdata(), y.get_ydata())\n assert_array_equal(x.get_ydata(), y.get_xdata())\n\n def test_kde_line_kws(self, flat_series):\n\n lw = 5\n ax = histplot(flat_series, kde=True, line_kws=dict(lw=lw))\n assert ax.lines[0].get_linewidth() == lw\n\n def test_kde_singular_data(self):\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n ax = histplot(x=np.ones(10), kde=True)\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n ax = histplot(x=[5], kde=True)\n assert not ax.lines\n\n def test_element_default(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(long_df, x=\"x\", ax=ax1)\n histplot(long_df, x=\"x\", ax=ax2, element=\"bars\")\n assert len(ax1.patches) == len(ax2.patches)\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(long_df, x=\"x\", hue=\"a\", ax=ax1)\n histplot(long_df, x=\"x\", hue=\"a\", ax=ax2, element=\"bars\")\n assert len(ax1.patches) == len(ax2.patches)\n\n def test_bars_no_fill(self, flat_series):\n\n alpha = .5\n ax = histplot(flat_series, element=\"bars\", fill=False, alpha=alpha)\n for bar in ax.patches:\n assert bar.get_facecolor() == (0, 0, 0, 0)\n assert bar.get_edgecolor()[-1] == alpha\n\n def test_step_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=True, bins=n, ax=ax1)\n histplot(flat_series, element=\"step\", fill=True, bins=n, ax=ax2)\n\n bar_heights = [b.get_height() for b in ax1.patches]\n bar_widths = [b.get_width() for b in ax1.patches]\n bar_edges = [b.get_x() for b in ax1.patches]\n\n fill = ax2.collections[0]\n x, y = fill.get_paths()[0].vertices[::-1].T\n\n assert_array_equal(x[1:2 * n:2], bar_edges)\n assert_array_equal(y[1:2 * n:2], bar_heights)\n\n assert x[n * 2] == bar_edges[-1] + bar_widths[-1]\n assert y[n * 2] == bar_heights[-1]\n\n def test_poly_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=True, bins=n, ax=ax1)\n histplot(flat_series, element=\"poly\", fill=True, bins=n, ax=ax2)\n\n bar_heights = np.array([b.get_height() for b in ax1.patches])\n bar_widths = np.array([b.get_width() for b in ax1.patches])\n bar_edges = np.array([b.get_x() for b in ax1.patches])\n\n fill = ax2.collections[0]\n x, y = fill.get_paths()[0].vertices[::-1].T\n\n assert_array_equal(x[1:n + 1], bar_edges + bar_widths / 2)\n assert_array_equal(y[1:n + 1], bar_heights)\n\n def test_poly_no_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=False, bins=n, ax=ax1)\n histplot(flat_series, element=\"poly\", fill=False, bins=n, ax=ax2)\n\n bar_heights = np.array([b.get_height() for b in ax1.patches])\n bar_widths = np.array([b.get_width() for b in ax1.patches])\n bar_edges = np.array([b.get_x() for b in ax1.patches])\n\n x, y = ax2.lines[0].get_xydata().T\n\n assert_array_equal(x, bar_edges + bar_widths / 2)\n assert_array_equal(y, bar_heights)\n\n def test_step_no_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(flat_series, element=\"bars\", fill=False, ax=ax1)\n histplot(flat_series, element=\"step\", fill=False, ax=ax2)\n\n bar_heights = [b.get_height() for b in ax1.patches]\n bar_widths = [b.get_width() for b in ax1.patches]\n bar_edges = [b.get_x() for b in ax1.patches]\n\n x, y = ax2.lines[0].get_xydata().T\n\n assert_array_equal(x[:-1], bar_edges)\n assert_array_equal(y[:-1], bar_heights)\n assert x[-1] == bar_edges[-1] + bar_widths[-1]\n assert y[-1] == y[-2]\n\n def test_step_fill_xy(self, flat_series):\n\n f, ax = plt.subplots()\n\n histplot(x=flat_series, element=\"step\", fill=True)\n histplot(y=flat_series, element=\"step\", fill=True)\n\n xverts = ax.collections[0].get_paths()[0].vertices\n yverts = ax.collections[1].get_paths()[0].vertices\n\n assert_array_equal(xverts, yverts[:, ::-1])\n\n def test_step_no_fill_xy(self, flat_series):\n\n f, ax = plt.subplots()\n\n histplot(x=flat_series, element=\"step\", fill=False)\n histplot(y=flat_series, element=\"step\", fill=False)\n\n xline, yline = ax.lines\n\n assert_array_equal(xline.get_xdata(), yline.get_ydata())\n assert_array_equal(xline.get_ydata(), yline.get_xdata())\n\n def test_weighted_histogram(self):\n\n ax = histplot(x=[0, 1, 2], weights=[1, 2, 3], discrete=True)\n\n bar_heights = [b.get_height() for b in ax.patches]\n assert bar_heights == [1, 2, 3]\n\n def test_weights_with_auto_bins(self, long_df):\n\n with pytest.warns(UserWarning):\n ax = histplot(long_df, x=\"x\", weights=\"f\")\n assert len(ax.patches) == 10\n\n def test_shrink(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n bw = 2\n shrink = .4\n\n histplot(long_df, x=\"x\", binwidth=bw, ax=ax1)\n histplot(long_df, x=\"x\", binwidth=bw, shrink=shrink, ax=ax2)\n\n for p1, p2 in zip(ax1.patches, ax2.patches):\n\n w1, w2 = p1.get_width(), p2.get_width()\n assert w2 == pytest.approx(shrink * w1)\n\n x1, x2 = p1.get_x(), p2.get_x()\n assert (x2 + w2 / 2) == pytest.approx(x1 + w1 / 2)\n\n def test_log_scale_explicit(self, rng):\n\n x = rng.lognormal(0, 2, 1000)\n ax = histplot(x, log_scale=True, binwidth=1)\n\n bar_widths = [b.get_width() for b in ax.patches]\n steps = np.divide(bar_widths[1:], bar_widths[:-1])\n assert np.allclose(steps, 10)\n\n def test_log_scale_implicit(self, rng):\n\n x = rng.lognormal(0, 2, 1000)\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n histplot(x, binwidth=1, ax=ax)\n\n bar_widths = [b.get_width() for b in ax.patches]\n steps = np.divide(bar_widths[1:], bar_widths[:-1])\n assert np.allclose(steps, 10)\n\n def test_log_scale_dodge(self, rng):\n\n x = rng.lognormal(0, 2, 100)\n hue = np.repeat([\"a\", \"b\"], 50)\n ax = histplot(x=x, hue=hue, bins=5, log_scale=True, multiple=\"dodge\")\n x_min = np.log([b.get_x() for b in ax.patches])\n x_max = np.log([b.get_x() + b.get_width() for b in ax.patches])\n assert np.unique(np.round(x_max - x_min, 10)).size == 1\n\n @pytest.mark.parametrize(\n \"fill\", [True, False],\n )\n def test_auto_linewidth(self, flat_series, fill):\n\n get_lw = lambda ax: ax.patches[0].get_linewidth() # noqa: E731\n\n kws = dict(element=\"bars\", fill=fill)\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(flat_series, **kws, bins=10, ax=ax1)\n histplot(flat_series, **kws, bins=100, ax=ax2)\n assert get_lw(ax1) > get_lw(ax2)\n\n f, ax1 = plt.subplots(figsize=(10, 5))\n f, ax2 = plt.subplots(figsize=(2, 5))\n histplot(flat_series, **kws, bins=30, ax=ax1)\n histplot(flat_series, **kws, bins=30, ax=ax2)\n assert get_lw(ax1) > get_lw(ax2)\n\n f, ax1 = plt.subplots(figsize=(4, 5))\n f, ax2 = plt.subplots(figsize=(4, 5))\n histplot(flat_series, **kws, bins=30, ax=ax1)\n histplot(10 ** flat_series, **kws, bins=30, log_scale=True, ax=ax2)\n assert get_lw(ax1) == pytest.approx(get_lw(ax2))\n\n f, ax1 = plt.subplots(figsize=(4, 5))\n f, ax2 = plt.subplots(figsize=(4, 5))\n histplot(y=[0, 1, 1], **kws, discrete=True, ax=ax1)\n histplot(y=[\"a\", \"b\", \"b\"], **kws, ax=ax2)\n assert get_lw(ax1) == pytest.approx(get_lw(ax2))\n\n def test_bar_kwargs(self, flat_series):\n\n lw = 2\n ec = (1, .2, .9, .5)\n ax = histplot(flat_series, binwidth=1, ec=ec, lw=lw)\n for bar in ax.patches:\n assert_colors_equal(bar.get_edgecolor(), ec)\n assert bar.get_linewidth() == lw\n\n def test_step_fill_kwargs(self, flat_series):\n\n lw = 2\n ec = (1, .2, .9, .5)\n ax = histplot(flat_series, element=\"step\", ec=ec, lw=lw)\n poly = ax.collections[0]\n assert_colors_equal(poly.get_edgecolor(), ec)\n assert poly.get_linewidth() == lw\n\n def test_step_line_kwargs(self, flat_series):\n\n lw = 2\n ls = \"--\"\n ax = histplot(flat_series, element=\"step\", fill=False, lw=lw, ls=ls)\n line = ax.lines[0]\n assert line.get_linewidth() == lw\n assert line.get_linestyle() == ls\n\n\nclass TestHistPlotBivariate:\n\n def test_mesh(self, long_df):\n\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(long_df[\"x\"], long_df[\"y\"])\n\n ax = histplot(long_df, x=\"x\", y=\"y\")\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_with_hue(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", hue=\"c\")\n\n hist = Histogram()\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_with_hue_unique_bins(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", hue=\"c\", common_bins=False)\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n hist = Histogram()\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_with_col_unique_bins(self, long_df):\n\n g = displot(long_df, x=\"x\", y=\"y\", col=\"c\", common_bins=False)\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n hist = Histogram()\n\n mesh = g.axes.flat[i].collections[0]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_log_scale(self, rng):\n\n x, y = rng.lognormal(0, 1, (2, 1000))\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(np.log10(x), np.log10(y))\n\n ax = histplot(x=x, y=y, log_scale=True)\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y_i, x_i) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == 10 ** x_i\n assert path.vertices[0, 1] == 10 ** y_i\n\n def test_mesh_thresh(self, long_df):\n\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(long_df[\"x\"], long_df[\"y\"])\n\n thresh = 5\n ax = histplot(long_df, x=\"x\", y=\"y\", thresh=thresh)\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, (counts <= thresh).T.flat)\n\n def test_mesh_sticky_edges(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", thresh=None)\n mesh = ax.collections[0]\n assert mesh.sticky_edges.x == [long_df[\"x\"].min(), long_df[\"x\"].max()]\n assert mesh.sticky_edges.y == [long_df[\"y\"].min(), long_df[\"y\"].max()]\n\n ax.clear()\n ax = histplot(long_df, x=\"x\", y=\"y\")\n mesh = ax.collections[0]\n assert not mesh.sticky_edges.x\n assert not mesh.sticky_edges.y\n\n def test_mesh_common_norm(self, long_df):\n\n stat = \"density\"\n ax = histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\", common_norm=True, stat=stat,\n )\n\n hist = Histogram(stat=\"density\")\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n density, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n scale = len(sub_df) / len(long_df)\n assert_array_equal(mesh_data.data, (density * scale).T.flat)\n\n def test_mesh_unique_norm(self, long_df):\n\n stat = \"density\"\n ax = histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\", common_norm=False, stat=stat,\n )\n\n hist = Histogram()\n bin_kws = hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n sub_hist = Histogram(bins=bin_kws[\"bins\"], stat=stat)\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n density, (x_edges, y_edges) = sub_hist(sub_df[\"x\"], sub_df[\"y\"])\n assert_array_equal(mesh_data.data, density.T.flat)\n\n @pytest.mark.parametrize(\"stat\", [\"probability\", \"proportion\", \"percent\"])\n def test_mesh_normalization(self, long_df, stat):\n\n ax = histplot(\n long_df, x=\"x\", y=\"y\", stat=stat,\n )\n\n mesh_data = ax.collections[0].get_array()\n expected_sum = {\"percent\": 100}.get(stat, 1)\n assert mesh_data.data.sum() == expected_sum\n\n def test_mesh_colors(self, long_df):\n\n color = \"r\"\n f, ax = plt.subplots()\n histplot(\n long_df, x=\"x\", y=\"y\", color=color,\n )\n mesh = ax.collections[0]\n assert_array_equal(\n mesh.get_cmap().colors,\n _DistributionPlotter()._cmap_from_color(color).colors,\n )\n\n f, ax = plt.subplots()\n histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\",\n )\n colors = color_palette()\n for i, mesh in enumerate(ax.collections):\n assert_array_equal(\n mesh.get_cmap().colors,\n _DistributionPlotter()._cmap_from_color(colors[i]).colors,\n )\n\n def test_color_limits(self, long_df):\n\n f, (ax1, ax2, ax3) = plt.subplots(3)\n kws = dict(data=long_df, x=\"x\", y=\"y\")\n hist = Histogram()\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n\n histplot(**kws, ax=ax1)\n assert ax1.collections[0].get_clim() == (0, counts.max())\n\n vmax = 10\n histplot(**kws, vmax=vmax, ax=ax2)\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n assert ax2.collections[0].get_clim() == (0, vmax)\n\n pmax = .8\n pthresh = .1\n f = _DistributionPlotter()._quantile_to_level\n\n histplot(**kws, pmax=pmax, pthresh=pthresh, ax=ax3)\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n mesh = ax3.collections[0]\n assert mesh.get_clim() == (0, f(counts, pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (counts <= f(counts, pthresh)).T.flat,\n )\n\n def test_hue_color_limits(self, long_df):\n\n _, (ax1, ax2, ax3, ax4) = plt.subplots(4)\n kws = dict(data=long_df, x=\"x\", y=\"y\", hue=\"c\", bins=4)\n\n hist = Histogram(bins=kws[\"bins\"])\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n full_counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n\n sub_counts = []\n for _, sub_df in long_df.groupby(kws[\"hue\"]):\n c, _ = hist(sub_df[\"x\"], sub_df[\"y\"])\n sub_counts.append(c)\n\n pmax = .8\n pthresh = .05\n f = _DistributionPlotter()._quantile_to_level\n\n histplot(**kws, common_norm=True, ax=ax1)\n for i, mesh in enumerate(ax1.collections):\n assert mesh.get_clim() == (0, full_counts.max())\n\n histplot(**kws, common_norm=False, ax=ax2)\n for i, mesh in enumerate(ax2.collections):\n assert mesh.get_clim() == (0, sub_counts[i].max())\n\n histplot(**kws, common_norm=True, pmax=pmax, pthresh=pthresh, ax=ax3)\n for i, mesh in enumerate(ax3.collections):\n assert mesh.get_clim() == (0, f(full_counts, pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (sub_counts[i] <= f(full_counts, pthresh)).T.flat,\n )\n\n histplot(**kws, common_norm=False, pmax=pmax, pthresh=pthresh, ax=ax4)\n for i, mesh in enumerate(ax4.collections):\n assert mesh.get_clim() == (0, f(sub_counts[i], pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (sub_counts[i] <= f(sub_counts[i], pthresh)).T.flat,\n )\n\n def test_colorbar(self, long_df):\n\n f, ax = plt.subplots()\n histplot(long_df, x=\"x\", y=\"y\", cbar=True, ax=ax)\n assert len(ax.figure.axes) == 2\n\n f, (ax, cax) = plt.subplots(2)\n histplot(long_df, x=\"x\", y=\"y\", cbar=True, cbar_ax=cax, ax=ax)\n assert len(ax.figure.axes) == 2\n\n\nclass TestECDFPlotUnivariate(SharedAxesLevelTests):\n\n func = staticmethod(ecdfplot)\n\n def get_last_color(self, ax):\n\n return to_rgb(ax.lines[-1].get_color())\n\n @pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n ecdfplot(data=long_df, ax=ax, **{variable: vector})\n\n xdata = [l.get_xdata() for l in ax.lines]\n for a, b in itertools.product(xdata, xdata):\n assert_array_equal(a, b)\n\n ydata = [l.get_ydata() for l in ax.lines]\n for a, b in itertools.product(ydata, ydata):\n assert_array_equal(a, b)\n\n def test_hue(self, long_df):\n\n ax = ecdfplot(long_df, x=\"x\", hue=\"a\")\n\n for line, color in zip(ax.lines[::-1], color_palette()):\n assert_colors_equal(line.get_color(), color)\n\n def test_line_kwargs(self, long_df):\n\n color = \"r\"\n ls = \"--\"\n lw = 3\n ax = ecdfplot(long_df, x=\"x\", color=color, ls=ls, lw=lw)\n\n for line in ax.lines:\n assert_colors_equal(line.get_color(), color)\n assert line.get_linestyle() == ls\n assert line.get_linewidth() == lw\n\n @pytest.mark.parametrize(\"data_var\", [\"x\", \"y\"])\n def test_drawstyle(self, flat_series, data_var):\n\n ax = ecdfplot(**{data_var: flat_series})\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n assert ax.lines[0].get_drawstyle() == drawstyles[data_var]\n\n @pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits(self, flat_series, data_var, stat_var):\n\n ax = ecdfplot(**{data_var: flat_series})\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 0\n assert data[-1] == 1\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, 1]\n\n @pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits_complementary(self, flat_series, data_var, stat_var):\n\n ax = ecdfplot(**{data_var: flat_series}, complementary=True)\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 1\n assert data[-1] == 0\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, 1]\n\n @pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_count(self, flat_series, data_var, stat_var):\n\n n = len(flat_series)\n ax = ecdfplot(**{data_var: flat_series}, stat=\"count\")\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 0\n assert data[-1] == n\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, n]\n\n def test_weights(self):\n\n ax = ecdfplot(x=[1, 2, 3], weights=[1, 1, 2])\n y = ax.lines[0].get_ydata()\n assert_array_equal(y, [0, .25, .5, 1])\n\n def test_bivariate_error(self, long_df):\n\n with pytest.raises(NotImplementedError, match=\"Bivariate ECDF plots\"):\n ecdfplot(data=long_df, x=\"x\", y=\"y\")\n\n def test_log_scale(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n\n ecdfplot(data=long_df, x=\"z\", ax=ax1)\n ecdfplot(data=long_df, x=\"z\", log_scale=True, ax=ax2)\n\n # Ignore first point, which either -inf (in linear) or 0 (in log)\n line1 = ax1.lines[0].get_xydata()[1:]\n line2 = ax2.lines[0].get_xydata()[1:]\n\n assert_array_almost_equal(line1, line2)\n\n\nclass TestDisPlot:\n\n # TODO probably good to move these utility attributes/methods somewhere else\n @pytest.mark.parametrize(\n \"kwargs\", [\n dict(),\n dict(x=\"x\"),\n dict(x=\"t\"),\n dict(x=\"a\"),\n dict(x=\"z\", log_scale=True),\n dict(x=\"x\", binwidth=4),\n dict(x=\"x\", weights=\"f\", bins=5),\n dict(x=\"x\", color=\"green\", linewidth=2, binwidth=4),\n dict(x=\"x\", hue=\"a\", fill=False),\n dict(x=\"y\", hue=\"a\", fill=False),\n dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n dict(x=\"x\", hue=\"a\", element=\"step\"),\n dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n dict(x=\"x\", hue=\"a\", kde=True),\n dict(x=\"x\", hue=\"a\", stat=\"density\", common_norm=False),\n dict(x=\"x\", y=\"y\"),\n ],\n )\n def test_versus_single_histplot(self, long_df, kwargs):\n\n ax = histplot(long_df, **kwargs)\n g = displot(long_df, **kwargs)\n assert_plots_equal(ax, g.ax)\n\n if ax.legend_ is not None:\n assert_legends_equal(ax.legend_, g._legend)\n\n if kwargs:\n long_df[\"_\"] = \"_\"\n g2 = displot(long_df, col=\"_\", **kwargs)\n assert_plots_equal(ax, g2.ax)\n\n @pytest.mark.parametrize(\n \"kwargs\", [\n dict(),\n dict(x=\"x\"),\n dict(x=\"t\"),\n dict(x=\"z\", log_scale=True),\n dict(x=\"x\", bw_adjust=.5),\n dict(x=\"x\", weights=\"f\"),\n dict(x=\"x\", color=\"green\", linewidth=2),\n dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n dict(x=\"x\", hue=\"a\", fill=True),\n dict(x=\"y\", hue=\"a\", fill=False),\n dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n dict(x=\"x\", y=\"y\"),\n ],\n )\n def test_versus_single_kdeplot(self, long_df, kwargs):\n\n ax = kdeplot(data=long_df, **kwargs)\n g = displot(long_df, kind=\"kde\", **kwargs)\n assert_plots_equal(ax, g.ax)\n\n if ax.legend_ is not None:\n assert_legends_equal(ax.legend_, g._legend)\n\n if kwargs:\n long_df[\"_\"] = \"_\"\n g2 = displot(long_df, kind=\"kde\", col=\"_\", **kwargs)\n assert_plots_equal(ax, g2.ax)\n\n @pytest.mark.parametrize(\n \"kwargs\", [\n dict(),\n dict(x=\"x\"),\n dict(x=\"t\"),\n dict(x=\"z\", log_scale=True),\n dict(x=\"x\", weights=\"f\"),\n dict(y=\"x\"),\n dict(x=\"x\", color=\"green\", linewidth=2),\n dict(x=\"x\", hue=\"a\", complementary=True),\n dict(x=\"x\", hue=\"a\", stat=\"count\"),\n dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n ],\n )\n def test_versus_single_ecdfplot(self, long_df, kwargs):\n\n ax = ecdfplot(data=long_df, **kwargs)\n g = displot(long_df, kind=\"ecdf\", **kwargs)\n assert_plots_equal(ax, g.ax)\n\n if ax.legend_ is not None:\n assert_legends_equal(ax.legend_, g._legend)\n\n if kwargs:\n long_df[\"_\"] = \"_\"\n g2 = displot(long_df, kind=\"ecdf\", col=\"_\", **kwargs)\n assert_plots_equal(ax, g2.ax)\n\n @pytest.mark.parametrize(\n \"kwargs\", [\n dict(x=\"x\"),\n dict(x=\"x\", y=\"y\"),\n dict(x=\"x\", hue=\"a\"),\n ]\n )\n def test_with_rug(self, long_df, kwargs):\n\n ax = plt.figure().subplots()\n histplot(data=long_df, **kwargs, ax=ax)\n rugplot(data=long_df, **kwargs, ax=ax)\n\n g = displot(long_df, rug=True, **kwargs)\n\n assert_plots_equal(ax, g.ax, labels=False)\n\n long_df[\"_\"] = \"_\"\n g2 = displot(long_df, col=\"_\", rug=True, **kwargs)\n\n assert_plots_equal(ax, g2.ax, labels=False)\n\n @pytest.mark.parametrize(\n \"facet_var\", [\"col\", \"row\"],\n )\n def test_facets(self, long_df, facet_var):\n\n kwargs = {facet_var: \"a\"}\n ax = kdeplot(data=long_df, x=\"x\", hue=\"a\")\n g = displot(long_df, x=\"x\", kind=\"kde\", **kwargs)\n\n legend_texts = ax.legend_.get_texts()\n\n for i, line in enumerate(ax.lines[::-1]):\n facet_ax = g.axes.flat[i]\n facet_line = facet_ax.lines[0]\n assert_array_equal(line.get_xydata(), facet_line.get_xydata())\n\n text = legend_texts[i].get_text()\n assert text in facet_ax.get_title()\n\n @pytest.mark.parametrize(\"multiple\", [\"dodge\", \"stack\", \"fill\"])\n def test_facet_multiple(self, long_df, multiple):\n\n bins = np.linspace(0, 20, 5)\n ax = histplot(\n data=long_df[long_df[\"c\"] == 0],\n x=\"x\", hue=\"a\", hue_order=[\"a\", \"b\", \"c\"],\n multiple=multiple, bins=bins,\n )\n\n g = displot(\n data=long_df, x=\"x\", hue=\"a\", col=\"c\", hue_order=[\"a\", \"b\", \"c\"],\n multiple=multiple, bins=bins,\n )\n\n assert_plots_equal(ax, g.axes_dict[0])\n\n def test_ax_warning(self, long_df):\n\n ax = plt.figure().subplots()\n with pytest.warns(UserWarning, match=\"`displot` is a figure-level\"):\n displot(long_df, x=\"x\", ax=ax)\n\n @pytest.mark.parametrize(\"key\", [\"col\", \"row\"])\n def test_array_faceting(self, long_df, key):\n\n a = long_df[\"a\"].to_numpy()\n vals = categorical_order(a)\n g = displot(long_df, x=\"x\", **{key: a})\n assert len(g.axes.flat) == len(vals)\n for ax, val in zip(g.axes.flat, vals):\n assert val in ax.get_title()\n\n def test_legend(self, long_df):\n\n g = displot(long_df, x=\"x\", hue=\"a\")\n assert g._legend is not None\n\n def test_empty(self):\n\n g = displot(x=[], y=[])\n assert isinstance(g, FacetGrid)\n\n def test_bivariate_ecdf_error(self, long_df):\n\n with pytest.raises(NotImplementedError):\n displot(long_df, x=\"x\", y=\"y\", kind=\"ecdf\")\n\n def test_bivariate_kde_norm(self, rng):\n\n x, y = rng.normal(0, 1, (2, 100))\n z = [0] * 80 + [1] * 20\n\n g = displot(x=x, y=y, col=z, kind=\"kde\", levels=10)\n l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)\n l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)\n assert l1 > l2\n\n g = displot(x=x, y=y, col=z, kind=\"kde\", levels=10, common_norm=False)\n l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)\n l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)\n assert l1 == l2\n\n def test_bivariate_hist_norm(self, rng):\n\n x, y = rng.normal(0, 1, (2, 100))\n z = [0] * 80 + [1] * 20\n\n g = displot(x=x, y=y, col=z, kind=\"hist\")\n clim1 = g.axes.flat[0].collections[0].get_clim()\n clim2 = g.axes.flat[1].collections[0].get_clim()\n assert clim1 == clim2\n\n g = displot(x=x, y=y, col=z, kind=\"hist\", common_norm=False)\n clim1 = g.axes.flat[0].collections[0].get_clim()\n clim2 = g.axes.flat[1].collections[0].get_clim()\n assert clim1[1] > clim2[1]\n\n def test_facetgrid_data(self, long_df):\n\n g = displot(\n data=long_df.to_dict(orient=\"list\"),\n x=\"z\",\n hue=long_df[\"a\"].rename(\"hue_var\"),\n col=long_df[\"c\"].to_numpy(),\n )\n expected_cols = set(long_df.columns.to_list() + [\"hue_var\", \"_col_\"])\n assert set(g.data.columns) == expected_cols\n assert_array_equal(g.data[\"hue_var\"], long_df[\"a\"])\n assert_array_equal(g.data[\"_col_\"], long_df[\"c\"])\n\n\ndef integrate(y, x):\n \"\"\"\"Simple numerical integration for testing KDE code.\"\"\"\n y = np.asarray(y)\n x = np.asarray(x)\n dx = np.diff(x)\n return (dx * y[:-1] + dx * y[1:]).sum() / 2\n"},{"col":0,"comment":"Make a sequential palette that blends from light to ``color``.\n\n The ``color`` parameter can be specified in a number of ways, including\n all options for defining a color in matplotlib and several additional\n color spaces that are handled by seaborn. You can also use the database\n of named colors from the XKCD color survey.\n\n If you are using a Jupyter notebook, you can also choose this palette\n interactively with the :func:`choose_light_palette` function.\n\n Parameters\n ----------\n color : base color for high values\n hex code, html color name, or tuple in `input` space.\n n_colors : int, optional\n number of colors in the palette\n reverse : bool, optional\n if True, reverse the direction of the blend\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n input : {'rgb', 'hls', 'husl', xkcd'}\n Color space to interpret the input color. The first three options\n apply to tuple inputs and the latter applies to string inputs.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n diverging_palette : Create a diverging palette with two colors.\n\n Examples\n --------\n .. include:: ../docstrings/light_palette.rst\n\n ","endLoc":529,"header":"def light_palette(color, n_colors=6, reverse=False, as_cmap=False, input=\"rgb\")","id":397,"name":"light_palette","nodeType":"Function","startLoc":484,"text":"def light_palette(color, n_colors=6, reverse=False, as_cmap=False, input=\"rgb\"):\n \"\"\"Make a sequential palette that blends from light to ``color``.\n\n The ``color`` parameter can be specified in a number of ways, including\n all options for defining a color in matplotlib and several additional\n color spaces that are handled by seaborn. You can also use the database\n of named colors from the XKCD color survey.\n\n If you are using a Jupyter notebook, you can also choose this palette\n interactively with the :func:`choose_light_palette` function.\n\n Parameters\n ----------\n color : base color for high values\n hex code, html color name, or tuple in `input` space.\n n_colors : int, optional\n number of colors in the palette\n reverse : bool, optional\n if True, reverse the direction of the blend\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n input : {'rgb', 'hls', 'husl', xkcd'}\n Color space to interpret the input color. The first three options\n apply to tuple inputs and the latter applies to string inputs.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n diverging_palette : Create a diverging palette with two colors.\n\n Examples\n --------\n .. include:: ../docstrings/light_palette.rst\n\n \"\"\"\n rgb = _color_to_rgb(color, input)\n h, s, l = husl.rgb_to_husl(*rgb)\n gray_s, gray_l = .15 * s, 95\n gray = _color_to_rgb((h, gray_s, gray_l), input=\"husl\")\n colors = [rgb, gray] if reverse else [gray, rgb]\n return blend_palette(colors, n_colors, as_cmap)"},{"col":0,"comment":"Add some more flexibility to color choices.","endLoc":430,"header":"def _color_to_rgb(color, input)","id":398,"name":"_color_to_rgb","nodeType":"Function","startLoc":420,"text":"def _color_to_rgb(color, input):\n \"\"\"Add some more flexibility to color choices.\"\"\"\n if input == \"hls\":\n color = colorsys.hls_to_rgb(*color)\n elif input == \"husl\":\n color = husl.husl_to_rgb(*color)\n color = tuple(np.clip(color, 0, 1))\n elif input == \"xkcd\":\n color = xkcd_rgb[color]\n\n return mpl.colors.to_rgb(color)"},{"col":4,"comment":"null","endLoc":89,"header":"def _resolve_properties(self, data, scales)","id":399,"name":"_resolve_properties","nodeType":"Function","startLoc":75,"text":"def _resolve_properties(self, data, scales):\n\n resolved = resolve_properties(self, data, scales)\n\n resolved[\"facecolor\"] = resolve_color(self, data, \"\", scales)\n resolved[\"edgecolor\"] = resolve_color(self, data, \"edge\", scales)\n\n fc = resolved[\"facecolor\"]\n if isinstance(fc, tuple):\n resolved[\"facecolor\"] = fc[0], fc[1], fc[2], fc[3] * resolved[\"fill\"]\n else:\n fc[:, 3] = fc[:, 3] * resolved[\"fill\"] # TODO Is inplace mod a problem?\n resolved[\"facecolor\"] = fc\n\n return resolved"},{"col":0,"comment":"null","endLoc":32,"header":"def husl_to_rgb(h, s, l)","id":400,"name":"husl_to_rgb","nodeType":"Function","startLoc":31,"text":"def husl_to_rgb(h, s, l):\n return lch_to_rgb(*husl_to_lch([h, s, l]))"},{"col":0,"comment":"null","endLoc":461,"header":"def _cmpkey(\n epoch: int,\n release: Tuple[int, ...],\n pre: Optional[Tuple[str, int]],\n post: Optional[Tuple[str, int]],\n dev: Optional[Tuple[str, int]],\n local: Optional[Tuple[SubLocalType]],\n) -> CmpKey","id":404,"name":"_cmpkey","nodeType":"Function","startLoc":401,"text":"def _cmpkey(\n epoch: int,\n release: Tuple[int, ...],\n pre: Optional[Tuple[str, int]],\n post: Optional[Tuple[str, int]],\n dev: Optional[Tuple[str, int]],\n local: Optional[Tuple[SubLocalType]],\n) -> CmpKey:\n\n # When we compare a release version, we want to compare it with all of the\n # trailing zeros removed. So we'll use a reverse the list, drop all the now\n # leading zeros until we come to something non zero, then take the rest\n # re-reverse it back into the correct order and make it a tuple and use\n # that for our sorting key.\n _release = tuple(\n reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))\n )\n\n # We need to \"trick\" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n # We'll do this by abusing the pre segment, but we _only_ want to do this\n # if there is not a pre or a post segment. If we have one of those then\n # the normal sorting rules will handle this case correctly.\n if pre is None and post is None and dev is not None:\n _pre: PrePostDevType = NegativeInfinity\n # Versions without a pre-release (except as noted above) should sort after\n # those with one.\n elif pre is None:\n _pre = Infinity\n else:\n _pre = pre\n\n # Versions without a post segment should sort before those with one.\n if post is None:\n _post: PrePostDevType = NegativeInfinity\n\n else:\n _post = post\n\n # Versions without a development segment should sort after those with one.\n if dev is None:\n _dev: PrePostDevType = Infinity\n\n else:\n _dev = dev\n\n if local is None:\n # Versions without a local segment should sort before those with one.\n _local: LocalType = NegativeInfinity\n else:\n # Versions with a local segment need that segment parsed to implement\n # the sorting rules in PEP440.\n # - Alpha numeric segments sort before numeric segments\n # - Alpha numeric segments sort lexicographically\n # - Numeric segments sort numerically\n # - Shorter versions sort before longer versions when the prefixes\n # match exactly\n _local = tuple(\n (i, \"\") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n )\n\n return epoch, _release, _pre, _post, _dev, _local"},{"col":42,"endLoc":416,"id":405,"nodeType":"Lambda","startLoc":416,"text":"lambda x: x == 0"},{"col":0,"comment":"null","endLoc":271,"header":"def husl_to_lch(triple)","id":406,"name":"husl_to_lch","nodeType":"Function","startLoc":260,"text":"def husl_to_lch(triple):\n H, S, L = triple\n\n if L > 99.9999999:\n return [100, 0.0, H]\n if L < 0.00000001:\n return [0.0, 0.0, H]\n\n mx = max_chroma(L, H)\n C = mx / 100.0 * S\n\n return [L, C, H]"},{"col":0,"comment":"null","endLoc":91,"header":"def max_chroma(L, H)","id":407,"name":"max_chroma","nodeType":"Function","startLoc":71,"text":"def max_chroma(L, H):\n hrad = math.radians(H)\n sinH = (math.sin(hrad))\n cosH = (math.cos(hrad))\n sub1 = (math.pow(L + 16, 3.0) / 1560896.0)\n sub2 = sub1 if sub1 > 0.008856 else (L / 903.3)\n result = float(\"inf\")\n for row in m:\n m1 = row[0]\n m2 = row[1]\n m3 = row[2]\n top = ((0.99915 * m1 + 1.05122 * m2 + 1.14460 * m3) * sub2)\n rbottom = (0.86330 * m3 - 0.17266 * m2)\n lbottom = (0.12949 * m3 - 0.38848 * m1)\n bottom = (rbottom * sinH + lbottom * cosH) * sub2\n\n for t in (0.0, 1.0):\n C = (L * (top - 1.05122 * t) / (bottom + 0.17266 * sinH * t))\n if C > 0.0 and C < result:\n result = C\n return result"},{"col":0,"comment":"null","endLoc":204,"header":"def _get_win_folder_with_ctypes(csidl_name)","id":408,"name":"_get_win_folder_with_ctypes","nodeType":"Function","startLoc":180,"text":"def _get_win_folder_with_ctypes(csidl_name):\n import ctypes\n\n csidl_const = {\n \"CSIDL_APPDATA\": 26,\n \"CSIDL_COMMON_APPDATA\": 35,\n \"CSIDL_LOCAL_APPDATA\": 28,\n }[csidl_name]\n\n buf = ctypes.create_unicode_buffer(1024)\n ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)\n\n # Downgrade to short path name if have highbit chars. See\n # .\n has_high_char = False\n for c in buf:\n if ord(c) > 255:\n has_high_char = True\n break\n if has_high_char:\n buf2 = ctypes.create_unicode_buffer(1024)\n if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):\n buf = buf2\n\n return buf.value"},{"col":0,"comment":"null","endLoc":3258,"header":"def catplot(\n data=None, *, x=None, y=None, hue=None, row=None, col=None,\n col_wrap=None, estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000,\n units=None, seed=None, order=None, hue_order=None, row_order=None,\n col_order=None, height=5, aspect=1, kind=\"strip\", native_scale=False,\n formatter=None, orient=None, color=None, palette=None, hue_norm=None,\n legend=\"auto\", legend_out=True, sharex=True, sharey=True,\n margin_titles=False, facet_kws=None, ci=\"deprecated\",\n **kwargs\n)","id":411,"name":"catplot","nodeType":"Function","startLoc":2999,"text":"def catplot(\n data=None, *, x=None, y=None, hue=None, row=None, col=None,\n col_wrap=None, estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000,\n units=None, seed=None, order=None, hue_order=None, row_order=None,\n col_order=None, height=5, aspect=1, kind=\"strip\", native_scale=False,\n formatter=None, orient=None, color=None, palette=None, hue_norm=None,\n legend=\"auto\", legend_out=True, sharex=True, sharey=True,\n margin_titles=False, facet_kws=None, ci=\"deprecated\",\n **kwargs\n):\n\n # Determine the plotting function\n try:\n plot_func = globals()[kind + \"plot\"]\n except KeyError:\n err = f\"Plot kind '{kind}' is not recognized\"\n raise ValueError(err)\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\"catplot is a figure-level function and does not accept \"\n f\"target axes. You may wish to try {kind}plot\")\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n refactored_kinds = [\"strip\", \"swarm\"]\n if kind in refactored_kinds:\n\n p = _CategoricalFacetPlotter(\n data=data,\n variables=_CategoricalFacetPlotter.get_semantics(locals()),\n order=order,\n orient=orient,\n require_numeric=False,\n legend=legend,\n )\n\n # XXX Copying a fair amount from displot, which is not ideal\n\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n\n # Adapt the plot_data dataframe for use with FacetGrid\n data = p.plot_data.rename(columns=p.variables)\n data = data.loc[:, ~data.columns.duplicated()]\n\n col_name = p.variables.get(\"col\", None)\n row_name = p.variables.get(\"row\", None)\n\n if facet_kws is None:\n facet_kws = {}\n\n g = FacetGrid(\n data=data, row=row_name, col=col_name,\n col_wrap=col_wrap, row_order=row_order,\n col_order=col_order, height=height,\n sharex=sharex, sharey=sharey,\n aspect=aspect,\n **facet_kws,\n )\n\n # Capture this here because scale_categorical is going to insert a (null)\n # x variable even if it is empty. It's not clear whether that needs to\n # happen or if disabling that is the cleaner solution.\n has_xy_data = p.has_xy_data\n\n if not native_scale or p.var_types[p.cat_axis] == \"categorical\":\n p.scale_categorical(p.cat_axis, order=order, formatter=formatter)\n\n p._attach(g)\n\n if not has_xy_data:\n return g\n\n hue_order = p._palette_without_hue_backcompat(palette, hue_order)\n palette, hue_order = p._hue_backcompat(color, palette, hue_order)\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # Set a default color\n # Otherwise each artist will be plotted separately and trip the color cycle\n if hue is None and color is None:\n color = \"C0\"\n\n if kind == \"strip\":\n\n # TODO get these defaults programmatically?\n jitter = kwargs.pop(\"jitter\", True)\n dodge = kwargs.pop(\"dodge\", False)\n edgecolor = kwargs.pop(\"edgecolor\", \"gray\") # XXX TODO default\n\n plot_kws = kwargs.copy()\n\n # XXX Copying possibly bad default decisions from original code for now\n plot_kws.setdefault(\"zorder\", 3)\n plot_kws.setdefault(\"s\", plot_kws.pop(\"size\", 5) ** 2)\n plot_kws.setdefault(\"linewidth\", 0)\n\n p.plot_strips(\n jitter=jitter,\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n plot_kws=plot_kws,\n )\n\n elif kind == \"swarm\":\n\n # TODO get these defaults programmatically?\n dodge = kwargs.pop(\"dodge\", False)\n edgecolor = kwargs.pop(\"edgecolor\", \"gray\") # XXX TODO default\n warn_thresh = kwargs.pop(\"warn_thresh\", .05)\n\n plot_kws = kwargs.copy()\n\n # XXX Copying possibly bad default decisions from original code for now\n plot_kws.setdefault(\"zorder\", 3)\n plot_kws.setdefault(\"s\", plot_kws.pop(\"size\", 5) ** 2)\n\n if plot_kws.setdefault(\"linewidth\", 0) is None:\n plot_kws[\"linewidth\"] = np.sqrt(plot_kws[\"s\"]) / 10\n\n p.plot_swarms(\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n warn_thresh=warn_thresh,\n plot_kws=plot_kws,\n )\n\n # XXX best way to do this housekeeping?\n for ax in g.axes.flat:\n p._adjust_cat_axis(ax, axis=p.cat_axis)\n\n g.set_axis_labels(\n p.variables.get(\"x\", None),\n p.variables.get(\"y\", None),\n )\n g.set_titles()\n g.tight_layout()\n\n # XXX Hack to get the legend data in the right place\n for ax in g.axes.flat:\n g._update_legend_data(ax)\n ax.legend_ = None\n\n if legend and (hue is not None) and (hue not in [x, row, col]):\n g.add_legend(title=hue, label_order=hue_order)\n\n return g\n\n # Don't allow usage of forthcoming functionality\n if native_scale is True:\n err = f\"native_scale not yet implemented for `kind={kind}`\"\n raise ValueError(err)\n if formatter is not None:\n err = f\"formatter not yet implemented for `kind={kind}`\"\n raise ValueError(err)\n\n # Alias the input variables to determine categorical order and palette\n # correctly in the case of a count plot\n if kind == \"count\":\n if x is None and y is not None:\n x_, y_, orient = y, y, \"h\"\n elif y is None and x is not None:\n x_, y_, orient = x, x, \"v\"\n else:\n raise ValueError(\"Either `x` or `y` must be None for kind='count'\")\n else:\n x_, y_ = x, y\n\n # Determine the order for the whole dataset, which will be used in all\n # facets to ensure representation of all data in the final plot\n plotter_class = {\n \"box\": _BoxPlotter,\n \"violin\": _ViolinPlotter,\n \"boxen\": _LVPlotter,\n \"bar\": _BarPlotter,\n \"point\": _PointPlotter,\n \"count\": _CountPlotter,\n }[kind]\n p = _CategoricalPlotter()\n p.require_numeric = plotter_class.require_numeric\n p.establish_variables(x_, y_, hue, data, orient, order, hue_order)\n if (\n order is not None\n or (sharex and p.orient == \"v\")\n or (sharey and p.orient == \"h\")\n ):\n # Sync categorical axis between facets to have the same categories\n order = p.group_names\n elif color is None and hue is None:\n msg = (\n \"Setting `{}=False` with `color=None` may cause different levels of the \"\n \"`{}` variable to share colors. This will change in a future version.\"\n )\n if not sharex and p.orient == \"v\":\n warnings.warn(msg.format(\"sharex\", \"x\"), UserWarning)\n if not sharey and p.orient == \"h\":\n warnings.warn(msg.format(\"sharey\", \"y\"), UserWarning)\n\n hue_order = p.hue_names\n\n # Determine the palette to use\n # (FacetGrid will pass a value for ``color`` to the plotting function\n # so we need to define ``palette`` to get default behavior for the\n # categorical functions\n p.establish_colors(color, palette, 1)\n if kind != \"point\" or hue is not None:\n palette = p.colors\n\n # Determine keyword arguments for the facets\n facet_kws = {} if facet_kws is None else facet_kws\n facet_kws.update(\n data=data, row=row, col=col,\n row_order=row_order, col_order=col_order,\n col_wrap=col_wrap, height=height, aspect=aspect,\n sharex=sharex, sharey=sharey,\n legend_out=legend_out, margin_titles=margin_titles,\n dropna=False,\n )\n\n # Determine keyword arguments for the plotting function\n plot_kws = dict(\n order=order, hue_order=hue_order,\n orient=orient, color=color, palette=palette,\n )\n plot_kws.update(kwargs)\n\n if kind in [\"bar\", \"point\"]:\n errorbar = utils._deprecate_ci(errorbar, ci)\n plot_kws.update(\n estimator=estimator, errorbar=errorbar,\n n_boot=n_boot, units=units, seed=seed,\n )\n\n # Initialize the facets\n g = FacetGrid(**facet_kws)\n\n # Draw the plot onto the facets\n g.map_dataframe(plot_func, x=x, y=y, hue=hue, **plot_kws)\n\n if p.orient == \"h\":\n g.set_axis_labels(p.value_label, p.group_label)\n else:\n g.set_axis_labels(p.group_label, p.value_label)\n\n # Special case axis labels for a count type plot\n if kind == \"count\":\n if x is None:\n g.set_axis_labels(x_var=\"count\")\n if y is None:\n g.set_axis_labels(y_var=\"count\")\n\n if legend and (hue is not None) and (hue not in [x, row, col]):\n hue_order = list(map(utils.to_utf8, hue_order))\n g.add_legend(title=hue, label_order=hue_order)\n\n return g"},{"col":0,"comment":"null","endLoc":230,"header":"def _get_win_folder_with_jna(csidl_name)","id":412,"name":"_get_win_folder_with_jna","nodeType":"Function","startLoc":206,"text":"def _get_win_folder_with_jna(csidl_name):\n import array\n from com.sun import jna\n from com.sun.jna.platform import win32\n\n buf_size = win32.WinDef.MAX_PATH * 2\n buf = array.zeros('c', buf_size)\n shell = win32.Shell32.INSTANCE\n shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)\n dir = jna.Native.toString(buf.tostring()).rstrip(\"\\0\")\n\n # Downgrade to short path name if have highbit chars. See\n # .\n has_high_char = False\n for c in dir:\n if ord(c) > 255:\n has_high_char = True\n break\n if has_high_char:\n buf = array.zeros('c', buf_size)\n kernel = win32.Kernel32.INSTANCE\n if kernel.GetShortPathName(dir, buf, buf_size):\n dir = jna.Native.toString(buf.tostring()).rstrip(\"\\0\")\n\n return dir"},{"col":0,"comment":"\n Return hues with constant lightness and saturation in the HUSL system.\n\n The hues are evenly sampled along a circular path. The resulting palette will be\n appropriate for categorical or cyclical data.\n\n The `h`, `l`, and `s` values should be between 0 and 1.\n\n This function is similar to :func:`hls_palette`, but it uses a nonlinear color\n space that is more perceptually uniform.\n\n Parameters\n ----------\n n_colors : int\n Number of colors in the palette.\n h : float\n The value of the first hue.\n l : float\n The lightness value.\n s : float\n The saturation intensity.\n as_cmap : bool\n If True, return a matplotlib colormap object.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n hls_palette : Make a palette using evenly spaced hues in the HSL system.\n\n Examples\n --------\n .. include:: ../docstrings/husl_palette.rst\n\n ","endLoc":363,"header":"def husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False)","id":416,"name":"husl_palette","nodeType":"Function","startLoc":312,"text":"def husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False): # noqa\n \"\"\"\n Return hues with constant lightness and saturation in the HUSL system.\n\n The hues are evenly sampled along a circular path. The resulting palette will be\n appropriate for categorical or cyclical data.\n\n The `h`, `l`, and `s` values should be between 0 and 1.\n\n This function is similar to :func:`hls_palette`, but it uses a nonlinear color\n space that is more perceptually uniform.\n\n Parameters\n ----------\n n_colors : int\n Number of colors in the palette.\n h : float\n The value of the first hue.\n l : float\n The lightness value.\n s : float\n The saturation intensity.\n as_cmap : bool\n If True, return a matplotlib colormap object.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n hls_palette : Make a palette using evenly spaced hues in the HSL system.\n\n Examples\n --------\n .. include:: ../docstrings/husl_palette.rst\n\n \"\"\"\n if as_cmap:\n n_colors = 256\n hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]\n hues += h\n hues %= 1\n hues *= 359\n s *= 99\n l *= 99 # noqa\n palette = [_color_to_rgb((h_i, s, l), input=\"husl\") for h_i in hues]\n if as_cmap:\n return mpl.colors.ListedColormap(palette, \"hsl\")\n else:\n return _ColorPalette(palette)"},{"col":4,"comment":"null","endLoc":330,"header":"def __new__(cls, __x: ConvertibleToFloat = ...) -> Self","id":417,"name":"__new__","nodeType":"Function","startLoc":330,"text":"def __new__(cls, __x: ConvertibleToFloat = ...) -> Self: ..."},{"col":0,"comment":"null","endLoc":64,"header":"def lch_to_rgb(l, c, h)","id":418,"name":"lch_to_rgb","nodeType":"Function","startLoc":63,"text":"def lch_to_rgb(l, c, h):\n return xyz_to_rgb(luv_to_xyz(lch_to_luv([l, c, h])))"},{"col":0,"comment":"null","endLoc":257,"header":"def lch_to_luv(triple)","id":419,"name":"lch_to_luv","nodeType":"Function","startLoc":250,"text":"def lch_to_luv(triple):\n L, C, H = triple\n\n Hrad = math.radians(H)\n U = (math.cos(Hrad) * C)\n V = (math.sin(Hrad) * C)\n\n return [L, U, V]"},{"col":0,"comment":"null","endLoc":235,"header":"def luv_to_xyz(triple)","id":420,"name":"luv_to_xyz","nodeType":"Function","startLoc":222,"text":"def luv_to_xyz(triple):\n L, U, V = triple\n\n if L == 0:\n return [0.0, 0.0, 0.0]\n\n varY = f_inv((L + 16.0) / 116.0)\n varU = U / (13.0 * L) + refU\n varV = V / (13.0 * L) + refV\n Y = varY * refY\n X = 0.0 - (9.0 * Y * varU) / ((varU - 4.0) * varV - varU * varV)\n Z = (9.0 * Y - (15.0 * varV * Y) - (varV * X)) / (3.0 * varV)\n\n return [X, Y, Z]"},{"col":0,"comment":"null","endLoc":137,"header":"def f_inv(t)","id":421,"name":"f_inv","nodeType":"Function","startLoc":133,"text":"def f_inv(t):\n if math.pow(t, 3.0) > lab_e:\n return (math.pow(t, 3.0))\n else:\n return (116.0 * t - 16.0) / lab_k"},{"col":0,"comment":"null","endLoc":194,"header":"def xyz_to_rgb(triple)","id":422,"name":"xyz_to_rgb","nodeType":"Function","startLoc":192,"text":"def xyz_to_rgb(triple):\n xyz = map(lambda row: dot_product(row, triple), m)\n return list(map(from_linear, xyz))"},{"col":0,"comment":"null","endLoc":123,"header":"def dot_product(a, b)","id":423,"name":"dot_product","nodeType":"Function","startLoc":122,"text":"def dot_product(a, b):\n return sum(map(operator.mul, a, b))"},{"col":0,"comment":"This is a fallback technique at best. I'm not sure if using the\n registry for this guarantees us the correct answer for all CSIDL_*\n names.\n ","endLoc":150,"header":"def _get_win_folder_from_registry(csidl_name)","id":424,"name":"_get_win_folder_from_registry","nodeType":"Function","startLoc":132,"text":"def _get_win_folder_from_registry(csidl_name):\n \"\"\"This is a fallback technique at best. I'm not sure if using the\n registry for this guarantees us the correct answer for all CSIDL_*\n names.\n \"\"\"\n import winreg as _winreg\n\n shell_folder_name = {\n \"CSIDL_APPDATA\": \"AppData\",\n \"CSIDL_COMMON_APPDATA\": \"Common AppData\",\n \"CSIDL_LOCAL_APPDATA\": \"Local AppData\",\n }[csidl_name]\n\n key = _winreg.OpenKey(\n _winreg.HKEY_CURRENT_USER,\n r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"\n )\n dir, type = _winreg.QueryValueEx(key, shell_folder_name)\n return dir"},{"col":4,"comment":"null","endLoc":1106,"header":"@overload\n def pop(self, __key: _KT) -> _VT","id":425,"name":"pop","nodeType":"Function","startLoc":1105,"text":"@overload\n def pop(self, __key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1108,"header":"@overload\n def pop(self, __key: _KT, __default: _VT) -> _VT","id":426,"name":"pop","nodeType":"Function","startLoc":1107,"text":"@overload\n def pop(self, __key: _KT, __default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1110,"header":"@overload\n def pop(self, __key: _KT, __default: _T) -> _VT | _T","id":427,"name":"pop","nodeType":"Function","startLoc":1109,"text":"@overload\n def pop(self, __key: _KT, __default: _T) -> _VT | _T: ..."},{"col":0,"comment":"Turn stringified cubehelix params into args/kwargs.","endLoc":796,"header":"def _parse_cubehelix_args(argstr)","id":433,"name":"_parse_cubehelix_args","nodeType":"Function","startLoc":764,"text":"def _parse_cubehelix_args(argstr):\n \"\"\"Turn stringified cubehelix params into args/kwargs.\"\"\"\n\n if argstr.startswith(\"ch:\"):\n argstr = argstr[3:]\n\n if argstr.endswith(\"_r\"):\n reverse = True\n argstr = argstr[:-2]\n else:\n reverse = False\n\n if not argstr:\n return [], {\"reverse\": reverse}\n\n all_args = argstr.split(\",\")\n\n args = [float(a.strip(\" \")) for a in all_args if \"=\" not in a]\n\n kwargs = [a.split(\"=\") for a in all_args if \"=\" in a]\n kwargs = {k.strip(\" \"): float(v.strip(\" \")) for k, v in kwargs}\n\n kwarg_map = dict(\n s=\"start\", r=\"rot\", g=\"gamma\",\n h=\"hue\", l=\"light\", d=\"dark\", # noqa: E741\n )\n\n kwargs = {kwarg_map.get(k, k): v for k, v in kwargs.items()}\n\n if reverse:\n kwargs[\"reverse\"] = True\n\n return args, kwargs"},{"col":4,"comment":"null","endLoc":30,"header":"@overload\n def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None","id":434,"name":"warn","nodeType":"Function","startLoc":29,"text":"@overload\n def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":32,"header":"@overload\n def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None","id":435,"name":"warn","nodeType":"Function","startLoc":31,"text":"@overload\n def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":1100,"header":"@overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None","id":436,"name":"get","nodeType":"Function","startLoc":1099,"text":"@overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None: ..."},{"col":4,"comment":"null","endLoc":1102,"header":"@overload\n def get(self, __key: _KT, __default: _VT) -> _VT","id":437,"name":"get","nodeType":"Function","startLoc":1101,"text":"@overload\n def get(self, __key: _KT, __default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1104,"header":"@overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T","id":438,"name":"get","nodeType":"Function","startLoc":1103,"text":"@overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T: ..."},{"col":4,"comment":"Subset a dictionary arguments with known semantic variables.","endLoc":661,"header":"@classmethod\n def get_semantics(cls, kwargs, semantics=None)","id":447,"name":"get_semantics","nodeType":"Function","startLoc":651,"text":"@classmethod\n def get_semantics(cls, kwargs, semantics=None):\n \"\"\"Subset a dictionary arguments with known semantic variables.\"\"\"\n # TODO this should be get_variables since we have included x and y\n if semantics is None:\n semantics = cls.semantics\n variables = {}\n for key, val in kwargs.items():\n if key in semantics and val is not None:\n variables[key] = val\n return variables"},{"col":0,"comment":"Make a sequential palette from the cubehelix system.\n\n This produces a colormap with linearly-decreasing (or increasing)\n brightness. That means that information will be preserved if printed to\n black and white or viewed by someone who is colorblind. \"cubehelix\" is\n also available as a matplotlib-based palette, but this function gives the\n user more control over the look of the palette and has a different set of\n defaults.\n\n In addition to using this function, it is also possible to generate a\n cubehelix palette generally in seaborn using a string starting with\n `ch:` and containing other parameters (e.g. `\"ch:s=.25,r=-.5\"`).\n\n Parameters\n ----------\n n_colors : int\n Number of colors in the palette.\n start : float, 0 <= start <= 3\n The hue value at the start of the helix.\n rot : float\n Rotations around the hue wheel over the range of the palette.\n gamma : float 0 <= gamma\n Nonlinearity to emphasize dark (gamma < 1) or light (gamma > 1) colors.\n hue : float, 0 <= hue <= 1\n Saturation of the colors.\n dark : float 0 <= dark <= 1\n Intensity of the darkest color in the palette.\n light : float 0 <= light <= 1\n Intensity of the lightest color in the palette.\n reverse : bool\n If True, the palette will go from dark to light.\n as_cmap : bool\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n choose_cubehelix_palette : Launch an interactive widget to select cubehelix\n palette parameters.\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n\n References\n ----------\n Green, D. A. (2011). \"A colour scheme for the display of astronomical\n intensity images\". Bulletin of the Astromical Society of India, Vol. 39,\n p. 289-295.\n\n Examples\n --------\n .. include:: ../docstrings/cubehelix_palette.rst\n\n ","endLoc":761,"header":"def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,\n light=.85, dark=.15, reverse=False, as_cmap=False)","id":448,"name":"cubehelix_palette","nodeType":"Function","startLoc":665,"text":"def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,\n light=.85, dark=.15, reverse=False, as_cmap=False):\n \"\"\"Make a sequential palette from the cubehelix system.\n\n This produces a colormap with linearly-decreasing (or increasing)\n brightness. That means that information will be preserved if printed to\n black and white or viewed by someone who is colorblind. \"cubehelix\" is\n also available as a matplotlib-based palette, but this function gives the\n user more control over the look of the palette and has a different set of\n defaults.\n\n In addition to using this function, it is also possible to generate a\n cubehelix palette generally in seaborn using a string starting with\n `ch:` and containing other parameters (e.g. `\"ch:s=.25,r=-.5\"`).\n\n Parameters\n ----------\n n_colors : int\n Number of colors in the palette.\n start : float, 0 <= start <= 3\n The hue value at the start of the helix.\n rot : float\n Rotations around the hue wheel over the range of the palette.\n gamma : float 0 <= gamma\n Nonlinearity to emphasize dark (gamma < 1) or light (gamma > 1) colors.\n hue : float, 0 <= hue <= 1\n Saturation of the colors.\n dark : float 0 <= dark <= 1\n Intensity of the darkest color in the palette.\n light : float 0 <= light <= 1\n Intensity of the lightest color in the palette.\n reverse : bool\n If True, the palette will go from dark to light.\n as_cmap : bool\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n choose_cubehelix_palette : Launch an interactive widget to select cubehelix\n palette parameters.\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n\n References\n ----------\n Green, D. A. (2011). \"A colour scheme for the display of astronomical\n intensity images\". Bulletin of the Astromical Society of India, Vol. 39,\n p. 289-295.\n\n Examples\n --------\n .. include:: ../docstrings/cubehelix_palette.rst\n\n \"\"\"\n def get_color_function(p0, p1):\n # Copied from matplotlib because it lives in private module\n def color(x):\n # Apply gamma factor to emphasise low or high intensity values\n xg = x ** gamma\n\n # Calculate amplitude and angle of deviation from the black\n # to white diagonal in the plane of constant\n # perceived intensity.\n a = hue * xg * (1 - xg) / 2\n\n phi = 2 * np.pi * (start / 3 + rot * x)\n\n return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))\n return color\n\n cdict = {\n \"red\": get_color_function(-0.14861, 1.78277),\n \"green\": get_color_function(-0.29227, -0.90649),\n \"blue\": get_color_function(1.97294, 0.0),\n }\n\n cmap = mpl.colors.LinearSegmentedColormap(\"cubehelix\", cdict)\n\n x = np.linspace(light, dark, int(n_colors))\n pal = cmap(x)[:, :3].tolist()\n if reverse:\n pal = pal[::-1]\n\n if as_cmap:\n x_256 = np.linspace(light, dark, 256)\n if reverse:\n x_256 = x_256[::-1]\n pal_256 = cmap(x_256)\n cmap = mpl.colors.ListedColormap(pal_256, \"seaborn_cubehelix\")\n return cmap\n else:\n return _ColorPalette(pal)"},{"col":4,"comment":"null","endLoc":119,"header":"def __init__(\n self,\n data=None,\n variables={},\n order=None,\n orient=None,\n require_numeric=False,\n legend=\"auto\",\n )","id":451,"name":"__init__","nodeType":"Function","startLoc":56,"text":"def __init__(\n self,\n data=None,\n variables={},\n order=None,\n orient=None,\n require_numeric=False,\n legend=\"auto\",\n ):\n\n super().__init__(data=data, variables=variables)\n\n # This method takes care of some bookkeeping that is necessary because the\n # original categorical plots (prior to the 2021 refactor) had some rules that\n # don't fit exactly into the logic of _core. It may be wise to have a second\n # round of refactoring that moves the logic deeper, but this will keep things\n # relatively sensible for now.\n\n # For wide data, orient determines assignment to x/y differently from the\n # wide_structure rules in _core. If we do decide to make orient part of the\n # _core variable assignment, we'll want to figure out how to express that.\n if self.input_format == \"wide\" and orient == \"h\":\n self.plot_data = self.plot_data.rename(columns={\"x\": \"y\", \"y\": \"x\"})\n orig_variables = set(self.variables)\n orig_x = self.variables.pop(\"x\", None)\n orig_y = self.variables.pop(\"y\", None)\n orig_x_type = self.var_types.pop(\"x\", None)\n orig_y_type = self.var_types.pop(\"y\", None)\n if \"x\" in orig_variables:\n self.variables[\"y\"] = orig_x\n self.var_types[\"y\"] = orig_x_type\n if \"y\" in orig_variables:\n self.variables[\"x\"] = orig_y\n self.var_types[\"x\"] = orig_y_type\n\n # The concept of an \"orientation\" is important to the original categorical\n # plots, but there's no provision for it in _core, so we need to do it here.\n # Note that it could be useful for the other functions in at least two ways\n # (orienting a univariate distribution plot from long-form data and selecting\n # the aggregation axis in lineplot), so we may want to eventually refactor it.\n self.orient = infer_orient(\n x=self.plot_data.get(\"x\", None),\n y=self.plot_data.get(\"y\", None),\n orient=orient,\n require_numeric=require_numeric,\n )\n\n self.legend = legend\n\n # Short-circuit in the case of an empty plot\n if not self.has_xy_data:\n return\n\n # Categorical plots can be \"univariate\" in which case they get an anonymous\n # category label on the opposite axis. Note: this duplicates code in the core\n # scale_categorical function. We need to do it here because of the next line.\n if self.cat_axis not in self.variables:\n self.variables[self.cat_axis] = None\n self.var_types[self.cat_axis] = \"categorical\"\n self.plot_data[self.cat_axis] = \"\"\n\n # Categorical variables have discrete levels that we need to track\n cat_levels = categorical_order(self.plot_data[self.cat_axis], order)\n self.var_levels[self.cat_axis] = cat_levels"},{"col":0,"comment":"\n Set the parameters that control the general style of the plots.\n\n The style parameters control properties like the color of the background and\n whether a grid is enabled by default. This is accomplished using the\n matplotlib rcParams system.\n\n The options are illustrated in the\n :doc:`aesthetics tutorial <../tutorial/aesthetics>`.\n\n See :func:`axes_style` to get the parameter values.\n\n Parameters\n ----------\n style : dict, or one of {darkgrid, whitegrid, dark, white, ticks}\n A dictionary of parameters or the name of a preconfigured style.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n style dictionaries. This only updates parameters that are\n considered part of the style definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/set_style.rst\n\n ","endLoc":332,"header":"def set_style(style=None, rc=None)","id":452,"name":"set_style","nodeType":"Function","startLoc":303,"text":"def set_style(style=None, rc=None):\n \"\"\"\n Set the parameters that control the general style of the plots.\n\n The style parameters control properties like the color of the background and\n whether a grid is enabled by default. This is accomplished using the\n matplotlib rcParams system.\n\n The options are illustrated in the\n :doc:`aesthetics tutorial <../tutorial/aesthetics>`.\n\n See :func:`axes_style` to get the parameter values.\n\n Parameters\n ----------\n style : dict, or one of {darkgrid, whitegrid, dark, white, ticks}\n A dictionary of parameters or the name of a preconfigured style.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n style dictionaries. This only updates parameters that are\n considered part of the style definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/set_style.rst\n\n \"\"\"\n style_object = axes_style(style, rc)\n mpl.rcParams.update(style_object)"},{"col":0,"comment":"\n Get the parameters that control the general style of the plots.\n\n The style parameters control properties like the color of the background and\n whether a grid is enabled by default. This is accomplished using the\n matplotlib rcParams system.\n\n The options are illustrated in the\n :doc:`aesthetics tutorial <../tutorial/aesthetics>`.\n\n This function can also be used as a context manager to temporarily\n alter the global defaults. See :func:`set_theme` or :func:`set_style`\n to modify the global defaults for all plots.\n\n Parameters\n ----------\n style : None, dict, or one of {darkgrid, whitegrid, dark, white, ticks}\n A dictionary of parameters or the name of a preconfigured style.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n style dictionaries. This only updates parameters that are\n considered part of the style definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/axes_style.rst\n\n ","endLoc":300,"header":"def axes_style(style=None, rc=None)","id":453,"name":"axes_style","nodeType":"Function","startLoc":146,"text":"def axes_style(style=None, rc=None):\n \"\"\"\n Get the parameters that control the general style of the plots.\n\n The style parameters control properties like the color of the background and\n whether a grid is enabled by default. This is accomplished using the\n matplotlib rcParams system.\n\n The options are illustrated in the\n :doc:`aesthetics tutorial <../tutorial/aesthetics>`.\n\n This function can also be used as a context manager to temporarily\n alter the global defaults. See :func:`set_theme` or :func:`set_style`\n to modify the global defaults for all plots.\n\n Parameters\n ----------\n style : None, dict, or one of {darkgrid, whitegrid, dark, white, ticks}\n A dictionary of parameters or the name of a preconfigured style.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n style dictionaries. This only updates parameters that are\n considered part of the style definition.\n\n Examples\n --------\n\n .. include:: ../docstrings/axes_style.rst\n\n \"\"\"\n if style is None:\n style_dict = {k: mpl.rcParams[k] for k in _style_keys}\n\n elif isinstance(style, dict):\n style_dict = style\n\n else:\n styles = [\"white\", \"dark\", \"whitegrid\", \"darkgrid\", \"ticks\"]\n if style not in styles:\n raise ValueError(f\"style must be one of {', '.join(styles)}\")\n\n # Define colors here\n dark_gray = \".15\"\n light_gray = \".8\"\n\n # Common parameters\n style_dict = {\n\n \"figure.facecolor\": \"white\",\n \"axes.labelcolor\": dark_gray,\n\n \"xtick.direction\": \"out\",\n \"ytick.direction\": \"out\",\n \"xtick.color\": dark_gray,\n \"ytick.color\": dark_gray,\n\n \"axes.axisbelow\": True,\n \"grid.linestyle\": \"-\",\n\n\n \"text.color\": dark_gray,\n \"font.family\": [\"sans-serif\"],\n \"font.sans-serif\": [\"Arial\", \"DejaVu Sans\", \"Liberation Sans\",\n \"Bitstream Vera Sans\", \"sans-serif\"],\n\n\n \"lines.solid_capstyle\": \"round\",\n \"patch.edgecolor\": \"w\",\n \"patch.force_edgecolor\": True,\n\n \"image.cmap\": \"rocket\",\n\n \"xtick.top\": False,\n \"ytick.right\": False,\n\n }\n\n # Set grid on or off\n if \"grid\" in style:\n style_dict.update({\n \"axes.grid\": True,\n })\n else:\n style_dict.update({\n \"axes.grid\": False,\n })\n\n # Set the color of the background, spines, and grids\n if style.startswith(\"dark\"):\n style_dict.update({\n\n \"axes.facecolor\": \"#EAEAF2\",\n \"axes.edgecolor\": \"white\",\n \"grid.color\": \"white\",\n\n \"axes.spines.left\": True,\n \"axes.spines.bottom\": True,\n \"axes.spines.right\": True,\n \"axes.spines.top\": True,\n\n })\n\n elif style == \"whitegrid\":\n style_dict.update({\n\n \"axes.facecolor\": \"white\",\n \"axes.edgecolor\": light_gray,\n \"grid.color\": light_gray,\n\n \"axes.spines.left\": True,\n \"axes.spines.bottom\": True,\n \"axes.spines.right\": True,\n \"axes.spines.top\": True,\n\n })\n\n elif style in [\"white\", \"ticks\"]:\n style_dict.update({\n\n \"axes.facecolor\": \"white\",\n \"axes.edgecolor\": dark_gray,\n \"grid.color\": light_gray,\n\n \"axes.spines.left\": True,\n \"axes.spines.bottom\": True,\n \"axes.spines.right\": True,\n \"axes.spines.top\": True,\n\n })\n\n # Show or hide the axes ticks\n if style == \"ticks\":\n style_dict.update({\n \"xtick.bottom\": True,\n \"ytick.left\": True,\n })\n else:\n style_dict.update({\n \"xtick.bottom\": False,\n \"ytick.left\": False,\n })\n\n # Remove entries that are not defined in the base list of valid keys\n # This lets us handle matplotlib <=/> 2.0\n style_dict = {k: v for k, v in style_dict.items() if k in _style_keys}\n\n # Override these settings with the provided rc dictionary\n if rc is not None:\n rc = {k: v for k, v in rc.items() if k in _style_keys}\n style_dict.update(rc)\n\n # Wrap in an _AxesStyle object so this can be used in a with statement\n style_object = _AxesStyle(style_dict)\n\n return style_object"},{"col":4,"comment":"null","endLoc":1088,"header":"def items(self) -> dict_items[_KT, _VT]","id":454,"name":"items","nodeType":"Function","startLoc":1088,"text":"def items(self) -> dict_items[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":649,"header":"def __init__(self, data=None, variables={})","id":456,"name":"__init__","nodeType":"Function","startLoc":632,"text":"def __init__(self, data=None, variables={}):\n\n self._var_levels = {}\n # var_ordered is relevant only for categorical axis variables, and may\n # be better handled by an internal axis information object that tracks\n # such information and is set up by the scale_* methods. The analogous\n # information for numeric axes would be information about log scales.\n self._var_ordered = {\"x\": False, \"y\": False} # alt., used DefaultDict\n self.assign_variables(data, variables)\n\n for var, cls in self._semantic_mappings.items():\n\n # Create the mapping function\n map_func = partial(cls.map, plotter=self)\n setattr(self, f\"map_{var}\", map_func)\n\n # Call the mapping function to initialize with default values\n getattr(self, f\"map_{var}\")()"},{"col":4,"comment":"Define plot variables, optionally using lookup from `data`.","endLoc":715,"header":"def assign_variables(self, data=None, variables={})","id":457,"name":"assign_variables","nodeType":"Function","startLoc":689,"text":"def assign_variables(self, data=None, variables={}):\n \"\"\"Define plot variables, optionally using lookup from `data`.\"\"\"\n x = variables.get(\"x\", None)\n y = variables.get(\"y\", None)\n\n if x is None and y is None:\n self.input_format = \"wide\"\n plot_data, variables = self._assign_variables_wideform(\n data, **variables,\n )\n else:\n self.input_format = \"long\"\n plot_data, variables = self._assign_variables_longform(\n data, **variables,\n )\n\n self.plot_data = plot_data\n self.variables = variables\n self.var_types = {\n v: variable_type(\n plot_data[v],\n boolean_type=\"numeric\" if v in \"xy\" else \"categorical\"\n )\n for v in variables\n }\n\n return self"},{"col":0,"comment":"Make a sequential palette that blends from dark to ``color``.\n\n This kind of palette is good for data that range between relatively\n uninteresting low values and interesting high values.\n\n The ``color`` parameter can be specified in a number of ways, including\n all options for defining a color in matplotlib and several additional\n color spaces that are handled by seaborn. You can also use the database\n of named colors from the XKCD color survey.\n\n If you are using the IPython notebook, you can also choose this palette\n interactively with the :func:`choose_dark_palette` function.\n\n Parameters\n ----------\n color : base color for high values\n hex, rgb-tuple, or html color name\n n_colors : int, optional\n number of colors in the palette\n reverse : bool, optional\n if True, reverse the direction of the blend\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n input : {'rgb', 'hls', 'husl', xkcd'}\n Color space to interpret the input color. The first three options\n apply to tuple inputs and the latter applies to string inputs.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n light_palette : Create a sequential palette with bright low values.\n diverging_palette : Create a diverging palette with two colors.\n\n Examples\n --------\n .. include:: ../docstrings/dark_palette.rst\n\n ","endLoc":481,"header":"def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input=\"rgb\")","id":458,"name":"dark_palette","nodeType":"Function","startLoc":433,"text":"def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input=\"rgb\"):\n \"\"\"Make a sequential palette that blends from dark to ``color``.\n\n This kind of palette is good for data that range between relatively\n uninteresting low values and interesting high values.\n\n The ``color`` parameter can be specified in a number of ways, including\n all options for defining a color in matplotlib and several additional\n color spaces that are handled by seaborn. You can also use the database\n of named colors from the XKCD color survey.\n\n If you are using the IPython notebook, you can also choose this palette\n interactively with the :func:`choose_dark_palette` function.\n\n Parameters\n ----------\n color : base color for high values\n hex, rgb-tuple, or html color name\n n_colors : int, optional\n number of colors in the palette\n reverse : bool, optional\n if True, reverse the direction of the blend\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n input : {'rgb', 'hls', 'husl', xkcd'}\n Color space to interpret the input color. The first three options\n apply to tuple inputs and the latter applies to string inputs.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n light_palette : Create a sequential palette with bright low values.\n diverging_palette : Create a diverging palette with two colors.\n\n Examples\n --------\n .. include:: ../docstrings/dark_palette.rst\n\n \"\"\"\n rgb = _color_to_rgb(color, input)\n h, s, l = husl.rgb_to_husl(*rgb)\n gray_s, gray_l = .15 * s, 15\n gray = _color_to_rgb((h, gray_s, gray_l), input=\"husl\")\n colors = [rgb, gray] if reverse else [gray, rgb]\n return blend_palette(colors, n_colors, as_cmap)"},{"col":4,"comment":"Define plot variables given wide-form data.\n\n Parameters\n ----------\n data : flat vector or collection of vectors\n Data can be a vector or mapping that is coerceable to a Series\n or a sequence- or mapping-based collection of such vectors, or a\n rectangular numpy array, or a Pandas DataFrame.\n kwargs : variable -> data mappings\n Behavior with keyword arguments is currently undefined.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n ","endLoc":857,"header":"def _assign_variables_wideform(self, data=None, **kwargs)","id":459,"name":"_assign_variables_wideform","nodeType":"Function","startLoc":717,"text":"def _assign_variables_wideform(self, data=None, **kwargs):\n \"\"\"Define plot variables given wide-form data.\n\n Parameters\n ----------\n data : flat vector or collection of vectors\n Data can be a vector or mapping that is coerceable to a Series\n or a sequence- or mapping-based collection of such vectors, or a\n rectangular numpy array, or a Pandas DataFrame.\n kwargs : variable -> data mappings\n Behavior with keyword arguments is currently undefined.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n \"\"\"\n # Raise if semantic or other variables are assigned in wide-form mode\n assigned = [k for k, v in kwargs.items() if v is not None]\n if any(assigned):\n s = \"s\" if len(assigned) > 1 else \"\"\n err = f\"The following variable{s} cannot be assigned with wide-form data: \"\n err += \", \".join(f\"`{v}`\" for v in assigned)\n raise ValueError(err)\n\n # Determine if the data object actually has any data in it\n empty = data is None or not len(data)\n\n # Then, determine if we have \"flat\" data (a single vector)\n if isinstance(data, dict):\n values = data.values()\n else:\n values = np.atleast_1d(np.asarray(data, dtype=object))\n flat = not any(\n isinstance(v, Iterable) and not isinstance(v, (str, bytes))\n for v in values\n )\n\n if empty:\n\n # Make an object with the structure of plot_data, but empty\n plot_data = pd.DataFrame()\n variables = {}\n\n elif flat:\n\n # Handle flat data by converting to pandas Series and using the\n # index and/or values to define x and/or y\n # (Could be accomplished with a more general to_series() interface)\n flat_data = pd.Series(data).copy()\n names = {\n \"@values\": flat_data.name,\n \"@index\": flat_data.index.name\n }\n\n plot_data = {}\n variables = {}\n\n for var in [\"x\", \"y\"]:\n if var in self.flat_structure:\n attr = self.flat_structure[var]\n plot_data[var] = getattr(flat_data, attr[1:])\n variables[var] = names[self.flat_structure[var]]\n\n plot_data = pd.DataFrame(plot_data)\n\n else:\n\n # Otherwise assume we have some collection of vectors.\n\n # Handle Python sequences such that entries end up in the columns,\n # not in the rows, of the intermediate wide DataFrame.\n # One way to accomplish this is to convert to a dict of Series.\n if isinstance(data, Sequence):\n data_dict = {}\n for i, var in enumerate(data):\n key = getattr(var, \"name\", i)\n # TODO is there a safer/more generic way to ensure Series?\n # sort of like np.asarray, but for pandas?\n data_dict[key] = pd.Series(var)\n\n data = data_dict\n\n # Pandas requires that dict values either be Series objects\n # or all have the same length, but we want to allow \"ragged\" inputs\n if isinstance(data, Mapping):\n data = {key: pd.Series(val) for key, val in data.items()}\n\n # Otherwise, delegate to the pandas DataFrame constructor\n # This is where we'd prefer to use a general interface that says\n # \"give me this data as a pandas DataFrame\", so we can accept\n # DataFrame objects from other libraries\n wide_data = pd.DataFrame(data, copy=True)\n\n # At this point we should reduce the dataframe to numeric cols\n numeric_cols = [\n k for k, v in wide_data.items() if variable_type(v) == \"numeric\"\n ]\n wide_data = wide_data[numeric_cols]\n\n # Now melt the data to long form\n melt_kws = {\"var_name\": \"@columns\", \"value_name\": \"@values\"}\n use_index = \"@index\" in self.wide_structure.values()\n if use_index:\n melt_kws[\"id_vars\"] = \"@index\"\n try:\n orig_categories = wide_data.columns.categories\n orig_ordered = wide_data.columns.ordered\n wide_data.columns = wide_data.columns.add_categories(\"@index\")\n except AttributeError:\n category_columns = False\n else:\n category_columns = True\n wide_data[\"@index\"] = wide_data.index.to_series()\n\n plot_data = wide_data.melt(**melt_kws)\n\n if use_index and category_columns:\n plot_data[\"@columns\"] = pd.Categorical(plot_data[\"@columns\"],\n orig_categories,\n orig_ordered)\n\n # Assign names corresponding to plot semantics\n for var, attr in self.wide_structure.items():\n plot_data[var] = plot_data[attr]\n\n # Define the variable names\n variables = {}\n for var, attr in self.wide_structure.items():\n obj = getattr(wide_data, attr[1:])\n variables[var] = getattr(obj, \"name\", None)\n\n # Remove redundant columns from plot_data\n plot_data = plot_data[list(variables)]\n\n return plot_data, variables"},{"col":0,"comment":"null","endLoc":40,"header":"def rgb_to_husl(r, g, b)","id":461,"name":"rgb_to_husl","nodeType":"Function","startLoc":39,"text":"def rgb_to_husl(r, g, b):\n return lch_to_husl(rgb_to_lch(r, g, b))"},{"col":0,"comment":"null","endLoc":68,"header":"def rgb_to_lch(r, g, b)","id":462,"name":"rgb_to_lch","nodeType":"Function","startLoc":67,"text":"def rgb_to_lch(r, g, b):\n return luv_to_lch(xyz_to_luv(rgb_to_xyz([r, g, b])))"},{"col":0,"comment":"null","endLoc":199,"header":"def rgb_to_xyz(triple)","id":463,"name":"rgb_to_xyz","nodeType":"Function","startLoc":197,"text":"def rgb_to_xyz(triple):\n rgbl = list(map(to_linear, triple))\n return list(map(lambda row: dot_product(row, rgbl), m_inv))"},{"col":4,"comment":"null","endLoc":1014,"header":"def append(self, __object: _T) -> None","id":464,"name":"append","nodeType":"Function","startLoc":1014,"text":"def append(self, __object: _T) -> None: ..."},{"col":14,"endLoc":193,"id":475,"nodeType":"Lambda","startLoc":193,"text":"lambda row: dot_product(row, triple)"},{"col":0,"comment":"Remove the top and right spines from plot(s).\n\n fig : matplotlib figure, optional\n Figure to despine all axes of, defaults to the current figure.\n ax : matplotlib axes, optional\n Specific axes object to despine. Ignored if fig is provided.\n top, right, left, bottom : boolean, optional\n If True, remove that spine.\n offset : int or dict, optional\n Absolute distance, in points, spines should be moved away\n from the axes (negative values move spines inward). A single value\n applies to all spines; a dict can be used to set offset values per\n side.\n trim : bool, optional\n If True, limit spines to the smallest and largest major tick\n on each non-despined axis.\n\n Returns\n -------\n None\n\n ","endLoc":393,"header":"def despine(fig=None, ax=None, top=True, right=True, left=False,\n bottom=False, offset=None, trim=False)","id":479,"name":"despine","nodeType":"Function","startLoc":294,"text":"def despine(fig=None, ax=None, top=True, right=True, left=False,\n bottom=False, offset=None, trim=False):\n \"\"\"Remove the top and right spines from plot(s).\n\n fig : matplotlib figure, optional\n Figure to despine all axes of, defaults to the current figure.\n ax : matplotlib axes, optional\n Specific axes object to despine. Ignored if fig is provided.\n top, right, left, bottom : boolean, optional\n If True, remove that spine.\n offset : int or dict, optional\n Absolute distance, in points, spines should be moved away\n from the axes (negative values move spines inward). A single value\n applies to all spines; a dict can be used to set offset values per\n side.\n trim : bool, optional\n If True, limit spines to the smallest and largest major tick\n on each non-despined axis.\n\n Returns\n -------\n None\n\n \"\"\"\n # Get references to the axes we want\n if fig is None and ax is None:\n axes = plt.gcf().axes\n elif fig is not None:\n axes = fig.axes\n elif ax is not None:\n axes = [ax]\n\n for ax_i in axes:\n for side in [\"top\", \"right\", \"left\", \"bottom\"]:\n # Toggle the spine objects\n is_visible = not locals()[side]\n ax_i.spines[side].set_visible(is_visible)\n if offset is not None and is_visible:\n try:\n val = offset.get(side, 0)\n except AttributeError:\n val = offset\n ax_i.spines[side].set_position(('outward', val))\n\n # Potentially move the ticks\n if left and not right:\n maj_on = any(\n t.tick1line.get_visible()\n for t in ax_i.yaxis.majorTicks\n )\n min_on = any(\n t.tick1line.get_visible()\n for t in ax_i.yaxis.minorTicks\n )\n ax_i.yaxis.set_ticks_position(\"right\")\n for t in ax_i.yaxis.majorTicks:\n t.tick2line.set_visible(maj_on)\n for t in ax_i.yaxis.minorTicks:\n t.tick2line.set_visible(min_on)\n\n if bottom and not top:\n maj_on = any(\n t.tick1line.get_visible()\n for t in ax_i.xaxis.majorTicks\n )\n min_on = any(\n t.tick1line.get_visible()\n for t in ax_i.xaxis.minorTicks\n )\n ax_i.xaxis.set_ticks_position(\"top\")\n for t in ax_i.xaxis.majorTicks:\n t.tick2line.set_visible(maj_on)\n for t in ax_i.xaxis.minorTicks:\n t.tick2line.set_visible(min_on)\n\n if trim:\n # clip off the parts of the spines that extend past major ticks\n xticks = np.asarray(ax_i.get_xticks())\n if xticks.size:\n firsttick = np.compress(xticks >= min(ax_i.get_xlim()),\n xticks)[0]\n lasttick = np.compress(xticks <= max(ax_i.get_xlim()),\n xticks)[-1]\n ax_i.spines['bottom'].set_bounds(firsttick, lasttick)\n ax_i.spines['top'].set_bounds(firsttick, lasttick)\n newticks = xticks.compress(xticks <= lasttick)\n newticks = newticks.compress(newticks >= firsttick)\n ax_i.set_xticks(newticks)\n\n yticks = np.asarray(ax_i.get_yticks())\n if yticks.size:\n firsttick = np.compress(yticks >= min(ax_i.get_ylim()),\n yticks)[0]\n lasttick = np.compress(yticks <= max(ax_i.get_ylim()),\n yticks)[-1]\n ax_i.spines['left'].set_bounds(firsttick, lasttick)\n ax_i.spines['right'].set_bounds(firsttick, lasttick)\n newticks = yticks.compress(yticks <= lasttick)\n newticks = newticks.compress(newticks >= firsttick)\n ax_i.set_yticks(newticks)"},{"className":"Property","col":0,"comment":"Base class for visual properties that can be set directly or be data scaling.","endLoc":140,"id":482,"nodeType":"Class","startLoc":47,"text":"class Property:\n \"\"\"Base class for visual properties that can be set directly or be data scaling.\"\"\"\n\n # When True, scales for this property will populate the legend by default\n legend = False\n\n # When True, scales for this property normalize data to [0, 1] before mapping\n normed = False\n\n def __init__(self, variable: str | None = None):\n \"\"\"Initialize the property with the name of the corresponding plot variable.\"\"\"\n if not variable:\n variable = self.__class__.__name__.lower()\n self.variable = variable\n\n def default_scale(self, data: Series) -> Scale:\n \"\"\"Given data, initialize appropriate scale class.\"\"\"\n # TODO allow variable_type to be \"boolean\" if that's a scale?\n # TODO how will this handle data with units that can be treated as numeric\n # if passed through a registered matplotlib converter?\n var_type = variable_type(data, boolean_type=\"numeric\")\n if var_type == \"numeric\":\n return Continuous()\n elif var_type == \"datetime\":\n return Temporal()\n # TODO others\n # time-based (TimeStamp, TimeDelta, Period)\n # boolean scale?\n else:\n return Nominal()\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n # TODO put these somewhere external for validation\n # TODO putting this here won't pick it up if subclasses define infer_scale\n # (e.g. color). How best to handle that? One option is to call super after\n # handling property-specific possibilities (e.g. for color check that the\n # arg is not a valid palette name) but that could get tricky.\n trans_args = [\"log\", \"symlog\", \"logit\", \"pow\", \"sqrt\"]\n if isinstance(arg, str):\n if any(arg.startswith(k) for k in trans_args):\n # TODO validate numeric type? That should happen centrally somewhere\n return Continuous(trans=arg)\n else:\n msg = f\"Unknown magic arg for {self.variable} scale: '{arg}'.\"\n raise ValueError(msg)\n else:\n arg_type = type(arg).__name__\n msg = f\"Magic arg for {self.variable} scale must be str, not {arg_type}.\"\n raise TypeError(msg)\n\n def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to property range.\"\"\"\n def identity(x):\n return x\n return identity\n\n def standardize(self, val: Any) -> Any:\n \"\"\"Coerce flexible property value to standardized representation.\"\"\"\n return val\n\n def _check_dict_entries(self, levels: list, values: dict) -> None:\n \"\"\"Input check when values are provided as a dictionary.\"\"\"\n missing = set(levels) - set(values)\n if missing:\n formatted = \", \".join(map(repr, sorted(missing, key=str)))\n err = f\"No entry in {self.variable} dictionary for {formatted}\"\n raise ValueError(err)\n\n def _check_list_length(self, levels: list, values: list) -> list:\n \"\"\"Input check when values are provided as a list.\"\"\"\n message = \"\"\n if len(levels) > len(values):\n message = \" \".join([\n f\"\\nThe {self.variable} list has fewer values ({len(values)})\",\n f\"than needed ({len(levels)}) and will cycle, which may\",\n \"produce an uninterpretable plot.\"\n ])\n values = [x for _, x in zip(levels, itertools.cycle(values))]\n\n elif len(values) > len(levels):\n message = \" \".join([\n f\"The {self.variable} list has more values ({len(values)})\",\n f\"than needed ({len(levels)}), which may not be intended.\",\n ])\n values = values[:len(levels)]\n\n # TODO look into custom PlotSpecWarning with better formatting\n if message:\n warnings.warn(message, UserWarning)\n\n return values"},{"col":4,"comment":"Given data, initialize appropriate scale class.","endLoc":76,"header":"def default_scale(self, data: Series) -> Scale","id":483,"name":"default_scale","nodeType":"Function","startLoc":62,"text":"def default_scale(self, data: Series) -> Scale:\n \"\"\"Given data, initialize appropriate scale class.\"\"\"\n # TODO allow variable_type to be \"boolean\" if that's a scale?\n # TODO how will this handle data with units that can be treated as numeric\n # if passed through a registered matplotlib converter?\n var_type = variable_type(data, boolean_type=\"numeric\")\n if var_type == \"numeric\":\n return Continuous()\n elif var_type == \"datetime\":\n return Temporal()\n # TODO others\n # time-based (TimeStamp, TimeDelta, Period)\n # boolean scale?\n else:\n return Nominal()"},{"col":0,"comment":"Set the matplotlib color cycle using a seaborn palette.\n\n Parameters\n ----------\n palette : seaborn color paltte | matplotlib colormap | hls | husl\n Palette definition. Should be something :func:`color_palette` can process.\n n_colors : int\n Number of colors in the cycle. The default number of colors will depend\n on the format of ``palette``, see the :func:`color_palette`\n documentation for more information.\n desat : float\n Proportion to desaturate each color by.\n color_codes : bool\n If ``True`` and ``palette`` is a seaborn palette, remap the shorthand\n color codes (e.g. \"b\", \"g\", \"r\", etc.) to the colors from this palette.\n\n See Also\n --------\n color_palette : build a color palette or set the color cycle temporarily\n in a ``with`` statement.\n set_context : set parameters to scale plot elements\n set_style : set the default parameters for figure style\n\n ","endLoc":534,"header":"def set_palette(palette, n_colors=None, desat=None, color_codes=False)","id":484,"name":"set_palette","nodeType":"Function","startLoc":502,"text":"def set_palette(palette, n_colors=None, desat=None, color_codes=False):\n \"\"\"Set the matplotlib color cycle using a seaborn palette.\n\n Parameters\n ----------\n palette : seaborn color paltte | matplotlib colormap | hls | husl\n Palette definition. Should be something :func:`color_palette` can process.\n n_colors : int\n Number of colors in the cycle. The default number of colors will depend\n on the format of ``palette``, see the :func:`color_palette`\n documentation for more information.\n desat : float\n Proportion to desaturate each color by.\n color_codes : bool\n If ``True`` and ``palette`` is a seaborn palette, remap the shorthand\n color codes (e.g. \"b\", \"g\", \"r\", etc.) to the colors from this palette.\n\n See Also\n --------\n color_palette : build a color palette or set the color cycle temporarily\n in a ``with`` statement.\n set_context : set parameters to scale plot elements\n set_style : set the default parameters for figure style\n\n \"\"\"\n colors = palettes.color_palette(palette, n_colors, desat)\n cyl = cycler('color', colors)\n mpl.rcParams['axes.prop_cycle'] = cyl\n if color_codes:\n try:\n palettes.set_color_codes(palette)\n except (ValueError, TypeError):\n pass"},{"col":0,"comment":"Change how matplotlib color shorthands are interpreted.\n\n Calling this will change how shorthand codes like \"b\" or \"g\"\n are interpreted by matplotlib in subsequent plots.\n\n Parameters\n ----------\n palette : {deep, muted, pastel, dark, bright, colorblind}\n Named seaborn palette to use as the source of colors.\n\n See Also\n --------\n set : Color codes can be set through the high-level seaborn style\n manager.\n set_palette : Color codes can also be set through the function that\n sets the matplotlib color cycle.\n\n ","endLoc":842,"header":"def set_color_codes(palette=\"deep\")","id":497,"name":"set_color_codes","nodeType":"Function","startLoc":799,"text":"def set_color_codes(palette=\"deep\"):\n \"\"\"Change how matplotlib color shorthands are interpreted.\n\n Calling this will change how shorthand codes like \"b\" or \"g\"\n are interpreted by matplotlib in subsequent plots.\n\n Parameters\n ----------\n palette : {deep, muted, pastel, dark, bright, colorblind}\n Named seaborn palette to use as the source of colors.\n\n See Also\n --------\n set : Color codes can be set through the high-level seaborn style\n manager.\n set_palette : Color codes can also be set through the function that\n sets the matplotlib color cycle.\n\n \"\"\"\n if palette == \"reset\":\n colors = [\n (0., 0., 1.),\n (0., .5, 0.),\n (1., 0., 0.),\n (.75, 0., .75),\n (.75, .75, 0.),\n (0., .75, .75),\n (0., 0., 0.)\n ]\n elif not isinstance(palette, str):\n err = \"set_color_codes requires a named seaborn palette\"\n raise TypeError(err)\n elif palette in SEABORN_PALETTES:\n if not palette.endswith(\"6\"):\n palette = palette + \"6\"\n colors = SEABORN_PALETTES[palette] + [(.1, .1, .1)]\n else:\n err = f\"Cannot set colors with palette '{palette}'\"\n raise ValueError(err)\n\n for code, color in zip(\"bgrmyck\", colors):\n rgb = mpl.colors.colorConverter.to_rgb(color)\n mpl.colors.colorConverter.colors[code] = rgb\n mpl.colors.colorConverter.cache[code] = rgb"},{"col":0,"comment":"null","endLoc":1465,"header":"def histplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Histogram computation parameters\n stat=\"count\", bins=\"auto\", binwidth=None, binrange=None,\n discrete=None, cumulative=False, common_bins=True, common_norm=True,\n # Histogram appearance parameters\n multiple=\"layer\", element=\"bars\", fill=True, shrink=1,\n # Histogram smoothing with a kernel density estimate\n kde=False, kde_kws=None, line_kws=None,\n # Bivariate histogram parameters\n thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n)","id":498,"name":"histplot","nodeType":"Function","startLoc":1374,"text":"def histplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Histogram computation parameters\n stat=\"count\", bins=\"auto\", binwidth=None, binrange=None,\n discrete=None, cumulative=False, common_bins=True, common_norm=True,\n # Histogram appearance parameters\n multiple=\"layer\", element=\"bars\", fill=True, shrink=1,\n # Histogram smoothing with a kernel density estimate\n kde=False, kde_kws=None, line_kws=None,\n # Bivariate histogram parameters\n thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n):\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, log_scale=log_scale)\n\n if p.univariate: # Note, bivariate plots won't cycle\n if fill:\n method = ax.bar if element == \"bars\" else ax.fill_between\n else:\n method = ax.plot\n color = _default_color(method, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # Default to discrete bins for categorical variables\n if discrete is None:\n discrete = p._default_discrete()\n\n estimate_kws = dict(\n stat=stat,\n bins=bins,\n binwidth=binwidth,\n binrange=binrange,\n discrete=discrete,\n cumulative=cumulative,\n )\n\n if p.univariate:\n\n p.plot_univariate_histogram(\n multiple=multiple,\n element=element,\n fill=fill,\n shrink=shrink,\n common_norm=common_norm,\n common_bins=common_bins,\n kde=kde,\n kde_kws=kde_kws,\n color=color,\n legend=legend,\n estimate_kws=estimate_kws,\n line_kws=line_kws,\n **kwargs,\n )\n\n else:\n\n p.plot_bivariate_histogram(\n common_bins=common_bins,\n common_norm=common_norm,\n thresh=thresh,\n pthresh=pthresh,\n pmax=pmax,\n color=color,\n legend=legend,\n cbar=cbar,\n cbar_ax=cbar_ax,\n cbar_kws=cbar_kws,\n estimate_kws=estimate_kws,\n **kwargs,\n )\n\n return ax"},{"col":4,"comment":"null","endLoc":248,"header":"def __repr__(self) -> str","id":500,"name":"__repr__","nodeType":"Function","startLoc":247,"text":"def __repr__(self) -> str:\n return f\"\""},{"col":4,"comment":"null","endLoc":276,"header":"def __str__(self) -> str","id":501,"name":"__str__","nodeType":"Function","startLoc":250,"text":"def __str__(self) -> str:\n parts = []\n\n # Epoch\n if self.epoch != 0:\n parts.append(f\"{self.epoch}!\")\n\n # Release segment\n parts.append(\".\".join(str(x) for x in self.release))\n\n # Pre-release\n if self.pre is not None:\n parts.append(\"\".join(str(x) for x in self.pre))\n\n # Post-release\n if self.post is not None:\n parts.append(f\".post{self.post}\")\n\n # Development release\n if self.dev is not None:\n parts.append(f\".dev{self.dev}\")\n\n # Local version segment\n if self.local is not None:\n parts.append(f\"+{self.local}\")\n\n return \"\".join(parts)"},{"col":0,"comment":"\n Make invisible-handle \"subtitles\" entries look more like titles.\n\n Note: This function is not part of the public API and may be changed or removed.\n\n ","endLoc":824,"header":"def adjust_legend_subtitles(legend)","id":504,"name":"adjust_legend_subtitles","nodeType":"Function","startLoc":807,"text":"def adjust_legend_subtitles(legend):\n \"\"\"\n Make invisible-handle \"subtitles\" entries look more like titles.\n\n Note: This function is not part of the public API and may be changed or removed.\n\n \"\"\"\n # Legend title not in rcParams until 3.0\n font_size = plt.rcParams.get(\"legend.title_fontsize\", None)\n hpackers = legend.findobj(mpl.offsetbox.VPacker)[0].get_children()\n for hpack in hpackers:\n draw_area, text_area = hpack.get_children()\n handles = draw_area.get_children()\n if not all(artist.get_visible() for artist in handles):\n draw_area.set_width(0)\n for text in text_area.get_children():\n if font_size is not None:\n text.set_size(font_size)"},{"col":0,"comment":"\n Determine whether a vector contains numeric, categorical, or datetime data.\n\n This function differs from the pandas typing API in two ways:\n\n - Python sequences or object-typed PyData objects are considered numeric if\n all of their entries are numeric.\n - String or mixed-type data are considered categorical even if not\n explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.\n\n Parameters\n ----------\n vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence\n Input data to test.\n boolean_type : 'numeric' or 'categorical'\n Type to use for vectors containing only 0s and 1s (and NAs).\n\n Returns\n -------\n var_type : 'numeric', 'categorical', or 'datetime'\n Name identifying the type of data in the vector.\n ","endLoc":1553,"header":"def variable_type(vector, boolean_type=\"numeric\")","id":505,"name":"variable_type","nodeType":"Function","startLoc":1473,"text":"def variable_type(vector, boolean_type=\"numeric\"):\n \"\"\"\n Determine whether a vector contains numeric, categorical, or datetime data.\n\n This function differs from the pandas typing API in two ways:\n\n - Python sequences or object-typed PyData objects are considered numeric if\n all of their entries are numeric.\n - String or mixed-type data are considered categorical even if not\n explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.\n\n Parameters\n ----------\n vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence\n Input data to test.\n boolean_type : 'numeric' or 'categorical'\n Type to use for vectors containing only 0s and 1s (and NAs).\n\n Returns\n -------\n var_type : 'numeric', 'categorical', or 'datetime'\n Name identifying the type of data in the vector.\n \"\"\"\n\n # If a categorical dtype is set, infer categorical\n if pd.api.types.is_categorical_dtype(vector):\n return VariableType(\"categorical\")\n\n # Special-case all-na data, which is always \"numeric\"\n if pd.isna(vector).all():\n return VariableType(\"numeric\")\n\n # Special-case binary/boolean data, allow caller to determine\n # This triggers a numpy warning when vector has strings/objects\n # https://github.com/numpy/numpy/issues/6784\n # Because we reduce with .all(), we are agnostic about whether the\n # comparison returns a scalar or vector, so we will ignore the warning.\n # It triggers a separate DeprecationWarning when the vector has datetimes:\n # https://github.com/numpy/numpy/issues/13548\n # This is considered a bug by numpy and will likely go away.\n with warnings.catch_warnings():\n warnings.simplefilter(\n action='ignore', category=(FutureWarning, DeprecationWarning)\n )\n if np.isin(vector, [0, 1, np.nan]).all():\n return VariableType(boolean_type)\n\n # Defer to positive pandas tests\n if pd.api.types.is_numeric_dtype(vector):\n return VariableType(\"numeric\")\n\n if pd.api.types.is_datetime64_dtype(vector):\n return VariableType(\"datetime\")\n\n # --- If we get to here, we need to check the entries\n\n # Check for a collection where everything is a number\n\n def all_numeric(x):\n for x_i in x:\n if not isinstance(x_i, Number):\n return False\n return True\n\n if all_numeric(vector):\n return VariableType(\"numeric\")\n\n # Check for a collection where everything is a datetime\n\n def all_datetime(x):\n for x_i in x:\n if not isinstance(x_i, (datetime, np.datetime64)):\n return False\n return True\n\n if all_datetime(vector):\n return VariableType(\"datetime\")\n\n # Otherwise, our final fallback is to consider things categorical\n\n return VariableType(\"categorical\")"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":32,"id":506,"name":"text","nodeType":"Attribute","startLoc":32,"text":"text"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":33,"id":507,"name":"color","nodeType":"Attribute","startLoc":33,"text":"color"},{"col":4,"comment":"null","endLoc":103,"header":"def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist","id":508,"name":"_legend_artist","nodeType":"Function","startLoc":91,"text":"def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n # TODO return some sensible default?\n key = {v: value for v in variables}\n key = self._resolve_properties(key, scales)\n artist = mpl.patches.Patch(\n facecolor=key[\"facecolor\"],\n edgecolor=key[\"edgecolor\"],\n linewidth=key[\"edgewidth\"],\n linestyle=key[\"edgestyle\"],\n )\n return artist"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":34,"id":509,"name":"alpha","nodeType":"Attribute","startLoc":34,"text":"alpha"},{"col":4,"comment":"null","endLoc":1466,"header":"def __init__(self, data)","id":510,"name":"__init__","nodeType":"Function","startLoc":1464,"text":"def __init__(self, data):\n assert data in self.allowed, data\n super().__init__(data)"},{"className":"Bar","col":0,"comment":"\n A bar mark drawn between baseline and data values.\n\n See also\n --------\n Bars : A faster bar mark with defaults more suitable for histograms.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Bar.rst\n\n ","endLoc":173,"id":511,"nodeType":"Class","startLoc":106,"text":"@document_properties\n@dataclass\nclass Bar(BarBase):\n \"\"\"\n A bar mark drawn between baseline and data values.\n\n See also\n --------\n Bars : A faster bar mark with defaults more suitable for histograms.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Bar.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(.7, grouping=False)\n fill: MappableBool = Mappable(True, grouping=False)\n edgecolor: MappableColor = Mappable(depend=\"color\", grouping=False)\n edgealpha: MappableFloat = Mappable(1, grouping=False)\n edgewidth: MappableFloat = Mappable(rc=\"patch.linewidth\", grouping=False)\n edgestyle: MappableStyle = Mappable(\"-\", grouping=False)\n # pattern: MappableString = Mappable(None) # TODO no Property yet\n\n width: MappableFloat = Mappable(.8, grouping=False)\n baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable?\n\n def _plot(self, split_gen, scales, orient):\n\n val_idx = [\"y\", \"x\"].index(orient)\n\n for _, data, ax in split_gen():\n\n bars, vals = self._make_patches(data, scales, orient)\n\n for bar in bars:\n\n # Because we are clipping the artist (see below), the edges end up\n # looking half as wide as they actually are. I don't love this clumsy\n # workaround, which is going to cause surprises if you work with the\n # artists directly. We may need to revisit after feedback.\n bar.set_linewidth(bar.get_linewidth() * 2)\n linestyle = bar.get_linestyle()\n if linestyle[1]:\n linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1]))\n bar.set_linestyle(linestyle)\n\n # This is a bit of a hack to handle the fact that the edge lines are\n # centered on the actual extents of the bar, and overlap when bars are\n # stacked or dodged. We may discover that this causes problems and needs\n # to be revisited at some point. Also it should be faster to clip with\n # a bbox than a path, but I cant't work out how to get the intersection\n # with the axes bbox.\n bar.set_clip_path(bar.get_path(), bar.get_transform() + ax.transData)\n if self.artist_kws.get(\"clip_on\", True):\n # It seems the above hack undoes the default axes clipping\n bar.set_clip_box(ax.bbox)\n bar.sticky_edges[val_idx][:] = (0, np.inf)\n ax.add_patch(bar)\n\n # Add a container which is useful for, e.g. Axes.bar_label\n if Version(mpl.__version__) >= Version(\"3.4.0\"):\n orientation = {\"x\": \"vertical\", \"y\": \"horizontal\"}[orient]\n container_kws = dict(datavalues=vals, orientation=orientation)\n else:\n container_kws = {}\n container = mpl.container.BarContainer(bars, **container_kws)\n ax.add_container(container)"},{"col":4,"comment":"null","endLoc":173,"header":"def _plot(self, split_gen, scales, orient)","id":512,"name":"_plot","nodeType":"Function","startLoc":133,"text":"def _plot(self, split_gen, scales, orient):\n\n val_idx = [\"y\", \"x\"].index(orient)\n\n for _, data, ax in split_gen():\n\n bars, vals = self._make_patches(data, scales, orient)\n\n for bar in bars:\n\n # Because we are clipping the artist (see below), the edges end up\n # looking half as wide as they actually are. I don't love this clumsy\n # workaround, which is going to cause surprises if you work with the\n # artists directly. We may need to revisit after feedback.\n bar.set_linewidth(bar.get_linewidth() * 2)\n linestyle = bar.get_linestyle()\n if linestyle[1]:\n linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1]))\n bar.set_linestyle(linestyle)\n\n # This is a bit of a hack to handle the fact that the edge lines are\n # centered on the actual extents of the bar, and overlap when bars are\n # stacked or dodged. We may discover that this causes problems and needs\n # to be revisited at some point. Also it should be faster to clip with\n # a bbox than a path, but I cant't work out how to get the intersection\n # with the axes bbox.\n bar.set_clip_path(bar.get_path(), bar.get_transform() + ax.transData)\n if self.artist_kws.get(\"clip_on\", True):\n # It seems the above hack undoes the default axes clipping\n bar.set_clip_box(ax.bbox)\n bar.sticky_edges[val_idx][:] = (0, np.inf)\n ax.add_patch(bar)\n\n # Add a container which is useful for, e.g. Axes.bar_label\n if Version(mpl.__version__) >= Version(\"3.4.0\"):\n orientation = {\"x\": \"vertical\", \"y\": \"horizontal\"}[orient]\n container_kws = dict(datavalues=vals, orientation=orientation)\n else:\n container_kws = {}\n container = mpl.container.BarContainer(bars, **container_kws)\n ax.add_container(container)"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":35,"id":513,"name":"fontsize","nodeType":"Attribute","startLoc":35,"text":"fontsize"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":36,"id":514,"name":"halign","nodeType":"Attribute","startLoc":36,"text":"halign"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":37,"id":515,"name":"valign","nodeType":"Attribute","startLoc":37,"text":"valign"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":38,"id":516,"name":"offset","nodeType":"Attribute","startLoc":38,"text":"offset"},{"attributeType":"null","col":16,"comment":"null","endLoc":5,"id":517,"name":"np","nodeType":"Attribute","startLoc":5,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":6,"id":518,"name":"mpl","nodeType":"Attribute","startLoc":6,"text":"mpl"},{"col":0,"comment":"Force draw of a matplotlib figure, accounting for back-compat.","endLoc":85,"header":"def _draw_figure(fig)","id":519,"name":"_draw_figure","nodeType":"Function","startLoc":77,"text":"def _draw_figure(fig):\n \"\"\"Force draw of a matplotlib figure, accounting for back-compat.\"\"\"\n # See https://github.com/matplotlib/matplotlib/issues/19197 for context\n fig.canvas.draw()\n if fig.stale:\n try:\n fig.draw(fig.canvas.get_renderer())\n except AttributeError:\n pass"},{"id":520,"name":".gitignore","nodeType":"TextFile","path":"examples","text":"*.html\n*_files/\n"},{"col":4,"comment":"null","endLoc":281,"header":"@property\n def epoch(self) -> int","id":521,"name":"epoch","nodeType":"Function","startLoc":278,"text":"@property\n def epoch(self) -> int:\n _epoch: int = self._version.epoch\n return _epoch"},{"col":4,"comment":"null","endLoc":286,"header":"@property\n def release(self) -> Tuple[int, ...]","id":522,"name":"release","nodeType":"Function","startLoc":283,"text":"@property\n def release(self) -> Tuple[int, ...]:\n _release: Tuple[int, ...] = self._version.release\n return _release"},{"col":4,"comment":"null","endLoc":291,"header":"@property\n def pre(self) -> Optional[Tuple[str, int]]","id":523,"name":"pre","nodeType":"Function","startLoc":288,"text":"@property\n def pre(self) -> Optional[Tuple[str, int]]:\n _pre: Optional[Tuple[str, int]] = self._version.pre\n return _pre"},{"col":4,"comment":"null","endLoc":295,"header":"@property\n def post(self) -> Optional[int]","id":524,"name":"post","nodeType":"Function","startLoc":293,"text":"@property\n def post(self) -> Optional[int]:\n return self._version.post[1] if self._version.post else None"},{"col":4,"comment":"null","endLoc":299,"header":"@property\n def dev(self) -> Optional[int]","id":525,"name":"dev","nodeType":"Function","startLoc":297,"text":"@property\n def dev(self) -> Optional[int]:\n return self._version.dev[1] if self._version.dev else None"},{"col":4,"comment":"null","endLoc":306,"header":"@property\n def local(self) -> Optional[str]","id":526,"name":"local","nodeType":"Function","startLoc":301,"text":"@property\n def local(self) -> Optional[str]:\n if self._version.local:\n return \".\".join(str(x) for x in self._version.local)\n else:\n return None"},{"col":4,"comment":"null","endLoc":1019,"header":"def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int","id":527,"name":"index","nodeType":"Function","startLoc":1019,"text":"def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ..."},{"col":4,"comment":"Extract the legend data from an axes object and save it.","endLoc":242,"header":"def _update_legend_data(self, ax)","id":528,"name":"_update_legend_data","nodeType":"Function","startLoc":225,"text":"def _update_legend_data(self, ax):\n \"\"\"Extract the legend data from an axes object and save it.\"\"\"\n data = {}\n\n # Get data directly from the legend, which is necessary\n # for newer functions that don't add labeled proxy artists\n if ax.legend_ is not None and self._extract_legend_handles:\n handles = ax.legend_.legendHandles\n labels = [t.get_text() for t in ax.legend_.texts]\n data.update({l: h for h, l in zip(handles, labels)})\n\n handles, labels = ax.get_legend_handles_labels()\n data.update({l: h for h, l in zip(handles, labels)})\n\n self._legend_data.update(data)\n\n # Now clear the legend\n ax.legend_ = None"},{"col":4,"comment":"null","endLoc":310,"header":"@property\n def public(self) -> str","id":529,"name":"public","nodeType":"Function","startLoc":308,"text":"@property\n def public(self) -> str:\n return str(self).split(\"+\", 1)[0]"},{"col":4,"comment":"null","endLoc":323,"header":"@property\n def base_version(self) -> str","id":532,"name":"base_version","nodeType":"Function","startLoc":312,"text":"@property\n def base_version(self) -> str:\n parts = []\n\n # Epoch\n if self.epoch != 0:\n parts.append(f\"{self.epoch}!\")\n\n # Release segment\n parts.append(\".\".join(str(x) for x in self.release))\n\n return \"\".join(parts)"},{"col":4,"comment":"null","endLoc":113,"header":"def __init__(\n self,\n data=None,\n variables={},\n )","id":533,"name":"__init__","nodeType":"Function","startLoc":107,"text":"def __init__(\n self,\n data=None,\n variables={},\n ):\n\n super().__init__(data=data, variables=variables)"},{"col":0,"comment":"Make a palette that blends between a list of colors.\n\n Parameters\n ----------\n colors : sequence of colors in various formats interpreted by `input`\n hex code, html color name, or tuple in `input` space.\n n_colors : int, optional\n Number of colors in the palette.\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n Examples\n --------\n .. include: ../docstrings/blend_palette.rst\n\n ","endLoc":609,"header":"def blend_palette(colors, n_colors=6, as_cmap=False, input=\"rgb\")","id":534,"name":"blend_palette","nodeType":"Function","startLoc":581,"text":"def blend_palette(colors, n_colors=6, as_cmap=False, input=\"rgb\"):\n \"\"\"Make a palette that blends between a list of colors.\n\n Parameters\n ----------\n colors : sequence of colors in various formats interpreted by `input`\n hex code, html color name, or tuple in `input` space.\n n_colors : int, optional\n Number of colors in the palette.\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n Examples\n --------\n .. include: ../docstrings/blend_palette.rst\n\n \"\"\"\n colors = [_color_to_rgb(color, input) for color in colors]\n name = \"blend\"\n pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)\n if not as_cmap:\n rgb_array = pal(np.linspace(0, 1, int(n_colors)))[:, :3] # no alpha\n pal = _ColorPalette(map(tuple, rgb_array))\n return pal"},{"col":4,"comment":"null","endLoc":327,"header":"@property\n def is_prerelease(self) -> bool","id":535,"name":"is_prerelease","nodeType":"Function","startLoc":325,"text":"@property\n def is_prerelease(self) -> bool:\n return self.dev is not None or self.pre is not None"},{"col":4,"comment":"null","endLoc":331,"header":"@property\n def is_postrelease(self) -> bool","id":536,"name":"is_postrelease","nodeType":"Function","startLoc":329,"text":"@property\n def is_postrelease(self) -> bool:\n return self.post is not None"},{"col":4,"comment":"null","endLoc":335,"header":"@property\n def is_devrelease(self) -> bool","id":537,"name":"is_devrelease","nodeType":"Function","startLoc":333,"text":"@property\n def is_devrelease(self) -> bool:\n return self.dev is not None"},{"col":4,"comment":"null","endLoc":339,"header":"@property\n def major(self) -> int","id":538,"name":"major","nodeType":"Function","startLoc":337,"text":"@property\n def major(self) -> int:\n return self.release[0] if len(self.release) >= 1 else 0"},{"col":4,"comment":"null","endLoc":343,"header":"@property\n def minor(self) -> int","id":539,"name":"minor","nodeType":"Function","startLoc":341,"text":"@property\n def minor(self) -> int:\n return self.release[1] if len(self.release) >= 2 else 0"},{"col":4,"comment":"null","endLoc":347,"header":"@property\n def micro(self) -> int","id":540,"name":"micro","nodeType":"Function","startLoc":345,"text":"@property\n def micro(self) -> int:\n return self.release[2] if len(self.release) >= 3 else 0"},{"attributeType":"null","col":4,"comment":"null","endLoc":216,"id":541,"name":"_regex","nodeType":"Attribute","startLoc":216,"text":"_regex"},{"attributeType":"(int, (int, ...), InfinityType | NegativeInfinityType | (str, int), InfinityType | NegativeInfinityType | (str, int), InfinityType | NegativeInfinityType | (str, int), NegativeInfinityType | (InfinityType | NegativeInfinityType | int | str | (InfinityType | NegativeInfinityType | int | str, str) | (NegativeInfinityType, InfinityType | NegativeInfinityType | int | str), ...)) | (int, (str, ...))","col":8,"comment":"null","endLoc":238,"id":542,"name":"_key","nodeType":"Attribute","startLoc":238,"text":"self._key"},{"col":20,"endLoc":199,"id":543,"nodeType":"Lambda","startLoc":199,"text":"lambda row: dot_product(row, rgbl)"},{"col":4,"comment":"Given data and a scaling argument, initialize appropriate scale class.","endLoc":96,"header":"def infer_scale(self, arg: Any, data: Series) -> Scale","id":544,"name":"infer_scale","nodeType":"Function","startLoc":78,"text":"def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n # TODO put these somewhere external for validation\n # TODO putting this here won't pick it up if subclasses define infer_scale\n # (e.g. color). How best to handle that? One option is to call super after\n # handling property-specific possibilities (e.g. for color check that the\n # arg is not a valid palette name) but that could get tricky.\n trans_args = [\"log\", \"symlog\", \"logit\", \"pow\", \"sqrt\"]\n if isinstance(arg, str):\n if any(arg.startswith(k) for k in trans_args):\n # TODO validate numeric type? That should happen centrally somewhere\n return Continuous(trans=arg)\n else:\n msg = f\"Unknown magic arg for {self.variable} scale: '{arg}'.\"\n raise ValueError(msg)\n else:\n arg_type = type(arg).__name__\n msg = f\"Magic arg for {self.variable} scale must be str, not {arg_type}.\"\n raise TypeError(msg)"},{"attributeType":"null","col":8,"comment":"null","endLoc":226,"id":545,"name":"_version","nodeType":"Attribute","startLoc":226,"text":"self._version"},{"col":0,"comment":"If needed, get a default color by using the matplotlib property cycle.","endLoc":165,"header":"def _default_color(method, hue, color, kws)","id":546,"name":"_default_color","nodeType":"Function","startLoc":88,"text":"def _default_color(method, hue, color, kws):\n \"\"\"If needed, get a default color by using the matplotlib property cycle.\"\"\"\n if hue is not None:\n # This warning is probably user-friendly, but it's currently triggered\n # in a FacetGrid context and I don't want to mess with that logic right now\n # if color is not None:\n # msg = \"`color` is ignored when `hue` is assigned.\"\n # warnings.warn(msg)\n return None\n\n if color is not None:\n return color\n\n elif method.__name__ == \"plot\":\n\n color = _normalize_kwargs(kws, mpl.lines.Line2D).get(\"color\")\n scout, = method([], [], scalex=False, scaley=False, color=color)\n color = scout.get_color()\n scout.remove()\n\n elif method.__name__ == \"scatter\":\n\n # Matplotlib will raise if the size of x/y don't match s/c,\n # and the latter might be in the kws dict\n scout_size = max(\n np.atleast_1d(kws.get(key, [])).shape[0]\n for key in [\"s\", \"c\", \"fc\", \"facecolor\", \"facecolors\"]\n )\n scout_x = scout_y = np.full(scout_size, np.nan)\n\n scout = method(scout_x, scout_y, **kws)\n facecolors = scout.get_facecolors()\n\n if not len(facecolors):\n # Handle bug in matplotlib <= 3.2 (I think)\n # This will limit the ability to use non color= kwargs to specify\n # a color in versions of matplotlib with the bug, but trying to\n # work out what the user wanted by re-implementing the broken logic\n # of inspecting the kwargs is probably too brittle.\n single_color = False\n else:\n single_color = np.unique(facecolors, axis=0).shape[0] == 1\n\n # Allow the user to specify an array of colors through various kwargs\n if \"c\" not in kws and single_color:\n color = to_rgb(facecolors[0])\n\n scout.remove()\n\n elif method.__name__ == \"bar\":\n\n # bar() needs masked, not empty data, to generate a patch\n scout, = method([np.nan], [np.nan], **kws)\n color = to_rgb(scout.get_facecolor())\n scout.remove()\n\n elif method.__name__ == \"fill_between\":\n\n # There is a bug on matplotlib < 3.3 where fill_between with\n # datetime units and empty data will set incorrect autoscale limits\n # To workaround it, we'll always return the first color in the cycle.\n # https://github.com/matplotlib/matplotlib/issues/17586\n ax = method.__self__\n datetime_axis = any([\n isinstance(ax.xaxis.converter, mpl.dates.DateConverter),\n isinstance(ax.yaxis.converter, mpl.dates.DateConverter),\n ])\n if Version(mpl.__version__) < Version(\"3.3\") and datetime_axis:\n return \"C0\"\n\n kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)\n\n scout = method([], [], **kws)\n facecolor = scout.get_facecolor()\n color = to_rgb(facecolor[0])\n scout.remove()\n\n return color"},{"col":0,"comment":"Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.","endLoc":777,"header":"def _normalize_kwargs(kws, artist)","id":547,"name":"_normalize_kwargs","nodeType":"Function","startLoc":760,"text":"def _normalize_kwargs(kws, artist):\n \"\"\"Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.\"\"\"\n _alias_map = {\n 'color': ['c'],\n 'linewidth': ['lw'],\n 'linestyle': ['ls'],\n 'facecolor': ['fc'],\n 'edgecolor': ['ec'],\n 'markerfacecolor': ['mfc'],\n 'markeredgecolor': ['mec'],\n 'markeredgewidth': ['mew'],\n 'markersize': ['ms']\n }\n try:\n kws = normalize_kwargs(kws, artist)\n except AttributeError:\n kws = normalize_kwargs(kws, _alias_map)\n return kws"},{"className":"Path","col":0,"comment":"\n A mark connecting data points in the order they appear.\n\n See also\n --------\n Line : A mark connecting data points with sorting along the orientation axis.\n Paths : A faster but less-flexible mark for drawing many paths.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Path.rst\n\n ","endLoc":117,"id":548,"nodeType":"Class","startLoc":21,"text":"@document_properties\n@dataclass\nclass Path(Mark):\n \"\"\"\n A mark connecting data points in the order they appear.\n\n See also\n --------\n Line : A mark connecting data points with sorting along the orientation axis.\n Paths : A faster but less-flexible mark for drawing many paths.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Path.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\")\n alpha: MappableFloat = Mappable(1)\n linewidth: MappableFloat = Mappable(rc=\"lines.linewidth\")\n linestyle: MappableString = Mappable(rc=\"lines.linestyle\")\n marker: MappableString = Mappable(rc=\"lines.marker\")\n pointsize: MappableFloat = Mappable(rc=\"lines.markersize\")\n fillcolor: MappableColor = Mappable(depend=\"color\")\n edgecolor: MappableColor = Mappable(depend=\"color\")\n edgewidth: MappableFloat = Mappable(rc=\"lines.markeredgewidth\")\n\n _sort: ClassVar[bool] = False\n\n def _plot(self, split_gen, scales, orient):\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n vals[\"fillcolor\"] = resolve_color(self, keys, prefix=\"fill\", scales=scales)\n vals[\"edgecolor\"] = resolve_color(self, keys, prefix=\"edge\", scales=scales)\n\n # https://github.com/matplotlib/matplotlib/pull/16692\n if Version(mpl.__version__) < Version(\"3.3.0\"):\n vals[\"marker\"] = vals[\"marker\"]._marker\n\n if self._sort:\n data = data.sort_values(orient, kind=\"mergesort\")\n\n artist_kws = self.artist_kws.copy()\n self._handle_capstyle(artist_kws, vals)\n\n line = mpl.lines.Line2D(\n data[\"x\"].to_numpy(),\n data[\"y\"].to_numpy(),\n color=vals[\"color\"],\n linewidth=vals[\"linewidth\"],\n linestyle=vals[\"linestyle\"],\n marker=vals[\"marker\"],\n markersize=vals[\"pointsize\"],\n markerfacecolor=vals[\"fillcolor\"],\n markeredgecolor=vals[\"edgecolor\"],\n markeredgewidth=vals[\"edgewidth\"],\n **artist_kws,\n )\n ax.add_line(line)\n\n def _legend_artist(self, variables, value, scales):\n\n keys = {v: value for v in variables}\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n vals[\"fillcolor\"] = resolve_color(self, keys, prefix=\"fill\", scales=scales)\n vals[\"edgecolor\"] = resolve_color(self, keys, prefix=\"edge\", scales=scales)\n\n # https://github.com/matplotlib/matplotlib/pull/16692\n if Version(mpl.__version__) < Version(\"3.3.0\"):\n vals[\"marker\"] = vals[\"marker\"]._marker\n\n artist_kws = self.artist_kws.copy()\n self._handle_capstyle(artist_kws, vals)\n\n return mpl.lines.Line2D(\n [], [],\n color=vals[\"color\"],\n linewidth=vals[\"linewidth\"],\n linestyle=vals[\"linestyle\"],\n marker=vals[\"marker\"],\n markersize=vals[\"pointsize\"],\n markerfacecolor=vals[\"fillcolor\"],\n markeredgecolor=vals[\"edgecolor\"],\n markeredgewidth=vals[\"edgewidth\"],\n **artist_kws,\n )\n\n def _handle_capstyle(self, kws, vals):\n\n # Work around for this matplotlib issue:\n # https://github.com/matplotlib/matplotlib/issues/23437\n if vals[\"linestyle\"][1] is None:\n capstyle = kws.get(\"solid_capstyle\", mpl.rcParams[\"lines.solid_capstyle\"])\n kws[\"dash_capstyle\"] = capstyle"},{"col":4,"comment":"null","endLoc":81,"header":"def _plot(self, split_gen, scales, orient)","id":549,"name":"_plot","nodeType":"Function","startLoc":49,"text":"def _plot(self, split_gen, scales, orient):\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n vals[\"fillcolor\"] = resolve_color(self, keys, prefix=\"fill\", scales=scales)\n vals[\"edgecolor\"] = resolve_color(self, keys, prefix=\"edge\", scales=scales)\n\n # https://github.com/matplotlib/matplotlib/pull/16692\n if Version(mpl.__version__) < Version(\"3.3.0\"):\n vals[\"marker\"] = vals[\"marker\"]._marker\n\n if self._sort:\n data = data.sort_values(orient, kind=\"mergesort\")\n\n artist_kws = self.artist_kws.copy()\n self._handle_capstyle(artist_kws, vals)\n\n line = mpl.lines.Line2D(\n data[\"x\"].to_numpy(),\n data[\"y\"].to_numpy(),\n color=vals[\"color\"],\n linewidth=vals[\"linewidth\"],\n linestyle=vals[\"linestyle\"],\n marker=vals[\"marker\"],\n markersize=vals[\"pointsize\"],\n markerfacecolor=vals[\"fillcolor\"],\n markeredgecolor=vals[\"edgecolor\"],\n markeredgewidth=vals[\"edgewidth\"],\n **artist_kws,\n )\n ax.add_line(line)"},{"col":0,"comment":"null","endLoc":219,"header":"def xyz_to_luv(triple)","id":550,"name":"xyz_to_luv","nodeType":"Function","startLoc":202,"text":"def xyz_to_luv(triple):\n X, Y, Z = triple\n\n if X == Y == Z == 0.0:\n return [0.0, 0.0, 0.0]\n\n varU = (4.0 * X) / (X + (15.0 * Y) + (3.0 * Z))\n varV = (9.0 * Y) / (X + (15.0 * Y) + (3.0 * Z))\n L = 116.0 * f(Y / refY) - 16.0\n\n # Black will create a divide-by-zero error\n if L == 0.0:\n return [0.0, 0.0, 0.0]\n\n U = 13.0 * L * (varU - refU)\n V = 13.0 * L * (varV - refV)\n\n return [L, U, V]"},{"col":0,"comment":"null","endLoc":130,"header":"def f(t)","id":551,"name":"f","nodeType":"Function","startLoc":126,"text":"def f(t):\n if t > lab_e:\n return (math.pow(t, 1.0 / 3.0))\n else:\n return (7.787 * t + 16.0 / 116.0)"},{"col":0,"comment":"null","endLoc":247,"header":"def luv_to_lch(triple)","id":552,"name":"luv_to_lch","nodeType":"Function","startLoc":238,"text":"def luv_to_lch(triple):\n L, U, V = triple\n\n C = (math.pow(math.pow(U, 2) + math.pow(V, 2), (1.0 / 2.0)))\n hrad = (math.atan2(V, U))\n H = math.degrees(hrad)\n if H < 0.0:\n H = 360.0 + H\n\n return [L, C, H]"},{"col":0,"comment":"null","endLoc":285,"header":"def lch_to_husl(triple)","id":555,"name":"lch_to_husl","nodeType":"Function","startLoc":274,"text":"def lch_to_husl(triple):\n L, C, H = triple\n\n if L > 99.9999999:\n return [H, 0.0, 100.0]\n if L < 0.00000001:\n return [H, 0.0, 0.0]\n\n mx = max_chroma(L, H)\n S = C / mx * 100.0\n\n return [H, S, L]"},{"col":0,"comment":"\n Return a palette or colormap from the matplotlib registry.\n\n For continuous palettes, evenly-spaced discrete samples are chosen while\n excluding the minimum and maximum value in the colormap to provide better\n contrast at the extremes.\n\n For qualitative palettes (e.g. those from colorbrewer), exact values are\n indexed (rather than interpolated), but fewer than `n_colors` can be returned\n if the palette does not define that many.\n\n Parameters\n ----------\n name : string\n Name of the palette. This should be a named matplotlib colormap.\n n_colors : int\n Number of discrete colors in the palette.\n\n Returns\n -------\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n Examples\n --------\n .. include: ../docstrings/mpl_palette.rst\n\n ","endLoc":417,"header":"def mpl_palette(name, n_colors=6, as_cmap=False)","id":556,"name":"mpl_palette","nodeType":"Function","startLoc":366,"text":"def mpl_palette(name, n_colors=6, as_cmap=False):\n \"\"\"\n Return a palette or colormap from the matplotlib registry.\n\n For continuous palettes, evenly-spaced discrete samples are chosen while\n excluding the minimum and maximum value in the colormap to provide better\n contrast at the extremes.\n\n For qualitative palettes (e.g. those from colorbrewer), exact values are\n indexed (rather than interpolated), but fewer than `n_colors` can be returned\n if the palette does not define that many.\n\n Parameters\n ----------\n name : string\n Name of the palette. This should be a named matplotlib colormap.\n n_colors : int\n Number of discrete colors in the palette.\n\n Returns\n -------\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n Examples\n --------\n .. include: ../docstrings/mpl_palette.rst\n\n \"\"\"\n if name.endswith(\"_d\"):\n sub_name = name[:-2]\n if sub_name.endswith(\"_r\"):\n reverse = True\n sub_name = sub_name[:-2]\n else:\n reverse = False\n pal = color_palette(sub_name, 2) + [\"#333333\"]\n if reverse:\n pal = pal[::-1]\n cmap = blend_palette(pal, n_colors, as_cmap=True)\n else:\n cmap = get_colormap(name)\n\n if name in MPL_QUAL_PALS:\n bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors]\n else:\n bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1]\n palette = list(map(tuple, cmap(bins)[:, :3]))\n\n if as_cmap:\n return cmap\n else:\n return _ColorPalette(palette)"},{"col":4,"comment":"Return a function that maps from data domain to property range.","endLoc":104,"header":"def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]","id":559,"name":"get_mapping","nodeType":"Function","startLoc":98,"text":"def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to property range.\"\"\"\n def identity(x):\n return x\n return identity"},{"col":4,"comment":"Coerce flexible property value to standardized representation.","endLoc":108,"header":"def standardize(self, val: Any) -> Any","id":560,"name":"standardize","nodeType":"Function","startLoc":106,"text":"def standardize(self, val: Any) -> Any:\n \"\"\"Coerce flexible property value to standardized representation.\"\"\"\n return val"},{"col":4,"comment":"Input check when values are provided as a dictionary.","endLoc":116,"header":"def _check_dict_entries(self, levels: list, values: dict) -> None","id":561,"name":"_check_dict_entries","nodeType":"Function","startLoc":110,"text":"def _check_dict_entries(self, levels: list, values: dict) -> None:\n \"\"\"Input check when values are provided as a dictionary.\"\"\"\n missing = set(levels) - set(values)\n if missing:\n formatted = \", \".join(map(repr, sorted(missing, key=str)))\n err = f\"No entry in {self.variable} dictionary for {formatted}\"\n raise ValueError(err)"},{"col":4,"comment":"null","endLoc":117,"header":"def _handle_capstyle(self, kws, vals)","id":562,"name":"_handle_capstyle","nodeType":"Function","startLoc":111,"text":"def _handle_capstyle(self, kws, vals):\n\n # Work around for this matplotlib issue:\n # https://github.com/matplotlib/matplotlib/issues/23437\n if vals[\"linestyle\"][1] is None:\n capstyle = kws.get(\"solid_capstyle\", mpl.rcParams[\"lines.solid_capstyle\"])\n kws[\"dash_capstyle\"] = capstyle"},{"col":4,"comment":"null","endLoc":109,"header":"def _legend_artist(self, variables, value, scales)","id":563,"name":"_legend_artist","nodeType":"Function","startLoc":83,"text":"def _legend_artist(self, variables, value, scales):\n\n keys = {v: value for v in variables}\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n vals[\"fillcolor\"] = resolve_color(self, keys, prefix=\"fill\", scales=scales)\n vals[\"edgecolor\"] = resolve_color(self, keys, prefix=\"edge\", scales=scales)\n\n # https://github.com/matplotlib/matplotlib/pull/16692\n if Version(mpl.__version__) < Version(\"3.3.0\"):\n vals[\"marker\"] = vals[\"marker\"]._marker\n\n artist_kws = self.artist_kws.copy()\n self._handle_capstyle(artist_kws, vals)\n\n return mpl.lines.Line2D(\n [], [],\n color=vals[\"color\"],\n linewidth=vals[\"linewidth\"],\n linestyle=vals[\"linestyle\"],\n marker=vals[\"marker\"],\n markersize=vals[\"pointsize\"],\n markerfacecolor=vals[\"fillcolor\"],\n markeredgecolor=vals[\"edgecolor\"],\n markeredgewidth=vals[\"edgewidth\"],\n **artist_kws,\n )"},{"col":0,"comment":"Return a list of unique data values.\n\n Determine an ordered list of levels in ``values``.\n\n Parameters\n ----------\n vector : list, array, Categorical, or Series\n Vector of \"categorical\" values\n order : list-like, optional\n Desired order of category levels to override the order determined\n from the ``values`` object.\n\n Returns\n -------\n order : list\n Ordered list of category levels not including null values.\n\n ","endLoc":1771,"header":"def categorical_order(vector, order=None)","id":564,"name":"categorical_order","nodeType":"Function","startLoc":1735,"text":"def categorical_order(vector, order=None):\n \"\"\"Return a list of unique data values.\n\n Determine an ordered list of levels in ``values``.\n\n Parameters\n ----------\n vector : list, array, Categorical, or Series\n Vector of \"categorical\" values\n order : list-like, optional\n Desired order of category levels to override the order determined\n from the ``values`` object.\n\n Returns\n -------\n order : list\n Ordered list of category levels not including null values.\n\n \"\"\"\n if order is None:\n if hasattr(vector, \"categories\"):\n order = vector.categories\n else:\n try:\n order = vector.cat.categories\n except (TypeError, AttributeError):\n\n try:\n order = vector.unique()\n except AttributeError:\n order = pd.unique(vector)\n\n if variable_type(vector) == \"numeric\":\n order = np.sort(order)\n\n order = filter(pd.notnull, order)\n return list(order)"},{"col":0,"comment":"null","endLoc":641,"header":"def lmplot(\n data=None, *,\n x=None, y=None, hue=None, col=None, row=None,\n palette=None, col_wrap=None, height=5, aspect=1, markers=\"o\",\n sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None,\n legend=True, legend_out=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None,\n line_kws=None, facet_kws=None,\n)","id":573,"name":"lmplot","nodeType":"Function","startLoc":560,"text":"def lmplot(\n data=None, *,\n x=None, y=None, hue=None, col=None, row=None,\n palette=None, col_wrap=None, height=5, aspect=1, markers=\"o\",\n sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None,\n legend=True, legend_out=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None,\n line_kws=None, facet_kws=None,\n):\n\n if facet_kws is None:\n facet_kws = {}\n\n def facet_kw_deprecation(key, val):\n msg = (\n f\"{key} is deprecated from the `lmplot` function signature. \"\n \"Please update your code to pass it using `facet_kws`.\"\n )\n if val is not None:\n warnings.warn(msg, UserWarning)\n facet_kws[key] = val\n\n facet_kw_deprecation(\"sharex\", sharex)\n facet_kw_deprecation(\"sharey\", sharey)\n facet_kw_deprecation(\"legend_out\", legend_out)\n\n if data is None:\n raise TypeError(\"Missing required keyword argument `data`.\")\n\n # Reduce the dataframe to only needed columns\n need_cols = [x, y, hue, col, row, units, x_partial, y_partial]\n cols = np.unique([a for a in need_cols if a is not None]).tolist()\n data = data[cols]\n\n # Initialize the grid\n facets = FacetGrid(\n data, row=row, col=col, hue=hue,\n palette=palette,\n row_order=row_order, col_order=col_order, hue_order=hue_order,\n height=height, aspect=aspect, col_wrap=col_wrap,\n **facet_kws,\n )\n\n # Add the markers here as FacetGrid has figured out how many levels of the\n # hue variable are needed and we don't want to duplicate that process\n if facets.hue_names is None:\n n_markers = 1\n else:\n n_markers = len(facets.hue_names)\n if not isinstance(markers, list):\n markers = [markers] * n_markers\n if len(markers) != n_markers:\n raise ValueError(\"markers must be a singleton or a list of markers \"\n \"for each level of the hue variable\")\n facets.hue_kws = {\"marker\": markers}\n\n def update_datalim(data, x, y, ax, **kws):\n xys = data[[x, y]].to_numpy().astype(float)\n ax.update_datalim(xys, updatey=False)\n ax.autoscale_view(scaley=False)\n\n facets.map_dataframe(update_datalim, x=x, y=y)\n\n # Draw the regression plot on each facet\n regplot_kws = dict(\n x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci,\n scatter=scatter, fit_reg=fit_reg, ci=ci, n_boot=n_boot, units=units,\n seed=seed, order=order, logistic=logistic, lowess=lowess,\n robust=robust, logx=logx, x_partial=x_partial, y_partial=y_partial,\n truncate=truncate, x_jitter=x_jitter, y_jitter=y_jitter,\n scatter_kws=scatter_kws, line_kws=line_kws,\n )\n facets.map_dataframe(regplot, x=x, y=y, **regplot_kws)\n facets.set_axis_labels(x, y)\n\n # Add a legend\n if legend and (hue is not None) and (hue not in [col, row]):\n facets.add_legend()\n return facets"},{"col":0,"comment":"Handle changes to matplotlib colormap interface in 3.6.","endLoc":135,"header":"def get_colormap(name)","id":574,"name":"get_colormap","nodeType":"Function","startLoc":130,"text":"def get_colormap(name):\n \"\"\"Handle changes to matplotlib colormap interface in 3.6.\"\"\"\n try:\n return mpl.colormaps[name]\n except AttributeError:\n return mpl.cm.get_cmap(name)"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":121,"id":575,"name":"color","nodeType":"Attribute","startLoc":121,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":122,"id":577,"name":"alpha","nodeType":"Attribute","startLoc":122,"text":"alpha"},{"col":4,"comment":"Get a list of colors for the hue variable.","endLoc":272,"header":"def _get_palette(self, data, hue, hue_order, palette)","id":578,"name":"_get_palette","nodeType":"Function","startLoc":244,"text":"def _get_palette(self, data, hue, hue_order, palette):\n \"\"\"Get a list of colors for the hue variable.\"\"\"\n if hue is None:\n palette = color_palette(n_colors=1)\n\n else:\n hue_names = categorical_order(data[hue], hue_order)\n n_colors = len(hue_names)\n\n # By default use either the current color palette or HUSL\n if palette is None:\n current_palette = utils.get_color_cycle()\n if n_colors > len(current_palette):\n colors = color_palette(\"husl\", n_colors)\n else:\n colors = color_palette(n_colors=n_colors)\n\n # Allow for palette to map from hue variable names\n elif isinstance(palette, dict):\n color_names = [palette[h] for h in hue_names]\n colors = color_palette(color_names, n_colors)\n\n # Otherwise act as if we just got a list of colors\n else:\n colors = color_palette(palette, n_colors)\n\n palette = color_palette(colors, n_colors)\n\n return palette"},{"attributeType":"bool | Mappable","col":4,"comment":"null","endLoc":123,"id":579,"name":"fill","nodeType":"Attribute","startLoc":123,"text":"fill"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":124,"id":580,"name":"edgecolor","nodeType":"Attribute","startLoc":124,"text":"edgecolor"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":125,"id":581,"name":"edgealpha","nodeType":"Attribute","startLoc":125,"text":"edgealpha"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":126,"id":582,"name":"edgewidth","nodeType":"Attribute","startLoc":126,"text":"edgewidth"},{"attributeType":"str | (float, ...) | (float, (float, ...) | None) | Mappable","col":4,"comment":"null","endLoc":127,"id":583,"name":"edgestyle","nodeType":"Attribute","startLoc":127,"text":"edgestyle"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":37,"id":584,"name":"color","nodeType":"Attribute","startLoc":37,"text":"color"},{"col":4,"comment":"null","endLoc":543,"header":"def __init__(\n self, data, *,\n row=None, col=None, hue=None, col_wrap=None,\n sharex=True, sharey=True, height=3, aspect=1, palette=None,\n row_order=None, col_order=None, hue_order=None, hue_kws=None,\n dropna=False, legend_out=True, despine=True,\n margin_titles=False, xlim=None, ylim=None, subplot_kws=None,\n gridspec_kws=None,\n )","id":587,"name":"__init__","nodeType":"Function","startLoc":366,"text":"def __init__(\n self, data, *,\n row=None, col=None, hue=None, col_wrap=None,\n sharex=True, sharey=True, height=3, aspect=1, palette=None,\n row_order=None, col_order=None, hue_order=None, hue_kws=None,\n dropna=False, legend_out=True, despine=True,\n margin_titles=False, xlim=None, ylim=None, subplot_kws=None,\n gridspec_kws=None,\n ):\n\n super().__init__()\n\n # Determine the hue facet layer information\n hue_var = hue\n if hue is None:\n hue_names = None\n else:\n hue_names = categorical_order(data[hue], hue_order)\n\n colors = self._get_palette(data, hue, hue_order, palette)\n\n # Set up the lists of names for the row and column facet variables\n if row is None:\n row_names = []\n else:\n row_names = categorical_order(data[row], row_order)\n\n if col is None:\n col_names = []\n else:\n col_names = categorical_order(data[col], col_order)\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n hue_kws = hue_kws if hue_kws is not None else {}\n\n # Make a boolean mask that is True anywhere there is an NA\n # value in one of the faceting variables, but only if dropna is True\n none_na = np.zeros(len(data), bool)\n if dropna:\n row_na = none_na if row is None else data[row].isnull()\n col_na = none_na if col is None else data[col].isnull()\n hue_na = none_na if hue is None else data[hue].isnull()\n not_na = ~(row_na | col_na | hue_na)\n else:\n not_na = ~none_na\n\n # Compute the grid shape\n ncol = 1 if col is None else len(col_names)\n nrow = 1 if row is None else len(row_names)\n self._n_facets = ncol * nrow\n\n self._col_wrap = col_wrap\n if col_wrap is not None:\n if row is not None:\n err = \"Cannot use `row` and `col_wrap` together.\"\n raise ValueError(err)\n ncol = col_wrap\n nrow = int(np.ceil(len(col_names) / col_wrap))\n self._ncol = ncol\n self._nrow = nrow\n\n # Calculate the base figure size\n # This can get stretched later by a legend\n # TODO this doesn't account for axis labels\n figsize = (ncol * height * aspect, nrow * height)\n\n # Validate some inputs\n if col_wrap is not None:\n margin_titles = False\n\n # Build the subplot keyword dictionary\n subplot_kws = {} if subplot_kws is None else subplot_kws.copy()\n gridspec_kws = {} if gridspec_kws is None else gridspec_kws.copy()\n if xlim is not None:\n subplot_kws[\"xlim\"] = xlim\n if ylim is not None:\n subplot_kws[\"ylim\"] = ylim\n\n # --- Initialize the subplot grid\n\n with _disable_autolayout():\n fig = plt.figure(figsize=figsize)\n\n if col_wrap is None:\n\n kwargs = dict(squeeze=False,\n sharex=sharex, sharey=sharey,\n subplot_kw=subplot_kws,\n gridspec_kw=gridspec_kws)\n\n axes = fig.subplots(nrow, ncol, **kwargs)\n\n if col is None and row is None:\n axes_dict = {}\n elif col is None:\n axes_dict = dict(zip(row_names, axes.flat))\n elif row is None:\n axes_dict = dict(zip(col_names, axes.flat))\n else:\n facet_product = product(row_names, col_names)\n axes_dict = dict(zip(facet_product, axes.flat))\n\n else:\n\n # If wrapping the col variable we need to make the grid ourselves\n if gridspec_kws:\n warnings.warn(\"`gridspec_kws` ignored when using `col_wrap`\")\n\n n_axes = len(col_names)\n axes = np.empty(n_axes, object)\n axes[0] = fig.add_subplot(nrow, ncol, 1, **subplot_kws)\n if sharex:\n subplot_kws[\"sharex\"] = axes[0]\n if sharey:\n subplot_kws[\"sharey\"] = axes[0]\n for i in range(1, n_axes):\n axes[i] = fig.add_subplot(nrow, ncol, i + 1, **subplot_kws)\n\n axes_dict = dict(zip(col_names, axes))\n\n # --- Set up the class attributes\n\n # Attributes that are part of the public API but accessed through\n # a property so that Sphinx adds them to the auto class doc\n self._figure = fig\n self._axes = axes\n self._axes_dict = axes_dict\n self._legend = None\n\n # Public attributes that aren't explicitly documented\n # (It's not obvious that having them be public was a good idea)\n self.data = data\n self.row_names = row_names\n self.col_names = col_names\n self.hue_names = hue_names\n self.hue_kws = hue_kws\n\n # Next the private variables\n self._nrow = nrow\n self._row_var = row\n self._ncol = ncol\n self._col_var = col\n\n self._margin_titles = margin_titles\n self._margin_titles_texts = []\n self._col_wrap = col_wrap\n self._hue_var = hue_var\n self._colors = colors\n self._legend_out = legend_out\n self._legend_data = {}\n self._x_var = None\n self._y_var = None\n self._sharex = sharex\n self._sharey = sharey\n self._dropna = dropna\n self._not_na = not_na\n\n # --- Make the axes look good\n\n self.set_titles()\n self.tight_layout()\n\n if despine:\n self.despine()\n\n if sharex in [True, 'col']:\n for ax in self._not_bottom_axes:\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n ax.xaxis.label.set_visible(False)\n\n if sharey in [True, 'row']:\n for ax in self._not_left_axes:\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n ax.yaxis.label.set_visible(False)"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":130,"id":588,"name":"width","nodeType":"Attribute","startLoc":130,"text":"width"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":131,"id":589,"name":"baseline","nodeType":"Attribute","startLoc":131,"text":"baseline"},{"className":"Bars","col":0,"comment":"\n A faster bar mark with defaults more suitable histograms.\n\n See also\n --------\n Bar : A bar mark drawn between baseline and data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Bars.rst\n\n ","endLoc":250,"id":590,"nodeType":"Class","startLoc":176,"text":"@document_properties\n@dataclass\nclass Bars(BarBase):\n \"\"\"\n A faster bar mark with defaults more suitable histograms.\n\n See also\n --------\n Bar : A bar mark drawn between baseline and data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Bars.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(.7, grouping=False)\n fill: MappableBool = Mappable(True, grouping=False)\n edgecolor: MappableColor = Mappable(rc=\"patch.edgecolor\", grouping=False)\n edgealpha: MappableFloat = Mappable(1, grouping=False)\n edgewidth: MappableFloat = Mappable(auto=True, grouping=False)\n edgestyle: MappableStyle = Mappable(\"-\", grouping=False)\n # pattern: MappableString = Mappable(None) # TODO no Property yet\n\n width: MappableFloat = Mappable(1, grouping=False)\n baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable?\n\n def _plot(self, split_gen, scales, orient):\n\n ori_idx = [\"x\", \"y\"].index(orient)\n val_idx = [\"y\", \"x\"].index(orient)\n\n patches = defaultdict(list)\n for _, data, ax in split_gen():\n bars, _ = self._make_patches(data, scales, orient)\n patches[ax].extend(bars)\n\n collections = {}\n for ax, ax_patches in patches.items():\n\n col = mpl.collections.PatchCollection(ax_patches, match_original=True)\n col.sticky_edges[val_idx][:] = (0, np.inf)\n ax.add_collection(col, autolim=False)\n collections[ax] = col\n\n # Workaround for matplotlib autoscaling bug\n # https://github.com/matplotlib/matplotlib/issues/11898\n # https://github.com/matplotlib/matplotlib/issues/23129\n xys = np.vstack([path.vertices for path in col.get_paths()])\n ax.update_datalim(xys)\n\n if \"edgewidth\" not in scales and isinstance(self.edgewidth, Mappable):\n\n for ax in collections:\n ax.autoscale_view()\n\n def get_dimensions(collection):\n edges, widths = [], []\n for verts in (path.vertices for path in collection.get_paths()):\n edges.append(min(verts[:, ori_idx]))\n widths.append(np.ptp(verts[:, ori_idx]))\n return np.array(edges), np.array(widths)\n\n min_width = np.inf\n for ax, col in collections.items():\n edges, widths = get_dimensions(col)\n points = 72 / ax.figure.dpi * abs(\n ax.transData.transform([edges + widths] * 2)\n - ax.transData.transform([edges] * 2)\n )\n min_width = min(min_width, min(points[:, ori_idx]))\n\n linewidth = min(.1 * min_width, mpl.rcParams[\"patch.linewidth\"])\n for _, col in collections.items():\n col.set_linewidth(linewidth)"},{"col":4,"comment":"null","endLoc":250,"header":"def _plot(self, split_gen, scales, orient)","id":591,"name":"_plot","nodeType":"Function","startLoc":203,"text":"def _plot(self, split_gen, scales, orient):\n\n ori_idx = [\"x\", \"y\"].index(orient)\n val_idx = [\"y\", \"x\"].index(orient)\n\n patches = defaultdict(list)\n for _, data, ax in split_gen():\n bars, _ = self._make_patches(data, scales, orient)\n patches[ax].extend(bars)\n\n collections = {}\n for ax, ax_patches in patches.items():\n\n col = mpl.collections.PatchCollection(ax_patches, match_original=True)\n col.sticky_edges[val_idx][:] = (0, np.inf)\n ax.add_collection(col, autolim=False)\n collections[ax] = col\n\n # Workaround for matplotlib autoscaling bug\n # https://github.com/matplotlib/matplotlib/issues/11898\n # https://github.com/matplotlib/matplotlib/issues/23129\n xys = np.vstack([path.vertices for path in col.get_paths()])\n ax.update_datalim(xys)\n\n if \"edgewidth\" not in scales and isinstance(self.edgewidth, Mappable):\n\n for ax in collections:\n ax.autoscale_view()\n\n def get_dimensions(collection):\n edges, widths = [], []\n for verts in (path.vertices for path in collection.get_paths()):\n edges.append(min(verts[:, ori_idx]))\n widths.append(np.ptp(verts[:, ori_idx]))\n return np.array(edges), np.array(widths)\n\n min_width = np.inf\n for ax, col in collections.items():\n edges, widths = get_dimensions(col)\n points = 72 / ax.figure.dpi * abs(\n ax.transData.transform([edges + widths] * 2)\n - ax.transData.transform([edges] * 2)\n )\n min_width = min(min_width, min(points[:, ori_idx]))\n\n linewidth = min(.1 * min_width, mpl.rcParams[\"patch.linewidth\"])\n for _, col in collections.items():\n col.set_linewidth(linewidth)"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":38,"id":592,"name":"alpha","nodeType":"Attribute","startLoc":38,"text":"alpha"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":39,"id":593,"name":"linewidth","nodeType":"Attribute","startLoc":39,"text":"linewidth"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":40,"id":594,"name":"linestyle","nodeType":"Attribute","startLoc":40,"text":"linestyle"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":41,"id":595,"name":"marker","nodeType":"Attribute","startLoc":41,"text":"marker"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":42,"id":596,"name":"pointsize","nodeType":"Attribute","startLoc":42,"text":"pointsize"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":43,"id":597,"name":"fillcolor","nodeType":"Attribute","startLoc":43,"text":"fillcolor"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":44,"id":598,"name":"edgecolor","nodeType":"Attribute","startLoc":44,"text":"edgecolor"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":45,"id":599,"name":"edgewidth","nodeType":"Attribute","startLoc":45,"text":"edgewidth"},{"attributeType":"bool","col":4,"comment":"null","endLoc":47,"id":600,"name":"_sort","nodeType":"Attribute","startLoc":47,"text":"_sort"},{"className":"Line","col":0,"comment":"\n A mark connecting data points with sorting along the orientation axis.\n\n See also\n --------\n Path : A mark connecting data points in the order they appear.\n Lines : A faster but less-flexible mark for drawing many lines.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Line.rst\n\n ","endLoc":136,"id":601,"nodeType":"Class","startLoc":120,"text":"@document_properties\n@dataclass\nclass Line(Path):\n \"\"\"\n A mark connecting data points with sorting along the orientation axis.\n\n See also\n --------\n Path : A mark connecting data points in the order they appear.\n Lines : A faster but less-flexible mark for drawing many lines.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Line.rst\n\n \"\"\"\n _sort: ClassVar[bool] = True"},{"attributeType":"bool","col":4,"comment":"null","endLoc":136,"id":602,"name":"_sort","nodeType":"Attribute","startLoc":136,"text":"_sort"},{"className":"Paths","col":0,"comment":"\n A faster but less-flexible mark for drawing many paths.\n\n See also\n --------\n Path : A mark connecting data points in the order they appear.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Paths.rst\n\n ","endLoc":226,"id":603,"nodeType":"Class","startLoc":139,"text":"@document_properties\n@dataclass\nclass Paths(Mark):\n \"\"\"\n A faster but less-flexible mark for drawing many paths.\n\n See also\n --------\n Path : A mark connecting data points in the order they appear.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Paths.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\")\n alpha: MappableFloat = Mappable(1)\n linewidth: MappableFloat = Mappable(rc=\"lines.linewidth\")\n linestyle: MappableString = Mappable(rc=\"lines.linestyle\")\n\n _sort: ClassVar[bool] = False\n\n def __post_init__(self):\n\n # LineCollection artists have a capstyle property but don't source its value\n # from the rc, so we do that manually here. Unfortunately, because we add\n # only one LineCollection, we have the use the same capstyle for all lines\n # even when they are dashed. It's a slight inconsistency, but looks fine IMO.\n self.artist_kws.setdefault(\"capstyle\", mpl.rcParams[\"lines.solid_capstyle\"])\n\n def _setup_lines(self, split_gen, scales, orient):\n\n line_data = {}\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n if ax not in line_data:\n line_data[ax] = {\n \"segments\": [],\n \"colors\": [],\n \"linewidths\": [],\n \"linestyles\": [],\n }\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n\n if self._sort:\n data = data.sort_values(orient, kind=\"mergesort\")\n\n # Column stack to avoid block consolidation\n xy = np.column_stack([data[\"x\"], data[\"y\"]])\n line_data[ax][\"segments\"].append(xy)\n line_data[ax][\"colors\"].append(vals[\"color\"])\n line_data[ax][\"linewidths\"].append(vals[\"linewidth\"])\n line_data[ax][\"linestyles\"].append(vals[\"linestyle\"])\n\n return line_data\n\n def _plot(self, split_gen, scales, orient):\n\n line_data = self._setup_lines(split_gen, scales, orient)\n\n for ax, ax_data in line_data.items():\n lines = mpl.collections.LineCollection(**ax_data, **self.artist_kws)\n # Handle datalim update manually\n # https://github.com/matplotlib/matplotlib/issues/23129\n ax.add_collection(lines, autolim=False)\n if ax_data[\"segments\"]:\n xy = np.concatenate(ax_data[\"segments\"])\n ax.update_datalim(xy)\n\n def _legend_artist(self, variables, value, scales):\n\n key = resolve_properties(self, {v: value for v in variables}, scales)\n\n artist_kws = self.artist_kws.copy()\n capstyle = artist_kws.pop(\"capstyle\")\n artist_kws[\"solid_capstyle\"] = capstyle\n artist_kws[\"dash_capstyle\"] = capstyle\n\n return mpl.lines.Line2D(\n [], [],\n color=key[\"color\"],\n linewidth=key[\"linewidth\"],\n linestyle=key[\"linestyle\"],\n **artist_kws,\n )"},{"col":4,"comment":"null","endLoc":167,"header":"def __post_init__(self)","id":604,"name":"__post_init__","nodeType":"Function","startLoc":161,"text":"def __post_init__(self):\n\n # LineCollection artists have a capstyle property but don't source its value\n # from the rc, so we do that manually here. Unfortunately, because we add\n # only one LineCollection, we have the use the same capstyle for all lines\n # even when they are dashed. It's a slight inconsistency, but looks fine IMO.\n self.artist_kws.setdefault(\"capstyle\", mpl.rcParams[\"lines.solid_capstyle\"])"},{"col":4,"comment":"The :class:`matplotlib.legend.Legend` object, if present.","endLoc":280,"header":"@property\n def legend(self)","id":607,"name":"legend","nodeType":"Function","startLoc":274,"text":"@property\n def legend(self):\n \"\"\"The :class:`matplotlib.legend.Legend` object, if present.\"\"\"\n try:\n return self._legend\n except AttributeError:\n return None"},{"col":4,"comment":"Modify the ticks, tick labels, and gridlines.\n\n Parameters\n ----------\n axis : {'x', 'y', 'both'}\n The axis on which to apply the formatting.\n kwargs : keyword arguments\n Additional keyword arguments to pass to\n :meth:`matplotlib.axes.Axes.tick_params`.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n ","endLoc":301,"header":"def tick_params(self, axis='both', **kwargs)","id":608,"name":"tick_params","nodeType":"Function","startLoc":282,"text":"def tick_params(self, axis='both', **kwargs):\n \"\"\"Modify the ticks, tick labels, and gridlines.\n\n Parameters\n ----------\n axis : {'x', 'y', 'both'}\n The axis on which to apply the formatting.\n kwargs : keyword arguments\n Additional keyword arguments to pass to\n :meth:`matplotlib.axes.Axes.tick_params`.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n \"\"\"\n for ax in self.figure.axes:\n ax.tick_params(axis=axis, **kwargs)\n return self"},{"attributeType":"null","col":4,"comment":"null","endLoc":100,"id":609,"name":"_margin_titles","nodeType":"Attribute","startLoc":100,"text":"_margin_titles"},{"attributeType":"null","col":4,"comment":"null","endLoc":101,"id":610,"name":"_legend_out","nodeType":"Attribute","startLoc":101,"text":"_legend_out"},{"attributeType":"null","col":12,"comment":"null","endLoc":183,"id":611,"name":"_legend","nodeType":"Attribute","startLoc":183,"text":"self._legend"},{"id":612,"name":"doc/_static","nodeType":"Package"},{"id":613,"name":"logo-wide-darkbg.svg","nodeType":"TextFile","path":"doc/_static","text":"\n\n\n\n \n \n \n \n 2020-09-07T14:14:00.795540\n image/svg+xml\n \n \n Matplotlib v3.3.1, https://matplotlib.org/\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":105,"id":614,"name":"_tight_layout_rect","nodeType":"Attribute","startLoc":105,"text":"self._tight_layout_rect"},{"attributeType":"null","col":8,"comment":"null","endLoc":106,"id":615,"name":"_tight_layout_pad","nodeType":"Attribute","startLoc":106,"text":"self._tight_layout_pad"},{"attributeType":"null","col":8,"comment":"null","endLoc":110,"id":616,"name":"_extract_legend_handles","nodeType":"Attribute","startLoc":110,"text":"self._extract_legend_handles"},{"attributeType":"null","col":12,"comment":"null","endLoc":204,"id":617,"name":"_space_needed","nodeType":"Attribute","startLoc":204,"text":"self._space_needed"},{"col":4,"comment":"null","endLoc":196,"header":"def _setup_lines(self, split_gen, scales, orient)","id":618,"name":"_setup_lines","nodeType":"Function","startLoc":169,"text":"def _setup_lines(self, split_gen, scales, orient):\n\n line_data = {}\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n if ax not in line_data:\n line_data[ax] = {\n \"segments\": [],\n \"colors\": [],\n \"linewidths\": [],\n \"linestyles\": [],\n }\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n\n if self._sort:\n data = data.sort_values(orient, kind=\"mergesort\")\n\n # Column stack to avoid block consolidation\n xy = np.column_stack([data[\"x\"], data[\"y\"]])\n line_data[ax][\"segments\"].append(xy)\n line_data[ax][\"colors\"].append(vals[\"color\"])\n line_data[ax][\"linewidths\"].append(vals[\"linewidth\"])\n line_data[ax][\"linestyles\"].append(vals[\"linestyle\"])\n\n return line_data"},{"col":4,"comment":"Generator for name indices and data subsets for each facet.\n\n Yields\n ------\n (i, j, k), data_ijk : tuple of ints, DataFrame\n The ints provide an index into the {row, col, hue}_names attribute,\n and the dataframe contains a subset of the full data corresponding\n to each facet. The generator yields subsets that correspond with\n the self.axes.flat iterator, or self.axes[i, j] when `col_wrap`\n is None.\n\n ","endLoc":675,"header":"def facet_data(self)","id":619,"name":"facet_data","nodeType":"Function","startLoc":637,"text":"def facet_data(self):\n \"\"\"Generator for name indices and data subsets for each facet.\n\n Yields\n ------\n (i, j, k), data_ijk : tuple of ints, DataFrame\n The ints provide an index into the {row, col, hue}_names attribute,\n and the dataframe contains a subset of the full data corresponding\n to each facet. The generator yields subsets that correspond with\n the self.axes.flat iterator, or self.axes[i, j] when `col_wrap`\n is None.\n\n \"\"\"\n data = self.data\n\n # Construct masks for the row variable\n if self.row_names:\n row_masks = [data[self._row_var] == n for n in self.row_names]\n else:\n row_masks = [np.repeat(True, len(self.data))]\n\n # Construct masks for the column variable\n if self.col_names:\n col_masks = [data[self._col_var] == n for n in self.col_names]\n else:\n col_masks = [np.repeat(True, len(self.data))]\n\n # Construct masks for the hue variable\n if self.hue_names:\n hue_masks = [data[self._hue_var] == n for n in self.hue_names]\n else:\n hue_masks = [np.repeat(True, len(self.data))]\n\n # Here is the main generator loop\n for (i, row), (j, col), (k, hue) in product(enumerate(row_masks),\n enumerate(col_masks),\n enumerate(hue_masks)):\n data_ijk = data[row & col & hue & self._not_na]\n yield (i, j, k), data_ijk"},{"col":4,"comment":"null","endLoc":209,"header":"def _plot(self, split_gen, scales, orient)","id":620,"name":"_plot","nodeType":"Function","startLoc":198,"text":"def _plot(self, split_gen, scales, orient):\n\n line_data = self._setup_lines(split_gen, scales, orient)\n\n for ax, ax_data in line_data.items():\n lines = mpl.collections.LineCollection(**ax_data, **self.artist_kws)\n # Handle datalim update manually\n # https://github.com/matplotlib/matplotlib/issues/23129\n ax.add_collection(lines, autolim=False)\n if ax_data[\"segments\"]:\n xy = np.concatenate(ax_data[\"segments\"])\n ax.update_datalim(xy)"},{"fileName":"matrix.py","filePath":"seaborn","id":621,"nodeType":"File","text":"\"\"\"Functions to visualize matrices of data.\"\"\"\nimport warnings\n\nimport matplotlib as mpl\nfrom matplotlib.collections import LineCollection\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport numpy as np\nimport pandas as pd\ntry:\n from scipy.cluster import hierarchy\n _no_scipy = False\nexcept ImportError:\n _no_scipy = True\n\nfrom . import cm\nfrom .axisgrid import Grid\nfrom ._compat import get_colormap\nfrom .utils import (\n despine,\n axis_ticklabels_overlap,\n relative_luminance,\n to_utf8,\n _draw_figure,\n)\n\n\n__all__ = [\"heatmap\", \"clustermap\"]\n\n\ndef _index_to_label(index):\n \"\"\"Convert a pandas index or multiindex to an axis label.\"\"\"\n if isinstance(index, pd.MultiIndex):\n return \"-\".join(map(to_utf8, index.names))\n else:\n return index.name\n\n\ndef _index_to_ticklabels(index):\n \"\"\"Convert a pandas index or multiindex into ticklabels.\"\"\"\n if isinstance(index, pd.MultiIndex):\n return [\"-\".join(map(to_utf8, i)) for i in index.values]\n else:\n return index.values\n\n\ndef _convert_colors(colors):\n \"\"\"Convert either a list of colors or nested lists of colors to RGB.\"\"\"\n to_rgb = mpl.colors.to_rgb\n\n try:\n to_rgb(colors[0])\n # If this works, there is only one level of colors\n return list(map(to_rgb, colors))\n except ValueError:\n # If we get here, we have nested lists\n return [list(map(to_rgb, l)) for l in colors]\n\n\ndef _matrix_mask(data, mask):\n \"\"\"Ensure that data and mask are compatible and add missing values.\n\n Values will be plotted for cells where ``mask`` is ``False``.\n\n ``data`` is expected to be a DataFrame; ``mask`` can be an array or\n a DataFrame.\n\n \"\"\"\n if mask is None:\n mask = np.zeros(data.shape, bool)\n\n if isinstance(mask, np.ndarray):\n # For array masks, ensure that shape matches data then convert\n if mask.shape != data.shape:\n raise ValueError(\"Mask must have the same shape as data.\")\n\n mask = pd.DataFrame(mask,\n index=data.index,\n columns=data.columns,\n dtype=bool)\n\n elif isinstance(mask, pd.DataFrame):\n # For DataFrame masks, ensure that semantic labels match data\n if not mask.index.equals(data.index) \\\n and mask.columns.equals(data.columns):\n err = \"Mask must have the same index and columns as data.\"\n raise ValueError(err)\n\n # Add any cells with missing data to the mask\n # This works around an issue where `plt.pcolormesh` doesn't represent\n # missing data properly\n mask = mask | pd.isnull(data)\n\n return mask\n\n\nclass _HeatMapper:\n \"\"\"Draw a heatmap plot of a matrix with nice labels and colormaps.\"\"\"\n\n def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt,\n annot_kws, cbar, cbar_kws,\n xticklabels=True, yticklabels=True, mask=None):\n \"\"\"Initialize the plotting object.\"\"\"\n # We always want to have a DataFrame with semantic information\n # and an ndarray to pass to matplotlib\n if isinstance(data, pd.DataFrame):\n plot_data = data.values\n else:\n plot_data = np.asarray(data)\n data = pd.DataFrame(plot_data)\n\n # Validate the mask and convert to DataFrame\n mask = _matrix_mask(data, mask)\n\n plot_data = np.ma.masked_where(np.asarray(mask), plot_data)\n\n # Get good names for the rows and columns\n xtickevery = 1\n if isinstance(xticklabels, int):\n xtickevery = xticklabels\n xticklabels = _index_to_ticklabels(data.columns)\n elif xticklabels is True:\n xticklabels = _index_to_ticklabels(data.columns)\n elif xticklabels is False:\n xticklabels = []\n\n ytickevery = 1\n if isinstance(yticklabels, int):\n ytickevery = yticklabels\n yticklabels = _index_to_ticklabels(data.index)\n elif yticklabels is True:\n yticklabels = _index_to_ticklabels(data.index)\n elif yticklabels is False:\n yticklabels = []\n\n if not len(xticklabels):\n self.xticks = []\n self.xticklabels = []\n elif isinstance(xticklabels, str) and xticklabels == \"auto\":\n self.xticks = \"auto\"\n self.xticklabels = _index_to_ticklabels(data.columns)\n else:\n self.xticks, self.xticklabels = self._skip_ticks(xticklabels,\n xtickevery)\n\n if not len(yticklabels):\n self.yticks = []\n self.yticklabels = []\n elif isinstance(yticklabels, str) and yticklabels == \"auto\":\n self.yticks = \"auto\"\n self.yticklabels = _index_to_ticklabels(data.index)\n else:\n self.yticks, self.yticklabels = self._skip_ticks(yticklabels,\n ytickevery)\n\n # Get good names for the axis labels\n xlabel = _index_to_label(data.columns)\n ylabel = _index_to_label(data.index)\n self.xlabel = xlabel if xlabel is not None else \"\"\n self.ylabel = ylabel if ylabel is not None else \"\"\n\n # Determine good default values for the colormapping\n self._determine_cmap_params(plot_data, vmin, vmax,\n cmap, center, robust)\n\n # Sort out the annotations\n if annot is None or annot is False:\n annot = False\n annot_data = None\n else:\n if isinstance(annot, bool):\n annot_data = plot_data\n else:\n annot_data = np.asarray(annot)\n if annot_data.shape != plot_data.shape:\n err = \"`data` and `annot` must have same shape.\"\n raise ValueError(err)\n annot = True\n\n # Save other attributes to the object\n self.data = data\n self.plot_data = plot_data\n\n self.annot = annot\n self.annot_data = annot_data\n\n self.fmt = fmt\n self.annot_kws = {} if annot_kws is None else annot_kws.copy()\n self.cbar = cbar\n self.cbar_kws = {} if cbar_kws is None else cbar_kws.copy()\n\n def _determine_cmap_params(self, plot_data, vmin, vmax,\n cmap, center, robust):\n \"\"\"Use some heuristics to set good defaults for colorbar and range.\"\"\"\n\n # plot_data is a np.ma.array instance\n calc_data = plot_data.astype(float).filled(np.nan)\n if vmin is None:\n if robust:\n vmin = np.nanpercentile(calc_data, 2)\n else:\n vmin = np.nanmin(calc_data)\n if vmax is None:\n if robust:\n vmax = np.nanpercentile(calc_data, 98)\n else:\n vmax = np.nanmax(calc_data)\n self.vmin, self.vmax = vmin, vmax\n\n # Choose default colormaps if not provided\n if cmap is None:\n if center is None:\n self.cmap = cm.rocket\n else:\n self.cmap = cm.icefire\n elif isinstance(cmap, str):\n self.cmap = get_colormap(cmap)\n elif isinstance(cmap, list):\n self.cmap = mpl.colors.ListedColormap(cmap)\n else:\n self.cmap = cmap\n\n # Recenter a divergent colormap\n if center is not None:\n\n # Copy bad values\n # in mpl<3.2 only masked values are honored with \"bad\" color spec\n # (see https://github.com/matplotlib/matplotlib/pull/14257)\n bad = self.cmap(np.ma.masked_invalid([np.nan]))[0]\n\n # under/over values are set for sure when cmap extremes\n # do not map to the same color as +-inf\n under = self.cmap(-np.inf)\n over = self.cmap(np.inf)\n under_set = under != self.cmap(0)\n over_set = over != self.cmap(self.cmap.N - 1)\n\n vrange = max(vmax - center, center - vmin)\n normlize = mpl.colors.Normalize(center - vrange, center + vrange)\n cmin, cmax = normlize([vmin, vmax])\n cc = np.linspace(cmin, cmax, 256)\n self.cmap = mpl.colors.ListedColormap(self.cmap(cc))\n self.cmap.set_bad(bad)\n if under_set:\n self.cmap.set_under(under)\n if over_set:\n self.cmap.set_over(over)\n\n def _annotate_heatmap(self, ax, mesh):\n \"\"\"Add textual labels with the value in each cell.\"\"\"\n mesh.update_scalarmappable()\n height, width = self.annot_data.shape\n xpos, ypos = np.meshgrid(np.arange(width) + .5, np.arange(height) + .5)\n for x, y, m, color, val in zip(xpos.flat, ypos.flat,\n mesh.get_array(), mesh.get_facecolors(),\n self.annot_data.flat):\n if m is not np.ma.masked:\n lum = relative_luminance(color)\n text_color = \".15\" if lum > .408 else \"w\"\n annotation = (\"{:\" + self.fmt + \"}\").format(val)\n text_kwargs = dict(color=text_color, ha=\"center\", va=\"center\")\n text_kwargs.update(self.annot_kws)\n ax.text(x, y, annotation, **text_kwargs)\n\n def _skip_ticks(self, labels, tickevery):\n \"\"\"Return ticks and labels at evenly spaced intervals.\"\"\"\n n = len(labels)\n if tickevery == 0:\n ticks, labels = [], []\n elif tickevery == 1:\n ticks, labels = np.arange(n) + .5, labels\n else:\n start, end, step = 0, n, tickevery\n ticks = np.arange(start, end, step) + .5\n labels = labels[start:end:step]\n return ticks, labels\n\n def _auto_ticks(self, ax, labels, axis):\n \"\"\"Determine ticks and ticklabels that minimize overlap.\"\"\"\n transform = ax.figure.dpi_scale_trans.inverted()\n bbox = ax.get_window_extent().transformed(transform)\n size = [bbox.width, bbox.height][axis]\n axis = [ax.xaxis, ax.yaxis][axis]\n tick, = axis.set_ticks([0])\n fontsize = tick.label1.get_size()\n max_ticks = int(size // (fontsize / 72))\n if max_ticks < 1:\n return [], []\n tick_every = len(labels) // max_ticks + 1\n tick_every = 1 if tick_every == 0 else tick_every\n ticks, labels = self._skip_ticks(labels, tick_every)\n return ticks, labels\n\n def plot(self, ax, cax, kws):\n \"\"\"Draw the heatmap on the provided Axes.\"\"\"\n # Remove all the Axes spines\n despine(ax=ax, left=True, bottom=True)\n\n # setting vmin/vmax in addition to norm is deprecated\n # so avoid setting if norm is set\n if \"norm\" not in kws:\n kws.setdefault(\"vmin\", self.vmin)\n kws.setdefault(\"vmax\", self.vmax)\n\n # Draw the heatmap\n mesh = ax.pcolormesh(self.plot_data, cmap=self.cmap, **kws)\n\n # Set the axis limits\n ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0]))\n\n # Invert the y axis to show the plot in matrix form\n ax.invert_yaxis()\n\n # Possibly add a colorbar\n if self.cbar:\n cb = ax.figure.colorbar(mesh, cax, ax, **self.cbar_kws)\n cb.outline.set_linewidth(0)\n # If rasterized is passed to pcolormesh, also rasterize the\n # colorbar to avoid white lines on the PDF rendering\n if kws.get('rasterized', False):\n cb.solids.set_rasterized(True)\n\n # Add row and column labels\n if isinstance(self.xticks, str) and self.xticks == \"auto\":\n xticks, xticklabels = self._auto_ticks(ax, self.xticklabels, 0)\n else:\n xticks, xticklabels = self.xticks, self.xticklabels\n\n if isinstance(self.yticks, str) and self.yticks == \"auto\":\n yticks, yticklabels = self._auto_ticks(ax, self.yticklabels, 1)\n else:\n yticks, yticklabels = self.yticks, self.yticklabels\n\n ax.set(xticks=xticks, yticks=yticks)\n xtl = ax.set_xticklabels(xticklabels)\n ytl = ax.set_yticklabels(yticklabels, rotation=\"vertical\")\n plt.setp(ytl, va=\"center\") # GH2484\n\n # Possibly rotate them if they overlap\n _draw_figure(ax.figure)\n\n if axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n if axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n\n # Add the axis labels\n ax.set(xlabel=self.xlabel, ylabel=self.ylabel)\n\n # Annotate the cells with the formatted values\n if self.annot:\n self._annotate_heatmap(ax, mesh)\n\n\ndef heatmap(\n data, *,\n vmin=None, vmax=None, cmap=None, center=None, robust=False,\n annot=None, fmt=\".2g\", annot_kws=None,\n linewidths=0, linecolor=\"white\",\n cbar=True, cbar_kws=None, cbar_ax=None,\n square=False, xticklabels=\"auto\", yticklabels=\"auto\",\n mask=None, ax=None,\n **kwargs\n):\n \"\"\"Plot rectangular data as a color-encoded matrix.\n\n This is an Axes-level function and will draw the heatmap into the\n currently-active Axes if none is provided to the ``ax`` argument. Part of\n this Axes space will be taken and used to plot a colormap, unless ``cbar``\n is False or a separate Axes is provided to ``cbar_ax``.\n\n Parameters\n ----------\n data : rectangular dataset\n 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame\n is provided, the index/column information will be used to label the\n columns and rows.\n vmin, vmax : floats, optional\n Values to anchor the colormap, otherwise they are inferred from the\n data and other keyword arguments.\n cmap : matplotlib colormap name or object, or list of colors, optional\n The mapping from data values to color space. If not provided, the\n default will depend on whether ``center`` is set.\n center : float, optional\n The value at which to center the colormap when plotting divergent data.\n Using this parameter will change the default ``cmap`` if none is\n specified.\n robust : bool, optional\n If True and ``vmin`` or ``vmax`` are absent, the colormap range is\n computed with robust quantiles instead of the extreme values.\n annot : bool or rectangular dataset, optional\n If True, write the data value in each cell. If an array-like with the\n same shape as ``data``, then use this to annotate the heatmap instead\n of the data. Note that DataFrames will match on position, not index.\n fmt : str, optional\n String formatting code to use when adding annotations.\n annot_kws : dict of key, value mappings, optional\n Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot``\n is True.\n linewidths : float, optional\n Width of the lines that will divide each cell.\n linecolor : color, optional\n Color of the lines that will divide each cell.\n cbar : bool, optional\n Whether to draw a colorbar.\n cbar_kws : dict of key, value mappings, optional\n Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`.\n cbar_ax : matplotlib Axes, optional\n Axes in which to draw the colorbar, otherwise take space from the\n main Axes.\n square : bool, optional\n If True, set the Axes aspect to \"equal\" so each cell will be\n square-shaped.\n xticklabels, yticklabels : \"auto\", bool, list-like, or int, optional\n If True, plot the column names of the dataframe. If False, don't plot\n the column names. If list-like, plot these alternate labels as the\n xticklabels. If an integer, use the column names but plot only every\n n label. If \"auto\", try to densely plot non-overlapping labels.\n mask : bool array or DataFrame, optional\n If passed, data will not be shown in cells where ``mask`` is True.\n Cells with missing values are automatically masked.\n ax : matplotlib Axes, optional\n Axes in which to draw the plot, otherwise use the currently-active\n Axes.\n kwargs : other keyword arguments\n All other keyword arguments are passed to\n :meth:`matplotlib.axes.Axes.pcolormesh`.\n\n Returns\n -------\n ax : matplotlib Axes\n Axes object with the heatmap.\n\n See Also\n --------\n clustermap : Plot a matrix using hierarchical clustering to arrange the\n rows and columns.\n\n Examples\n --------\n\n .. include:: ../docstrings/heatmap.rst\n\n \"\"\"\n # Initialize the plotter object\n plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt,\n annot_kws, cbar, cbar_kws, xticklabels,\n yticklabels, mask)\n\n # Add the pcolormesh kwargs here\n kwargs[\"linewidths\"] = linewidths\n kwargs[\"edgecolor\"] = linecolor\n\n # Draw the plot and return the Axes\n if ax is None:\n ax = plt.gca()\n if square:\n ax.set_aspect(\"equal\")\n plotter.plot(ax, cbar_ax, kwargs)\n return ax\n\n\nclass _DendrogramPlotter:\n \"\"\"Object for drawing tree of similarities between data rows/columns\"\"\"\n\n def __init__(self, data, linkage, metric, method, axis, label, rotate):\n \"\"\"Plot a dendrogram of the relationships between the columns of data\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n \"\"\"\n self.axis = axis\n if self.axis == 1:\n data = data.T\n\n if isinstance(data, pd.DataFrame):\n array = data.values\n else:\n array = np.asarray(data)\n data = pd.DataFrame(array)\n\n self.array = array\n self.data = data\n\n self.shape = self.data.shape\n self.metric = metric\n self.method = method\n self.axis = axis\n self.label = label\n self.rotate = rotate\n\n if linkage is None:\n self.linkage = self.calculated_linkage\n else:\n self.linkage = linkage\n self.dendrogram = self.calculate_dendrogram()\n\n # Dendrogram ends are always at multiples of 5, who knows why\n ticks = 10 * np.arange(self.data.shape[0]) + 5\n\n if self.label:\n ticklabels = _index_to_ticklabels(self.data.index)\n ticklabels = [ticklabels[i] for i in self.reordered_ind]\n if self.rotate:\n self.xticks = []\n self.yticks = ticks\n self.xticklabels = []\n\n self.yticklabels = ticklabels\n self.ylabel = _index_to_label(self.data.index)\n self.xlabel = ''\n else:\n self.xticks = ticks\n self.yticks = []\n self.xticklabels = ticklabels\n self.yticklabels = []\n self.ylabel = ''\n self.xlabel = _index_to_label(self.data.index)\n else:\n self.xticks, self.yticks = [], []\n self.yticklabels, self.xticklabels = [], []\n self.xlabel, self.ylabel = '', ''\n\n self.dependent_coord = self.dendrogram['dcoord']\n self.independent_coord = self.dendrogram['icoord']\n\n def _calculate_linkage_scipy(self):\n linkage = hierarchy.linkage(self.array, method=self.method,\n metric=self.metric)\n return linkage\n\n def _calculate_linkage_fastcluster(self):\n import fastcluster\n # Fastcluster has a memory-saving vectorized version, but only\n # with certain linkage methods, and mostly with euclidean metric\n # vector_methods = ('single', 'centroid', 'median', 'ward')\n euclidean_methods = ('centroid', 'median', 'ward')\n euclidean = self.metric == 'euclidean' and self.method in \\\n euclidean_methods\n if euclidean or self.method == 'single':\n return fastcluster.linkage_vector(self.array,\n method=self.method,\n metric=self.metric)\n else:\n linkage = fastcluster.linkage(self.array, method=self.method,\n metric=self.metric)\n return linkage\n\n @property\n def calculated_linkage(self):\n\n try:\n return self._calculate_linkage_fastcluster()\n except ImportError:\n if np.product(self.shape) >= 10000:\n msg = (\"Clustering large matrix with scipy. Installing \"\n \"`fastcluster` may give better performance.\")\n warnings.warn(msg)\n\n return self._calculate_linkage_scipy()\n\n def calculate_dendrogram(self):\n \"\"\"Calculates a dendrogram based on the linkage matrix\n\n Made a separate function, not a property because don't want to\n recalculate the dendrogram every time it is accessed.\n\n Returns\n -------\n dendrogram : dict\n Dendrogram dictionary as returned by scipy.cluster.hierarchy\n .dendrogram. The important key-value pairing is\n \"reordered_ind\" which indicates the re-ordering of the matrix\n \"\"\"\n return hierarchy.dendrogram(self.linkage, no_plot=True,\n color_threshold=-np.inf)\n\n @property\n def reordered_ind(self):\n \"\"\"Indices of the matrix, reordered by the dendrogram\"\"\"\n return self.dendrogram['leaves']\n\n def plot(self, ax, tree_kws):\n \"\"\"Plots a dendrogram of the similarities between data on the axes\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n Axes object upon which the dendrogram is plotted\n\n \"\"\"\n tree_kws = {} if tree_kws is None else tree_kws.copy()\n tree_kws.setdefault(\"linewidths\", .5)\n tree_kws.setdefault(\"colors\", tree_kws.pop(\"color\", (.2, .2, .2)))\n\n if self.rotate and self.axis == 0:\n coords = zip(self.dependent_coord, self.independent_coord)\n else:\n coords = zip(self.independent_coord, self.dependent_coord)\n lines = LineCollection([list(zip(x, y)) for x, y in coords],\n **tree_kws)\n\n ax.add_collection(lines)\n number_of_leaves = len(self.reordered_ind)\n max_dependent_coord = max(map(max, self.dependent_coord))\n\n if self.rotate:\n ax.yaxis.set_ticks_position('right')\n\n # Constants 10 and 1.05 come from\n # `scipy.cluster.hierarchy._plot_dendrogram`\n ax.set_ylim(0, number_of_leaves * 10)\n ax.set_xlim(0, max_dependent_coord * 1.05)\n\n ax.invert_xaxis()\n ax.invert_yaxis()\n else:\n # Constants 10 and 1.05 come from\n # `scipy.cluster.hierarchy._plot_dendrogram`\n ax.set_xlim(0, number_of_leaves * 10)\n ax.set_ylim(0, max_dependent_coord * 1.05)\n\n despine(ax=ax, bottom=True, left=True)\n\n ax.set(xticks=self.xticks, yticks=self.yticks,\n xlabel=self.xlabel, ylabel=self.ylabel)\n xtl = ax.set_xticklabels(self.xticklabels)\n ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical')\n\n # Force a draw of the plot to avoid matplotlib window error\n _draw_figure(ax.figure)\n\n if len(ytl) > 0 and axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n if len(xtl) > 0 and axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n return self\n\n\ndef dendrogram(\n data, *,\n linkage=None, axis=1, label=True, metric='euclidean',\n method='average', rotate=False, tree_kws=None, ax=None\n):\n \"\"\"Draw a tree diagram of relationships within a matrix\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n linkage : numpy.array, optional\n Linkage matrix\n axis : int, optional\n Which axis to use to calculate linkage. 0 is rows, 1 is columns.\n label : bool, optional\n If True, label the dendrogram at leaves with column or row names\n metric : str, optional\n Distance metric. Anything valid for scipy.spatial.distance.pdist\n method : str, optional\n Linkage method to use. Anything valid for\n scipy.cluster.hierarchy.linkage\n rotate : bool, optional\n When plotting the matrix, whether to rotate it 90 degrees\n counter-clockwise, so the leaves face right\n tree_kws : dict, optional\n Keyword arguments for the ``matplotlib.collections.LineCollection``\n that is used for plotting the lines of the dendrogram tree.\n ax : matplotlib axis, optional\n Axis to plot on, otherwise uses current axis\n\n Returns\n -------\n dendrogramplotter : _DendrogramPlotter\n A Dendrogram plotter object.\n\n Notes\n -----\n Access the reordered dendrogram indices with\n dendrogramplotter.reordered_ind\n\n \"\"\"\n if _no_scipy:\n raise RuntimeError(\"dendrogram requires scipy to be installed\")\n\n plotter = _DendrogramPlotter(data, linkage=linkage, axis=axis,\n metric=metric, method=method,\n label=label, rotate=rotate)\n if ax is None:\n ax = plt.gca()\n\n return plotter.plot(ax=ax, tree_kws=tree_kws)\n\n\nclass ClusterGrid(Grid):\n\n def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None,\n figsize=None, row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=None, colors_ratio=None, cbar_pos=None):\n \"\"\"Grid object for organizing clustered heatmap input on to axes\"\"\"\n if _no_scipy:\n raise RuntimeError(\"ClusterGrid requires scipy to be available\")\n\n if isinstance(data, pd.DataFrame):\n self.data = data\n else:\n self.data = pd.DataFrame(data)\n\n self.data2d = self.format_data(self.data, pivot_kws, z_score,\n standard_scale)\n\n self.mask = _matrix_mask(self.data2d, mask)\n\n self._figure = plt.figure(figsize=figsize)\n\n self.row_colors, self.row_color_labels = \\\n self._preprocess_colors(data, row_colors, axis=0)\n self.col_colors, self.col_color_labels = \\\n self._preprocess_colors(data, col_colors, axis=1)\n\n try:\n row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio\n except TypeError:\n row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio\n\n try:\n row_colors_ratio, col_colors_ratio = colors_ratio\n except TypeError:\n row_colors_ratio = col_colors_ratio = colors_ratio\n\n width_ratios = self.dim_ratios(self.row_colors,\n row_dendrogram_ratio,\n row_colors_ratio)\n height_ratios = self.dim_ratios(self.col_colors,\n col_dendrogram_ratio,\n col_colors_ratio)\n\n nrows = 2 if self.col_colors is None else 3\n ncols = 2 if self.row_colors is None else 3\n\n self.gs = gridspec.GridSpec(nrows, ncols,\n width_ratios=width_ratios,\n height_ratios=height_ratios)\n\n self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0])\n self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1])\n self.ax_row_dendrogram.set_axis_off()\n self.ax_col_dendrogram.set_axis_off()\n\n self.ax_row_colors = None\n self.ax_col_colors = None\n\n if self.row_colors is not None:\n self.ax_row_colors = self._figure.add_subplot(\n self.gs[-1, 1])\n if self.col_colors is not None:\n self.ax_col_colors = self._figure.add_subplot(\n self.gs[1, -1])\n\n self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1])\n if cbar_pos is None:\n self.ax_cbar = self.cax = None\n else:\n # Initialize the colorbar axes in the gridspec so that tight_layout\n # works. We will move it where it belongs later. This is a hack.\n self.ax_cbar = self._figure.add_subplot(self.gs[0, 0])\n self.cax = self.ax_cbar # Backwards compatibility\n self.cbar_pos = cbar_pos\n\n self.dendrogram_row = None\n self.dendrogram_col = None\n\n def _preprocess_colors(self, data, colors, axis):\n \"\"\"Preprocess {row/col}_colors to extract labels and convert colors.\"\"\"\n labels = None\n\n if colors is not None:\n if isinstance(colors, (pd.DataFrame, pd.Series)):\n\n # If data is unindexed, raise\n if (not hasattr(data, \"index\") and axis == 0) or (\n not hasattr(data, \"columns\") and axis == 1\n ):\n axis_name = \"col\" if axis else \"row\"\n msg = (f\"{axis_name}_colors indices can't be matched with data \"\n f\"indices. Provide {axis_name}_colors as a non-indexed \"\n \"datatype, e.g. by using `.to_numpy()``\")\n raise TypeError(msg)\n\n # Ensure colors match data indices\n if axis == 0:\n colors = colors.reindex(data.index)\n else:\n colors = colors.reindex(data.columns)\n\n # Replace na's with white color\n # TODO We should set these to transparent instead\n colors = colors.astype(object).fillna('white')\n\n # Extract color values and labels from frame/series\n if isinstance(colors, pd.DataFrame):\n labels = list(colors.columns)\n colors = colors.T.values\n else:\n if colors.name is None:\n labels = [\"\"]\n else:\n labels = [colors.name]\n colors = colors.values\n\n colors = _convert_colors(colors)\n\n return colors, labels\n\n def format_data(self, data, pivot_kws, z_score=None,\n standard_scale=None):\n \"\"\"Extract variables from data or use directly.\"\"\"\n\n # Either the data is already in 2d matrix format, or need to do a pivot\n if pivot_kws is not None:\n data2d = data.pivot(**pivot_kws)\n else:\n data2d = data\n\n if z_score is not None and standard_scale is not None:\n raise ValueError(\n 'Cannot perform both z-scoring and standard-scaling on data')\n\n if z_score is not None:\n data2d = self.z_score(data2d, z_score)\n if standard_scale is not None:\n data2d = self.standard_scale(data2d, standard_scale)\n return data2d\n\n @staticmethod\n def z_score(data2d, axis=1):\n \"\"\"Standarize the mean and variance of the data axis\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n normalized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n \"\"\"\n if axis == 1:\n z_scored = data2d\n else:\n z_scored = data2d.T\n\n z_scored = (z_scored - z_scored.mean()) / z_scored.std()\n\n if axis == 1:\n return z_scored\n else:\n return z_scored.T\n\n @staticmethod\n def standard_scale(data2d, axis=1):\n \"\"\"Divide the data by the difference between the max and min\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n standardized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n\n \"\"\"\n # Normalize these values to range from 0 to 1\n if axis == 1:\n standardized = data2d\n else:\n standardized = data2d.T\n\n subtract = standardized.min()\n standardized = (standardized - subtract) / (\n standardized.max() - standardized.min())\n\n if axis == 1:\n return standardized\n else:\n return standardized.T\n\n def dim_ratios(self, colors, dendrogram_ratio, colors_ratio):\n \"\"\"Get the proportions of the figure taken up by each axes.\"\"\"\n ratios = [dendrogram_ratio]\n\n if colors is not None:\n # Colors are encoded as rgb, so there is an extra dimension\n if np.ndim(colors) > 2:\n n_colors = len(colors)\n else:\n n_colors = 1\n\n ratios += [n_colors * colors_ratio]\n\n # Add the ratio for the heatmap itself\n ratios.append(1 - sum(ratios))\n\n return ratios\n\n @staticmethod\n def color_list_to_matrix_and_cmap(colors, ind, axis=0):\n \"\"\"Turns a list of colors into a numpy matrix and matplotlib colormap\n\n These arguments can now be plotted using heatmap(matrix, cmap)\n and the provided colors will be plotted.\n\n Parameters\n ----------\n colors : list of matplotlib colors\n Colors to label the rows or columns of a dataframe.\n ind : list of ints\n Ordering of the rows or columns, to reorder the original colors\n by the clustered dendrogram order\n axis : int\n Which axis this is labeling\n\n Returns\n -------\n matrix : numpy.array\n A numpy array of integer values, where each indexes into the cmap\n cmap : matplotlib.colors.ListedColormap\n\n \"\"\"\n try:\n mpl.colors.to_rgb(colors[0])\n except ValueError:\n # We have a 2D color structure\n m, n = len(colors), len(colors[0])\n if not all(len(c) == n for c in colors[1:]):\n raise ValueError(\"Multiple side color vectors must have same size\")\n else:\n # We have one vector of colors\n m, n = 1, len(colors)\n colors = [colors]\n\n # Map from unique colors to colormap index value\n unique_colors = {}\n matrix = np.zeros((m, n), int)\n for i, inner in enumerate(colors):\n for j, color in enumerate(inner):\n idx = unique_colors.setdefault(color, len(unique_colors))\n matrix[i, j] = idx\n\n # Reorder for clustering and transpose for axis\n matrix = matrix[:, ind]\n if axis == 0:\n matrix = matrix.T\n\n cmap = mpl.colors.ListedColormap(list(unique_colors))\n return matrix, cmap\n\n def plot_dendrograms(self, row_cluster, col_cluster, metric, method,\n row_linkage, col_linkage, tree_kws):\n # Plot the row dendrogram\n if row_cluster:\n self.dendrogram_row = dendrogram(\n self.data2d, metric=metric, method=method, label=False, axis=0,\n ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage,\n tree_kws=tree_kws\n )\n else:\n self.ax_row_dendrogram.set_xticks([])\n self.ax_row_dendrogram.set_yticks([])\n # PLot the column dendrogram\n if col_cluster:\n self.dendrogram_col = dendrogram(\n self.data2d, metric=metric, method=method, label=False,\n axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage,\n tree_kws=tree_kws\n )\n else:\n self.ax_col_dendrogram.set_xticks([])\n self.ax_col_dendrogram.set_yticks([])\n despine(ax=self.ax_row_dendrogram, bottom=True, left=True)\n despine(ax=self.ax_col_dendrogram, bottom=True, left=True)\n\n def plot_colors(self, xind, yind, **kws):\n \"\"\"Plots color labels between the dendrogram and the heatmap\n\n Parameters\n ----------\n heatmap_kws : dict\n Keyword arguments heatmap\n\n \"\"\"\n # Remove any custom colormap and centering\n # TODO this code has consistently caused problems when we\n # have missed kwargs that need to be excluded that it might\n # be better to rewrite *in*clusively.\n kws = kws.copy()\n kws.pop('cmap', None)\n kws.pop('norm', None)\n kws.pop('center', None)\n kws.pop('annot', None)\n kws.pop('vmin', None)\n kws.pop('vmax', None)\n kws.pop('robust', None)\n kws.pop('xticklabels', None)\n kws.pop('yticklabels', None)\n\n # Plot the row colors\n if self.row_colors is not None:\n matrix, cmap = self.color_list_to_matrix_and_cmap(\n self.row_colors, yind, axis=0)\n\n # Get row_color labels\n if self.row_color_labels is not None:\n row_color_labels = self.row_color_labels\n else:\n row_color_labels = False\n\n heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors,\n xticklabels=row_color_labels, yticklabels=False, **kws)\n\n # Adjust rotation of labels\n if row_color_labels is not False:\n plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90)\n else:\n despine(self.ax_row_colors, left=True, bottom=True)\n\n # Plot the column colors\n if self.col_colors is not None:\n matrix, cmap = self.color_list_to_matrix_and_cmap(\n self.col_colors, xind, axis=1)\n\n # Get col_color labels\n if self.col_color_labels is not None:\n col_color_labels = self.col_color_labels\n else:\n col_color_labels = False\n\n heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors,\n xticklabels=False, yticklabels=col_color_labels, **kws)\n\n # Adjust rotation of labels, place on right side\n if col_color_labels is not False:\n self.ax_col_colors.yaxis.tick_right()\n plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0)\n else:\n despine(self.ax_col_colors, left=True, bottom=True)\n\n def plot_matrix(self, colorbar_kws, xind, yind, **kws):\n self.data2d = self.data2d.iloc[yind, xind]\n self.mask = self.mask.iloc[yind, xind]\n\n # Try to reorganize specified tick labels, if provided\n xtl = kws.pop(\"xticklabels\", \"auto\")\n try:\n xtl = np.asarray(xtl)[xind]\n except (TypeError, IndexError):\n pass\n ytl = kws.pop(\"yticklabels\", \"auto\")\n try:\n ytl = np.asarray(ytl)[yind]\n except (TypeError, IndexError):\n pass\n\n # Reorganize the annotations to match the heatmap\n annot = kws.pop(\"annot\", None)\n if annot is None or annot is False:\n pass\n else:\n if isinstance(annot, bool):\n annot_data = self.data2d\n else:\n annot_data = np.asarray(annot)\n if annot_data.shape != self.data2d.shape:\n err = \"`data` and `annot` must have same shape.\"\n raise ValueError(err)\n annot_data = annot_data[yind][:, xind]\n annot = annot_data\n\n # Setting ax_cbar=None in clustermap call implies no colorbar\n kws.setdefault(\"cbar\", self.ax_cbar is not None)\n heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar,\n cbar_kws=colorbar_kws, mask=self.mask,\n xticklabels=xtl, yticklabels=ytl, annot=annot, **kws)\n\n ytl = self.ax_heatmap.get_yticklabels()\n ytl_rot = None if not ytl else ytl[0].get_rotation()\n self.ax_heatmap.yaxis.set_ticks_position('right')\n self.ax_heatmap.yaxis.set_label_position('right')\n if ytl_rot is not None:\n ytl = self.ax_heatmap.get_yticklabels()\n plt.setp(ytl, rotation=ytl_rot)\n\n tight_params = dict(h_pad=.02, w_pad=.02)\n if self.ax_cbar is None:\n self._figure.tight_layout(**tight_params)\n else:\n # Turn the colorbar axes off for tight layout so that its\n # ticks don't interfere with the rest of the plot layout.\n # Then move it.\n self.ax_cbar.set_axis_off()\n self._figure.tight_layout(**tight_params)\n self.ax_cbar.set_axis_on()\n self.ax_cbar.set_position(self.cbar_pos)\n\n def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster,\n row_linkage, col_linkage, tree_kws, **kws):\n\n # heatmap square=True sets the aspect ratio on the axes, but that is\n # not compatible with the multi-axes layout of clustergrid\n if kws.get(\"square\", False):\n msg = \"``square=True`` ignored in clustermap\"\n warnings.warn(msg)\n kws.pop(\"square\")\n\n colorbar_kws = {} if colorbar_kws is None else colorbar_kws\n\n self.plot_dendrograms(row_cluster, col_cluster, metric, method,\n row_linkage=row_linkage, col_linkage=col_linkage,\n tree_kws=tree_kws)\n try:\n xind = self.dendrogram_col.reordered_ind\n except AttributeError:\n xind = np.arange(self.data2d.shape[1])\n try:\n yind = self.dendrogram_row.reordered_ind\n except AttributeError:\n yind = np.arange(self.data2d.shape[0])\n\n self.plot_colors(xind, yind, **kws)\n self.plot_matrix(colorbar_kws, xind, yind, **kws)\n return self\n\n\ndef clustermap(\n data, *,\n pivot_kws=None, method='average', metric='euclidean',\n z_score=None, standard_scale=None, figsize=(10, 10),\n cbar_kws=None, row_cluster=True, col_cluster=True,\n row_linkage=None, col_linkage=None,\n row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=.2, colors_ratio=0.03,\n cbar_pos=(.02, .8, .05, .18), tree_kws=None,\n **kwargs\n):\n \"\"\"\n Plot a matrix dataset as a hierarchically-clustered heatmap.\n\n This function requires scipy to be available.\n\n Parameters\n ----------\n data : 2D array-like\n Rectangular data for clustering. Cannot contain NAs.\n pivot_kws : dict, optional\n If `data` is a tidy dataframe, can provide keyword arguments for\n pivot to create a rectangular dataframe.\n method : str, optional\n Linkage method to use for calculating clusters. See\n :func:`scipy.cluster.hierarchy.linkage` documentation for more\n information.\n metric : str, optional\n Distance metric to use for the data. See\n :func:`scipy.spatial.distance.pdist` documentation for more options.\n To use different metrics (or methods) for rows and columns, you may\n construct each linkage matrix yourself and provide them as\n `{row,col}_linkage`.\n z_score : int or None, optional\n Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores\n for the rows or the columns. Z scores are: z = (x - mean)/std, so\n values in each row (column) will get the mean of the row (column)\n subtracted, then divided by the standard deviation of the row (column).\n This ensures that each row (column) has mean of 0 and variance of 1.\n standard_scale : int or None, optional\n Either 0 (rows) or 1 (columns). Whether or not to standardize that\n dimension, meaning for each row or column, subtract the minimum and\n divide each by its maximum.\n figsize : tuple of (width, height), optional\n Overall size of the figure.\n cbar_kws : dict, optional\n Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to\n add a label to the colorbar.\n {row,col}_cluster : bool, optional\n If ``True``, cluster the {rows, columns}.\n {row,col}_linkage : :class:`numpy.ndarray`, optional\n Precomputed linkage matrix for the rows or columns. See\n :func:`scipy.cluster.hierarchy.linkage` for specific formats.\n {row,col}_colors : list-like or pandas DataFrame/Series, optional\n List of colors to label for either the rows or columns. Useful to evaluate\n whether samples within a group are clustered together. Can use nested lists or\n DataFrame for multiple color levels of labeling. If given as a\n :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are\n extracted from the DataFrames column names or from the name of the Series.\n DataFrame/Series colors are also matched to the data by their index, ensuring\n colors are drawn in the correct order.\n mask : bool array or DataFrame, optional\n If passed, data will not be shown in cells where `mask` is True.\n Cells with missing values are automatically masked. Only used for\n visualizing, not for calculating.\n {dendrogram,colors}_ratio : float, or pair of floats, optional\n Proportion of the figure size devoted to the two marginal elements. If\n a pair is given, they correspond to (row, col) ratios.\n cbar_pos : tuple of (left, bottom, width, height), optional\n Position of the colorbar axes in the figure. Setting to ``None`` will\n disable the colorbar.\n tree_kws : dict, optional\n Parameters for the :class:`matplotlib.collections.LineCollection`\n that is used to plot the lines of the dendrogram tree.\n kwargs : other keyword arguments\n All other keyword arguments are passed to :func:`heatmap`.\n\n Returns\n -------\n :class:`ClusterGrid`\n A :class:`ClusterGrid` instance.\n\n See Also\n --------\n heatmap : Plot rectangular data as a color-encoded matrix.\n\n Notes\n -----\n The returned object has a ``savefig`` method that should be used if you\n want to save the figure object without clipping the dendrograms.\n\n To access the reordered row indices, use:\n ``clustergrid.dendrogram_row.reordered_ind``\n\n Column indices, use:\n ``clustergrid.dendrogram_col.reordered_ind``\n\n Examples\n --------\n\n .. include:: ../docstrings/clustermap.rst\n\n \"\"\"\n if _no_scipy:\n raise RuntimeError(\"clustermap requires scipy to be available\")\n\n plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize,\n row_colors=row_colors, col_colors=col_colors,\n z_score=z_score, standard_scale=standard_scale,\n mask=mask, dendrogram_ratio=dendrogram_ratio,\n colors_ratio=colors_ratio, cbar_pos=cbar_pos)\n\n return plotter.plot(metric=metric, method=method,\n colorbar_kws=cbar_kws,\n row_cluster=row_cluster, col_cluster=col_cluster,\n row_linkage=row_linkage, col_linkage=col_linkage,\n tree_kws=tree_kws, **kwargs)\n"},{"col":0,"comment":"Return a boolean for whether the list of ticklabels have overlaps.\n\n Parameters\n ----------\n labels : list of matplotlib ticklabels\n\n Returns\n -------\n overlap : boolean\n True if any of the labels overlap.\n\n ","endLoc":663,"header":"def axis_ticklabels_overlap(labels)","id":622,"name":"axis_ticklabels_overlap","nodeType":"Function","startLoc":642,"text":"def axis_ticklabels_overlap(labels):\n \"\"\"Return a boolean for whether the list of ticklabels have overlaps.\n\n Parameters\n ----------\n labels : list of matplotlib ticklabels\n\n Returns\n -------\n overlap : boolean\n True if any of the labels overlap.\n\n \"\"\"\n if not labels:\n return False\n try:\n bboxes = [l.get_window_extent() for l in labels]\n overlaps = [b.count_overlaps(bboxes) for b in bboxes]\n return max(overlaps) > 1\n except RuntimeError:\n # Issue on macos backend raises an error in the above code\n return False"},{"col":0,"comment":"Calculate the relative luminance of a color according to W3C standards\n\n Parameters\n ----------\n color : matplotlib color or sequence of matplotlib colors\n Hex code, rgb-tuple, or html color name.\n\n Returns\n -------\n luminance : float(s) between 0 and 1\n\n ","endLoc":728,"header":"def relative_luminance(color)","id":623,"name":"relative_luminance","nodeType":"Function","startLoc":709,"text":"def relative_luminance(color):\n \"\"\"Calculate the relative luminance of a color according to W3C standards\n\n Parameters\n ----------\n color : matplotlib color or sequence of matplotlib colors\n Hex code, rgb-tuple, or html color name.\n\n Returns\n -------\n luminance : float(s) between 0 and 1\n\n \"\"\"\n rgb = mpl.colors.colorConverter.to_rgba_array(color)[:, :3]\n rgb = np.where(rgb <= .03928, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)\n lum = rgb.dot([.2126, .7152, .0722])\n try:\n return lum.item()\n except ValueError:\n return lum"},{"col":0,"comment":"Return a string representing a Python object.\n\n Strings (i.e. type ``str``) are returned unchanged.\n\n Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.\n\n For other objects, the method ``__str__()`` is called, and the result is\n returned as a string.\n\n Parameters\n ----------\n obj : object\n Any Python object\n\n Returns\n -------\n s : str\n UTF-8-decoded string representation of ``obj``\n\n ","endLoc":757,"header":"def to_utf8(obj)","id":624,"name":"to_utf8","nodeType":"Function","startLoc":731,"text":"def to_utf8(obj):\n \"\"\"Return a string representing a Python object.\n\n Strings (i.e. type ``str``) are returned unchanged.\n\n Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.\n\n For other objects, the method ``__str__()`` is called, and the result is\n returned as a string.\n\n Parameters\n ----------\n obj : object\n Any Python object\n\n Returns\n -------\n s : str\n UTF-8-decoded string representation of ``obj``\n\n \"\"\"\n if isinstance(obj, str):\n return obj\n try:\n return obj.decode(encoding=\"utf-8\")\n except AttributeError: # obj is not bytes-like\n return str(obj)"},{"col":0,"comment":"Decrease the saturation channel of a color by some percent.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n prop : float\n saturation channel of color will be multiplied by this value\n\n Returns\n -------\n new_color : rgb tuple\n desaturated color code in RGB tuple representation\n\n ","endLoc":200,"header":"def desaturate(color, prop)","id":625,"name":"desaturate","nodeType":"Function","startLoc":168,"text":"def desaturate(color, prop):\n \"\"\"Decrease the saturation channel of a color by some percent.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n prop : float\n saturation channel of color will be multiplied by this value\n\n Returns\n -------\n new_color : rgb tuple\n desaturated color code in RGB tuple representation\n\n \"\"\"\n # Check inputs\n if not 0 <= prop <= 1:\n raise ValueError(\"prop must be between 0 and 1\")\n\n # Get rgb tuple rep\n rgb = to_rgb(color)\n\n # Convert to hls\n h, l, s = colorsys.rgb_to_hls(*rgb)\n\n # Desaturate the saturation channel\n s *= prop\n\n # Convert back to rgb\n new_color = colorsys.hls_to_rgb(h, l, s)\n\n return new_color"},{"col":0,"comment":"null","endLoc":5,"header":"def rgb_to_hls(r: float, g: float, b: float) -> tuple[float, float, float]","id":626,"name":"rgb_to_hls","nodeType":"Function","startLoc":5,"text":"def rgb_to_hls(r: float, g: float, b: float) -> tuple[float, float, float]: ..."},{"className":"KDE","col":0,"comment":"Univariate and bivariate kernel density estimator.","endLoc":194,"id":627,"nodeType":"Class","startLoc":41,"text":"class KDE:\n \"\"\"Univariate and bivariate kernel density estimator.\"\"\"\n def __init__(\n self, *,\n bw_method=None,\n bw_adjust=1,\n gridsize=200,\n cut=3,\n clip=None,\n cumulative=False,\n ):\n \"\"\"Initialize the estimator with its parameters.\n\n Parameters\n ----------\n bw_method : string, scalar, or callable, optional\n Method for determining the smoothing bandwidth to use; passed to\n :class:`scipy.stats.gaussian_kde`.\n bw_adjust : number, optional\n Factor that multiplicatively scales the value chosen using\n ``bw_method``. Increasing will make the curve smoother. See Notes.\n gridsize : int, optional\n Number of points on each dimension of the evaluation grid.\n cut : number, optional\n Factor, multiplied by the smoothing bandwidth, that determines how\n far the evaluation grid extends past the extreme datapoints. When\n set to 0, truncate the curve at the data limits.\n clip : pair of numbers or None, or a pair of such pairs\n Do not evaluate the density outside of these limits.\n cumulative : bool, optional\n If True, estimate a cumulative distribution function. Requires scipy.\n\n \"\"\"\n if clip is None:\n clip = None, None\n\n self.bw_method = bw_method\n self.bw_adjust = bw_adjust\n self.gridsize = gridsize\n self.cut = cut\n self.clip = clip\n self.cumulative = cumulative\n\n if cumulative and _no_scipy:\n raise RuntimeError(\"Cumulative KDE evaluation requires scipy\")\n\n self.support = None\n\n def _define_support_grid(self, x, bw, cut, clip, gridsize):\n \"\"\"Create the grid of evaluation points depending for vector x.\"\"\"\n clip_lo = -np.inf if clip[0] is None else clip[0]\n clip_hi = +np.inf if clip[1] is None else clip[1]\n gridmin = max(x.min() - bw * cut, clip_lo)\n gridmax = min(x.max() + bw * cut, clip_hi)\n return np.linspace(gridmin, gridmax, gridsize)\n\n def _define_support_univariate(self, x, weights):\n \"\"\"Create a 1D grid of evaluation points.\"\"\"\n kde = self._fit(x, weights)\n bw = np.sqrt(kde.covariance.squeeze())\n grid = self._define_support_grid(\n x, bw, self.cut, self.clip, self.gridsize\n )\n return grid\n\n def _define_support_bivariate(self, x1, x2, weights):\n \"\"\"Create a 2D grid of evaluation points.\"\"\"\n clip = self.clip\n if clip[0] is None or np.isscalar(clip[0]):\n clip = (clip, clip)\n\n kde = self._fit([x1, x2], weights)\n bw = np.sqrt(np.diag(kde.covariance).squeeze())\n\n grid1 = self._define_support_grid(\n x1, bw[0], self.cut, clip[0], self.gridsize\n )\n grid2 = self._define_support_grid(\n x2, bw[1], self.cut, clip[1], self.gridsize\n )\n\n return grid1, grid2\n\n def define_support(self, x1, x2=None, weights=None, cache=True):\n \"\"\"Create the evaluation grid for a given data set.\"\"\"\n if x2 is None:\n support = self._define_support_univariate(x1, weights)\n else:\n support = self._define_support_bivariate(x1, x2, weights)\n\n if cache:\n self.support = support\n\n return support\n\n def _fit(self, fit_data, weights=None):\n \"\"\"Fit the scipy kde while adding bw_adjust logic and version check.\"\"\"\n fit_kws = {\"bw_method\": self.bw_method}\n if weights is not None:\n fit_kws[\"weights\"] = weights\n\n kde = gaussian_kde(fit_data, **fit_kws)\n kde.set_bandwidth(kde.factor * self.bw_adjust)\n\n return kde\n\n def _eval_univariate(self, x, weights=None):\n \"\"\"Fit and evaluate a univariate on univariate data.\"\"\"\n support = self.support\n if support is None:\n support = self.define_support(x, cache=False)\n\n kde = self._fit(x, weights)\n\n if self.cumulative:\n s_0 = support[0]\n density = np.array([\n kde.integrate_box_1d(s_0, s_i) for s_i in support\n ])\n else:\n density = kde(support)\n\n return density, support\n\n def _eval_bivariate(self, x1, x2, weights=None):\n \"\"\"Fit and evaluate a univariate on bivariate data.\"\"\"\n support = self.support\n if support is None:\n support = self.define_support(x1, x2, cache=False)\n\n kde = self._fit([x1, x2], weights)\n\n if self.cumulative:\n\n grid1, grid2 = support\n density = np.zeros((grid1.size, grid2.size))\n p0 = grid1.min(), grid2.min()\n for i, xi in enumerate(grid1):\n for j, xj in enumerate(grid2):\n density[i, j] = kde.integrate_box(p0, (xi, xj))\n\n else:\n\n xx1, xx2 = np.meshgrid(*support)\n density = kde([xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)\n\n return density, support\n\n def __call__(self, x1, x2=None, weights=None):\n \"\"\"Fit and evaluate on univariate or bivariate data.\"\"\"\n if x2 is None:\n return self._eval_univariate(x1, weights)\n else:\n return self._eval_bivariate(x1, x2, weights)"},{"col":4,"comment":"Initialize the estimator with its parameters.\n\n Parameters\n ----------\n bw_method : string, scalar, or callable, optional\n Method for determining the smoothing bandwidth to use; passed to\n :class:`scipy.stats.gaussian_kde`.\n bw_adjust : number, optional\n Factor that multiplicatively scales the value chosen using\n ``bw_method``. Increasing will make the curve smoother. See Notes.\n gridsize : int, optional\n Number of points on each dimension of the evaluation grid.\n cut : number, optional\n Factor, multiplied by the smoothing bandwidth, that determines how\n far the evaluation grid extends past the extreme datapoints. When\n set to 0, truncate the curve at the data limits.\n clip : pair of numbers or None, or a pair of such pairs\n Do not evaluate the density outside of these limits.\n cumulative : bool, optional\n If True, estimate a cumulative distribution function. Requires scipy.\n\n ","endLoc":87,"header":"def __init__(\n self, *,\n bw_method=None,\n bw_adjust=1,\n gridsize=200,\n cut=3,\n clip=None,\n cumulative=False,\n )","id":628,"name":"__init__","nodeType":"Function","startLoc":43,"text":"def __init__(\n self, *,\n bw_method=None,\n bw_adjust=1,\n gridsize=200,\n cut=3,\n clip=None,\n cumulative=False,\n ):\n \"\"\"Initialize the estimator with its parameters.\n\n Parameters\n ----------\n bw_method : string, scalar, or callable, optional\n Method for determining the smoothing bandwidth to use; passed to\n :class:`scipy.stats.gaussian_kde`.\n bw_adjust : number, optional\n Factor that multiplicatively scales the value chosen using\n ``bw_method``. Increasing will make the curve smoother. See Notes.\n gridsize : int, optional\n Number of points on each dimension of the evaluation grid.\n cut : number, optional\n Factor, multiplied by the smoothing bandwidth, that determines how\n far the evaluation grid extends past the extreme datapoints. When\n set to 0, truncate the curve at the data limits.\n clip : pair of numbers or None, or a pair of such pairs\n Do not evaluate the density outside of these limits.\n cumulative : bool, optional\n If True, estimate a cumulative distribution function. Requires scipy.\n\n \"\"\"\n if clip is None:\n clip = None, None\n\n self.bw_method = bw_method\n self.bw_adjust = bw_adjust\n self.gridsize = gridsize\n self.cut = cut\n self.clip = clip\n self.cumulative = cumulative\n\n if cumulative and _no_scipy:\n raise RuntimeError(\"Cumulative KDE evaluation requires scipy\")\n\n self.support = None"},{"col":4,"comment":"Create the grid of evaluation points depending for vector x.","endLoc":95,"header":"def _define_support_grid(self, x, bw, cut, clip, gridsize)","id":630,"name":"_define_support_grid","nodeType":"Function","startLoc":89,"text":"def _define_support_grid(self, x, bw, cut, clip, gridsize):\n \"\"\"Create the grid of evaluation points depending for vector x.\"\"\"\n clip_lo = -np.inf if clip[0] is None else clip[0]\n clip_hi = +np.inf if clip[1] is None else clip[1]\n gridmin = max(x.min() - bw * cut, clip_lo)\n gridmax = min(x.max() + bw * cut, clip_hi)\n return np.linspace(gridmin, gridmax, gridsize)"},{"col":4,"comment":"null","endLoc":42,"header":"def __init__(self, iterable: Iterable[_T], /) -> None","id":631,"name":"__init__","nodeType":"Function","startLoc":42,"text":"def __init__(self, iterable: Iterable[_T], /) -> None: ..."},{"col":0,"comment":"null","endLoc":1546,"header":"@overload\ndef next(__i: SupportsNext[_T]) -> _T","id":633,"name":"next","nodeType":"Function","startLoc":1545,"text":"@overload\ndef next(__i: SupportsNext[_T]) -> _T: ..."},{"col":0,"comment":"null","endLoc":1548,"header":"@overload\ndef next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT","id":634,"name":"next","nodeType":"Function","startLoc":1547,"text":"@overload\ndef next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ..."},{"col":4,"comment":"Create a 1D grid of evaluation points.","endLoc":104,"header":"def _define_support_univariate(self, x, weights)","id":635,"name":"_define_support_univariate","nodeType":"Function","startLoc":97,"text":"def _define_support_univariate(self, x, weights):\n \"\"\"Create a 1D grid of evaluation points.\"\"\"\n kde = self._fit(x, weights)\n bw = np.sqrt(kde.covariance.squeeze())\n grid = self._define_support_grid(\n x, bw, self.cut, self.clip, self.gridsize\n )\n return grid"},{"col":4,"comment":"Fit the scipy kde while adding bw_adjust logic and version check.","endLoc":145,"header":"def _fit(self, fit_data, weights=None)","id":636,"name":"_fit","nodeType":"Function","startLoc":136,"text":"def _fit(self, fit_data, weights=None):\n \"\"\"Fit the scipy kde while adding bw_adjust logic and version check.\"\"\"\n fit_kws = {\"bw_method\": self.bw_method}\n if weights is not None:\n fit_kws[\"weights\"] = weights\n\n kde = gaussian_kde(fit_data, **fit_kws)\n kde.set_bandwidth(kde.factor * self.bw_adjust)\n\n return kde"},{"className":"_HeatMapper","col":0,"comment":"Draw a heatmap plot of a matrix with nice labels and colormaps.","endLoc":352,"id":637,"nodeType":"Class","startLoc":97,"text":"class _HeatMapper:\n \"\"\"Draw a heatmap plot of a matrix with nice labels and colormaps.\"\"\"\n\n def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt,\n annot_kws, cbar, cbar_kws,\n xticklabels=True, yticklabels=True, mask=None):\n \"\"\"Initialize the plotting object.\"\"\"\n # We always want to have a DataFrame with semantic information\n # and an ndarray to pass to matplotlib\n if isinstance(data, pd.DataFrame):\n plot_data = data.values\n else:\n plot_data = np.asarray(data)\n data = pd.DataFrame(plot_data)\n\n # Validate the mask and convert to DataFrame\n mask = _matrix_mask(data, mask)\n\n plot_data = np.ma.masked_where(np.asarray(mask), plot_data)\n\n # Get good names for the rows and columns\n xtickevery = 1\n if isinstance(xticklabels, int):\n xtickevery = xticklabels\n xticklabels = _index_to_ticklabels(data.columns)\n elif xticklabels is True:\n xticklabels = _index_to_ticklabels(data.columns)\n elif xticklabels is False:\n xticklabels = []\n\n ytickevery = 1\n if isinstance(yticklabels, int):\n ytickevery = yticklabels\n yticklabels = _index_to_ticklabels(data.index)\n elif yticklabels is True:\n yticklabels = _index_to_ticklabels(data.index)\n elif yticklabels is False:\n yticklabels = []\n\n if not len(xticklabels):\n self.xticks = []\n self.xticklabels = []\n elif isinstance(xticklabels, str) and xticklabels == \"auto\":\n self.xticks = \"auto\"\n self.xticklabels = _index_to_ticklabels(data.columns)\n else:\n self.xticks, self.xticklabels = self._skip_ticks(xticklabels,\n xtickevery)\n\n if not len(yticklabels):\n self.yticks = []\n self.yticklabels = []\n elif isinstance(yticklabels, str) and yticklabels == \"auto\":\n self.yticks = \"auto\"\n self.yticklabels = _index_to_ticklabels(data.index)\n else:\n self.yticks, self.yticklabels = self._skip_ticks(yticklabels,\n ytickevery)\n\n # Get good names for the axis labels\n xlabel = _index_to_label(data.columns)\n ylabel = _index_to_label(data.index)\n self.xlabel = xlabel if xlabel is not None else \"\"\n self.ylabel = ylabel if ylabel is not None else \"\"\n\n # Determine good default values for the colormapping\n self._determine_cmap_params(plot_data, vmin, vmax,\n cmap, center, robust)\n\n # Sort out the annotations\n if annot is None or annot is False:\n annot = False\n annot_data = None\n else:\n if isinstance(annot, bool):\n annot_data = plot_data\n else:\n annot_data = np.asarray(annot)\n if annot_data.shape != plot_data.shape:\n err = \"`data` and `annot` must have same shape.\"\n raise ValueError(err)\n annot = True\n\n # Save other attributes to the object\n self.data = data\n self.plot_data = plot_data\n\n self.annot = annot\n self.annot_data = annot_data\n\n self.fmt = fmt\n self.annot_kws = {} if annot_kws is None else annot_kws.copy()\n self.cbar = cbar\n self.cbar_kws = {} if cbar_kws is None else cbar_kws.copy()\n\n def _determine_cmap_params(self, plot_data, vmin, vmax,\n cmap, center, robust):\n \"\"\"Use some heuristics to set good defaults for colorbar and range.\"\"\"\n\n # plot_data is a np.ma.array instance\n calc_data = plot_data.astype(float).filled(np.nan)\n if vmin is None:\n if robust:\n vmin = np.nanpercentile(calc_data, 2)\n else:\n vmin = np.nanmin(calc_data)\n if vmax is None:\n if robust:\n vmax = np.nanpercentile(calc_data, 98)\n else:\n vmax = np.nanmax(calc_data)\n self.vmin, self.vmax = vmin, vmax\n\n # Choose default colormaps if not provided\n if cmap is None:\n if center is None:\n self.cmap = cm.rocket\n else:\n self.cmap = cm.icefire\n elif isinstance(cmap, str):\n self.cmap = get_colormap(cmap)\n elif isinstance(cmap, list):\n self.cmap = mpl.colors.ListedColormap(cmap)\n else:\n self.cmap = cmap\n\n # Recenter a divergent colormap\n if center is not None:\n\n # Copy bad values\n # in mpl<3.2 only masked values are honored with \"bad\" color spec\n # (see https://github.com/matplotlib/matplotlib/pull/14257)\n bad = self.cmap(np.ma.masked_invalid([np.nan]))[0]\n\n # under/over values are set for sure when cmap extremes\n # do not map to the same color as +-inf\n under = self.cmap(-np.inf)\n over = self.cmap(np.inf)\n under_set = under != self.cmap(0)\n over_set = over != self.cmap(self.cmap.N - 1)\n\n vrange = max(vmax - center, center - vmin)\n normlize = mpl.colors.Normalize(center - vrange, center + vrange)\n cmin, cmax = normlize([vmin, vmax])\n cc = np.linspace(cmin, cmax, 256)\n self.cmap = mpl.colors.ListedColormap(self.cmap(cc))\n self.cmap.set_bad(bad)\n if under_set:\n self.cmap.set_under(under)\n if over_set:\n self.cmap.set_over(over)\n\n def _annotate_heatmap(self, ax, mesh):\n \"\"\"Add textual labels with the value in each cell.\"\"\"\n mesh.update_scalarmappable()\n height, width = self.annot_data.shape\n xpos, ypos = np.meshgrid(np.arange(width) + .5, np.arange(height) + .5)\n for x, y, m, color, val in zip(xpos.flat, ypos.flat,\n mesh.get_array(), mesh.get_facecolors(),\n self.annot_data.flat):\n if m is not np.ma.masked:\n lum = relative_luminance(color)\n text_color = \".15\" if lum > .408 else \"w\"\n annotation = (\"{:\" + self.fmt + \"}\").format(val)\n text_kwargs = dict(color=text_color, ha=\"center\", va=\"center\")\n text_kwargs.update(self.annot_kws)\n ax.text(x, y, annotation, **text_kwargs)\n\n def _skip_ticks(self, labels, tickevery):\n \"\"\"Return ticks and labels at evenly spaced intervals.\"\"\"\n n = len(labels)\n if tickevery == 0:\n ticks, labels = [], []\n elif tickevery == 1:\n ticks, labels = np.arange(n) + .5, labels\n else:\n start, end, step = 0, n, tickevery\n ticks = np.arange(start, end, step) + .5\n labels = labels[start:end:step]\n return ticks, labels\n\n def _auto_ticks(self, ax, labels, axis):\n \"\"\"Determine ticks and ticklabels that minimize overlap.\"\"\"\n transform = ax.figure.dpi_scale_trans.inverted()\n bbox = ax.get_window_extent().transformed(transform)\n size = [bbox.width, bbox.height][axis]\n axis = [ax.xaxis, ax.yaxis][axis]\n tick, = axis.set_ticks([0])\n fontsize = tick.label1.get_size()\n max_ticks = int(size // (fontsize / 72))\n if max_ticks < 1:\n return [], []\n tick_every = len(labels) // max_ticks + 1\n tick_every = 1 if tick_every == 0 else tick_every\n ticks, labels = self._skip_ticks(labels, tick_every)\n return ticks, labels\n\n def plot(self, ax, cax, kws):\n \"\"\"Draw the heatmap on the provided Axes.\"\"\"\n # Remove all the Axes spines\n despine(ax=ax, left=True, bottom=True)\n\n # setting vmin/vmax in addition to norm is deprecated\n # so avoid setting if norm is set\n if \"norm\" not in kws:\n kws.setdefault(\"vmin\", self.vmin)\n kws.setdefault(\"vmax\", self.vmax)\n\n # Draw the heatmap\n mesh = ax.pcolormesh(self.plot_data, cmap=self.cmap, **kws)\n\n # Set the axis limits\n ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0]))\n\n # Invert the y axis to show the plot in matrix form\n ax.invert_yaxis()\n\n # Possibly add a colorbar\n if self.cbar:\n cb = ax.figure.colorbar(mesh, cax, ax, **self.cbar_kws)\n cb.outline.set_linewidth(0)\n # If rasterized is passed to pcolormesh, also rasterize the\n # colorbar to avoid white lines on the PDF rendering\n if kws.get('rasterized', False):\n cb.solids.set_rasterized(True)\n\n # Add row and column labels\n if isinstance(self.xticks, str) and self.xticks == \"auto\":\n xticks, xticklabels = self._auto_ticks(ax, self.xticklabels, 0)\n else:\n xticks, xticklabels = self.xticks, self.xticklabels\n\n if isinstance(self.yticks, str) and self.yticks == \"auto\":\n yticks, yticklabels = self._auto_ticks(ax, self.yticklabels, 1)\n else:\n yticks, yticklabels = self.yticks, self.yticklabels\n\n ax.set(xticks=xticks, yticks=yticks)\n xtl = ax.set_xticklabels(xticklabels)\n ytl = ax.set_yticklabels(yticklabels, rotation=\"vertical\")\n plt.setp(ytl, va=\"center\") # GH2484\n\n # Possibly rotate them if they overlap\n _draw_figure(ax.figure)\n\n if axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n if axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n\n # Add the axis labels\n ax.set(xlabel=self.xlabel, ylabel=self.ylabel)\n\n # Annotate the cells with the formatted values\n if self.annot:\n self._annotate_heatmap(ax, mesh)"},{"col":4,"comment":"Initialize the plotting object.","endLoc":190,"header":"def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt,\n annot_kws, cbar, cbar_kws,\n xticklabels=True, yticklabels=True, mask=None)","id":638,"name":"__init__","nodeType":"Function","startLoc":100,"text":"def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt,\n annot_kws, cbar, cbar_kws,\n xticklabels=True, yticklabels=True, mask=None):\n \"\"\"Initialize the plotting object.\"\"\"\n # We always want to have a DataFrame with semantic information\n # and an ndarray to pass to matplotlib\n if isinstance(data, pd.DataFrame):\n plot_data = data.values\n else:\n plot_data = np.asarray(data)\n data = pd.DataFrame(plot_data)\n\n # Validate the mask and convert to DataFrame\n mask = _matrix_mask(data, mask)\n\n plot_data = np.ma.masked_where(np.asarray(mask), plot_data)\n\n # Get good names for the rows and columns\n xtickevery = 1\n if isinstance(xticklabels, int):\n xtickevery = xticklabels\n xticklabels = _index_to_ticklabels(data.columns)\n elif xticklabels is True:\n xticklabels = _index_to_ticklabels(data.columns)\n elif xticklabels is False:\n xticklabels = []\n\n ytickevery = 1\n if isinstance(yticklabels, int):\n ytickevery = yticklabels\n yticklabels = _index_to_ticklabels(data.index)\n elif yticklabels is True:\n yticklabels = _index_to_ticklabels(data.index)\n elif yticklabels is False:\n yticklabels = []\n\n if not len(xticklabels):\n self.xticks = []\n self.xticklabels = []\n elif isinstance(xticklabels, str) and xticklabels == \"auto\":\n self.xticks = \"auto\"\n self.xticklabels = _index_to_ticklabels(data.columns)\n else:\n self.xticks, self.xticklabels = self._skip_ticks(xticklabels,\n xtickevery)\n\n if not len(yticklabels):\n self.yticks = []\n self.yticklabels = []\n elif isinstance(yticklabels, str) and yticklabels == \"auto\":\n self.yticks = \"auto\"\n self.yticklabels = _index_to_ticklabels(data.index)\n else:\n self.yticks, self.yticklabels = self._skip_ticks(yticklabels,\n ytickevery)\n\n # Get good names for the axis labels\n xlabel = _index_to_label(data.columns)\n ylabel = _index_to_label(data.index)\n self.xlabel = xlabel if xlabel is not None else \"\"\n self.ylabel = ylabel if ylabel is not None else \"\"\n\n # Determine good default values for the colormapping\n self._determine_cmap_params(plot_data, vmin, vmax,\n cmap, center, robust)\n\n # Sort out the annotations\n if annot is None or annot is False:\n annot = False\n annot_data = None\n else:\n if isinstance(annot, bool):\n annot_data = plot_data\n else:\n annot_data = np.asarray(annot)\n if annot_data.shape != plot_data.shape:\n err = \"`data` and `annot` must have same shape.\"\n raise ValueError(err)\n annot = True\n\n # Save other attributes to the object\n self.data = data\n self.plot_data = plot_data\n\n self.annot = annot\n self.annot_data = annot_data\n\n self.fmt = fmt\n self.annot_kws = {} if annot_kws is None else annot_kws.copy()\n self.cbar = cbar\n self.cbar_kws = {} if cbar_kws is None else cbar_kws.copy()"},{"col":4,"comment":"null","endLoc":226,"header":"def _legend_artist(self, variables, value, scales)","id":639,"name":"_legend_artist","nodeType":"Function","startLoc":211,"text":"def _legend_artist(self, variables, value, scales):\n\n key = resolve_properties(self, {v: value for v in variables}, scales)\n\n artist_kws = self.artist_kws.copy()\n capstyle = artist_kws.pop(\"capstyle\")\n artist_kws[\"solid_capstyle\"] = capstyle\n artist_kws[\"dash_capstyle\"] = capstyle\n\n return mpl.lines.Line2D(\n [], [],\n color=key[\"color\"],\n linewidth=key[\"linewidth\"],\n linestyle=key[\"linestyle\"],\n **artist_kws,\n )"},{"col":0,"comment":"Ensure that data and mask are compatible and add missing values.\n\n Values will be plotted for cells where ``mask`` is ``False``.\n\n ``data`` is expected to be a DataFrame; ``mask`` can be an array or\n a DataFrame.\n\n ","endLoc":94,"header":"def _matrix_mask(data, mask)","id":640,"name":"_matrix_mask","nodeType":"Function","startLoc":60,"text":"def _matrix_mask(data, mask):\n \"\"\"Ensure that data and mask are compatible and add missing values.\n\n Values will be plotted for cells where ``mask`` is ``False``.\n\n ``data`` is expected to be a DataFrame; ``mask`` can be an array or\n a DataFrame.\n\n \"\"\"\n if mask is None:\n mask = np.zeros(data.shape, bool)\n\n if isinstance(mask, np.ndarray):\n # For array masks, ensure that shape matches data then convert\n if mask.shape != data.shape:\n raise ValueError(\"Mask must have the same shape as data.\")\n\n mask = pd.DataFrame(mask,\n index=data.index,\n columns=data.columns,\n dtype=bool)\n\n elif isinstance(mask, pd.DataFrame):\n # For DataFrame masks, ensure that semantic labels match data\n if not mask.index.equals(data.index) \\\n and mask.columns.equals(data.columns):\n err = \"Mask must have the same index and columns as data.\"\n raise ValueError(err)\n\n # Add any cells with missing data to the mask\n # This works around an issue where `plt.pcolormesh` doesn't represent\n # missing data properly\n mask = mask | pd.isnull(data)\n\n return mask"},{"col":4,"comment":"Define plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data : dict-like collection of vectors\n Input data where variable names map to vector values.\n kwargs : variable -> data mappings\n Keys are seaborn variables (x, y, hue, ...) and values are vectors\n in any format that can construct a :class:`pandas.DataFrame` or\n names of columns or index levels in ``data``.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in ``data``.\n\n ","endLoc":971,"header":"def _assign_variables_longform(self, data=None, **kwargs)","id":641,"name":"_assign_variables_longform","nodeType":"Function","startLoc":859,"text":"def _assign_variables_longform(self, data=None, **kwargs):\n \"\"\"Define plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data : dict-like collection of vectors\n Input data where variable names map to vector values.\n kwargs : variable -> data mappings\n Keys are seaborn variables (x, y, hue, ...) and values are vectors\n in any format that can construct a :class:`pandas.DataFrame` or\n names of columns or index levels in ``data``.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in ``data``.\n\n \"\"\"\n plot_data = {}\n variables = {}\n\n # Data is optional; all variables can be defined as vectors\n if data is None:\n data = {}\n\n # TODO should we try a data.to_dict() or similar here to more\n # generally accept objects with that interface?\n # Note that dict(df) also works for pandas, and gives us what we\n # want, whereas DataFrame.to_dict() gives a nested dict instead of\n # a dict of series.\n\n # Variables can also be extracted from the index attribute\n # TODO is this the most general way to enable it?\n # There is no index.to_dict on multiindex, unfortunately\n try:\n index = data.index.to_frame()\n except AttributeError:\n index = {}\n\n # The caller will determine the order of variables in plot_data\n for key, val in kwargs.items():\n\n # First try to treat the argument as a key for the data collection.\n # But be flexible about what can be used as a key.\n # Usually it will be a string, but allow numbers or tuples too when\n # taking from the main data object. Only allow strings to reference\n # fields in the index, because otherwise there is too much ambiguity.\n try:\n val_as_data_key = (\n val in data\n or (isinstance(val, (str, bytes)) and val in index)\n )\n except (KeyError, TypeError):\n val_as_data_key = False\n\n if val_as_data_key:\n\n # We know that __getitem__ will work\n\n if val in data:\n plot_data[key] = data[val]\n elif val in index:\n plot_data[key] = index[val]\n variables[key] = val\n\n elif isinstance(val, (str, bytes)):\n\n # This looks like a column name but we don't know what it means!\n\n err = f\"Could not interpret value `{val}` for parameter `{key}`\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, assume the value is itself data\n\n # Raise when data object is present and a vector can't matched\n if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series):\n if np.ndim(val) and len(data) != len(val):\n val_cls = val.__class__.__name__\n err = (\n f\"Length of {val_cls} vectors must match length of `data`\"\n f\" when both are used, but `data` has length {len(data)}\"\n f\" and the vector passed to `{key}` has length {len(val)}.\"\n )\n raise ValueError(err)\n\n plot_data[key] = val\n\n # Try to infer the name of the variable\n variables[key] = getattr(val, \"name\", None)\n\n # Construct a tidy plot DataFrame. This will convert a number of\n # types automatically, aligning on index in case of pandas objects\n plot_data = pd.DataFrame(plot_data)\n\n # Reduce the variables dictionary to fields with valid data\n variables = {\n var: name\n for var, name in variables.items()\n if plot_data[var].notnull().any()\n }\n\n return plot_data, variables"},{"col":0,"comment":"Convert a pandas index or multiindex into ticklabels.","endLoc":44,"header":"def _index_to_ticklabels(index)","id":642,"name":"_index_to_ticklabels","nodeType":"Function","startLoc":39,"text":"def _index_to_ticklabels(index):\n \"\"\"Convert a pandas index or multiindex into ticklabels.\"\"\"\n if isinstance(index, pd.MultiIndex):\n return [\"-\".join(map(to_utf8, i)) for i in index.values]\n else:\n return index.values"},{"col":4,"comment":"null","endLoc":211,"header":"def __init__(self, dataset, bw_method=None, weights=None)","id":643,"name":"__init__","nodeType":"Function","startLoc":195,"text":"def __init__(self, dataset, bw_method=None, weights=None):\n self.dataset = atleast_2d(asarray(dataset))\n if not self.dataset.size > 1:\n raise ValueError(\"`dataset` input should have multiple elements.\")\n\n self.d, self.n = self.dataset.shape\n\n if weights is not None:\n self._weights = atleast_1d(weights).astype(float)\n self._weights /= sum(self._weights)\n if self.weights.ndim != 1:\n raise ValueError(\"`weights` input should be one-dimensional.\")\n if len(self._weights) != self.n:\n raise ValueError(\"`weights` input should be of length n\")\n self._neff = 1/sum(self._weights**2)\n\n self.set_bandwidth(bw_method=bw_method)"},{"col":4,"comment":"Input check when values are provided as a list.","endLoc":140,"header":"def _check_list_length(self, levels: list, values: list) -> list","id":644,"name":"_check_list_length","nodeType":"Function","startLoc":118,"text":"def _check_list_length(self, levels: list, values: list) -> list:\n \"\"\"Input check when values are provided as a list.\"\"\"\n message = \"\"\n if len(levels) > len(values):\n message = \" \".join([\n f\"\\nThe {self.variable} list has fewer values ({len(values)})\",\n f\"than needed ({len(levels)}) and will cycle, which may\",\n \"produce an uninterpretable plot.\"\n ])\n values = [x for _, x in zip(levels, itertools.cycle(values))]\n\n elif len(values) > len(levels):\n message = \" \".join([\n f\"The {self.variable} list has more values ({len(values)})\",\n f\"than needed ({len(levels)}), which may not be intended.\",\n ])\n values = values[:len(levels)]\n\n # TODO look into custom PlotSpecWarning with better formatting\n if message:\n warnings.warn(message, UserWarning)\n\n return values"},{"col":0,"comment":"Raise if value for param is not in options.","endLoc":785,"header":"def _check_argument(param, options, value)","id":645,"name":"_check_argument","nodeType":"Function","startLoc":780,"text":"def _check_argument(param, options, value):\n \"\"\"Raise if value for param is not in options.\"\"\"\n if value not in options:\n raise ValueError(\n f\"`{param}` must be one of {options}, but {repr(value)} was passed.\"\n )"},{"col":4,"comment":"Compute the estimator bandwidth with given method.\n\n The new bandwidth calculated after a call to `set_bandwidth` is used\n for subsequent evaluations of the estimated density.\n\n Parameters\n ----------\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a\n scalar, this will be used directly as `kde.factor`. If a callable,\n it should take a `gaussian_kde` instance as only parameter and\n return a scalar. If None (default), nothing happens; the current\n `kde.covariance_factor` method is kept.\n\n Notes\n -----\n .. versionadded:: 0.11\n\n ","endLoc":337,"header":"def set_bandwidth(self, bw_method=None)","id":647,"name":"set_bandwidth","nodeType":"Function","startLoc":299,"text":"def set_bandwidth(self, bw_method=None):\n \"\"\"Compute the estimator bandwidth with given method.\n\n The new bandwidth calculated after a call to `set_bandwidth` is used\n for subsequent evaluations of the estimated density.\n\n Parameters\n ----------\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a\n scalar, this will be used directly as `kde.factor`. If a callable,\n it should take a `gaussian_kde` instance as only parameter and\n return a scalar. If None (default), nothing happens; the current\n `kde.covariance_factor` method is kept.\n\n Notes\n -----\n .. versionadded:: 0.11\n\n \"\"\"\n if bw_method is None:\n pass\n elif bw_method == 'scott':\n self.covariance_factor = self.scotts_factor\n elif bw_method == 'silverman':\n self.covariance_factor = self.silverman_factor\n elif np.isscalar(bw_method) and not isinstance(bw_method, str):\n self._bw_method = 'use constant'\n self.covariance_factor = lambda: bw_method\n elif callable(bw_method):\n self._bw_method = bw_method\n self.covariance_factor = lambda: self._bw_method(self)\n else:\n msg = \"`bw_method` should be 'scott', 'silverman', a scalar \" \\\n \"or a callable.\"\n raise ValueError(msg)\n\n self._compute_covariance()"},{"col":0,"comment":"Helper method for removing null values from data vectors.\n\n Parameters\n ----------\n vector : vector object\n Must implement boolean masking with [] subscript syntax.\n\n Returns\n -------\n clean_clean : same type as ``vector``\n Vector of data with null values removed. May be a copy or a view.\n\n ","endLoc":274,"header":"def remove_na(vector)","id":648,"name":"remove_na","nodeType":"Function","startLoc":260,"text":"def remove_na(vector):\n \"\"\"Helper method for removing null values from data vectors.\n\n Parameters\n ----------\n vector : vector object\n Must implement boolean masking with [] subscript syntax.\n\n Returns\n -------\n clean_clean : same type as ``vector``\n Vector of data with null values removed. May be a copy or a view.\n\n \"\"\"\n return vector[pd.notnull(vector)]"},{"col":37,"endLoc":328,"id":649,"nodeType":"Lambda","startLoc":328,"text":"lambda: bw_method"},{"className":"SemanticMapping","col":0,"comment":"Base class for mapping data values to plot attributes.","endLoc":91,"id":650,"nodeType":"Class","startLoc":29,"text":"class SemanticMapping:\n \"\"\"Base class for mapping data values to plot attributes.\"\"\"\n\n # -- Default attributes that all SemanticMapping subclasses must set\n\n # Whether the mapping is numeric, categorical, or datetime\n map_type = None\n\n # Ordered list of unique values in the input data\n levels = None\n\n # A mapping from the data values to corresponding plot attributes\n lookup_table = None\n\n def __init__(self, plotter):\n\n # TODO Putting this here so we can continue to use a lot of the\n # logic that's built into the library, but the idea of this class\n # is to move towards semantic mappings that are agnostic about the\n # kind of plot they're going to be used to draw.\n # Fully achieving that is going to take some thinking.\n self.plotter = plotter\n\n def map(cls, plotter, *args, **kwargs):\n # This method is assigned the __init__ docstring\n method_name = f\"_{cls.__name__[:-7].lower()}_map\"\n setattr(plotter, method_name, cls(plotter, *args, **kwargs))\n return plotter\n\n def _check_list_length(self, levels, values, variable):\n \"\"\"Input check when values are provided as a list.\"\"\"\n # Copied from _core/properties; eventually will be replaced for that.\n message = \"\"\n if len(levels) > len(values):\n message = \" \".join([\n f\"\\nThe {variable} list has fewer values ({len(values)})\",\n f\"than needed ({len(levels)}) and will cycle, which may\",\n \"produce an uninterpretable plot.\"\n ])\n values = [x for _, x in zip(levels, itertools.cycle(values))]\n\n elif len(values) > len(levels):\n message = \" \".join([\n f\"The {variable} list has more values ({len(values)})\",\n f\"than needed ({len(levels)}), which may not be intended.\",\n ])\n values = values[:len(levels)]\n\n if message:\n warnings.warn(message, UserWarning, stacklevel=6)\n\n return values\n\n def _lookup_single(self, key):\n \"\"\"Apply the mapping to a single data value.\"\"\"\n return self.lookup_table[key]\n\n def __call__(self, key, *args, **kwargs):\n \"\"\"Get the attribute(s) values for the data key.\"\"\"\n if isinstance(key, (list, np.ndarray, pd.Series)):\n return [self._lookup_single(k, *args, **kwargs) for k in key]\n else:\n return self._lookup_single(key, *args, **kwargs)"},{"col":4,"comment":"null","endLoc":50,"header":"def __init__(self, plotter)","id":651,"name":"__init__","nodeType":"Function","startLoc":43,"text":"def __init__(self, plotter):\n\n # TODO Putting this here so we can continue to use a lot of the\n # logic that's built into the library, but the idea of this class\n # is to move towards semantic mappings that are agnostic about the\n # kind of plot they're going to be used to draw.\n # Fully achieving that is going to take some thinking.\n self.plotter = plotter"},{"col":4,"comment":"null","endLoc":56,"header":"def map(cls, plotter, *args, **kwargs)","id":652,"name":"map","nodeType":"Function","startLoc":52,"text":"def map(cls, plotter, *args, **kwargs):\n # This method is assigned the __init__ docstring\n method_name = f\"_{cls.__name__[:-7].lower()}_map\"\n setattr(plotter, method_name, cls(plotter, *args, **kwargs))\n return plotter"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":154,"id":654,"name":"color","nodeType":"Attribute","startLoc":154,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":155,"id":655,"name":"alpha","nodeType":"Attribute","startLoc":155,"text":"alpha"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":156,"id":656,"name":"linewidth","nodeType":"Attribute","startLoc":156,"text":"linewidth"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":157,"id":657,"name":"linestyle","nodeType":"Attribute","startLoc":157,"text":"linestyle"},{"col":4,"comment":"Get the attribute(s) values for the data key.","endLoc":91,"header":"def __call__(self, key, *args, **kwargs)","id":658,"name":"__call__","nodeType":"Function","startLoc":86,"text":"def __call__(self, key, *args, **kwargs):\n \"\"\"Get the attribute(s) values for the data key.\"\"\"\n if isinstance(key, (list, np.ndarray, pd.Series)):\n return [self._lookup_single(k, *args, **kwargs) for k in key]\n else:\n return self._lookup_single(key, *args, **kwargs)"},{"attributeType":"bool","col":4,"comment":"null","endLoc":159,"id":659,"name":"_sort","nodeType":"Attribute","startLoc":159,"text":"_sort"},{"className":"Lines","col":0,"comment":"\n A faster but less-flexible mark for drawing many lines.\n\n See also\n --------\n Line : A mark connecting data points with sorting along the orientation axis.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Lines.rst\n\n ","endLoc":244,"id":660,"nodeType":"Class","startLoc":229,"text":"@document_properties\n@dataclass\nclass Lines(Paths):\n \"\"\"\n A faster but less-flexible mark for drawing many lines.\n\n See also\n --------\n Line : A mark connecting data points with sorting along the orientation axis.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Lines.rst\n\n \"\"\"\n _sort: ClassVar[bool] = True"},{"attributeType":"bool","col":4,"comment":"null","endLoc":244,"id":661,"name":"_sort","nodeType":"Attribute","startLoc":244,"text":"_sort"},{"col":4,"comment":"null","endLoc":1015,"header":"def extend(self, __iterable: Iterable[_T]) -> None","id":662,"name":"extend","nodeType":"Function","startLoc":1015,"text":"def extend(self, __iterable: Iterable[_T]) -> None: ..."},{"col":37,"endLoc":331,"id":663,"nodeType":"Lambda","startLoc":331,"text":"lambda: self._bw_method(self)"},{"className":"Range","col":0,"comment":"\n An oriented line mark drawn between min/max values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Range.rst\n\n ","endLoc":295,"id":664,"nodeType":"Class","startLoc":247,"text":"@document_properties\n@dataclass\nclass Range(Paths):\n \"\"\"\n An oriented line mark drawn between min/max values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Range.rst\n\n \"\"\"\n def _setup_lines(self, split_gen, scales, orient):\n\n line_data = {}\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n if ax not in line_data:\n line_data[ax] = {\n \"segments\": [],\n \"colors\": [],\n \"linewidths\": [],\n \"linestyles\": [],\n }\n\n # TODO better checks on what variables we have\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n\n # TODO what if only one exist?\n if not set(data.columns) & {f\"{other}min\", f\"{other}max\"}:\n agg = {f\"{other}min\": (other, \"min\"), f\"{other}max\": (other, \"max\")}\n data = data.groupby(orient).agg(**agg).reset_index()\n\n cols = [orient, f\"{other}min\", f\"{other}max\"]\n data = data[cols].melt(orient, value_name=other)[[\"x\", \"y\"]]\n segments = [d.to_numpy() for _, d in data.groupby(orient)]\n\n line_data[ax][\"segments\"].extend(segments)\n\n n = len(segments)\n line_data[ax][\"colors\"].extend([vals[\"color\"]] * n)\n line_data[ax][\"linewidths\"].extend([vals[\"linewidth\"]] * n)\n line_data[ax][\"linestyles\"].extend([vals[\"linestyle\"]] * n)\n\n return line_data"},{"col":4,"comment":"null","endLoc":295,"header":"def _setup_lines(self, split_gen, scales, orient)","id":665,"name":"_setup_lines","nodeType":"Function","startLoc":258,"text":"def _setup_lines(self, split_gen, scales, orient):\n\n line_data = {}\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n\n for keys, data, ax in split_gen(keep_na=not self._sort):\n\n if ax not in line_data:\n line_data[ax] = {\n \"segments\": [],\n \"colors\": [],\n \"linewidths\": [],\n \"linestyles\": [],\n }\n\n # TODO better checks on what variables we have\n\n vals = resolve_properties(self, keys, scales)\n vals[\"color\"] = resolve_color(self, keys, scales=scales)\n\n # TODO what if only one exist?\n if not set(data.columns) & {f\"{other}min\", f\"{other}max\"}:\n agg = {f\"{other}min\": (other, \"min\"), f\"{other}max\": (other, \"max\")}\n data = data.groupby(orient).agg(**agg).reset_index()\n\n cols = [orient, f\"{other}min\", f\"{other}max\"]\n data = data[cols].melt(orient, value_name=other)[[\"x\", \"y\"]]\n segments = [d.to_numpy() for _, d in data.groupby(orient)]\n\n line_data[ax][\"segments\"].extend(segments)\n\n n = len(segments)\n line_data[ax][\"colors\"].extend([vals[\"color\"]] * n)\n line_data[ax][\"linewidths\"].extend([vals[\"linewidth\"]] * n)\n line_data[ax][\"linestyles\"].extend([vals[\"linestyle\"]] * n)\n\n return line_data"},{"col":4,"comment":"Computes the covariance matrix for each Gaussian kernel using\n covariance_factor().\n ","endLoc":353,"header":"def _compute_covariance(self)","id":666,"name":"_compute_covariance","nodeType":"Function","startLoc":339,"text":"def _compute_covariance(self):\n \"\"\"Computes the covariance matrix for each Gaussian kernel using\n covariance_factor().\n \"\"\"\n self.factor = self.covariance_factor()\n # Cache covariance and inverse covariance of the data\n if not hasattr(self, '_data_inv_cov'):\n self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,\n bias=False,\n aweights=self.weights))\n self._data_inv_cov = linalg.inv(self._data_covariance)\n\n self.covariance = self._data_covariance * self.factor**2\n self.inv_cov = self._data_inv_cov / self.factor**2\n self._norm_factor = sqrt(linalg.det(2*pi*self.covariance))"},{"col":4,"comment":"Compute Scott's factor.\n\n Returns\n -------\n s : float\n Scott's factor.\n ","endLoc":279,"header":"def scotts_factor(self)","id":667,"name":"scotts_factor","nodeType":"Function","startLoc":271,"text":"def scotts_factor(self):\n \"\"\"Compute Scott's factor.\n\n Returns\n -------\n s : float\n Scott's factor.\n \"\"\"\n return power(self.neff, -1./(self.d+4))"},{"col":4,"comment":"Apply the mapping to a single data value.","endLoc":84,"header":"def _lookup_single(self, key)","id":668,"name":"_lookup_single","nodeType":"Function","startLoc":82,"text":"def _lookup_single(self, key):\n \"\"\"Apply the mapping to a single data value.\"\"\"\n return self.lookup_table[key]"},{"col":4,"comment":"Input check when values are provided as a list.","endLoc":80,"header":"def _check_list_length(self, levels, values, variable)","id":669,"name":"_check_list_length","nodeType":"Function","startLoc":58,"text":"def _check_list_length(self, levels, values, variable):\n \"\"\"Input check when values are provided as a list.\"\"\"\n # Copied from _core/properties; eventually will be replaced for that.\n message = \"\"\n if len(levels) > len(values):\n message = \" \".join([\n f\"\\nThe {variable} list has fewer values ({len(values)})\",\n f\"than needed ({len(levels)}) and will cycle, which may\",\n \"produce an uninterpretable plot.\"\n ])\n values = [x for _, x in zip(levels, itertools.cycle(values))]\n\n elif len(values) > len(levels):\n message = \" \".join([\n f\"The {variable} list has more values ({len(values)})\",\n f\"than needed ({len(levels)}), which may not be intended.\",\n ])\n values = values[:len(levels)]\n\n if message:\n warnings.warn(message, UserWarning, stacklevel=6)\n\n return values"},{"col":4,"comment":"Create a 2D grid of evaluation points.","endLoc":122,"header":"def _define_support_bivariate(self, x1, x2, weights)","id":670,"name":"_define_support_bivariate","nodeType":"Function","startLoc":106,"text":"def _define_support_bivariate(self, x1, x2, weights):\n \"\"\"Create a 2D grid of evaluation points.\"\"\"\n clip = self.clip\n if clip[0] is None or np.isscalar(clip[0]):\n clip = (clip, clip)\n\n kde = self._fit([x1, x2], weights)\n bw = np.sqrt(np.diag(kde.covariance).squeeze())\n\n grid1 = self._define_support_grid(\n x1, bw[0], self.cut, clip[0], self.gridsize\n )\n grid2 = self._define_support_grid(\n x2, bw[1], self.cut, clip[1], self.gridsize\n )\n\n return grid1, grid2"},{"col":4,"comment":"Create the evaluation grid for a given data set.","endLoc":134,"header":"def define_support(self, x1, x2=None, weights=None, cache=True)","id":671,"name":"define_support","nodeType":"Function","startLoc":124,"text":"def define_support(self, x1, x2=None, weights=None, cache=True):\n \"\"\"Create the evaluation grid for a given data set.\"\"\"\n if x2 is None:\n support = self._define_support_univariate(x1, weights)\n else:\n support = self._define_support_bivariate(x1, x2, weights)\n\n if cache:\n self.support = support\n\n return support"},{"col":4,"comment":"Fit and evaluate a univariate on univariate data.","endLoc":163,"header":"def _eval_univariate(self, x, weights=None)","id":672,"name":"_eval_univariate","nodeType":"Function","startLoc":147,"text":"def _eval_univariate(self, x, weights=None):\n \"\"\"Fit and evaluate a univariate on univariate data.\"\"\"\n support = self.support\n if support is None:\n support = self.define_support(x, cache=False)\n\n kde = self._fit(x, weights)\n\n if self.cumulative:\n s_0 = support[0]\n density = np.array([\n kde.integrate_box_1d(s_0, s_i) for s_i in support\n ])\n else:\n density = kde(support)\n\n return density, support"},{"col":4,"comment":"Fit and evaluate a univariate on bivariate data.","endLoc":187,"header":"def _eval_bivariate(self, x1, x2, weights=None)","id":673,"name":"_eval_bivariate","nodeType":"Function","startLoc":165,"text":"def _eval_bivariate(self, x1, x2, weights=None):\n \"\"\"Fit and evaluate a univariate on bivariate data.\"\"\"\n support = self.support\n if support is None:\n support = self.define_support(x1, x2, cache=False)\n\n kde = self._fit([x1, x2], weights)\n\n if self.cumulative:\n\n grid1, grid2 = support\n density = np.zeros((grid1.size, grid2.size))\n p0 = grid1.min(), grid2.min()\n for i, xi in enumerate(grid1):\n for j, xj in enumerate(grid2):\n density[i, j] = kde.integrate_box(p0, (xi, xj))\n\n else:\n\n xx1, xx2 = np.meshgrid(*support)\n density = kde([xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)\n\n return density, support"},{"col":0,"comment":"Determine how the plot should be oriented based on the data.\n\n For historical reasons, the convention is to call a plot \"horizontally\"\n or \"vertically\" oriented based on the axis representing its dependent\n variable. Practically, this is used when determining the axis for\n numerical aggregation.\n\n Parameters\n ----------\n x, y : Vector data or None\n Positional data vectors for the plot.\n orient : string or None\n Specified orientation, which must start with \"v\" or \"h\" if not None.\n require_numeric : bool\n If set, raise when the implied dependent variable is not numeric.\n\n Returns\n -------\n orient : \"v\" or \"h\"\n\n Raises\n ------\n ValueError: When `orient` is not None and does not start with \"h\" or \"v\"\n TypeError: When dependent variable is not numeric, with `require_numeric`\n\n ","endLoc":1635,"header":"def infer_orient(x=None, y=None, orient=None, require_numeric=True)","id":674,"name":"infer_orient","nodeType":"Function","startLoc":1556,"text":"def infer_orient(x=None, y=None, orient=None, require_numeric=True):\n \"\"\"Determine how the plot should be oriented based on the data.\n\n For historical reasons, the convention is to call a plot \"horizontally\"\n or \"vertically\" oriented based on the axis representing its dependent\n variable. Practically, this is used when determining the axis for\n numerical aggregation.\n\n Parameters\n ----------\n x, y : Vector data or None\n Positional data vectors for the plot.\n orient : string or None\n Specified orientation, which must start with \"v\" or \"h\" if not None.\n require_numeric : bool\n If set, raise when the implied dependent variable is not numeric.\n\n Returns\n -------\n orient : \"v\" or \"h\"\n\n Raises\n ------\n ValueError: When `orient` is not None and does not start with \"h\" or \"v\"\n TypeError: When dependent variable is not numeric, with `require_numeric`\n\n \"\"\"\n\n x_type = None if x is None else variable_type(x)\n y_type = None if y is None else variable_type(y)\n\n nonnumeric_dv_error = \"{} orientation requires numeric `{}` variable.\"\n single_var_warning = \"{} orientation ignored with only `{}` specified.\"\n\n if x is None:\n if str(orient).startswith(\"h\"):\n warnings.warn(single_var_warning.format(\"Horizontal\", \"y\"))\n if require_numeric and y_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Vertical\", \"y\"))\n return \"v\"\n\n elif y is None:\n if str(orient).startswith(\"v\"):\n warnings.warn(single_var_warning.format(\"Vertical\", \"x\"))\n if require_numeric and x_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Horizontal\", \"x\"))\n return \"h\"\n\n elif str(orient).startswith(\"v\"):\n if require_numeric and y_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Vertical\", \"y\"))\n return \"v\"\n\n elif str(orient).startswith(\"h\"):\n if require_numeric and x_type != \"numeric\":\n raise TypeError(nonnumeric_dv_error.format(\"Horizontal\", \"x\"))\n return \"h\"\n\n elif orient is not None:\n err = (\n \"`orient` must start with 'v' or 'h' or be None, \"\n f\"but `{repr(orient)}` was passed.\"\n )\n raise ValueError(err)\n\n elif x_type != \"categorical\" and y_type == \"categorical\":\n return \"h\"\n\n elif x_type != \"numeric\" and y_type == \"numeric\":\n return \"v\"\n\n elif x_type == \"numeric\" and y_type != \"numeric\":\n return \"h\"\n\n elif require_numeric and \"numeric\" not in (x_type, y_type):\n err = \"Neither the `x` nor `y` variable appears to be numeric.\"\n raise TypeError(err)\n\n else:\n return \"v\""},{"col":4,"comment":"Fit and evaluate on univariate or bivariate data.","endLoc":194,"header":"def __call__(self, x1, x2=None, weights=None)","id":675,"name":"__call__","nodeType":"Function","startLoc":189,"text":"def __call__(self, x1, x2=None, weights=None):\n \"\"\"Fit and evaluate on univariate or bivariate data.\"\"\"\n if x2 is None:\n return self._eval_univariate(x1, weights)\n else:\n return self._eval_bivariate(x1, x2, weights)"},{"attributeType":"null","col":8,"comment":"null","endLoc":80,"id":676,"name":"cut","nodeType":"Attribute","startLoc":80,"text":"self.cut"},{"attributeType":"null","col":8,"comment":"null","endLoc":79,"id":677,"name":"gridsize","nodeType":"Attribute","startLoc":79,"text":"self.gridsize"},{"attributeType":"null","col":16,"comment":"null","endLoc":5,"id":678,"name":"np","nodeType":"Attribute","startLoc":5,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":6,"id":679,"name":"mpl","nodeType":"Attribute","startLoc":6,"text":"mpl"},{"id":680,"name":"ecdfplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Plot a univariate distribution along the x axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns; sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"sns.ecdfplot(data=penguins, x=\\\"flipper_length_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Flip the plot by assigning the data variable to the y axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.ecdfplot(data=penguins, y=\\\"flipper_length_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"If neither `x` nor `y` is assigned, the dataset is treated as wide-form, and a histogram is drawn for each numeric column:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.ecdfplot(data=penguins.filter(like=\\\"bill_\\\", axis=\\\"columns\\\"))\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"You can also draw multiple histograms from a long-form dataset with hue mapping:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.ecdfplot(data=penguins, x=\\\"bill_length_mm\\\", hue=\\\"species\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"The default distribution statistic is normalized to show a proportion, but you can show absolute counts instead:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.ecdfplot(data=penguins, x=\\\"bill_length_mm\\\", hue=\\\"species\\\", stat=\\\"count\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to plot the empirical complementary CDF (1 - CDF):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.ecdfplot(data=penguins, x=\\\"bill_length_mm\\\", hue=\\\"species\\\", complementary=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":681,"name":"doc/whatsnew","nodeType":"Package"},{"id":682,"name":"v0.2.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.2.0 (December 2013)\n----------------------\n\nThis is a major release from 0.1 with a number of API changes, enhancements,\nand bug fixes.\n\nHighlights include an overhaul of timeseries plotting to work intelligently\nwith dataframes, the new function ``interactplot()`` for visualizing continuous\ninteractions, bivariate kernel density estimates in ``kdeplot()``, and\nsignificant improvements to color palette handling.\n\nVersion 0.2 also introduces experimental support for Python 3.\n\nIn addition to the library enhancements, the documentation has been\nsubstantially rewritten to reflect the new features and improve the\npresentation of the ideas behind the package.\n\nAPI changes\n~~~~~~~~~~~\n\n- The ``tsplot()`` function was rewritten to accept data in a long-form\n ``DataFrame`` and to plot different traces by condition. This introduced a\n relatively minor but unavoidable API change, where instead of doing\n ``sns.tsplot(time, heights)``, you now must do ``sns.tsplot(heights,\n time=time)`` (the ``time`` parameter is now optional, for quicker\n specification of simple plots). Additionally, the ``\"obs_traces\"`` and\n ``\"obs_points\"`` error styles in ``tsplot()`` have been renamed to\n ``\"unit_traces\"`` and ``\"unit_points\"``, respectively.\n\n- Functions that fit kernel density estimates (``kdeplot()`` and\n ``violinplot()``) now use ``statsmodels`` instead of ``scipy``, and the\n parameters that influence the density estimate have changed accordingly. This\n allows for increased flexibility in specifying the bandwidth and kernel, and\n smarter choices for defining the range of the support. Default options should\n produce plots that are very close to the old defaults.\n\n- The ``kdeplot()`` function now takes a second positional argument of data for\n drawing bivariate densities.\n\n- The ``violin()`` function has been changed to ``violinplot()``, for consistency.\n In 0.2, ``violin`` will still work, but it will fire a ``UserWarning``.\n\nNew plotting functions\n~~~~~~~~~~~~~~~~~~~~~~\n\n- The ``interactplot()`` function draws a contour plot for an interactive\n linear model (i.e., the contour shows ``y-hat`` from the model ``y ~ x1 *\n x2``) over a scatterplot between the two predictor variables. This plot\n should aid the understanding of an interaction between two continuous\n variables.\n\n- The ``kdeplot()`` function can now draw a bivariate density estimate as a\n contour plot if provided with two-dimensional input data.\n\n- The ``palplot()`` function provides a simple grid-based visualization of a\n color palette.\n\nOther changes\n~~~~~~~~~~~~~\n\nPlotting functions\n^^^^^^^^^^^^^^^^^^\n\n- The ``corrplot()`` function can be drawn without the correlation coefficient\n annotation and with variable names on the side of the plot to work with large\n datasets.\n\n- Additionally, ``corrplot()`` sets the color palette intelligently based on\n the direction of the specified test.\n\n- The ``distplot()`` histogram uses a reference rule to choose the bin size if it\n is not provided.\n\n- Added the ``x_bins`` option in ``lmplot()`` for binning a continuous\n predictor variable, allowing for clearer trends with many datapoints.\n\n- Enhanced support for labeling plot elements and axes based on ``name``\n attributes in several distribution plot functions and ``tsplot()`` for\n smarter Pandas integration.\n\n- Scatter points in ``lmplot()`` are slightly transparent so it is easy to see\n where observations overlap.\n\n- Added the ``order`` parameter to ``boxplot()`` and ``violinplot()`` to\n control the order of the bins when using a Pandas object.\n\n- When an ``ax`` argument is not provided to a plotting function, it grabs the\n currently active axis instead of drawing a new one.\n\nColor palettes\n^^^^^^^^^^^^^^\n\n- Added the ``dark_palette()`` and ``blend_palette()`` for on-the-fly creation\n of blended color palettes.\n\n- The color palette machinery is now intelligent about qualitative ColorBrewer\n palettes (``Set1``, ``Paired``, etc.), which are properly treated as discrete.\n\n- Seaborn color palettes (``deep``, ``muted``, etc.) have been standardized in\n terms of basic hue sequence, and all palettes now have 6 colors.\n\n- Introduced ``{mpl_palette}_d`` palettes, which make a palette with the basic\n color scheme of the source palette, but with a sequential blend from dark\n instead of light colors for use with line/scatter/contour plots.\n\n- Added the ``palette_context()`` function for blockwise color palettes\n controlled by a ``with`` statement.\n\nPlot styling\n^^^^^^^^^^^^\n\n- Added the ``despine()`` function for easily removing plot spines.\n\n- A new plot style, ``\"ticks\"`` has been added.\n\n- Tick labels are padded a bit farther from the axis in all styles, avoiding\n collisions at (0, 0).\n\nGeneral package issues\n^^^^^^^^^^^^^^^^^^^^^^\n\n- Reorganized the package by breaking up the monolithic ``plotobjs`` module\n into smaller modules grouped by general objective of the constituent plots.\n\n- Removed the ``scikits-learn`` dependency in ``moss``.\n\n- Installing with ``pip`` should automatically install most missing dependencies.\n\n- The example notebooks are now used as an automated test suite.\n\nBug fixes\n~~~~~~~~~\n\n- Fixed a bug where labels did not match data for ``boxplot()`` and ``violinplot()``\n when using a groupby.\n\n- Fixed a bug in the ``desaturate()`` function.\n\n- Fixed a bug in the ``coefplot()`` figure size calculation.\n\n- Fixed a bug where ``regplot()`` choked on list input.\n\n- Fixed buggy behavior when drawing horizontal boxplots.\n\n- Specifying bins for the ``distplot()`` histogram now works.\n\n- Fixed a bug where ``kdeplot()`` would reset the axis height and cut off\n existing data.\n\n- All axis styling has been moved out of the top-level ``seaborn.set()``\n function, so context or color palette can be cleanly changed.\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":82,"id":683,"name":"cumulative","nodeType":"Attribute","startLoc":82,"text":"self.cumulative"},{"attributeType":"null","col":8,"comment":"null","endLoc":87,"id":684,"name":"support","nodeType":"Attribute","startLoc":87,"text":"self.support"},{"attributeType":"null","col":8,"comment":"null","endLoc":78,"id":685,"name":"bw_adjust","nodeType":"Attribute","startLoc":78,"text":"self.bw_adjust"},{"attributeType":"null","col":8,"comment":"null","endLoc":81,"id":686,"name":"clip","nodeType":"Attribute","startLoc":81,"text":"self.clip"},{"attributeType":"null","col":8,"comment":"null","endLoc":77,"id":688,"name":"bw_method","nodeType":"Attribute","startLoc":77,"text":"self.bw_method"},{"className":"Histogram","col":0,"comment":"Univariate and bivariate histogram estimator.","endLoc":398,"id":689,"nodeType":"Class","startLoc":199,"text":"class Histogram:\n \"\"\"Univariate and bivariate histogram estimator.\"\"\"\n def __init__(\n self,\n stat=\"count\",\n bins=\"auto\",\n binwidth=None,\n binrange=None,\n discrete=False,\n cumulative=False,\n ):\n \"\"\"Initialize the estimator with its parameters.\n\n Parameters\n ----------\n stat : str\n Aggregate statistic to compute in each bin.\n\n - `count`: show the number of observations in each bin\n - `frequency`: show the number of observations divided by the bin width\n - `probability` or `proportion`: normalize such that bar heights sum to 1\n - `percent`: normalize such that bar heights sum to 100\n - `density`: normalize such that the total area of the histogram equals 1\n\n bins : str, number, vector, or a pair of such values\n Generic bin parameter that can be the name of a reference rule,\n the number of bins, or the breaks of the bins.\n Passed to :func:`numpy.histogram_bin_edges`.\n binwidth : number or pair of numbers\n Width of each bin, overrides ``bins`` but can be used with\n ``binrange``.\n binrange : pair of numbers or a pair of pairs\n Lowest and highest value for bin edges; can be used either\n with ``bins`` or ``binwidth``. Defaults to data extremes.\n discrete : bool or pair of bools\n If True, set ``binwidth`` and ``binrange`` such that bin\n edges cover integer values in the dataset.\n cumulative : bool\n If True, return the cumulative statistic.\n\n \"\"\"\n stat_choices = [\n \"count\", \"frequency\", \"density\", \"probability\", \"proportion\", \"percent\",\n ]\n _check_argument(\"stat\", stat_choices, stat)\n\n self.stat = stat\n self.bins = bins\n self.binwidth = binwidth\n self.binrange = binrange\n self.discrete = discrete\n self.cumulative = cumulative\n\n self.bin_kws = None\n\n def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete):\n \"\"\"Inner function that takes bin parameters as arguments.\"\"\"\n if binrange is None:\n start, stop = x.min(), x.max()\n else:\n start, stop = binrange\n\n if discrete:\n bin_edges = np.arange(start - .5, stop + 1.5)\n elif binwidth is not None:\n step = binwidth\n bin_edges = np.arange(start, stop + step, step)\n # Handle roundoff error (maybe there is a less clumsy way?)\n if bin_edges.max() < stop or len(bin_edges) < 2:\n bin_edges = np.append(bin_edges, bin_edges.max() + step)\n else:\n bin_edges = np.histogram_bin_edges(\n x, bins, binrange, weights,\n )\n return bin_edges\n\n def define_bin_params(self, x1, x2=None, weights=None, cache=True):\n \"\"\"Given data, return numpy.histogram parameters to define bins.\"\"\"\n if x2 is None:\n\n bin_edges = self._define_bin_edges(\n x1, weights, self.bins, self.binwidth, self.binrange, self.discrete,\n )\n\n if isinstance(self.bins, (str, Number)):\n n_bins = len(bin_edges) - 1\n bin_range = bin_edges.min(), bin_edges.max()\n bin_kws = dict(bins=n_bins, range=bin_range)\n else:\n bin_kws = dict(bins=bin_edges)\n\n else:\n\n bin_edges = []\n for i, x in enumerate([x1, x2]):\n\n # Resolve out whether bin parameters are shared\n # or specific to each variable\n\n bins = self.bins\n if not bins or isinstance(bins, (str, Number)):\n pass\n elif isinstance(bins[i], str):\n bins = bins[i]\n elif len(bins) == 2:\n bins = bins[i]\n\n binwidth = self.binwidth\n if binwidth is None:\n pass\n elif not isinstance(binwidth, Number):\n binwidth = binwidth[i]\n\n binrange = self.binrange\n if binrange is None:\n pass\n elif not isinstance(binrange[0], Number):\n binrange = binrange[i]\n\n discrete = self.discrete\n if not isinstance(discrete, bool):\n discrete = discrete[i]\n\n # Define the bins for this variable\n\n bin_edges.append(self._define_bin_edges(\n x, weights, bins, binwidth, binrange, discrete,\n ))\n\n bin_kws = dict(bins=tuple(bin_edges))\n\n if cache:\n self.bin_kws = bin_kws\n\n return bin_kws\n\n def _eval_bivariate(self, x1, x2, weights):\n \"\"\"Inner function for histogram of two variables.\"\"\"\n bin_kws = self.bin_kws\n if bin_kws is None:\n bin_kws = self.define_bin_params(x1, x2, cache=False)\n\n density = self.stat == \"density\"\n\n hist, *bin_edges = np.histogram2d(\n x1, x2, **bin_kws, weights=weights, density=density\n )\n\n area = np.outer(\n np.diff(bin_edges[0]),\n np.diff(bin_edges[1]),\n )\n\n if self.stat == \"probability\" or self.stat == \"proportion\":\n hist = hist.astype(float) / hist.sum()\n elif self.stat == \"percent\":\n hist = hist.astype(float) / hist.sum() * 100\n elif self.stat == \"frequency\":\n hist = hist.astype(float) / area\n\n if self.cumulative:\n if self.stat in [\"density\", \"frequency\"]:\n hist = (hist * area).cumsum(axis=0).cumsum(axis=1)\n else:\n hist = hist.cumsum(axis=0).cumsum(axis=1)\n\n return hist, bin_edges\n\n def _eval_univariate(self, x, weights):\n \"\"\"Inner function for histogram of one variable.\"\"\"\n bin_kws = self.bin_kws\n if bin_kws is None:\n bin_kws = self.define_bin_params(x, weights=weights, cache=False)\n\n density = self.stat == \"density\"\n hist, bin_edges = np.histogram(\n x, **bin_kws, weights=weights, density=density,\n )\n\n if self.stat == \"probability\" or self.stat == \"proportion\":\n hist = hist.astype(float) / hist.sum()\n elif self.stat == \"percent\":\n hist = hist.astype(float) / hist.sum() * 100\n elif self.stat == \"frequency\":\n hist = hist.astype(float) / np.diff(bin_edges)\n\n if self.cumulative:\n if self.stat in [\"density\", \"frequency\"]:\n hist = (hist * np.diff(bin_edges)).cumsum()\n else:\n hist = hist.cumsum()\n\n return hist, bin_edges\n\n def __call__(self, x1, x2=None, weights=None):\n \"\"\"Count the occurrences in each bin, maybe normalize.\"\"\"\n if x2 is None:\n return self._eval_univariate(x1, weights)\n else:\n return self._eval_bivariate(x1, x2, weights)"},{"col":4,"comment":"Initialize the estimator with its parameters.\n\n Parameters\n ----------\n stat : str\n Aggregate statistic to compute in each bin.\n\n - `count`: show the number of observations in each bin\n - `frequency`: show the number of observations divided by the bin width\n - `probability` or `proportion`: normalize such that bar heights sum to 1\n - `percent`: normalize such that bar heights sum to 100\n - `density`: normalize such that the total area of the histogram equals 1\n\n bins : str, number, vector, or a pair of such values\n Generic bin parameter that can be the name of a reference rule,\n the number of bins, or the breaks of the bins.\n Passed to :func:`numpy.histogram_bin_edges`.\n binwidth : number or pair of numbers\n Width of each bin, overrides ``bins`` but can be used with\n ``binrange``.\n binrange : pair of numbers or a pair of pairs\n Lowest and highest value for bin edges; can be used either\n with ``bins`` or ``binwidth``. Defaults to data extremes.\n discrete : bool or pair of bools\n If True, set ``binwidth`` and ``binrange`` such that bin\n edges cover integer values in the dataset.\n cumulative : bool\n If True, return the cumulative statistic.\n\n ","endLoc":252,"header":"def __init__(\n self,\n stat=\"count\",\n bins=\"auto\",\n binwidth=None,\n binrange=None,\n discrete=False,\n cumulative=False,\n )","id":690,"name":"__init__","nodeType":"Function","startLoc":201,"text":"def __init__(\n self,\n stat=\"count\",\n bins=\"auto\",\n binwidth=None,\n binrange=None,\n discrete=False,\n cumulative=False,\n ):\n \"\"\"Initialize the estimator with its parameters.\n\n Parameters\n ----------\n stat : str\n Aggregate statistic to compute in each bin.\n\n - `count`: show the number of observations in each bin\n - `frequency`: show the number of observations divided by the bin width\n - `probability` or `proportion`: normalize such that bar heights sum to 1\n - `percent`: normalize such that bar heights sum to 100\n - `density`: normalize such that the total area of the histogram equals 1\n\n bins : str, number, vector, or a pair of such values\n Generic bin parameter that can be the name of a reference rule,\n the number of bins, or the breaks of the bins.\n Passed to :func:`numpy.histogram_bin_edges`.\n binwidth : number or pair of numbers\n Width of each bin, overrides ``bins`` but can be used with\n ``binrange``.\n binrange : pair of numbers or a pair of pairs\n Lowest and highest value for bin edges; can be used either\n with ``bins`` or ``binwidth``. Defaults to data extremes.\n discrete : bool or pair of bools\n If True, set ``binwidth`` and ``binrange`` such that bin\n edges cover integer values in the dataset.\n cumulative : bool\n If True, return the cumulative statistic.\n\n \"\"\"\n stat_choices = [\n \"count\", \"frequency\", \"density\", \"probability\", \"proportion\", \"percent\",\n ]\n _check_argument(\"stat\", stat_choices, stat)\n\n self.stat = stat\n self.bins = bins\n self.binwidth = binwidth\n self.binrange = binrange\n self.discrete = discrete\n self.cumulative = cumulative\n\n self.bin_kws = None"},{"col":4,"comment":"Inner function that takes bin parameters as arguments.","endLoc":273,"header":"def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete)","id":691,"name":"_define_bin_edges","nodeType":"Function","startLoc":254,"text":"def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete):\n \"\"\"Inner function that takes bin parameters as arguments.\"\"\"\n if binrange is None:\n start, stop = x.min(), x.max()\n else:\n start, stop = binrange\n\n if discrete:\n bin_edges = np.arange(start - .5, stop + 1.5)\n elif binwidth is not None:\n step = binwidth\n bin_edges = np.arange(start, stop + step, step)\n # Handle roundoff error (maybe there is a less clumsy way?)\n if bin_edges.max() < stop or len(bin_edges) < 2:\n bin_edges = np.append(bin_edges, bin_edges.max() + step)\n else:\n bin_edges = np.histogram_bin_edges(\n x, bins, binrange, weights,\n )\n return bin_edges"},{"col":4,"comment":"Given data, return numpy.histogram parameters to define bins.","endLoc":333,"header":"def define_bin_params(self, x1, x2=None, weights=None, cache=True)","id":692,"name":"define_bin_params","nodeType":"Function","startLoc":275,"text":"def define_bin_params(self, x1, x2=None, weights=None, cache=True):\n \"\"\"Given data, return numpy.histogram parameters to define bins.\"\"\"\n if x2 is None:\n\n bin_edges = self._define_bin_edges(\n x1, weights, self.bins, self.binwidth, self.binrange, self.discrete,\n )\n\n if isinstance(self.bins, (str, Number)):\n n_bins = len(bin_edges) - 1\n bin_range = bin_edges.min(), bin_edges.max()\n bin_kws = dict(bins=n_bins, range=bin_range)\n else:\n bin_kws = dict(bins=bin_edges)\n\n else:\n\n bin_edges = []\n for i, x in enumerate([x1, x2]):\n\n # Resolve out whether bin parameters are shared\n # or specific to each variable\n\n bins = self.bins\n if not bins or isinstance(bins, (str, Number)):\n pass\n elif isinstance(bins[i], str):\n bins = bins[i]\n elif len(bins) == 2:\n bins = bins[i]\n\n binwidth = self.binwidth\n if binwidth is None:\n pass\n elif not isinstance(binwidth, Number):\n binwidth = binwidth[i]\n\n binrange = self.binrange\n if binrange is None:\n pass\n elif not isinstance(binrange[0], Number):\n binrange = binrange[i]\n\n discrete = self.discrete\n if not isinstance(discrete, bool):\n discrete = discrete[i]\n\n # Define the bins for this variable\n\n bin_edges.append(self._define_bin_edges(\n x, weights, bins, binwidth, binrange, discrete,\n ))\n\n bin_kws = dict(bins=tuple(bin_edges))\n\n if cache:\n self.bin_kws = bin_kws\n\n return bin_kws"},{"id":693,"name":"logo-wide-lightbg.svg","nodeType":"TextFile","path":"doc/_static","text":"\n\n\n\n \n \n \n \n 2020-09-07T14:13:58.676334\n image/svg+xml\n \n \n Matplotlib v3.3.1, https://matplotlib.org/\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"col":4,"comment":"Return ticks and labels at evenly spaced intervals.","endLoc":276,"header":"def _skip_ticks(self, labels, tickevery)","id":694,"name":"_skip_ticks","nodeType":"Function","startLoc":265,"text":"def _skip_ticks(self, labels, tickevery):\n \"\"\"Return ticks and labels at evenly spaced intervals.\"\"\"\n n = len(labels)\n if tickevery == 0:\n ticks, labels = [], []\n elif tickevery == 1:\n ticks, labels = np.arange(n) + .5, labels\n else:\n start, end, step = 0, n, tickevery\n ticks = np.arange(start, end, step) + .5\n labels = labels[start:end:step]\n return ticks, labels"},{"col":0,"comment":"Convert a pandas index or multiindex to an axis label.","endLoc":36,"header":"def _index_to_label(index)","id":695,"name":"_index_to_label","nodeType":"Function","startLoc":31,"text":"def _index_to_label(index):\n \"\"\"Convert a pandas index or multiindex to an axis label.\"\"\"\n if isinstance(index, pd.MultiIndex):\n return \"-\".join(map(to_utf8, index.names))\n else:\n return index.name"},{"fileName":"_compat.py","filePath":"seaborn","id":696,"nodeType":"File","text":"import numpy as np\nimport matplotlib as mpl\nfrom seaborn.external.version import Version\n\n\ndef MarkerStyle(marker=None, fillstyle=None):\n \"\"\"\n Allow MarkerStyle to accept a MarkerStyle object as parameter.\n\n Supports matplotlib < 3.3.0\n https://github.com/matplotlib/matplotlib/pull/16692\n\n \"\"\"\n if isinstance(marker, mpl.markers.MarkerStyle):\n if fillstyle is None:\n return marker\n else:\n marker = marker.get_marker()\n return mpl.markers.MarkerStyle(marker, fillstyle)\n\n\ndef norm_from_scale(scale, norm):\n \"\"\"Produce a Normalize object given a Scale and min/max domain limits.\"\"\"\n # This is an internal maplotlib function that simplifies things to access\n # It is likely to become part of the matplotlib API at some point:\n # https://github.com/matplotlib/matplotlib/issues/20329\n if isinstance(norm, mpl.colors.Normalize):\n return norm\n\n if scale is None:\n return None\n\n if norm is None:\n vmin = vmax = None\n else:\n vmin, vmax = norm # TODO more helpful error if this fails?\n\n class ScaledNorm(mpl.colors.Normalize):\n\n def __call__(self, value, clip=None):\n # From github.com/matplotlib/matplotlib/blob/v3.4.2/lib/matplotlib/colors.py\n # See github.com/matplotlib/matplotlib/tree/v3.4.2/LICENSE\n value, is_scalar = self.process_value(value)\n self.autoscale_None(value)\n if self.vmin > self.vmax:\n raise ValueError(\"vmin must be less or equal to vmax\")\n if self.vmin == self.vmax:\n return np.full_like(value, 0)\n if clip is None:\n clip = self.clip\n if clip:\n value = np.clip(value, self.vmin, self.vmax)\n # ***** Seaborn changes start ****\n t_value = self.transform(value).reshape(np.shape(value))\n t_vmin, t_vmax = self.transform([self.vmin, self.vmax])\n # ***** Seaborn changes end *****\n if not np.isfinite([t_vmin, t_vmax]).all():\n raise ValueError(\"Invalid vmin or vmax\")\n t_value -= t_vmin\n t_value /= (t_vmax - t_vmin)\n t_value = np.ma.masked_invalid(t_value, copy=False)\n return t_value[0] if is_scalar else t_value\n\n new_norm = ScaledNorm(vmin, vmax)\n new_norm.transform = scale.get_transform().transform\n\n return new_norm\n\n\ndef scale_factory(scale, axis, **kwargs):\n \"\"\"\n Backwards compatability for creation of independent scales.\n\n Matplotlib scales require an Axis object for instantiation on < 3.4.\n But the axis is not used, aside from extraction of the axis_name in LogScale.\n\n \"\"\"\n modify_transform = False\n if Version(mpl.__version__) < Version(\"3.4\"):\n if axis[0] in \"xy\":\n modify_transform = True\n axis = axis[0]\n base = kwargs.pop(\"base\", None)\n if base is not None:\n kwargs[f\"base{axis}\"] = base\n nonpos = kwargs.pop(\"nonpositive\", None)\n if nonpos is not None:\n kwargs[f\"nonpos{axis}\"] = nonpos\n\n if isinstance(scale, str):\n class Axis:\n axis_name = axis\n axis = Axis()\n\n scale = mpl.scale.scale_factory(scale, axis, **kwargs)\n\n if modify_transform:\n transform = scale.get_transform()\n transform.base = kwargs.get(\"base\", 10)\n if kwargs.get(\"nonpositive\") == \"mask\":\n # Setting a private attribute, but we only get here\n # on an old matplotlib, so this won't break going forwards\n transform._clip = False\n\n return scale\n\n\ndef set_scale_obj(ax, axis, scale):\n \"\"\"Handle backwards compatability with setting matplotlib scale.\"\"\"\n if Version(mpl.__version__) < Version(\"3.4\"):\n # The ability to pass a BaseScale instance to Axes.set_{}scale was added\n # to matplotlib in version 3.4.0: GH: matplotlib/matplotlib/pull/19089\n # Workaround: use the scale name, which is restrictive only if the user\n # wants to define a custom scale; they'll need to update the registry too.\n if scale.name is None:\n # Hack to support our custom Formatter-less CatScale\n return\n method = getattr(ax, f\"set_{axis}scale\")\n kws = {}\n if scale.name == \"function\":\n trans = scale.get_transform()\n kws[\"functions\"] = (trans._forward, trans._inverse)\n method(scale.name, **kws)\n axis_obj = getattr(ax, f\"{axis}axis\")\n scale.set_default_locators_and_formatters(axis_obj)\n else:\n ax.set(**{f\"{axis}scale\": scale})\n\n\ndef get_colormap(name):\n \"\"\"Handle changes to matplotlib colormap interface in 3.6.\"\"\"\n try:\n return mpl.colormaps[name]\n except AttributeError:\n return mpl.cm.get_cmap(name)\n\n\ndef register_colormap(name, cmap):\n \"\"\"Handle changes to matplotlib colormap interface in 3.6.\"\"\"\n try:\n if name not in mpl.colormaps:\n mpl.colormaps.register(cmap, name=name)\n except AttributeError:\n mpl.cm.register_cmap(name, cmap)\n\n\ndef set_layout_engine(fig, engine):\n \"\"\"Handle changes to auto layout engine interface in 3.6\"\"\"\n if hasattr(fig, \"set_layout_engine\"):\n fig.set_layout_engine(engine)\n else:\n if engine == \"tight\":\n fig.set_tight_layout(True)\n elif engine == \"constrained\":\n fig.set_constrained_layout(True)\n\n\ndef share_axis(ax0, ax1, which):\n \"\"\"Handle changes to post-hoc axis sharing.\"\"\"\n if Version(mpl.__version__) < Version(\"3.5.0\"):\n group = getattr(ax0, f\"get_shared_{which}_axes\")()\n group.join(ax1, ax0)\n else:\n getattr(ax1, f\"share{which}\")(ax0)\n"},{"col":0,"comment":"\n Allow MarkerStyle to accept a MarkerStyle object as parameter.\n\n Supports matplotlib < 3.3.0\n https://github.com/matplotlib/matplotlib/pull/16692\n\n ","endLoc":19,"header":"def MarkerStyle(marker=None, fillstyle=None)","id":697,"name":"MarkerStyle","nodeType":"Function","startLoc":6,"text":"def MarkerStyle(marker=None, fillstyle=None):\n \"\"\"\n Allow MarkerStyle to accept a MarkerStyle object as parameter.\n\n Supports matplotlib < 3.3.0\n https://github.com/matplotlib/matplotlib/pull/16692\n\n \"\"\"\n if isinstance(marker, mpl.markers.MarkerStyle):\n if fillstyle is None:\n return marker\n else:\n marker = marker.get_marker()\n return mpl.markers.MarkerStyle(marker, fillstyle)"},{"attributeType":"null","col":4,"comment":"null","endLoc":51,"id":699,"name":"legend","nodeType":"Attribute","startLoc":51,"text":"legend"},{"attributeType":"null","col":4,"comment":"null","endLoc":54,"id":700,"name":"normed","nodeType":"Attribute","startLoc":54,"text":"normed"},{"attributeType":"str | None","col":8,"comment":"null","endLoc":60,"id":702,"name":"variable","nodeType":"Attribute","startLoc":60,"text":"self.variable"},{"col":0,"comment":"Produce a Normalize object given a Scale and min/max domain limits.","endLoc":67,"header":"def norm_from_scale(scale, norm)","id":703,"name":"norm_from_scale","nodeType":"Function","startLoc":22,"text":"def norm_from_scale(scale, norm):\n \"\"\"Produce a Normalize object given a Scale and min/max domain limits.\"\"\"\n # This is an internal maplotlib function that simplifies things to access\n # It is likely to become part of the matplotlib API at some point:\n # https://github.com/matplotlib/matplotlib/issues/20329\n if isinstance(norm, mpl.colors.Normalize):\n return norm\n\n if scale is None:\n return None\n\n if norm is None:\n vmin = vmax = None\n else:\n vmin, vmax = norm # TODO more helpful error if this fails?\n\n class ScaledNorm(mpl.colors.Normalize):\n\n def __call__(self, value, clip=None):\n # From github.com/matplotlib/matplotlib/blob/v3.4.2/lib/matplotlib/colors.py\n # See github.com/matplotlib/matplotlib/tree/v3.4.2/LICENSE\n value, is_scalar = self.process_value(value)\n self.autoscale_None(value)\n if self.vmin > self.vmax:\n raise ValueError(\"vmin must be less or equal to vmax\")\n if self.vmin == self.vmax:\n return np.full_like(value, 0)\n if clip is None:\n clip = self.clip\n if clip:\n value = np.clip(value, self.vmin, self.vmax)\n # ***** Seaborn changes start ****\n t_value = self.transform(value).reshape(np.shape(value))\n t_vmin, t_vmax = self.transform([self.vmin, self.vmax])\n # ***** Seaborn changes end *****\n if not np.isfinite([t_vmin, t_vmax]).all():\n raise ValueError(\"Invalid vmin or vmax\")\n t_value -= t_vmin\n t_value /= (t_vmax - t_vmin)\n t_value = np.ma.masked_invalid(t_value, copy=False)\n return t_value[0] if is_scalar else t_value\n\n new_norm = ScaledNorm(vmin, vmax)\n new_norm.transform = scale.get_transform().transform\n\n return new_norm"},{"className":"Nominal","col":0,"comment":"\n A categorical scale without relative importance / magnitude.\n ","endLoc":295,"id":704,"nodeType":"Class","startLoc":137,"text":"@dataclass\nclass Nominal(Scale):\n \"\"\"\n A categorical scale without relative importance / magnitude.\n \"\"\"\n # Categorical (convert to strings), un-sortable\n\n values: tuple | str | list | dict | None = None\n order: list | None = None\n\n _priority: ClassVar[int] = 3\n\n def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n\n new = copy(self)\n if new._tick_params is None:\n new = new.tick()\n if new._label_params is None:\n new = new.label()\n\n # TODO flexibility over format() which isn't great for numbers / dates\n stringify = np.vectorize(format)\n\n units_seed = categorical_order(data, new.order)\n\n # TODO move to Nominal._get_scale?\n # TODO this needs some more complicated rethinking about how to pass\n # a unit dictionary down to these methods, along with how much we want\n # to invest in their API. What is it useful for tick() to do here?\n # (Ordinal may be different if we draw that contrast).\n # Any customization we do to allow, e.g., label wrapping will probably\n # require defining our own Formatter subclass.\n # We could also potentially implement auto-wrapping in an Axis subclass\n # (see Axis.draw ... it already is computing the bboxes).\n # major_locator, minor_locator = new._get_locators(**new._tick_params)\n # major_formatter = new._get_formatter(major_locator, **new._label_params)\n\n class CatScale(mpl.scale.LinearScale):\n name = None # To work around mpl<3.4 compat issues\n\n def set_default_locators_and_formatters(self, axis):\n ...\n # axis.set_major_locator(major_locator)\n # if minor_locator is not None:\n # axis.set_minor_locator(minor_locator)\n # axis.set_major_formatter(major_formatter)\n\n mpl_scale = CatScale(data.name)\n if axis is None:\n axis = PseudoAxis(mpl_scale)\n\n # TODO Currently just used in non-Coordinate contexts, but should\n # we use this to (A) set the padding we want for categorial plots\n # and (B) allow the values parameter for a Coordinate to set xlim/ylim\n axis.set_view_interval(0, len(units_seed) - 1)\n\n new._matplotlib_scale = mpl_scale\n\n # TODO array cast necessary to handle float/int mixture, which we need\n # to solve in a more systematic way probably\n # (i.e. if we have [1, 2.5], do we want [1.0, 2.5]? Unclear)\n axis.update_units(stringify(np.array(units_seed)))\n\n # TODO define this more centrally\n def convert_units(x):\n # TODO only do this with explicit order?\n # (But also category dtype?)\n # TODO isin fails when units_seed mixes numbers and strings (numpy error?)\n # but np.isin also does not seem any faster? (Maybe not broadcasting in C)\n # keep = x.isin(units_seed)\n keep = np.array([x_ in units_seed for x_ in x], bool)\n out = np.full(len(x), np.nan)\n out[keep] = axis.convert_units(stringify(x[keep]))\n return out\n\n new._pipeline = [\n convert_units,\n prop.get_mapping(new, data),\n # TODO how to handle color representation consistency?\n ]\n\n def spacer(x):\n return 1\n\n new._spacer = spacer\n\n if prop.legend:\n new._legend = units_seed, list(stringify(units_seed))\n\n return new\n\n def tick(self, locator: Locator | None = None):\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n\n Returns\n -------\n Copy of self with new tick configuration.\n\n \"\"\"\n new = copy(self)\n new._tick_params = {\n \"locator\": locator,\n }\n return new\n\n def label(self, formatter: Formatter | None = None):\n \"\"\"\n Configure the selection of labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured matplotlib formatter; other parameters will not be used.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n new = copy(self)\n new._label_params = {\n \"formatter\": formatter,\n }\n return new\n\n def _get_locators(self, locator):\n\n if locator is not None:\n return locator, None\n\n locator = mpl.category.StrCategoryLocator({})\n\n return locator, None\n\n def _get_formatter(self, locator, formatter):\n\n if formatter is not None:\n return formatter\n\n formatter = mpl.category.StrCategoryFormatter({})\n\n return formatter"},{"col":4,"comment":"null","endLoc":228,"header":"def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale","id":705,"name":"_setup","nodeType":"Function","startLoc":149,"text":"def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n\n new = copy(self)\n if new._tick_params is None:\n new = new.tick()\n if new._label_params is None:\n new = new.label()\n\n # TODO flexibility over format() which isn't great for numbers / dates\n stringify = np.vectorize(format)\n\n units_seed = categorical_order(data, new.order)\n\n # TODO move to Nominal._get_scale?\n # TODO this needs some more complicated rethinking about how to pass\n # a unit dictionary down to these methods, along with how much we want\n # to invest in their API. What is it useful for tick() to do here?\n # (Ordinal may be different if we draw that contrast).\n # Any customization we do to allow, e.g., label wrapping will probably\n # require defining our own Formatter subclass.\n # We could also potentially implement auto-wrapping in an Axis subclass\n # (see Axis.draw ... it already is computing the bboxes).\n # major_locator, minor_locator = new._get_locators(**new._tick_params)\n # major_formatter = new._get_formatter(major_locator, **new._label_params)\n\n class CatScale(mpl.scale.LinearScale):\n name = None # To work around mpl<3.4 compat issues\n\n def set_default_locators_and_formatters(self, axis):\n ...\n # axis.set_major_locator(major_locator)\n # if minor_locator is not None:\n # axis.set_minor_locator(minor_locator)\n # axis.set_major_formatter(major_formatter)\n\n mpl_scale = CatScale(data.name)\n if axis is None:\n axis = PseudoAxis(mpl_scale)\n\n # TODO Currently just used in non-Coordinate contexts, but should\n # we use this to (A) set the padding we want for categorial plots\n # and (B) allow the values parameter for a Coordinate to set xlim/ylim\n axis.set_view_interval(0, len(units_seed) - 1)\n\n new._matplotlib_scale = mpl_scale\n\n # TODO array cast necessary to handle float/int mixture, which we need\n # to solve in a more systematic way probably\n # (i.e. if we have [1, 2.5], do we want [1.0, 2.5]? Unclear)\n axis.update_units(stringify(np.array(units_seed)))\n\n # TODO define this more centrally\n def convert_units(x):\n # TODO only do this with explicit order?\n # (But also category dtype?)\n # TODO isin fails when units_seed mixes numbers and strings (numpy error?)\n # but np.isin also does not seem any faster? (Maybe not broadcasting in C)\n # keep = x.isin(units_seed)\n keep = np.array([x_ in units_seed for x_ in x], bool)\n out = np.full(len(x), np.nan)\n out[keep] = axis.convert_units(stringify(x[keep]))\n return out\n\n new._pipeline = [\n convert_units,\n prop.get_mapping(new, data),\n # TODO how to handle color representation consistency?\n ]\n\n def spacer(x):\n return 1\n\n new._spacer = spacer\n\n if prop.legend:\n new._legend = units_seed, list(stringify(units_seed))\n\n return new"},{"col":4,"comment":"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n\n Returns\n -------\n Copy of self with new tick configuration.\n\n ","endLoc":252,"header":"def tick(self, locator: Locator | None = None)","id":706,"name":"tick","nodeType":"Function","startLoc":230,"text":"def tick(self, locator: Locator | None = None):\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n\n Returns\n -------\n Copy of self with new tick configuration.\n\n \"\"\"\n new = copy(self)\n new._tick_params = {\n \"locator\": locator,\n }\n return new"},{"col":4,"comment":"\n Configure the selection of labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured matplotlib formatter; other parameters will not be used.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n ","endLoc":277,"header":"def label(self, formatter: Formatter | None = None)","id":707,"name":"label","nodeType":"Function","startLoc":254,"text":"def label(self, formatter: Formatter | None = None):\n \"\"\"\n Configure the selection of labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n At the moment, it is probably not very useful.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured matplotlib formatter; other parameters will not be used.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n new = copy(self)\n new._label_params = {\n \"formatter\": formatter,\n }\n return new"},{"attributeType":"None","col":4,"comment":"null","endLoc":35,"id":708,"name":"map_type","nodeType":"Attribute","startLoc":35,"text":"map_type"},{"attributeType":"None","col":4,"comment":"null","endLoc":38,"id":709,"name":"levels","nodeType":"Attribute","startLoc":38,"text":"levels"},{"attributeType":"None","col":4,"comment":"null","endLoc":41,"id":710,"name":"lookup_table","nodeType":"Attribute","startLoc":41,"text":"lookup_table"},{"attributeType":"null","col":8,"comment":"null","endLoc":50,"id":711,"name":"plotter","nodeType":"Attribute","startLoc":50,"text":"self.plotter"},{"col":4,"comment":"null","endLoc":196,"header":"@overload\n def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]","id":712,"name":"__new__","nodeType":"Function","startLoc":195,"text":"@overload\n def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ..."},{"col":4,"comment":"null","endLoc":198,"header":"@overload\n def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]","id":713,"name":"__new__","nodeType":"Function","startLoc":197,"text":"@overload\n def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]: ..."},{"col":4,"comment":"null","endLoc":200,"header":"@overload\n def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]","id":714,"name":"__new__","nodeType":"Function","startLoc":199,"text":"@overload\n def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]: ..."},{"col":4,"comment":"null","endLoc":204,"header":"@overload\n def __new__(\n cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /\n ) -> product[tuple[_T1, _T2, _T3, _T4]]","id":715,"name":"__new__","nodeType":"Function","startLoc":201,"text":"@overload\n def __new__(\n cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /\n ) -> product[tuple[_T1, _T2, _T3, _T4]]: ..."},{"col":4,"comment":"null","endLoc":208,"header":"@overload\n def __new__(\n cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], /\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]","id":716,"name":"__new__","nodeType":"Function","startLoc":205,"text":"@overload\n def __new__(\n cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], /\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]: ..."},{"col":4,"comment":"null","endLoc":219,"header":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]","id":717,"name":"__new__","nodeType":"Function","startLoc":209,"text":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ..."},{"col":4,"comment":"null","endLoc":231,"header":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7]]","id":718,"name":"__new__","nodeType":"Function","startLoc":220,"text":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ..."},{"col":4,"comment":"null","endLoc":244,"header":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]","id":719,"name":"__new__","nodeType":"Function","startLoc":232,"text":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]: ..."},{"col":4,"comment":"null","endLoc":258,"header":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n iter9: Iterable[_T9],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]","id":720,"name":"__new__","nodeType":"Function","startLoc":245,"text":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n iter9: Iterable[_T9],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]: ..."},{"className":"HueMapping","col":0,"comment":"Mapping that sets artist colors according to data values.","endLoc":288,"id":721,"nodeType":"Class","startLoc":94,"text":"@share_init_params_with_map\nclass HueMapping(SemanticMapping):\n \"\"\"Mapping that sets artist colors according to data values.\"\"\"\n # A specification of the colors that should appear in the plot\n palette = None\n\n # An object that normalizes data values to [0, 1] range for color mapping\n norm = None\n\n # A continuous colormap object for interpolating in a numeric context\n cmap = None\n\n def __init__(\n self, plotter, palette=None, order=None, norm=None,\n ):\n \"\"\"Map the levels of the `hue` variable to distinct colors.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"hue\", pd.Series(dtype=float))\n\n if data.isna().all():\n if palette is not None:\n msg = \"Ignoring `palette` because no `hue` variable has been assigned.\"\n warnings.warn(msg, stacklevel=4)\n else:\n\n map_type = self.infer_map_type(\n palette, norm, plotter.input_format, plotter.var_types[\"hue\"]\n )\n\n # Our goal is to end up with a dictionary mapping every unique\n # value in `data` to a color. We will also keep track of the\n # metadata about this mapping we will need for, e.g., a legend\n\n # --- Option 1: numeric mapping with a matplotlib colormap\n\n if map_type == \"numeric\":\n\n data = pd.to_numeric(data)\n levels, lookup_table, norm, cmap = self.numeric_mapping(\n data, palette, norm,\n )\n\n # --- Option 2: categorical mapping using seaborn palette\n\n elif map_type == \"categorical\":\n\n cmap = norm = None\n levels, lookup_table = self.categorical_mapping(\n data, palette, order,\n )\n\n # --- Option 3: datetime mapping\n\n else:\n # TODO this needs actual implementation\n cmap = norm = None\n levels, lookup_table = self.categorical_mapping(\n # Casting data to list to handle differences in the way\n # pandas and numpy represent datetime64 data\n list(data), palette, order,\n )\n\n self.map_type = map_type\n self.lookup_table = lookup_table\n self.palette = palette\n self.levels = levels\n self.norm = norm\n self.cmap = cmap\n\n def _lookup_single(self, key):\n \"\"\"Get the color for a single value, using colormap to interpolate.\"\"\"\n try:\n # Use a value that's in the original data vector\n value = self.lookup_table[key]\n except KeyError:\n\n if self.norm is None:\n # Currently we only get here in scatterplot with hue_order,\n # because scatterplot does not consider hue a grouping variable\n # So unused hue levels are in the data, but not the lookup table\n return (0, 0, 0, 0)\n\n # Use the colormap to interpolate between existing datapoints\n # (e.g. in the context of making a continuous legend)\n try:\n normed = self.norm(key)\n except TypeError as err:\n if np.isnan(key):\n value = (0, 0, 0, 0)\n else:\n raise err\n else:\n if np.ma.is_masked(normed):\n normed = np.nan\n value = self.cmap(normed)\n return value\n\n def infer_map_type(self, palette, norm, input_format, var_type):\n \"\"\"Determine how to implement the mapping.\"\"\"\n if palette in QUAL_PALETTES:\n map_type = \"categorical\"\n elif norm is not None:\n map_type = \"numeric\"\n elif isinstance(palette, (dict, list)):\n map_type = \"categorical\"\n elif input_format == \"wide\":\n map_type = \"categorical\"\n else:\n map_type = var_type\n\n return map_type\n\n def categorical_mapping(self, data, palette, order):\n \"\"\"Determine colors when the hue mapping is categorical.\"\"\"\n # -- Identify the order and name of the levels\n\n levels = categorical_order(data, order)\n n_colors = len(levels)\n\n # -- Identify the set of colors to use\n\n if isinstance(palette, dict):\n\n missing = set(levels) - set(palette)\n if any(missing):\n err = \"The palette dictionary is missing keys: {}\"\n raise ValueError(err.format(missing))\n\n lookup_table = palette\n\n else:\n\n if palette is None:\n if n_colors <= len(get_color_cycle()):\n colors = color_palette(None, n_colors)\n else:\n colors = color_palette(\"husl\", n_colors)\n elif isinstance(palette, list):\n colors = self._check_list_length(levels, palette, \"palette\")\n else:\n colors = color_palette(palette, n_colors)\n\n lookup_table = dict(zip(levels, colors))\n\n return levels, lookup_table\n\n def numeric_mapping(self, data, palette, norm):\n \"\"\"Determine colors when the hue variable is quantitative.\"\"\"\n if isinstance(palette, dict):\n\n # The presence of a norm object overrides a dictionary of hues\n # in specifying a numeric mapping, so we need to process it here.\n levels = list(sorted(palette))\n colors = [palette[k] for k in sorted(palette)]\n cmap = mpl.colors.ListedColormap(colors)\n lookup_table = palette.copy()\n\n else:\n\n # The levels are the sorted unique values in the data\n levels = list(np.sort(remove_na(data.unique())))\n\n # --- Sort out the colormap to use from the palette argument\n\n # Default numeric palette is our default cubehelix palette\n # TODO do we want to do something complicated to ensure contrast?\n palette = \"ch:\" if palette is None else palette\n\n if isinstance(palette, mpl.colors.Colormap):\n cmap = palette\n else:\n cmap = color_palette(palette, as_cmap=True)\n\n # Now sort out the data normalization\n if norm is None:\n norm = mpl.colors.Normalize()\n elif isinstance(norm, tuple):\n norm = mpl.colors.Normalize(*norm)\n elif not isinstance(norm, mpl.colors.Normalize):\n err = \"``hue_norm`` must be None, tuple, or Normalize object.\"\n raise ValueError(err)\n\n if not norm.scaled():\n norm(np.asarray(data.dropna()))\n\n lookup_table = dict(zip(levels, cmap(norm(levels))))\n\n return levels, lookup_table, norm, cmap"},{"col":4,"comment":"null","endLoc":273,"header":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n iter9: Iterable[_T9],\n iter10: Iterable[_T10],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]","id":722,"name":"__new__","nodeType":"Function","startLoc":259,"text":"@overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n iter9: Iterable[_T9],\n iter10: Iterable[_T10],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]: ..."},{"col":4,"comment":"null","endLoc":275,"header":"@overload\n def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]","id":723,"name":"__new__","nodeType":"Function","startLoc":274,"text":"@overload\n def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ..."},{"col":4,"comment":"Apply a plotting function to each facet's subset of the data.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. It\n must plot to the currently active matplotlib Axes and take a\n `color` keyword argument. If faceting on the `hue` dimension,\n it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n ","endLoc":757,"header":"def map(self, func, *args, **kwargs)","id":724,"name":"map","nodeType":"Function","startLoc":677,"text":"def map(self, func, *args, **kwargs):\n \"\"\"Apply a plotting function to each facet's subset of the data.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. It\n must plot to the currently active matplotlib Axes and take a\n `color` keyword argument. If faceting on the `hue` dimension,\n it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # How we use the function depends on where it comes from\n func_module = str(getattr(func, \"__module__\", \"\"))\n\n # Check for categorical plots without order information\n if func_module == \"seaborn.categorical\":\n if \"order\" not in kwargs:\n warning = (\"Using the {} function without specifying \"\n \"`order` is likely to produce an incorrect \"\n \"plot.\".format(func.__name__))\n warnings.warn(warning)\n if len(args) == 3 and \"hue_order\" not in kwargs:\n warning = (\"Using the {} function without specifying \"\n \"`hue_order` is likely to produce an incorrect \"\n \"plot.\".format(func.__name__))\n warnings.warn(warning)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.size:\n continue\n\n # Get the current axis\n modify_state = not func_module.startswith(\"seaborn\")\n ax = self.facet_axis(row_i, col_j, modify_state)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = utils.to_utf8(self.hue_names[hue_k])\n\n # Get the actual data we are going to plot with\n plot_data = data_ijk[list(args)]\n if self._dropna:\n plot_data = plot_data.dropna()\n plot_args = [v for k, v in plot_data.items()]\n\n # Some matplotlib functions don't handle pandas objects correctly\n if func_module.startswith(\"matplotlib\"):\n plot_args = [v.values for v in plot_args]\n\n # Draw the plot\n self._facet_plot(func, ax, plot_args, kwargs)\n\n # Finalize the annotations and layout\n self._finalize_grid(args[:2])\n\n return self"},{"col":4,"comment":"Map the levels of the `hue` variable to distinct colors.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n ","endLoc":168,"header":"def __init__(\n self, plotter, palette=None, order=None, norm=None,\n )","id":725,"name":"__init__","nodeType":"Function","startLoc":106,"text":"def __init__(\n self, plotter, palette=None, order=None, norm=None,\n ):\n \"\"\"Map the levels of the `hue` variable to distinct colors.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"hue\", pd.Series(dtype=float))\n\n if data.isna().all():\n if palette is not None:\n msg = \"Ignoring `palette` because no `hue` variable has been assigned.\"\n warnings.warn(msg, stacklevel=4)\n else:\n\n map_type = self.infer_map_type(\n palette, norm, plotter.input_format, plotter.var_types[\"hue\"]\n )\n\n # Our goal is to end up with a dictionary mapping every unique\n # value in `data` to a color. We will also keep track of the\n # metadata about this mapping we will need for, e.g., a legend\n\n # --- Option 1: numeric mapping with a matplotlib colormap\n\n if map_type == \"numeric\":\n\n data = pd.to_numeric(data)\n levels, lookup_table, norm, cmap = self.numeric_mapping(\n data, palette, norm,\n )\n\n # --- Option 2: categorical mapping using seaborn palette\n\n elif map_type == \"categorical\":\n\n cmap = norm = None\n levels, lookup_table = self.categorical_mapping(\n data, palette, order,\n )\n\n # --- Option 3: datetime mapping\n\n else:\n # TODO this needs actual implementation\n cmap = norm = None\n levels, lookup_table = self.categorical_mapping(\n # Casting data to list to handle differences in the way\n # pandas and numpy represent datetime64 data\n list(data), palette, order,\n )\n\n self.map_type = map_type\n self.lookup_table = lookup_table\n self.palette = palette\n self.levels = levels\n self.norm = norm\n self.cmap = cmap"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":191,"id":726,"name":"color","nodeType":"Attribute","startLoc":191,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":192,"id":727,"name":"alpha","nodeType":"Attribute","startLoc":192,"text":"alpha"},{"attributeType":"bool | Mappable","col":4,"comment":"null","endLoc":193,"id":728,"name":"fill","nodeType":"Attribute","startLoc":193,"text":"fill"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":194,"id":729,"name":"edgecolor","nodeType":"Attribute","startLoc":194,"text":"edgecolor"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":195,"id":730,"name":"edgealpha","nodeType":"Attribute","startLoc":195,"text":"edgealpha"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":196,"id":731,"name":"edgewidth","nodeType":"Attribute","startLoc":196,"text":"edgewidth"},{"attributeType":"str | (float, ...) | (float, (float, ...) | None) | Mappable","col":4,"comment":"null","endLoc":197,"id":732,"name":"edgestyle","nodeType":"Attribute","startLoc":197,"text":"edgestyle"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":200,"id":733,"name":"width","nodeType":"Attribute","startLoc":200,"text":"width"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":201,"id":734,"name":"baseline","nodeType":"Attribute","startLoc":201,"text":"baseline"},{"attributeType":"null","col":16,"comment":"null","endLoc":5,"id":735,"name":"np","nodeType":"Attribute","startLoc":5,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":6,"id":736,"name":"mpl","nodeType":"Attribute","startLoc":6,"text":"mpl"},{"col":0,"comment":"","endLoc":1,"header":"bar.py#","id":737,"name":"","nodeType":"Function","startLoc":1,"text":"if TYPE_CHECKING:\n from typing import Any\n from matplotlib.artist import Artist\n from seaborn._core.scales import Scale"},{"col":4,"comment":"null","endLoc":801,"header":"def __init__(self, scale)","id":738,"name":"__init__","nodeType":"Function","startLoc":788,"text":"def __init__(self, scale):\n\n self.converter = None\n self.units = None\n self.scale = scale\n self.major = mpl.axis.Ticker()\n self.minor = mpl.axis.Ticker()\n\n # It appears that this needs to be initialized this way on matplotlib 3.1,\n # but not later versions. It is unclear whether there are any issues with it.\n self._data_interval = None, None\n\n scale.set_default_locators_and_formatters(self)\n # self.set_default_intervals() Is this ever needed?"},{"id":739,"name":"v0.2.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.2.1 (December 2013)\n----------------------\n\nThis is a bugfix release, with no new features.\n\nBug fixes\n~~~~~~~~~\n\n- Changed the mechanics of ``violinplot()`` and ``boxplot()`` when using a\n ``Series`` object as data and performing a ``groupby`` to assign data to\n bins to address a problem that arises in Pandas 0.13.\n\n- Additionally fixed the ``groupby`` code to work with all styles of group\n specification (specifically, using a dictionary or a function now works).\n\n- Fixed a bug where artifacts from the kde fitting could undershoot and create\n a plot where the density axis starts below 0.\n\n- Ensured that data used for kde fitting is double-typed to avoid a low-level\n statsmodels error.\n\n- Changed the implementation of the histogram bin-width reference rule to\n take a ceiling of the estimated number of bins.\n"},{"col":4,"comment":"Determine how to implement the mapping.","endLoc":211,"header":"def infer_map_type(self, palette, norm, input_format, var_type)","id":740,"name":"infer_map_type","nodeType":"Function","startLoc":198,"text":"def infer_map_type(self, palette, norm, input_format, var_type):\n \"\"\"Determine how to implement the mapping.\"\"\"\n if palette in QUAL_PALETTES:\n map_type = \"categorical\"\n elif norm is not None:\n map_type = \"numeric\"\n elif isinstance(palette, (dict, list)):\n map_type = \"categorical\"\n elif input_format == \"wide\":\n map_type = \"categorical\"\n else:\n map_type = var_type\n\n return map_type"},{"col":0,"comment":"\n Backwards compatability for creation of independent scales.\n\n Matplotlib scales require an Axis object for instantiation on < 3.4.\n But the axis is not used, aside from extraction of the axis_name in LogScale.\n\n ","endLoc":105,"header":"def scale_factory(scale, axis, **kwargs)","id":741,"name":"scale_factory","nodeType":"Function","startLoc":70,"text":"def scale_factory(scale, axis, **kwargs):\n \"\"\"\n Backwards compatability for creation of independent scales.\n\n Matplotlib scales require an Axis object for instantiation on < 3.4.\n But the axis is not used, aside from extraction of the axis_name in LogScale.\n\n \"\"\"\n modify_transform = False\n if Version(mpl.__version__) < Version(\"3.4\"):\n if axis[0] in \"xy\":\n modify_transform = True\n axis = axis[0]\n base = kwargs.pop(\"base\", None)\n if base is not None:\n kwargs[f\"base{axis}\"] = base\n nonpos = kwargs.pop(\"nonpositive\", None)\n if nonpos is not None:\n kwargs[f\"nonpos{axis}\"] = nonpos\n\n if isinstance(scale, str):\n class Axis:\n axis_name = axis\n axis = Axis()\n\n scale = mpl.scale.scale_factory(scale, axis, **kwargs)\n\n if modify_transform:\n transform = scale.get_transform()\n transform.base = kwargs.get(\"base\", 10)\n if kwargs.get(\"nonpositive\") == \"mask\":\n # Setting a private attribute, but we only get here\n # on an old matplotlib, so this won't break going forwards\n transform._clip = False\n\n return scale"},{"fileName":"scatterplot_matrix.py","filePath":"examples","id":742,"nodeType":"File","text":"\"\"\"\nScatterplot Matrix\n==================\n\n_thumb: .3, .2\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\n\ndf = sns.load_dataset(\"penguins\")\nsns.pairplot(df, hue=\"species\")\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":743,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"col":4,"comment":"null","endLoc":804,"header":"def set_view_interval(self, vmin, vmax)","id":744,"name":"set_view_interval","nodeType":"Function","startLoc":803,"text":"def set_view_interval(self, vmin, vmax):\n self._view_interval = vmin, vmax"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":745,"name":"df","nodeType":"Attribute","startLoc":10,"text":"df"},{"col":0,"comment":"","endLoc":6,"header":"scatterplot_matrix.py#","id":746,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot Matrix\n==================\n\n_thumb: .3, .2\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\ndf = sns.load_dataset(\"penguins\")\n\nsns.pairplot(df, hue=\"species\")"},{"col":0,"comment":"Plot pairwise relationships in a dataset.\n\n By default, this function will create a grid of Axes such that each numeric\n variable in ``data`` will by shared across the y-axes across a single row and\n the x-axes across a single column. The diagonal plots are treated\n differently: a univariate distribution plot is drawn to show the marginal\n distribution of the data in each column.\n\n It is also possible to show a subset of variables or plot different\n variables on the rows and columns.\n\n This is a high-level interface for :class:`PairGrid` that is intended to\n make it easy to draw a few common styles. You should use :class:`PairGrid`\n directly if you need more flexibility.\n\n Parameters\n ----------\n data : `pandas.DataFrame`\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : name of variable in ``data``\n Variable in ``data`` to map plot aspects to different colors.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n kind : {'scatter', 'kde', 'hist', 'reg'}\n Kind of plot to make.\n diag_kind : {'auto', 'hist', 'kde', None}\n Kind of plot for the diagonal subplots. If 'auto', choose based on\n whether or not ``hue`` is used.\n markers : single matplotlib marker code or list\n Either the marker to use for all scatterplot points or a list of markers\n with a length the same as the number of levels in the hue variable so that\n differently colored points will also have different scatterplot\n markers.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n dropna : boolean\n Drop missing values from the data before plotting.\n {plot, diag, grid}_kws : dicts\n Dictionaries of keyword arguments. ``plot_kws`` are passed to the\n bivariate plotting function, ``diag_kws`` are passed to the univariate\n plotting function, and ``grid_kws`` are passed to the :class:`PairGrid`\n constructor.\n\n Returns\n -------\n grid : :class:`PairGrid`\n Returns the underlying :class:`PairGrid` instance for further tweaking.\n\n See Also\n --------\n PairGrid : Subplot grid for more flexible plotting of pairwise relationships.\n JointGrid : Grid for plotting joint and marginal distributions of two variables.\n\n Examples\n --------\n\n .. include:: ../docstrings/pairplot.rst\n\n ","endLoc":2176,"header":"def pairplot(\n data, *,\n hue=None, hue_order=None, palette=None,\n vars=None, x_vars=None, y_vars=None,\n kind=\"scatter\", diag_kind=\"auto\", markers=None,\n height=2.5, aspect=1, corner=False, dropna=False,\n plot_kws=None, diag_kws=None, grid_kws=None, size=None,\n)","id":747,"name":"pairplot","nodeType":"Function","startLoc":2005,"text":"def pairplot(\n data, *,\n hue=None, hue_order=None, palette=None,\n vars=None, x_vars=None, y_vars=None,\n kind=\"scatter\", diag_kind=\"auto\", markers=None,\n height=2.5, aspect=1, corner=False, dropna=False,\n plot_kws=None, diag_kws=None, grid_kws=None, size=None,\n):\n \"\"\"Plot pairwise relationships in a dataset.\n\n By default, this function will create a grid of Axes such that each numeric\n variable in ``data`` will by shared across the y-axes across a single row and\n the x-axes across a single column. The diagonal plots are treated\n differently: a univariate distribution plot is drawn to show the marginal\n distribution of the data in each column.\n\n It is also possible to show a subset of variables or plot different\n variables on the rows and columns.\n\n This is a high-level interface for :class:`PairGrid` that is intended to\n make it easy to draw a few common styles. You should use :class:`PairGrid`\n directly if you need more flexibility.\n\n Parameters\n ----------\n data : `pandas.DataFrame`\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : name of variable in ``data``\n Variable in ``data`` to map plot aspects to different colors.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n kind : {'scatter', 'kde', 'hist', 'reg'}\n Kind of plot to make.\n diag_kind : {'auto', 'hist', 'kde', None}\n Kind of plot for the diagonal subplots. If 'auto', choose based on\n whether or not ``hue`` is used.\n markers : single matplotlib marker code or list\n Either the marker to use for all scatterplot points or a list of markers\n with a length the same as the number of levels in the hue variable so that\n differently colored points will also have different scatterplot\n markers.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n dropna : boolean\n Drop missing values from the data before plotting.\n {plot, diag, grid}_kws : dicts\n Dictionaries of keyword arguments. ``plot_kws`` are passed to the\n bivariate plotting function, ``diag_kws`` are passed to the univariate\n plotting function, and ``grid_kws`` are passed to the :class:`PairGrid`\n constructor.\n\n Returns\n -------\n grid : :class:`PairGrid`\n Returns the underlying :class:`PairGrid` instance for further tweaking.\n\n See Also\n --------\n PairGrid : Subplot grid for more flexible plotting of pairwise relationships.\n JointGrid : Grid for plotting joint and marginal distributions of two variables.\n\n Examples\n --------\n\n .. include:: ../docstrings/pairplot.rst\n\n \"\"\"\n # Avoid circular import\n from .distributions import histplot, kdeplot\n\n # Handle deprecations\n if size is not None:\n height = size\n msg = (\"The `size` parameter has been renamed to `height`; \"\n \"please update your code.\")\n warnings.warn(msg, UserWarning)\n\n if not isinstance(data, pd.DataFrame):\n raise TypeError(\n f\"'data' must be pandas DataFrame object, not: {type(data)}\")\n\n plot_kws = {} if plot_kws is None else plot_kws.copy()\n diag_kws = {} if diag_kws is None else diag_kws.copy()\n grid_kws = {} if grid_kws is None else grid_kws.copy()\n\n # Resolve \"auto\" diag kind\n if diag_kind == \"auto\":\n if hue is None:\n diag_kind = \"kde\" if kind == \"kde\" else \"hist\"\n else:\n diag_kind = \"hist\" if kind == \"hist\" else \"kde\"\n\n # Set up the PairGrid\n grid_kws.setdefault(\"diag_sharey\", diag_kind == \"hist\")\n grid = PairGrid(data, vars=vars, x_vars=x_vars, y_vars=y_vars, hue=hue,\n hue_order=hue_order, palette=palette, corner=corner,\n height=height, aspect=aspect, dropna=dropna, **grid_kws)\n\n # Add the markers here as PairGrid has figured out how many levels of the\n # hue variable are needed and we don't want to duplicate that process\n if markers is not None:\n if kind == \"reg\":\n # Needed until regplot supports style\n if grid.hue_names is None:\n n_markers = 1\n else:\n n_markers = len(grid.hue_names)\n if not isinstance(markers, list):\n markers = [markers] * n_markers\n if len(markers) != n_markers:\n raise ValueError(\"markers must be a singleton or a list of \"\n \"markers for each level of the hue variable\")\n grid.hue_kws = {\"marker\": markers}\n elif kind == \"scatter\":\n if isinstance(markers, str):\n plot_kws[\"marker\"] = markers\n elif hue is not None:\n plot_kws[\"style\"] = data[hue]\n plot_kws[\"markers\"] = markers\n\n # Draw the marginal plots on the diagonal\n diag_kws = diag_kws.copy()\n diag_kws.setdefault(\"legend\", False)\n if diag_kind == \"hist\":\n grid.map_diag(histplot, **diag_kws)\n elif diag_kind == \"kde\":\n diag_kws.setdefault(\"fill\", True)\n diag_kws.setdefault(\"warn_singular\", False)\n grid.map_diag(kdeplot, **diag_kws)\n\n # Maybe plot on the off-diagonals\n if diag_kind is not None:\n plotter = grid.map_offdiag\n else:\n plotter = grid.map\n\n if kind == \"scatter\":\n from .relational import scatterplot # Avoid circular import\n plotter(scatterplot, **plot_kws)\n elif kind == \"reg\":\n from .regression import regplot # Avoid circular import\n plotter(regplot, **plot_kws)\n elif kind == \"kde\":\n from .distributions import kdeplot # Avoid circular import\n plot_kws.setdefault(\"warn_singular\", False)\n plotter(kdeplot, **plot_kws)\n elif kind == \"hist\":\n from .distributions import histplot # Avoid circular import\n plotter(histplot, **plot_kws)\n\n # Add a legend\n if hue is not None:\n grid.add_legend()\n\n grid.tight_layout()\n\n return grid"},{"col":4,"comment":"Pass units to the internal converter, potentially updating its mapping.","endLoc":860,"header":"def update_units(self, x)","id":748,"name":"update_units","nodeType":"Function","startLoc":844,"text":"def update_units(self, x):\n \"\"\"Pass units to the internal converter, potentially updating its mapping.\"\"\"\n self.converter = mpl.units.registry.get_converter(x)\n if self.converter is not None:\n self.converter.default_units(x, self)\n\n info = self.converter.axisinfo(self.units, self)\n\n if info is None:\n return\n if info.majloc is not None:\n self.set_major_locator(info.majloc)\n if info.majfmt is not None:\n self.set_major_formatter(info.majfmt)\n\n # This is in matplotlib method; do we need this?\n # self.set_default_intervals()"},{"col":4,"comment":"null","endLoc":827,"header":"def set_major_locator(self, locator)","id":749,"name":"set_major_locator","nodeType":"Function","startLoc":825,"text":"def set_major_locator(self, locator):\n self.major.locator = locator\n locator.set_axis(self)"},{"col":4,"comment":"null","endLoc":831,"header":"def set_major_formatter(self, formatter)","id":750,"name":"set_major_formatter","nodeType":"Function","startLoc":829,"text":"def set_major_formatter(self, formatter):\n self.major.formatter = formatter\n formatter.set_axis(self)"},{"col":4,"comment":"Return a numeric representation of the input data.","endLoc":868,"header":"def convert_units(self, x)","id":751,"name":"convert_units","nodeType":"Function","startLoc":862,"text":"def convert_units(self, x):\n \"\"\"Return a numeric representation of the input data.\"\"\"\n if np.issubdtype(np.asarray(x).dtype, np.number):\n return x\n elif self.converter is None:\n return x\n return self.converter.convert(x, self.units, self)"},{"col":0,"comment":"\n Warn on usage of ci= and convert to appropriate errorbar= arg.\n\n ci was deprecated when errorbar was added in 0.12. It should not be removed\n completely for some time, but it can be moved out of function definitions\n (and extracted from kwargs) after one cycle.\n\n ","endLoc":849,"header":"def _deprecate_ci(errorbar, ci)","id":754,"name":"_deprecate_ci","nodeType":"Function","startLoc":827,"text":"def _deprecate_ci(errorbar, ci):\n \"\"\"\n Warn on usage of ci= and convert to appropriate errorbar= arg.\n\n ci was deprecated when errorbar was added in 0.12. It should not be removed\n completely for some time, but it can be moved out of function definitions\n (and extracted from kwargs) after one cycle.\n\n \"\"\"\n if ci != \"deprecated\":\n if ci is None:\n errorbar = None\n elif ci == \"sd\":\n errorbar = \"sd\"\n else:\n errorbar = (\"ci\", ci)\n msg = (\n \"\\n\\nThe `ci` parameter is deprecated. \"\n f\"Use `errorbar={repr(errorbar)}` for the same effect.\\n\"\n )\n warnings.warn(msg, FutureWarning, stacklevel=3)\n\n return errorbar"},{"col":4,"comment":"Use some heuristics to set good defaults for colorbar and range.","endLoc":247,"header":"def _determine_cmap_params(self, plot_data, vmin, vmax,\n cmap, center, robust)","id":755,"name":"_determine_cmap_params","nodeType":"Function","startLoc":192,"text":"def _determine_cmap_params(self, plot_data, vmin, vmax,\n cmap, center, robust):\n \"\"\"Use some heuristics to set good defaults for colorbar and range.\"\"\"\n\n # plot_data is a np.ma.array instance\n calc_data = plot_data.astype(float).filled(np.nan)\n if vmin is None:\n if robust:\n vmin = np.nanpercentile(calc_data, 2)\n else:\n vmin = np.nanmin(calc_data)\n if vmax is None:\n if robust:\n vmax = np.nanpercentile(calc_data, 98)\n else:\n vmax = np.nanmax(calc_data)\n self.vmin, self.vmax = vmin, vmax\n\n # Choose default colormaps if not provided\n if cmap is None:\n if center is None:\n self.cmap = cm.rocket\n else:\n self.cmap = cm.icefire\n elif isinstance(cmap, str):\n self.cmap = get_colormap(cmap)\n elif isinstance(cmap, list):\n self.cmap = mpl.colors.ListedColormap(cmap)\n else:\n self.cmap = cmap\n\n # Recenter a divergent colormap\n if center is not None:\n\n # Copy bad values\n # in mpl<3.2 only masked values are honored with \"bad\" color spec\n # (see https://github.com/matplotlib/matplotlib/pull/14257)\n bad = self.cmap(np.ma.masked_invalid([np.nan]))[0]\n\n # under/over values are set for sure when cmap extremes\n # do not map to the same color as +-inf\n under = self.cmap(-np.inf)\n over = self.cmap(np.inf)\n under_set = under != self.cmap(0)\n over_set = over != self.cmap(self.cmap.N - 1)\n\n vrange = max(vmax - center, center - vmin)\n normlize = mpl.colors.Normalize(center - vrange, center + vrange)\n cmin, cmax = normlize([vmin, vmax])\n cc = np.linspace(cmin, cmax, 256)\n self.cmap = mpl.colors.ListedColormap(self.cmap(cc))\n self.cmap.set_bad(bad)\n if under_set:\n self.cmap.set_under(under)\n if over_set:\n self.cmap.set_over(over)"},{"col":4,"comment":"Make the axis identified by these indices active and return it.","endLoc":870,"header":"def facet_axis(self, row_i, col_j, modify_state=True)","id":756,"name":"facet_axis","nodeType":"Function","startLoc":858,"text":"def facet_axis(self, row_i, col_j, modify_state=True):\n \"\"\"Make the axis identified by these indices active and return it.\"\"\"\n\n # Calculate the actual indices of the axes to plot on\n if self._col_wrap is not None:\n ax = self.axes.flat[col_j]\n else:\n ax = self.axes[row_i, col_j]\n\n # Get a reference to the axes object we want, and make it active\n if modify_state:\n plt.sca(ax)\n return ax"},{"col":4,"comment":"null","endLoc":836,"header":"def _facet_color(self, hue_index, kw_color)","id":757,"name":"_facet_color","nodeType":"Function","startLoc":830,"text":"def _facet_color(self, hue_index, kw_color):\n\n color = self._colors[hue_index]\n if kw_color is not None:\n return kw_color\n elif color is not None:\n return color"},{"col":4,"comment":"null","endLoc":851,"header":"def _facet_plot(self, func, ax, plot_args, plot_kwargs)","id":758,"name":"_facet_plot","nodeType":"Function","startLoc":838,"text":"def _facet_plot(self, func, ax, plot_args, plot_kwargs):\n\n # Draw the plot\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs = plot_kwargs.copy()\n semantics = [\"x\", \"y\", \"hue\", \"size\", \"style\"]\n for key, val in zip(semantics, plot_args):\n plot_kwargs[key] = val\n plot_args = []\n plot_kwargs[\"ax\"] = ax\n func(*plot_args, **plot_kwargs)\n\n # Sort out the supporting information\n self._update_legend_data(ax)"},{"col":4,"comment":"null","endLoc":286,"header":"def _get_locators(self, locator)","id":759,"name":"_get_locators","nodeType":"Function","startLoc":279,"text":"def _get_locators(self, locator):\n\n if locator is not None:\n return locator, None\n\n locator = mpl.category.StrCategoryLocator({})\n\n return locator, None"},{"col":4,"comment":"Finalize the annotations and layout.","endLoc":856,"header":"def _finalize_grid(self, axlabels)","id":760,"name":"_finalize_grid","nodeType":"Function","startLoc":853,"text":"def _finalize_grid(self, axlabels):\n \"\"\"Finalize the annotations and layout.\"\"\"\n self.set_axis_labels(*axlabels)\n self.tight_layout()"},{"col":4,"comment":"null","endLoc":295,"header":"def _get_formatter(self, locator, formatter)","id":761,"name":"_get_formatter","nodeType":"Function","startLoc":288,"text":"def _get_formatter(self, locator, formatter):\n\n if formatter is not None:\n return formatter\n\n formatter = mpl.category.StrCategoryFormatter({})\n\n return formatter"},{"col":4,"comment":"Set axis labels on the left column and bottom row of the grid.","endLoc":886,"header":"def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs)","id":762,"name":"set_axis_labels","nodeType":"Function","startLoc":877,"text":"def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs):\n \"\"\"Set axis labels on the left column and bottom row of the grid.\"\"\"\n if x_var is not None:\n self._x_var = x_var\n self.set_xlabels(x_var, clear_inner=clear_inner, **kwargs)\n if y_var is not None:\n self._y_var = y_var\n self.set_ylabels(y_var, clear_inner=clear_inner, **kwargs)\n\n return self"},{"attributeType":"tuple | str | list | dict | None","col":4,"comment":"null","endLoc":144,"id":763,"name":"values","nodeType":"Attribute","startLoc":144,"text":"values"},{"attributeType":"list | None","col":4,"comment":"null","endLoc":145,"id":764,"name":"order","nodeType":"Attribute","startLoc":145,"text":"order"},{"attributeType":"int","col":4,"comment":"null","endLoc":147,"id":765,"name":"_priority","nodeType":"Attribute","startLoc":147,"text":"_priority"},{"col":4,"comment":"Label the x axis on the bottom row of the grid.","endLoc":897,"header":"def set_xlabels(self, label=None, clear_inner=True, **kwargs)","id":766,"name":"set_xlabels","nodeType":"Function","startLoc":888,"text":"def set_xlabels(self, label=None, clear_inner=True, **kwargs):\n \"\"\"Label the x axis on the bottom row of the grid.\"\"\"\n if label is None:\n label = self._x_var\n for ax in self._bottom_axes:\n ax.set_xlabel(label, **kwargs)\n if clear_inner:\n for ax in self._not_bottom_axes:\n ax.set_xlabel(\"\")\n return self"},{"col":4,"comment":"Label the y axis on the left column of the grid.","endLoc":908,"header":"def set_ylabels(self, label=None, clear_inner=True, **kwargs)","id":767,"name":"set_ylabels","nodeType":"Function","startLoc":899,"text":"def set_ylabels(self, label=None, clear_inner=True, **kwargs):\n \"\"\"Label the y axis on the left column of the grid.\"\"\"\n if label is None:\n label = self._y_var\n for ax in self._left_axes:\n ax.set_ylabel(label, **kwargs)\n if clear_inner:\n for ax in self._not_left_axes:\n ax.set_ylabel(\"\")\n return self"},{"className":"Ordinal","col":0,"comment":"null","endLoc":301,"id":768,"nodeType":"Class","startLoc":298,"text":"@dataclass\nclass Ordinal(Scale):\n # Categorical (convert to strings), sortable, can skip ticklabels\n ..."},{"className":"Discrete","col":0,"comment":"null","endLoc":307,"id":769,"nodeType":"Class","startLoc":304,"text":"@dataclass\nclass Discrete(Scale):\n # Numeric, integral, can skip ticks/ticklabels\n ..."},{"className":"ContinuousBase","col":0,"comment":"null","endLoc":411,"id":770,"nodeType":"Class","startLoc":310,"text":"@dataclass\nclass ContinuousBase(Scale):\n\n values: tuple | str | None = None\n norm: tuple | None = None\n\n def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n\n new = copy(self)\n if new._tick_params is None:\n new = new.tick()\n if new._label_params is None:\n new = new.label()\n\n forward, inverse = new._get_transform()\n\n mpl_scale = new._get_scale(str(data.name), forward, inverse)\n\n if axis is None:\n axis = PseudoAxis(mpl_scale)\n axis.update_units(data)\n\n mpl_scale.set_default_locators_and_formatters(axis)\n new._matplotlib_scale = mpl_scale\n\n normalize: Optional[Callable[[ArrayLike], ArrayLike]]\n if prop.normed:\n if new.norm is None:\n vmin, vmax = data.min(), data.max()\n else:\n vmin, vmax = new.norm\n vmin, vmax = axis.convert_units((vmin, vmax))\n a = forward(vmin)\n b = forward(vmax) - forward(vmin)\n\n def normalize(x):\n return (x - a) / b\n\n else:\n normalize = vmin = vmax = None\n\n new._pipeline = [\n axis.convert_units,\n forward,\n normalize,\n prop.get_mapping(new, data)\n ]\n\n def spacer(x):\n x = x.dropna().unique()\n if len(x) < 2:\n return np.nan\n return np.min(np.diff(np.sort(x)))\n new._spacer = spacer\n\n # TODO How to allow disabling of legend for all uses of property?\n # Could add a Scale parameter, or perhaps Scale.suppress()?\n # Are there other useful parameters that would be in Scale.legend()\n # besides allowing Scale.legend(False)?\n if prop.legend:\n axis.set_view_interval(vmin, vmax)\n locs = axis.major.locator()\n locs = locs[(vmin <= locs) & (locs <= vmax)]\n labels = axis.major.formatter.format_ticks(locs)\n new._legend = list(locs), list(labels)\n\n return new\n\n def _get_transform(self):\n\n arg = self.trans\n\n def get_param(method, default):\n if arg == method:\n return default\n return float(arg[len(method):])\n\n if arg is None:\n return _make_identity_transforms()\n elif isinstance(arg, tuple):\n return arg\n elif isinstance(arg, str):\n if arg == \"ln\":\n return _make_log_transforms()\n elif arg == \"logit\":\n base = get_param(\"logit\", 10)\n return _make_logit_transforms(base)\n elif arg.startswith(\"log\"):\n base = get_param(\"log\", 10)\n return _make_log_transforms(base)\n elif arg.startswith(\"symlog\"):\n c = get_param(\"symlog\", 1)\n return _make_symlog_transforms(c)\n elif arg.startswith(\"pow\"):\n exp = get_param(\"pow\", 2)\n return _make_power_transforms(exp)\n elif arg == \"sqrt\":\n return _make_sqrt_transforms()\n else:\n raise ValueError(f\"Unknown value provided for trans: {arg!r}\")"},{"col":4,"comment":"Like ``.map`` but passes args as strings and inserts data in kwargs.\n\n This method is suitable for plotting with functions that accept a\n long-form DataFrame as a `data` keyword argument and access the\n data in that DataFrame using string variable names.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. Unlike\n the `map` method, a function used here must \"understand\" Pandas\n objects. It also must plot to the currently active matplotlib Axes\n and take a `color` keyword argument. If faceting on the `hue`\n dimension, it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n ","endLoc":828,"header":"def map_dataframe(self, func, *args, **kwargs)","id":771,"name":"map_dataframe","nodeType":"Function","startLoc":759,"text":"def map_dataframe(self, func, *args, **kwargs):\n \"\"\"Like ``.map`` but passes args as strings and inserts data in kwargs.\n\n This method is suitable for plotting with functions that accept a\n long-form DataFrame as a `data` keyword argument and access the\n data in that DataFrame using string variable names.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. Unlike\n the `map` method, a function used here must \"understand\" Pandas\n objects. It also must plot to the currently active matplotlib Axes\n and take a `color` keyword argument. If faceting on the `hue`\n dimension, it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.size:\n continue\n\n # Get the current axis\n modify_state = not str(func.__module__).startswith(\"seaborn\")\n ax = self.facet_axis(row_i, col_j, modify_state)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = self.hue_names[hue_k]\n\n # Stick the facet dataframe into the kwargs\n if self._dropna:\n data_ijk = data_ijk.dropna()\n kwargs[\"data\"] = data_ijk\n\n # Draw the plot\n self._facet_plot(func, ax, args, kwargs)\n\n # For axis labels, prefer to use positional args for backcompat\n # but also extract the x/y kwargs and use if no corresponding arg\n axis_labels = [kwargs.get(\"x\", None), kwargs.get(\"y\", None)]\n for i, val in enumerate(args[:2]):\n axis_labels[i] = val\n self._finalize_grid(axis_labels)\n\n return self"},{"col":4,"comment":"null","endLoc":378,"header":"def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale","id":772,"name":"_setup","nodeType":"Function","startLoc":316,"text":"def _setup(\n self, data: Series, prop: Property, axis: Axis | None = None,\n ) -> Scale:\n\n new = copy(self)\n if new._tick_params is None:\n new = new.tick()\n if new._label_params is None:\n new = new.label()\n\n forward, inverse = new._get_transform()\n\n mpl_scale = new._get_scale(str(data.name), forward, inverse)\n\n if axis is None:\n axis = PseudoAxis(mpl_scale)\n axis.update_units(data)\n\n mpl_scale.set_default_locators_and_formatters(axis)\n new._matplotlib_scale = mpl_scale\n\n normalize: Optional[Callable[[ArrayLike], ArrayLike]]\n if prop.normed:\n if new.norm is None:\n vmin, vmax = data.min(), data.max()\n else:\n vmin, vmax = new.norm\n vmin, vmax = axis.convert_units((vmin, vmax))\n a = forward(vmin)\n b = forward(vmax) - forward(vmin)\n\n def normalize(x):\n return (x - a) / b\n\n else:\n normalize = vmin = vmax = None\n\n new._pipeline = [\n axis.convert_units,\n forward,\n normalize,\n prop.get_mapping(new, data)\n ]\n\n def spacer(x):\n x = x.dropna().unique()\n if len(x) < 2:\n return np.nan\n return np.min(np.diff(np.sort(x)))\n new._spacer = spacer\n\n # TODO How to allow disabling of legend for all uses of property?\n # Could add a Scale parameter, or perhaps Scale.suppress()?\n # Are there other useful parameters that would be in Scale.legend()\n # besides allowing Scale.legend(False)?\n if prop.legend:\n axis.set_view_interval(vmin, vmax)\n locs = axis.major.locator()\n locs = locs[(vmin <= locs) & (locs <= vmax)]\n labels = axis.major.formatter.format_ticks(locs)\n new._legend = list(locs), list(labels)\n\n return new"},{"col":4,"comment":"Inner function for histogram of two variables.","endLoc":365,"header":"def _eval_bivariate(self, x1, x2, weights)","id":773,"name":"_eval_bivariate","nodeType":"Function","startLoc":335,"text":"def _eval_bivariate(self, x1, x2, weights):\n \"\"\"Inner function for histogram of two variables.\"\"\"\n bin_kws = self.bin_kws\n if bin_kws is None:\n bin_kws = self.define_bin_params(x1, x2, cache=False)\n\n density = self.stat == \"density\"\n\n hist, *bin_edges = np.histogram2d(\n x1, x2, **bin_kws, weights=weights, density=density\n )\n\n area = np.outer(\n np.diff(bin_edges[0]),\n np.diff(bin_edges[1]),\n )\n\n if self.stat == \"probability\" or self.stat == \"proportion\":\n hist = hist.astype(float) / hist.sum()\n elif self.stat == \"percent\":\n hist = hist.astype(float) / hist.sum() * 100\n elif self.stat == \"frequency\":\n hist = hist.astype(float) / area\n\n if self.cumulative:\n if self.stat in [\"density\", \"frequency\"]:\n hist = (hist * area).cumsum(axis=0).cumsum(axis=1)\n else:\n hist = hist.cumsum(axis=0).cumsum(axis=1)\n\n return hist, bin_edges"},{"col":4,"comment":"Initialize the plot figure and PairGrid object.\n\n Parameters\n ----------\n data : DataFrame\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : string (variable name)\n Variable in ``data`` to map plot aspects to different colors. This\n variable will be excluded from the default x and y variables.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n layout_pad : scalar\n Padding between axes; passed to ``fig.tight_layout``.\n despine : boolean\n Remove the top and right spines from the plots.\n dropna : boolean\n Drop missing values from the data before plotting.\n\n See Also\n --------\n pairplot : Easily drawing common uses of :class:`PairGrid`.\n FacetGrid : Subplot grid for plotting conditional relationships.\n\n Examples\n --------\n\n .. include:: ../docstrings/PairGrid.rst\n\n ","endLoc":1358,"header":"def __init__(\n self, data, *, hue=None, vars=None, x_vars=None, y_vars=None,\n hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True,\n height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False,\n )","id":774,"name":"__init__","nodeType":"Function","startLoc":1186,"text":"def __init__(\n self, data, *, hue=None, vars=None, x_vars=None, y_vars=None,\n hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True,\n height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False,\n ):\n \"\"\"Initialize the plot figure and PairGrid object.\n\n Parameters\n ----------\n data : DataFrame\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : string (variable name)\n Variable in ``data`` to map plot aspects to different colors. This\n variable will be excluded from the default x and y variables.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n layout_pad : scalar\n Padding between axes; passed to ``fig.tight_layout``.\n despine : boolean\n Remove the top and right spines from the plots.\n dropna : boolean\n Drop missing values from the data before plotting.\n\n See Also\n --------\n pairplot : Easily drawing common uses of :class:`PairGrid`.\n FacetGrid : Subplot grid for plotting conditional relationships.\n\n Examples\n --------\n\n .. include:: ../docstrings/PairGrid.rst\n\n \"\"\"\n\n super().__init__()\n\n # Sort out the variables that define the grid\n numeric_cols = self._find_numeric_cols(data)\n if hue in numeric_cols:\n numeric_cols.remove(hue)\n if vars is not None:\n x_vars = list(vars)\n y_vars = list(vars)\n if x_vars is None:\n x_vars = numeric_cols\n if y_vars is None:\n y_vars = numeric_cols\n\n if np.isscalar(x_vars):\n x_vars = [x_vars]\n if np.isscalar(y_vars):\n y_vars = [y_vars]\n\n self.x_vars = x_vars = list(x_vars)\n self.y_vars = y_vars = list(y_vars)\n self.square_grid = self.x_vars == self.y_vars\n\n if not x_vars:\n raise ValueError(\"No variables found for grid columns.\")\n if not y_vars:\n raise ValueError(\"No variables found for grid rows.\")\n\n # Create the figure and the array of subplots\n figsize = len(x_vars) * height * aspect, len(y_vars) * height\n\n with _disable_autolayout():\n fig = plt.figure(figsize=figsize)\n\n axes = fig.subplots(len(y_vars), len(x_vars),\n sharex=\"col\", sharey=\"row\",\n squeeze=False)\n\n # Possibly remove upper axes to make a corner grid\n # Note: setting up the axes is usually the most time-intensive part\n # of using the PairGrid. We are foregoing the speed improvement that\n # we would get by just not setting up the hidden axes so that we can\n # avoid implementing fig.subplots ourselves. But worth thinking about.\n self._corner = corner\n if corner:\n hide_indices = np.triu_indices_from(axes, 1)\n for i, j in zip(*hide_indices):\n axes[i, j].remove()\n axes[i, j] = None\n\n self._figure = fig\n self.axes = axes\n self.data = data\n\n # Save what we are going to do with the diagonal\n self.diag_sharey = diag_sharey\n self.diag_vars = None\n self.diag_axes = None\n\n self._dropna = dropna\n\n # Label the axes\n self._add_axis_labels()\n\n # Sort out the hue variable\n self._hue_var = hue\n if hue is None:\n self.hue_names = hue_order = [\"_nolegend_\"]\n self.hue_vals = pd.Series([\"_nolegend_\"] * len(data),\n index=data.index)\n else:\n # We need hue_order and hue_names because the former is used to control\n # the order of drawing and the latter is used to control the order of\n # the legend. hue_names can become string-typed while hue_order must\n # retain the type of the input data. This is messy but results from\n # the fact that PairGrid can implement the hue-mapping logic itself\n # (and was originally written exclusively that way) but now can delegate\n # to the axes-level functions, while always handling legend creation.\n # See GH2307\n hue_names = hue_order = categorical_order(data[hue], hue_order)\n if dropna:\n # Filter NA from the list of unique hue names\n hue_names = list(filter(pd.notnull, hue_names))\n self.hue_names = hue_names\n self.hue_vals = data[hue]\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n self.hue_kws = hue_kws if hue_kws is not None else {}\n\n self._orig_palette = palette\n self._hue_order = hue_order\n self.palette = self._get_palette(data, hue, hue_order, palette)\n self._legend_data = {}\n\n # Make the plot look nice\n for ax in axes[:-1, :].flat:\n if ax is None:\n continue\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n ax.xaxis.label.set_visible(False)\n\n for ax in axes[:, 1:].flat:\n if ax is None:\n continue\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n ax.yaxis.label.set_visible(False)\n\n self._tight_layout_rect = [.01, .01, .99, .99]\n self._tight_layout_pad = layout_pad\n self._despine = despine\n if despine:\n utils.despine(fig=fig)\n self.tight_layout(pad=layout_pad)"},{"col":4,"comment":"Inner function for histogram of one variable.","endLoc":391,"header":"def _eval_univariate(self, x, weights)","id":775,"name":"_eval_univariate","nodeType":"Function","startLoc":367,"text":"def _eval_univariate(self, x, weights):\n \"\"\"Inner function for histogram of one variable.\"\"\"\n bin_kws = self.bin_kws\n if bin_kws is None:\n bin_kws = self.define_bin_params(x, weights=weights, cache=False)\n\n density = self.stat == \"density\"\n hist, bin_edges = np.histogram(\n x, **bin_kws, weights=weights, density=density,\n )\n\n if self.stat == \"probability\" or self.stat == \"proportion\":\n hist = hist.astype(float) / hist.sum()\n elif self.stat == \"percent\":\n hist = hist.astype(float) / hist.sum() * 100\n elif self.stat == \"frequency\":\n hist = hist.astype(float) / np.diff(bin_edges)\n\n if self.cumulative:\n if self.stat in [\"density\", \"frequency\"]:\n hist = (hist * np.diff(bin_edges)).cumsum()\n else:\n hist = hist.cumsum()\n\n return hist, bin_edges"},{"col":4,"comment":"Add textual labels with the value in each cell.","endLoc":263,"header":"def _annotate_heatmap(self, ax, mesh)","id":776,"name":"_annotate_heatmap","nodeType":"Function","startLoc":249,"text":"def _annotate_heatmap(self, ax, mesh):\n \"\"\"Add textual labels with the value in each cell.\"\"\"\n mesh.update_scalarmappable()\n height, width = self.annot_data.shape\n xpos, ypos = np.meshgrid(np.arange(width) + .5, np.arange(height) + .5)\n for x, y, m, color, val in zip(xpos.flat, ypos.flat,\n mesh.get_array(), mesh.get_facecolors(),\n self.annot_data.flat):\n if m is not np.ma.masked:\n lum = relative_luminance(color)\n text_color = \".15\" if lum > .408 else \"w\"\n annotation = (\"{:\" + self.fmt + \"}\").format(val)\n text_kwargs = dict(color=text_color, ha=\"center\", va=\"center\")\n text_kwargs.update(self.annot_kws)\n ax.text(x, y, annotation, **text_kwargs)"},{"col":4,"comment":"Count the occurrences in each bin, maybe normalize.","endLoc":398,"header":"def __call__(self, x1, x2=None, weights=None)","id":777,"name":"__call__","nodeType":"Function","startLoc":393,"text":"def __call__(self, x1, x2=None, weights=None):\n \"\"\"Count the occurrences in each bin, maybe normalize.\"\"\"\n if x2 is None:\n return self._eval_univariate(x1, weights)\n else:\n return self._eval_bivariate(x1, x2, weights)"},{"attributeType":"bool","col":8,"comment":"null","endLoc":249,"id":778,"name":"discrete","nodeType":"Attribute","startLoc":249,"text":"self.discrete"},{"col":4,"comment":"Find which variables in a DataFrame are numeric.","endLoc":1670,"header":"def _find_numeric_cols(self, data)","id":779,"name":"_find_numeric_cols","nodeType":"Function","startLoc":1664,"text":"def _find_numeric_cols(self, data):\n \"\"\"Find which variables in a DataFrame are numeric.\"\"\"\n numeric_cols = []\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n numeric_cols.append(col)\n return numeric_cols"},{"attributeType":"str","col":8,"comment":"null","endLoc":245,"id":780,"name":"stat","nodeType":"Attribute","startLoc":245,"text":"self.stat"},{"col":4,"comment":"Remove axis spines from the facets.","endLoc":875,"header":"def despine(self, **kwargs)","id":781,"name":"despine","nodeType":"Function","startLoc":872,"text":"def despine(self, **kwargs):\n \"\"\"Remove axis spines from the facets.\"\"\"\n utils.despine(self._figure, **kwargs)\n return self"},{"col":4,"comment":"Set x axis tick labels of the grid.","endLoc":924,"header":"def set_xticklabels(self, labels=None, step=None, **kwargs)","id":782,"name":"set_xticklabels","nodeType":"Function","startLoc":910,"text":"def set_xticklabels(self, labels=None, step=None, **kwargs):\n \"\"\"Set x axis tick labels of the grid.\"\"\"\n for ax in self.axes.flat:\n curr_ticks = ax.get_xticks()\n ax.set_xticks(curr_ticks)\n if labels is None:\n curr_labels = [l.get_text() for l in ax.get_xticklabels()]\n if step is not None:\n xticks = ax.get_xticks()[::step]\n curr_labels = curr_labels[::step]\n ax.set_xticks(xticks)\n ax.set_xticklabels(curr_labels, **kwargs)\n else:\n ax.set_xticklabels(labels, **kwargs)\n return self"},{"col":4,"comment":"Set y axis tick labels on the left column of the grid.","endLoc":936,"header":"def set_yticklabels(self, labels=None, **kwargs)","id":783,"name":"set_yticklabels","nodeType":"Function","startLoc":926,"text":"def set_yticklabels(self, labels=None, **kwargs):\n \"\"\"Set y axis tick labels on the left column of the grid.\"\"\"\n for ax in self.axes.flat:\n curr_ticks = ax.get_yticks()\n ax.set_yticks(curr_ticks)\n if labels is None:\n curr_labels = [l.get_text() for l in ax.get_yticklabels()]\n ax.set_yticklabels(curr_labels, **kwargs)\n else:\n ax.set_yticklabels(labels, **kwargs)\n return self"},{"col":4,"comment":"Draw titles either above each facet or on the grid margins.\n\n Parameters\n ----------\n template : string\n Template for all titles with the formatting keys {col_var} and\n {col_name} (if using a `col` faceting variable) and/or {row_var}\n and {row_name} (if using a `row` faceting variable).\n row_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {row_var} and {row_name} formatting keys.\n col_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {col_var} and {col_name} formatting keys.\n\n Returns\n -------\n self: object\n Returns self.\n\n ","endLoc":1028,"header":"def set_titles(self, template=None, row_template=None, col_template=None,\n **kwargs)","id":784,"name":"set_titles","nodeType":"Function","startLoc":938,"text":"def set_titles(self, template=None, row_template=None, col_template=None,\n **kwargs):\n \"\"\"Draw titles either above each facet or on the grid margins.\n\n Parameters\n ----------\n template : string\n Template for all titles with the formatting keys {col_var} and\n {col_name} (if using a `col` faceting variable) and/or {row_var}\n and {row_name} (if using a `row` faceting variable).\n row_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {row_var} and {row_name} formatting keys.\n col_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {col_var} and {col_name} formatting keys.\n\n Returns\n -------\n self: object\n Returns self.\n\n \"\"\"\n args = dict(row_var=self._row_var, col_var=self._col_var)\n kwargs[\"size\"] = kwargs.pop(\"size\", mpl.rcParams[\"axes.labelsize\"])\n\n # Establish default templates\n if row_template is None:\n row_template = \"{row_var} = {row_name}\"\n if col_template is None:\n col_template = \"{col_var} = {col_name}\"\n if template is None:\n if self._row_var is None:\n template = col_template\n elif self._col_var is None:\n template = row_template\n else:\n template = \" | \".join([row_template, col_template])\n\n row_template = utils.to_utf8(row_template)\n col_template = utils.to_utf8(col_template)\n template = utils.to_utf8(template)\n\n if self._margin_titles:\n\n # Remove any existing title texts\n for text in self._margin_titles_texts:\n text.remove()\n self._margin_titles_texts = []\n\n if self.row_names is not None:\n # Draw the row titles on the right edge of the grid\n for i, row_name in enumerate(self.row_names):\n ax = self.axes[i, -1]\n args.update(dict(row_name=row_name))\n title = row_template.format(**args)\n text = ax.annotate(\n title, xy=(1.02, .5), xycoords=\"axes fraction\",\n rotation=270, ha=\"left\", va=\"center\",\n **kwargs\n )\n self._margin_titles_texts.append(text)\n\n if self.col_names is not None:\n # Draw the column titles as normal titles\n for j, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = col_template.format(**args)\n self.axes[0, j].set_title(title, **kwargs)\n\n return self\n\n # Otherwise title each facet with all the necessary information\n if (self._row_var is not None) and (self._col_var is not None):\n for i, row_name in enumerate(self.row_names):\n for j, col_name in enumerate(self.col_names):\n args.update(dict(row_name=row_name, col_name=col_name))\n title = template.format(**args)\n self.axes[i, j].set_title(title, **kwargs)\n elif self.row_names is not None and len(self.row_names):\n for i, row_name in enumerate(self.row_names):\n args.update(dict(row_name=row_name))\n title = template.format(**args)\n self.axes[i, 0].set_title(title, **kwargs)\n elif self.col_names is not None and len(self.col_names):\n for i, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = template.format(**args)\n # Index the flat array so col_wrap works\n self.axes.flat[i].set_title(title, **kwargs)\n return self"},{"attributeType":"null","col":8,"comment":"null","endLoc":246,"id":785,"name":"bins","nodeType":"Attribute","startLoc":246,"text":"self.bins"},{"col":0,"comment":"Handle backwards compatability with setting matplotlib scale.","endLoc":127,"header":"def set_scale_obj(ax, axis, scale)","id":786,"name":"set_scale_obj","nodeType":"Function","startLoc":108,"text":"def set_scale_obj(ax, axis, scale):\n \"\"\"Handle backwards compatability with setting matplotlib scale.\"\"\"\n if Version(mpl.__version__) < Version(\"3.4\"):\n # The ability to pass a BaseScale instance to Axes.set_{}scale was added\n # to matplotlib in version 3.4.0: GH: matplotlib/matplotlib/pull/19089\n # Workaround: use the scale name, which is restrictive only if the user\n # wants to define a custom scale; they'll need to update the registry too.\n if scale.name is None:\n # Hack to support our custom Formatter-less CatScale\n return\n method = getattr(ax, f\"set_{axis}scale\")\n kws = {}\n if scale.name == \"function\":\n trans = scale.get_transform()\n kws[\"functions\"] = (trans._forward, trans._inverse)\n method(scale.name, **kws)\n axis_obj = getattr(ax, f\"{axis}axis\")\n scale.set_default_locators_and_formatters(axis_obj)\n else:\n ax.set(**{f\"{axis}scale\": scale})"},{"attributeType":"null","col":8,"comment":"null","endLoc":252,"id":787,"name":"bin_kws","nodeType":"Attribute","startLoc":252,"text":"self.bin_kws"},{"attributeType":"null","col":8,"comment":"null","endLoc":247,"id":788,"name":"binwidth","nodeType":"Attribute","startLoc":247,"text":"self.binwidth"},{"col":4,"comment":"null","endLoc":411,"header":"def _get_transform(self)","id":789,"name":"_get_transform","nodeType":"Function","startLoc":380,"text":"def _get_transform(self):\n\n arg = self.trans\n\n def get_param(method, default):\n if arg == method:\n return default\n return float(arg[len(method):])\n\n if arg is None:\n return _make_identity_transforms()\n elif isinstance(arg, tuple):\n return arg\n elif isinstance(arg, str):\n if arg == \"ln\":\n return _make_log_transforms()\n elif arg == \"logit\":\n base = get_param(\"logit\", 10)\n return _make_logit_transforms(base)\n elif arg.startswith(\"log\"):\n base = get_param(\"log\", 10)\n return _make_log_transforms(base)\n elif arg.startswith(\"symlog\"):\n c = get_param(\"symlog\", 1)\n return _make_symlog_transforms(c)\n elif arg.startswith(\"pow\"):\n exp = get_param(\"pow\", 2)\n return _make_power_transforms(exp)\n elif arg == \"sqrt\":\n return _make_sqrt_transforms()\n else:\n raise ValueError(f\"Unknown value provided for trans: {arg!r}\")"},{"attributeType":"null","col":8,"comment":"null","endLoc":248,"id":790,"name":"binrange","nodeType":"Attribute","startLoc":248,"text":"self.binrange"},{"col":0,"comment":"null","endLoc":891,"header":"def _make_identity_transforms() -> TransFuncs","id":791,"name":"_make_identity_transforms","nodeType":"Function","startLoc":886,"text":"def _make_identity_transforms() -> TransFuncs:\n\n def identity(x):\n return x\n\n return identity, identity"},{"col":0,"comment":"null","endLoc":931,"header":"def _make_log_transforms(base: float | None = None) -> TransFuncs","id":792,"name":"_make_log_transforms","nodeType":"Function","startLoc":909,"text":"def _make_log_transforms(base: float | None = None) -> TransFuncs:\n\n fs: TransFuncs\n if base is None:\n fs = np.log, np.exp\n elif base == 2:\n fs = np.log2, partial(np.power, 2)\n elif base == 10:\n fs = np.log10, partial(np.power, 10)\n else:\n def forward(x):\n return np.log(x) / np.log(base)\n fs = forward, partial(np.power, base)\n\n def log(x: ArrayLike) -> ArrayLike:\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return fs[0](x)\n\n def exp(x: ArrayLike) -> ArrayLike:\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return fs[1](x)\n\n return log, exp"},{"col":0,"comment":"Handle changes to matplotlib colormap interface in 3.6.","endLoc":144,"header":"def register_colormap(name, cmap)","id":793,"name":"register_colormap","nodeType":"Function","startLoc":138,"text":"def register_colormap(name, cmap):\n \"\"\"Handle changes to matplotlib colormap interface in 3.6.\"\"\"\n try:\n if name not in mpl.colormaps:\n mpl.colormaps.register(cmap, name=name)\n except AttributeError:\n mpl.cm.register_cmap(name, cmap)"},{"col":0,"comment":"Handle changes to auto layout engine interface in 3.6","endLoc":155,"header":"def set_layout_engine(fig, engine)","id":794,"name":"set_layout_engine","nodeType":"Function","startLoc":147,"text":"def set_layout_engine(fig, engine):\n \"\"\"Handle changes to auto layout engine interface in 3.6\"\"\"\n if hasattr(fig, \"set_layout_engine\"):\n fig.set_layout_engine(engine)\n else:\n if engine == \"tight\":\n fig.set_tight_layout(True)\n elif engine == \"constrained\":\n fig.set_constrained_layout(True)"},{"attributeType":"bool","col":8,"comment":"null","endLoc":250,"id":795,"name":"cumulative","nodeType":"Attribute","startLoc":250,"text":"self.cumulative"},{"col":0,"comment":"Handle changes to post-hoc axis sharing.","endLoc":164,"header":"def share_axis(ax0, ax1, which)","id":796,"name":"share_axis","nodeType":"Function","startLoc":158,"text":"def share_axis(ax0, ax1, which):\n \"\"\"Handle changes to post-hoc axis sharing.\"\"\"\n if Version(mpl.__version__) < Version(\"3.5.0\"):\n group = getattr(ax0, f\"get_shared_{which}_axes\")()\n group.join(ax1, ax0)\n else:\n getattr(ax1, f\"share{which}\")(ax0)"},{"attributeType":"null","col":4,"comment":"null","endLoc":32,"id":797,"name":"_no_scipy","nodeType":"Attribute","startLoc":32,"text":"_no_scipy"},{"className":"_DistributionPlotter","col":0,"comment":"null","endLoc":1362,"id":798,"nodeType":"Class","startLoc":100,"text":"class _DistributionPlotter(VectorPlotter):\n\n semantics = \"x\", \"y\", \"hue\", \"weights\"\n\n wide_structure = {\"x\": \"@values\", \"hue\": \"@columns\"}\n flat_structure = {\"x\": \"@values\"}\n\n def __init__(\n self,\n data=None,\n variables={},\n ):\n\n super().__init__(data=data, variables=variables)\n\n @property\n def univariate(self):\n \"\"\"Return True if only x or y are used.\"\"\"\n # TODO this could go down to core, but putting it here now.\n # We'd want to be conceptually clear that univariate only applies\n # to x/y and not to other semantics, which can exist.\n # We haven't settled on a good conceptual name for x/y.\n return bool({\"x\", \"y\"} - set(self.variables))\n\n @property\n def data_variable(self):\n \"\"\"Return the variable with data for univariate plots.\"\"\"\n # TODO This could also be in core, but it should have a better name.\n if not self.univariate:\n raise AttributeError(\"This is not a univariate plot\")\n return {\"x\", \"y\"}.intersection(self.variables).pop()\n\n @property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n # TODO see above points about where this should go\n return bool({\"x\", \"y\"} & set(self.variables))\n\n def _add_legend(\n self,\n ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,\n ):\n \"\"\"Add artists that reflect semantic mappings and put then in a legend.\"\"\"\n # TODO note that this doesn't handle numeric mappings like the relational plots\n handles = []\n labels = []\n for level in self._hue_map.levels:\n color = self._hue_map(level)\n\n kws = self._artist_kws(\n artist_kws, fill, element, multiple, color, alpha\n )\n\n # color gets added to the kws to workaround an issue with barplot's color\n # cycle integration but it causes problems in this context where we are\n # setting artist properties directly, so pop it off here\n if \"facecolor\" in kws:\n kws.pop(\"color\", None)\n\n handles.append(artist(**kws))\n labels.append(level)\n\n if isinstance(ax_obj, mpl.axes.Axes):\n ax_obj.legend(handles, labels, title=self.variables[\"hue\"], **legend_kws)\n else: # i.e. a FacetGrid. TODO make this better\n legend_data = dict(zip(labels, handles))\n ax_obj.add_legend(\n legend_data,\n title=self.variables[\"hue\"],\n label_order=self.var_levels[\"hue\"],\n **legend_kws\n )\n\n def _artist_kws(self, kws, fill, element, multiple, color, alpha):\n \"\"\"Handle differences between artists in filled/unfilled plots.\"\"\"\n kws = kws.copy()\n if fill:\n kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)\n kws.setdefault(\"facecolor\", to_rgba(color, alpha))\n\n if element == \"bars\":\n # Make bar() interface with property cycle correctly\n # https://github.com/matplotlib/matplotlib/issues/19385\n kws[\"color\"] = \"none\"\n\n if multiple in [\"stack\", \"fill\"] or element == \"bars\":\n kws.setdefault(\"edgecolor\", mpl.rcParams[\"patch.edgecolor\"])\n else:\n kws.setdefault(\"edgecolor\", to_rgba(color, 1))\n elif element == \"bars\":\n kws[\"facecolor\"] = \"none\"\n kws[\"edgecolor\"] = to_rgba(color, alpha)\n else:\n kws[\"color\"] = to_rgba(color, alpha)\n return kws\n\n def _quantile_to_level(self, data, quantile):\n \"\"\"Return data levels corresponding to quantile cuts of mass.\"\"\"\n isoprop = np.asarray(quantile)\n values = np.ravel(data)\n sorted_values = np.sort(values)[::-1]\n normalized_values = np.cumsum(sorted_values) / values.sum()\n idx = np.searchsorted(normalized_values, 1 - isoprop)\n levels = np.take(sorted_values, idx, mode=\"clip\")\n return levels\n\n def _cmap_from_color(self, color):\n \"\"\"Return a sequential colormap given a color seed.\"\"\"\n # Like so much else here, this is broadly useful, but keeping it\n # in this class to signify that I haven't thought overly hard about it...\n r, g, b, _ = to_rgba(color)\n h, s, _ = husl.rgb_to_husl(r, g, b)\n xx = np.linspace(-1, 1, int(1.15 * 256))[:256]\n ramp = np.zeros((256, 3))\n ramp[:, 0] = h\n ramp[:, 1] = s * np.cos(xx)\n ramp[:, 2] = np.linspace(35, 80, 256)\n colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1)\n return mpl.colors.ListedColormap(colors[::-1])\n\n def _default_discrete(self):\n \"\"\"Find default values for discrete hist estimation based on variable type.\"\"\"\n if self.univariate:\n discrete = self.var_types[self.data_variable] == \"categorical\"\n else:\n discrete_x = self.var_types[\"x\"] == \"categorical\"\n discrete_y = self.var_types[\"y\"] == \"categorical\"\n discrete = discrete_x, discrete_y\n return discrete\n\n def _resolve_multiple(self, curves, multiple):\n \"\"\"Modify the density data structure to handle multiple densities.\"\"\"\n\n # Default baselines have all densities starting at 0\n baselines = {k: np.zeros_like(v) for k, v in curves.items()}\n\n # TODO we should have some central clearinghouse for checking if any\n # \"grouping\" (terminnology?) semantics have been assigned\n if \"hue\" not in self.variables:\n return curves, baselines\n\n if multiple in (\"stack\", \"fill\"):\n\n # Setting stack or fill means that the curves share a\n # support grid / set of bin edges, so we can make a dataframe\n # Reverse the column order to plot from top to bottom\n curves = pd.DataFrame(curves).iloc[:, ::-1]\n\n # Find column groups that are nested within col/row variables\n column_groups = {}\n for i, keyd in enumerate(map(dict, curves.columns)):\n facet_key = keyd.get(\"col\", None), keyd.get(\"row\", None)\n column_groups.setdefault(facet_key, [])\n column_groups[facet_key].append(i)\n\n baselines = curves.copy()\n for col_idxs in column_groups.values():\n cols = curves.columns[col_idxs]\n\n norm_constant = curves[cols].sum(axis=\"columns\")\n\n # Take the cumulative sum to stack\n curves[cols] = curves[cols].cumsum(axis=\"columns\")\n\n # Normalize by row sum to fill\n if multiple == \"fill\":\n curves[cols] = curves[cols].div(norm_constant, axis=\"index\")\n\n # Define where each segment starts\n baselines[cols] = curves[cols].shift(1, axis=1).fillna(0)\n\n if multiple == \"dodge\":\n\n # Account for the unique semantic (non-faceting) levels\n # This will require rethiniking if we add other semantics!\n hue_levels = self.var_levels[\"hue\"]\n n = len(hue_levels)\n for key in curves:\n level = dict(key)[\"hue\"]\n hist = curves[key].reset_index(name=\"heights\")\n level_idx = hue_levels.index(level)\n if self._log_scaled(self.data_variable):\n log_min = np.log10(hist[\"edges\"])\n log_max = np.log10(hist[\"edges\"] + hist[\"widths\"])\n log_width = (log_max - log_min) / n\n new_min = np.power(10, log_min + level_idx * log_width)\n new_max = np.power(10, log_min + (level_idx + 1) * log_width)\n hist[\"widths\"] = new_max - new_min\n hist[\"edges\"] = new_min\n else:\n hist[\"widths\"] /= n\n hist[\"edges\"] += level_idx * hist[\"widths\"]\n\n curves[key] = hist.set_index([\"edges\", \"widths\"])[\"heights\"]\n\n return curves, baselines\n\n # -------------------------------------------------------------------------------- #\n # Computation\n # -------------------------------------------------------------------------------- #\n\n def _compute_univariate_density(\n self,\n data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular=True,\n ):\n\n # Initialize the estimator object\n estimator = KDE(**estimate_kws)\n\n if set(self.variables) - {\"x\", \"y\"}:\n if common_grid:\n all_observations = self.comp_data.dropna()\n estimator.define_support(all_observations[data_variable])\n else:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n if common_norm and \"weights\" in all_data:\n whole_weight = all_data[\"weights\"].sum()\n else:\n whole_weight = len(all_data)\n\n densities = {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set and remove nulls\n observations = sub_data[data_variable]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n part_weight = weights.sum()\n else:\n weights = None\n part_weight = len(sub_data)\n\n # Estimate the density of observations at this level\n variance = np.nan_to_num(observations.var())\n singular = len(observations) < 2 or math.isclose(variance, 0)\n try:\n if not singular:\n # Convoluted approach needed because numerical failures\n # can manifest in a few different ways.\n density, support = estimator(observations, weights=weights)\n except np.linalg.LinAlgError:\n singular = True\n\n if singular:\n msg = (\n \"Dataset has 0 variance; skipping density estimate. \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning, stacklevel=4)\n continue\n\n if log_scale:\n support = np.power(10, support)\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= part_weight / whole_weight\n\n # Store the density for this level\n key = tuple(sub_vars.items())\n densities[key] = pd.Series(density, index=support)\n\n return densities\n\n # -------------------------------------------------------------------------------- #\n # Plotting\n # -------------------------------------------------------------------------------- #\n\n def plot_univariate_histogram(\n self,\n multiple,\n element,\n fill,\n common_norm,\n common_bins,\n shrink,\n kde,\n kde_kws,\n color,\n legend,\n line_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # -- Default keyword dicts\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n estimate_kws = {} if estimate_kws is None else estimate_kws.copy()\n\n # -- Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\", \"dodge\"], multiple)\n _check_argument(\"element\", [\"bars\", \"step\", \"poly\"], element)\n\n auto_bins_with_weights = (\n \"weights\" in self.variables\n and estimate_kws[\"bins\"] == \"auto\"\n and estimate_kws[\"binwidth\"] is None\n and not estimate_kws[\"discrete\"]\n )\n if auto_bins_with_weights:\n msg = (\n \"`bins` cannot be 'auto' when using weights. \"\n \"Setting `bins=10`, but you will likely want to adjust.\"\n )\n warnings.warn(msg, UserWarning)\n estimate_kws[\"bins\"] = 10\n\n # Simplify downstream code if we are not normalizing\n if estimate_kws[\"stat\"] == \"count\":\n common_norm = False\n\n orient = self.data_variable\n\n # Now initialize the Histogram estimator\n estimator = Hist(**estimate_kws)\n histograms = {}\n\n # Do pre-compute housekeeping related to multiple groups\n all_data = self.comp_data.dropna()\n all_weights = all_data.get(\"weights\", None)\n\n multiple_histograms = set(self.variables) - {\"x\", \"y\"}\n if multiple_histograms:\n if common_bins:\n bin_kws = estimator._define_bin_params(all_data, orient, None)\n else:\n common_norm = False\n\n if common_norm and all_weights is not None:\n whole_weight = all_weights.sum()\n else:\n whole_weight = len(all_data)\n\n # Estimate the smoothed kernel densities, for use later\n if kde:\n # TODO alternatively, clip at min/max bins?\n kde_kws.setdefault(\"cut\", 0)\n kde_kws[\"cumulative\"] = estimate_kws[\"cumulative\"]\n log_scale = self._log_scaled(self.data_variable)\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_bins,\n kde_kws,\n log_scale,\n warn_singular=False,\n )\n\n # First pass through the data to compute the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Prepare the relevant data\n key = tuple(sub_vars.items())\n orient = self.data_variable\n\n if \"weights\" in self.variables:\n sub_data[\"weight\"] = sub_data.pop(\"weights\")\n part_weight = sub_data[\"weight\"].sum()\n else:\n part_weight = len(sub_data)\n\n # Do the histogram computation\n if not (multiple_histograms and common_bins):\n bin_kws = estimator._define_bin_params(sub_data, orient, None)\n res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws))\n heights = res[estimator.stat].to_numpy()\n widths = res[\"space\"].to_numpy()\n edges = res[orient].to_numpy() - widths / 2\n\n # Convert edges back to original units for plotting\n if self._log_scaled(self.data_variable):\n widths = np.power(10, edges + widths) - np.power(10, edges)\n edges = np.power(10, edges)\n\n # Rescale the smoothed curve to match the histogram\n if kde and key in densities:\n density = densities[key]\n if estimator.cumulative:\n hist_norm = heights.max()\n else:\n hist_norm = (heights * widths).sum()\n densities[key] *= hist_norm\n\n # Pack the histogram data and metadata together\n edges = edges + (1 - shrink) / 2 * widths\n widths *= shrink\n index = pd.MultiIndex.from_arrays([\n pd.Index(edges, name=\"edges\"),\n pd.Index(widths, name=\"widths\"),\n ])\n hist = pd.Series(heights, index=index, name=\"heights\")\n\n # Apply scaling to normalize across groups\n if common_norm:\n hist *= part_weight / whole_weight\n\n # Store the finalized histogram data for future plotting\n histograms[key] = hist\n\n # Modify the histogram and density data to resolve multiple groups\n histograms, baselines = self._resolve_multiple(histograms, multiple)\n if kde:\n densities, _ = self._resolve_multiple(\n densities, None if multiple == \"dodge\" else multiple\n )\n\n # Set autoscaling-related meta\n sticky_stat = (0, 1) if multiple == \"fill\" else (0, np.inf)\n if multiple == \"fill\":\n # Filled plots should not have any margins\n bin_vals = histograms.index.to_frame()\n edges = bin_vals[\"edges\"]\n widths = bin_vals[\"widths\"]\n sticky_data = (\n edges.min(),\n edges.max() + widths.loc[edges.idxmax()]\n )\n else:\n sticky_data = []\n\n # --- Handle default visual attributes\n\n # Note: default linewidth is determined after plotting\n\n # Default alpha should depend on other parameters\n if fill:\n # Note: will need to account for other grouping semantics if added\n if \"hue\" in self.variables and multiple == \"layer\":\n default_alpha = .5 if element == \"bars\" else .25\n elif kde:\n default_alpha = .5\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n hist_artists = []\n\n # Go back through the dataset and draw the plots\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n key = tuple(sub_vars.items())\n hist = histograms[key].rename(\"heights\").reset_index()\n bottom = np.asarray(baselines[key])\n\n ax = self._get_axes(sub_vars)\n\n # Define the matplotlib attributes that depend on semantic mapping\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, element, multiple, sub_color, alpha\n )\n\n if element == \"bars\":\n\n # Use matplotlib bar plotting\n\n plot_func = ax.bar if self.data_variable == \"x\" else ax.barh\n artists = plot_func(\n hist[\"edges\"],\n hist[\"heights\"] - bottom,\n hist[\"widths\"],\n bottom,\n align=\"edge\",\n **artist_kws,\n )\n\n for bar in artists:\n if self.data_variable == \"x\":\n bar.sticky_edges.x[:] = sticky_data\n bar.sticky_edges.y[:] = sticky_stat\n else:\n bar.sticky_edges.x[:] = sticky_stat\n bar.sticky_edges.y[:] = sticky_data\n\n hist_artists.extend(artists)\n\n else:\n\n # Use either fill_between or plot to draw hull of histogram\n if element == \"step\":\n\n final = hist.iloc[-1]\n x = np.append(hist[\"edges\"], final[\"edges\"] + final[\"widths\"])\n y = np.append(hist[\"heights\"], final[\"heights\"])\n b = np.append(bottom, bottom[-1])\n\n if self.data_variable == \"x\":\n step = \"post\"\n drawstyle = \"steps-post\"\n else:\n step = \"post\" # fillbetweenx handles mapping internally\n drawstyle = \"steps-pre\"\n\n elif element == \"poly\":\n\n x = hist[\"edges\"] + hist[\"widths\"] / 2\n y = hist[\"heights\"]\n b = bottom\n\n step = None\n drawstyle = None\n\n if self.data_variable == \"x\":\n if fill:\n artist = ax.fill_between(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_data\n artist.sticky_edges.y[:] = sticky_stat\n else:\n if fill:\n artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_stat\n artist.sticky_edges.y[:] = sticky_data\n\n hist_artists.append(artist)\n\n if kde:\n\n # Add in the density curves\n\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n\n if \"x\" in self.variables:\n line_args = support, density\n sticky_x, sticky_y = None, (0, np.inf)\n else:\n line_args = density, support\n sticky_x, sticky_y = (0, np.inf), None\n\n line_kws[\"color\"] = to_rgba(sub_color, 1)\n line, = ax.plot(\n *line_args, **line_kws,\n )\n\n if sticky_x is not None:\n line.sticky_edges.x[:] = sticky_x\n if sticky_y is not None:\n line.sticky_edges.y[:] = sticky_y\n\n if element == \"bars\" and \"linewidth\" not in plot_kws:\n\n # Now we handle linewidth, which depends on the scaling of the plot\n\n # We will base everything on the minimum bin width\n hist_metadata = pd.concat([\n # Use .items for generality over dict or df\n h.index.to_frame() for _, h in histograms.items()\n ]).reset_index(drop=True)\n thin_bar_idx = hist_metadata[\"widths\"].idxmin()\n binwidth = hist_metadata.loc[thin_bar_idx, \"widths\"]\n left_edge = hist_metadata.loc[thin_bar_idx, \"edges\"]\n\n # Set initial value\n default_linewidth = math.inf\n\n # Loop through subsets based only on facet variables\n for sub_vars, _ in self.iter_data():\n\n ax = self._get_axes(sub_vars)\n\n # Needed in some cases to get valid transforms.\n # Innocuous in other cases?\n ax.autoscale_view()\n\n # Convert binwidth from data coordinates to pixels\n pts_x, pts_y = 72 / ax.figure.dpi * abs(\n ax.transData.transform([left_edge + binwidth] * 2)\n - ax.transData.transform([left_edge] * 2)\n )\n if self.data_variable == \"x\":\n binwidth_points = pts_x\n else:\n binwidth_points = pts_y\n\n # The relative size of the lines depends on the appearance\n # This is a provisional value and may need more tweaking\n default_linewidth = min(.1 * binwidth_points, default_linewidth)\n\n # Set the attributes\n for bar in hist_artists:\n\n # Don't let the lines get too thick\n max_linewidth = bar.get_linewidth()\n if not fill:\n max_linewidth *= 1.5\n\n linewidth = min(default_linewidth, max_linewidth)\n\n # If not filling, don't let lines disappear\n if not fill:\n min_linewidth = .5\n linewidth = max(linewidth, min_linewidth)\n\n bar.set_linewidth(linewidth)\n\n # --- Finalize the plot ----\n\n # Axis labels\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = estimator.stat.capitalize()\n if self.data_variable == \"y\":\n default_x = estimator.stat.capitalize()\n self._add_axis_labels(ax, default_x, default_y)\n\n # Legend for semantic variables\n if \"hue\" in self.variables and legend:\n\n if fill or element == \"bars\":\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, element, multiple, alpha, plot_kws, {},\n )\n\n def plot_bivariate_histogram(\n self,\n common_bins, common_norm,\n thresh, pthresh, pmax,\n color, legend,\n cbar, cbar_ax, cbar_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # Default keyword dicts\n cbar_kws = {} if cbar_kws is None else cbar_kws.copy()\n\n # Now initialize the Histogram estimator\n estimator = Histogram(**estimate_kws)\n\n # Do pre-compute housekeeping related to multiple groups\n if set(self.variables) - {\"x\", \"y\"}:\n all_data = self.comp_data.dropna()\n if common_bins:\n estimator.define_bin_params(\n all_data[\"x\"],\n all_data[\"y\"],\n all_data.get(\"weights\", None),\n )\n else:\n common_norm = False\n\n # -- Determine colormap threshold and norm based on the full data\n\n full_heights = []\n for _, sub_data in self.iter_data(from_comp_data=True):\n sub_heights, _ = estimator(\n sub_data[\"x\"], sub_data[\"y\"], sub_data.get(\"weights\", None)\n )\n full_heights.append(sub_heights)\n\n common_color_norm = not set(self.variables) - {\"x\", \"y\"} or common_norm\n\n if pthresh is not None and common_color_norm:\n thresh = self._quantile_to_level(full_heights, pthresh)\n\n plot_kws.setdefault(\"vmin\", 0)\n if common_color_norm:\n if pmax is not None:\n vmax = self._quantile_to_level(full_heights, pmax)\n else:\n vmax = plot_kws.pop(\"vmax\", max(map(np.max, full_heights)))\n else:\n vmax = None\n\n # Get a default color\n # (We won't follow the color cycle here, as multiple plots are unlikely)\n if color is None:\n color = \"C0\"\n\n # --- Loop over data (subsets) and draw the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n if sub_data.empty:\n continue\n\n # Do the histogram computation\n heights, (x_edges, y_edges) = estimator(\n sub_data[\"x\"],\n sub_data[\"y\"],\n weights=sub_data.get(\"weights\", None),\n )\n\n # Check for log scaling on the data axis\n if self._log_scaled(\"x\"):\n x_edges = np.power(10, x_edges)\n if self._log_scaled(\"y\"):\n y_edges = np.power(10, y_edges)\n\n # Apply scaling to normalize across groups\n if estimator.stat != \"count\" and common_norm:\n heights *= len(sub_data) / len(all_data)\n\n # Define the specific kwargs for this artist\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n color = self._hue_map(sub_vars[\"hue\"])\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n else:\n cmap = artist_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n elif cmap is None:\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n\n # Set the upper norm on the colormap\n if not common_color_norm and pmax is not None:\n vmax = self._quantile_to_level(heights, pmax)\n if vmax is not None:\n artist_kws[\"vmax\"] = vmax\n\n # Make cells at or below the threshold transparent\n if not common_color_norm and pthresh:\n thresh = self._quantile_to_level(heights, pthresh)\n if thresh is not None:\n heights = np.ma.masked_less_equal(heights, thresh)\n\n # Get the axes for this plot\n ax = self._get_axes(sub_vars)\n\n # pcolormesh is going to turn the grid off, but we want to keep it\n # I'm not sure if there's a better way to get the grid state\n x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()])\n y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()])\n\n mesh = ax.pcolormesh(\n x_edges,\n y_edges,\n heights.T,\n **artist_kws,\n )\n\n # pcolormesh sets sticky edges, but we only want them if not thresholding\n if thresh is not None:\n mesh.sticky_edges.x[:] = []\n mesh.sticky_edges.y[:] = []\n\n # Add an optional colorbar\n # Note, we want to improve this. When hue is used, it will stack\n # multiple colorbars with redundant ticks in an ugly way.\n # But it's going to take some work to have multiple colorbars that\n # share ticks nicely.\n if cbar:\n ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws)\n\n # Reset the grid state\n if x_grid:\n ax.grid(True, axis=\"x\")\n if y_grid:\n ax.grid(True, axis=\"y\")\n\n # --- Finalize the plot\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n artist = partial(mpl.patches.Patch)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, True, False, \"layer\", 1, artist_kws, {},\n )\n\n def plot_univariate_density(\n self,\n multiple,\n common_norm,\n common_grid,\n warn_singular,\n fill,\n color,\n legend,\n estimate_kws,\n **plot_kws,\n ):\n\n # Handle conditional defaults\n if fill is None:\n fill = multiple in (\"stack\", \"fill\")\n\n # Preprocess the matplotlib keyword dictionaries\n if fill:\n artist = mpl.collections.PolyCollection\n else:\n artist = mpl.lines.Line2D\n plot_kws = _normalize_kwargs(plot_kws, artist)\n\n # Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\"], multiple)\n\n # Always share the evaluation grid when stacking\n subsets = bool(set(self.variables) - {\"x\", \"y\"})\n if subsets and multiple in (\"stack\", \"fill\"):\n common_grid = True\n\n # Check if the data axis is log scaled\n log_scale = self._log_scaled(self.data_variable)\n\n # Do the computation\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular,\n )\n\n # Adjust densities based on the `multiple` rule\n densities, baselines = self._resolve_multiple(densities, multiple)\n\n # Control the interaction with autoscaling by defining sticky_edges\n # i.e. we don't want autoscale margins below the density curve\n sticky_density = (0, 1) if multiple == \"fill\" else (0, np.inf)\n\n if multiple == \"fill\":\n # Filled plots should not have any margins\n sticky_support = densities.index.min(), densities.index.max()\n else:\n sticky_support = []\n\n if fill:\n if multiple == \"layer\":\n default_alpha = .25\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n # Now iterate through the subsets and draw the densities\n # We go backwards so stacked densities read from top-to-bottom\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n # Extract the support grid and density curve for this level\n key = tuple(sub_vars.items())\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n fill_from = baselines[key]\n\n ax = self._get_axes(sub_vars)\n\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, False, multiple, sub_color, alpha\n )\n\n # Either plot a curve with observation values on the x axis\n if \"x\" in self.variables:\n\n if fill:\n artist = ax.fill_between(support, fill_from, density, **artist_kws)\n\n else:\n artist, = ax.plot(support, density, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_support\n artist.sticky_edges.y[:] = sticky_density\n\n # Or plot a curve with observation values on the y axis\n else:\n if fill:\n artist = ax.fill_betweenx(support, fill_from, density, **artist_kws)\n else:\n artist, = ax.plot(density, support, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_density\n artist.sticky_edges.y[:] = sticky_support\n\n # --- Finalize the plot ----\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = \"Density\"\n if self.data_variable == \"y\":\n default_x = \"Density\"\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, multiple, alpha, plot_kws, {},\n )\n\n def plot_bivariate_density(\n self,\n common_norm,\n fill,\n levels,\n thresh,\n color,\n legend,\n cbar,\n warn_singular,\n cbar_ax,\n cbar_kws,\n estimate_kws,\n **contour_kws,\n ):\n\n contour_kws = contour_kws.copy()\n\n estimator = KDE(**estimate_kws)\n\n if not set(self.variables) - {\"x\", \"y\"}:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n\n # Loop through the subsets and estimate the KDEs\n densities, supports = {}, {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set\n observations = sub_data[[\"x\", \"y\"]]\n min_variance = observations.var().fillna(0).min()\n observations = observations[\"x\"], observations[\"y\"]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n else:\n weights = None\n\n # Estimate the density of observations at this level\n singular = math.isclose(min_variance, 0)\n try:\n if not singular:\n density, support = estimator(*observations, weights=weights)\n except np.linalg.LinAlgError:\n # Testing for 0 variance doesn't catch all cases where scipy raises,\n # but we can also get a ValueError, so we need this convoluted approach\n singular = True\n\n if singular:\n msg = (\n \"KDE cannot be estimated (0 variance or perfect covariance). \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning, stacklevel=3)\n continue\n\n # Transform the support grid back to the original scale\n xx, yy = support\n if self._log_scaled(\"x\"):\n xx = np.power(10, xx)\n if self._log_scaled(\"y\"):\n yy = np.power(10, yy)\n support = xx, yy\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= len(sub_data) / len(all_data)\n\n key = tuple(sub_vars.items())\n densities[key] = density\n supports[key] = support\n\n # Define a grid of iso-proportion levels\n if thresh is None:\n thresh = 0\n if isinstance(levels, Number):\n levels = np.linspace(thresh, 1, levels)\n else:\n if min(levels) < 0 or max(levels) > 1:\n raise ValueError(\"levels must be in [0, 1]\")\n\n # Transform from iso-proportions to iso-densities\n if common_norm:\n common_levels = self._quantile_to_level(\n list(densities.values()), levels,\n )\n draw_levels = {k: common_levels for k in densities}\n else:\n draw_levels = {\n k: self._quantile_to_level(d, levels)\n for k, d in densities.items()\n }\n\n # Define the coloring of the contours\n if \"hue\" in self.variables:\n for param in [\"cmap\", \"colors\"]:\n if param in contour_kws:\n msg = f\"{param} parameter ignored when using hue mapping.\"\n warnings.warn(msg, UserWarning)\n contour_kws.pop(param)\n else:\n\n # Work out a default coloring of the contours\n coloring_given = set(contour_kws) & {\"cmap\", \"colors\"}\n if fill and not coloring_given:\n cmap = self._cmap_from_color(color)\n contour_kws[\"cmap\"] = cmap\n if not fill and not coloring_given:\n contour_kws[\"colors\"] = [color]\n\n # Use our internal colormap lookup\n cmap = contour_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n if cmap is not None:\n contour_kws[\"cmap\"] = cmap\n\n # Loop through the subsets again and plot the data\n for sub_vars, _ in self.iter_data(\"hue\"):\n\n if \"hue\" in sub_vars:\n color = self._hue_map(sub_vars[\"hue\"])\n if fill:\n contour_kws[\"cmap\"] = self._cmap_from_color(color)\n else:\n contour_kws[\"colors\"] = [color]\n\n ax = self._get_axes(sub_vars)\n\n # Choose the function to plot with\n # TODO could add a pcolormesh based option as well\n # Which would look something like element=\"raster\"\n if fill:\n contour_func = ax.contourf\n else:\n contour_func = ax.contour\n\n key = tuple(sub_vars.items())\n if key not in densities:\n continue\n density = densities[key]\n xx, yy = supports[key]\n\n label = contour_kws.pop(\"label\", None)\n\n cset = contour_func(\n xx, yy, density,\n levels=draw_levels[key],\n **contour_kws,\n )\n\n if \"hue\" not in self.variables:\n cset.collections[0].set_label(label)\n\n # Add a color bar representing the contour heights\n # Note: this shows iso densities, not iso proportions\n # See more notes in histplot about how this could be improved\n if cbar:\n cbar_kws = {} if cbar_kws is None else cbar_kws\n ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)\n\n # --- Finalize the plot\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, \"layer\", 1, artist_kws, {},\n )\n\n def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws):\n\n estimator = ECDF(**estimate_kws)\n\n # Set the draw style to step the right way for the data variable\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n plot_kws[\"drawstyle\"] = drawstyles[self.data_variable]\n\n # Loop through the subsets, transform and plot the data\n for sub_vars, sub_data in self.iter_data(\n \"hue\", reverse=True, from_comp_data=True,\n ):\n\n # Compute the ECDF\n if sub_data.empty:\n continue\n\n observations = sub_data[self.data_variable]\n weights = sub_data.get(\"weights\", None)\n stat, vals = estimator(observations, weights=weights)\n\n # Assign attributes based on semantic mapping\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n artist_kws[\"color\"] = self._hue_map(sub_vars[\"hue\"])\n\n # Return the data variable to the linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(self.data_variable):\n vals = np.power(10, vals)\n vals[0] = -np.inf\n\n # Work out the orientation of the plot\n if self.data_variable == \"x\":\n plot_args = vals, stat\n stat_variable = \"y\"\n else:\n plot_args = stat, vals\n stat_variable = \"x\"\n\n if estimator.stat == \"count\":\n top_edge = len(observations)\n else:\n top_edge = 1\n\n # Draw the line for this subset\n ax = self._get_axes(sub_vars)\n artist, = ax.plot(*plot_args, **artist_kws)\n sticky_edges = getattr(artist.sticky_edges, stat_variable)\n sticky_edges[:] = 0, top_edge\n\n # --- Finalize the plot ----\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n stat = estimator.stat.capitalize()\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = stat\n if self.data_variable == \"y\":\n default_x = stat\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n artist = partial(mpl.lines.Line2D, [], [])\n alpha = plot_kws.get(\"alpha\", 1)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, False, False, None, alpha, plot_kws, {},\n )\n\n def plot_rug(self, height, expand_margins, legend, **kws):\n\n for sub_vars, sub_data, in self.iter_data(from_comp_data=True):\n\n ax = self._get_axes(sub_vars)\n\n kws.setdefault(\"linewidth\", 1)\n\n if expand_margins:\n xmarg, ymarg = ax.margins()\n if \"x\" in self.variables:\n ymarg += height * 2\n if \"y\" in self.variables:\n xmarg += height * 2\n ax.margins(x=xmarg, y=ymarg)\n\n if \"hue\" in self.variables:\n kws.pop(\"c\", None)\n kws.pop(\"color\", None)\n\n if \"x\" in self.variables:\n self._plot_single_rug(sub_data, \"x\", height, ax, kws)\n if \"y\" in self.variables:\n self._plot_single_rug(sub_data, \"y\", height, ax, kws)\n\n # --- Finalize the plot\n self._add_axis_labels(ax)\n if \"hue\" in self.variables and legend:\n # TODO ideally i'd like the legend artist to look like a rug\n legend_artist = partial(mpl.lines.Line2D, [], [])\n self._add_legend(\n ax, legend_artist, False, False, None, 1, {}, {},\n )\n\n def _plot_single_rug(self, sub_data, var, height, ax, kws):\n \"\"\"Draw a rugplot along one axis of the plot.\"\"\"\n vector = sub_data[var]\n n = len(vector)\n\n # Return data to linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(var):\n vector = np.power(10, vector)\n\n # We'll always add a single collection with varying colors\n if \"hue\" in self.variables:\n colors = self._hue_map(sub_data[\"hue\"])\n else:\n colors = None\n\n # Build the array of values for the LineCollection\n if var == \"x\":\n\n trans = tx.blended_transform_factory(ax.transData, ax.transAxes)\n xy_pairs = np.column_stack([\n np.repeat(vector, 2), np.tile([0, height], n)\n ])\n\n if var == \"y\":\n\n trans = tx.blended_transform_factory(ax.transAxes, ax.transData)\n xy_pairs = np.column_stack([\n np.tile([0, height], n), np.repeat(vector, 2)\n ])\n\n # Draw the lines on the plot\n line_segs = xy_pairs.reshape([n, 2, 2])\n ax.add_collection(LineCollection(\n line_segs, transform=trans, colors=colors, **kws\n ))\n\n ax.autoscale_view(scalex=var == \"x\", scaley=var == \"y\")"},{"className":"VectorPlotter","col":0,"comment":"Base class for objects underlying *plot functions.","endLoc":1450,"id":799,"nodeType":"Class","startLoc":613,"text":"class VectorPlotter:\n \"\"\"Base class for objects underlying *plot functions.\"\"\"\n\n _semantic_mappings = {\n \"hue\": HueMapping,\n \"size\": SizeMapping,\n \"style\": StyleMapping,\n }\n\n # TODO units is another example of a non-mapping \"semantic\"\n # we need a general name for this and separate handling\n semantics = \"x\", \"y\", \"hue\", \"size\", \"style\", \"units\"\n wide_structure = {\n \"x\": \"@index\", \"y\": \"@values\", \"hue\": \"@columns\", \"style\": \"@columns\",\n }\n flat_structure = {\"x\": \"@index\", \"y\": \"@values\"}\n\n _default_size_range = 1, 2 # Unused but needed in tests, ugh\n\n def __init__(self, data=None, variables={}):\n\n self._var_levels = {}\n # var_ordered is relevant only for categorical axis variables, and may\n # be better handled by an internal axis information object that tracks\n # such information and is set up by the scale_* methods. The analogous\n # information for numeric axes would be information about log scales.\n self._var_ordered = {\"x\": False, \"y\": False} # alt., used DefaultDict\n self.assign_variables(data, variables)\n\n for var, cls in self._semantic_mappings.items():\n\n # Create the mapping function\n map_func = partial(cls.map, plotter=self)\n setattr(self, f\"map_{var}\", map_func)\n\n # Call the mapping function to initialize with default values\n getattr(self, f\"map_{var}\")()\n\n @classmethod\n def get_semantics(cls, kwargs, semantics=None):\n \"\"\"Subset a dictionary arguments with known semantic variables.\"\"\"\n # TODO this should be get_variables since we have included x and y\n if semantics is None:\n semantics = cls.semantics\n variables = {}\n for key, val in kwargs.items():\n if key in semantics and val is not None:\n variables[key] = val\n return variables\n\n @property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n return bool({\"x\", \"y\"} & set(self.variables))\n\n @property\n def var_levels(self):\n \"\"\"Property interface to ordered list of variables levels.\n\n Each time it's accessed, it updates the var_levels dictionary with the\n list of levels in the current semantic mappers. But it also allows the\n dictionary to persist, so it can be used to set levels by a key. This is\n used to track the list of col/row levels using an attached FacetGrid\n object, but it's kind of messy and ideally fixed by improving the\n faceting logic so it interfaces better with the modern approach to\n tracking plot variables.\n\n \"\"\"\n for var in self.variables:\n try:\n map_obj = getattr(self, f\"_{var}_map\")\n self._var_levels[var] = map_obj.levels\n except AttributeError:\n pass\n return self._var_levels\n\n def assign_variables(self, data=None, variables={}):\n \"\"\"Define plot variables, optionally using lookup from `data`.\"\"\"\n x = variables.get(\"x\", None)\n y = variables.get(\"y\", None)\n\n if x is None and y is None:\n self.input_format = \"wide\"\n plot_data, variables = self._assign_variables_wideform(\n data, **variables,\n )\n else:\n self.input_format = \"long\"\n plot_data, variables = self._assign_variables_longform(\n data, **variables,\n )\n\n self.plot_data = plot_data\n self.variables = variables\n self.var_types = {\n v: variable_type(\n plot_data[v],\n boolean_type=\"numeric\" if v in \"xy\" else \"categorical\"\n )\n for v in variables\n }\n\n return self\n\n def _assign_variables_wideform(self, data=None, **kwargs):\n \"\"\"Define plot variables given wide-form data.\n\n Parameters\n ----------\n data : flat vector or collection of vectors\n Data can be a vector or mapping that is coerceable to a Series\n or a sequence- or mapping-based collection of such vectors, or a\n rectangular numpy array, or a Pandas DataFrame.\n kwargs : variable -> data mappings\n Behavior with keyword arguments is currently undefined.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n \"\"\"\n # Raise if semantic or other variables are assigned in wide-form mode\n assigned = [k for k, v in kwargs.items() if v is not None]\n if any(assigned):\n s = \"s\" if len(assigned) > 1 else \"\"\n err = f\"The following variable{s} cannot be assigned with wide-form data: \"\n err += \", \".join(f\"`{v}`\" for v in assigned)\n raise ValueError(err)\n\n # Determine if the data object actually has any data in it\n empty = data is None or not len(data)\n\n # Then, determine if we have \"flat\" data (a single vector)\n if isinstance(data, dict):\n values = data.values()\n else:\n values = np.atleast_1d(np.asarray(data, dtype=object))\n flat = not any(\n isinstance(v, Iterable) and not isinstance(v, (str, bytes))\n for v in values\n )\n\n if empty:\n\n # Make an object with the structure of plot_data, but empty\n plot_data = pd.DataFrame()\n variables = {}\n\n elif flat:\n\n # Handle flat data by converting to pandas Series and using the\n # index and/or values to define x and/or y\n # (Could be accomplished with a more general to_series() interface)\n flat_data = pd.Series(data).copy()\n names = {\n \"@values\": flat_data.name,\n \"@index\": flat_data.index.name\n }\n\n plot_data = {}\n variables = {}\n\n for var in [\"x\", \"y\"]:\n if var in self.flat_structure:\n attr = self.flat_structure[var]\n plot_data[var] = getattr(flat_data, attr[1:])\n variables[var] = names[self.flat_structure[var]]\n\n plot_data = pd.DataFrame(plot_data)\n\n else:\n\n # Otherwise assume we have some collection of vectors.\n\n # Handle Python sequences such that entries end up in the columns,\n # not in the rows, of the intermediate wide DataFrame.\n # One way to accomplish this is to convert to a dict of Series.\n if isinstance(data, Sequence):\n data_dict = {}\n for i, var in enumerate(data):\n key = getattr(var, \"name\", i)\n # TODO is there a safer/more generic way to ensure Series?\n # sort of like np.asarray, but for pandas?\n data_dict[key] = pd.Series(var)\n\n data = data_dict\n\n # Pandas requires that dict values either be Series objects\n # or all have the same length, but we want to allow \"ragged\" inputs\n if isinstance(data, Mapping):\n data = {key: pd.Series(val) for key, val in data.items()}\n\n # Otherwise, delegate to the pandas DataFrame constructor\n # This is where we'd prefer to use a general interface that says\n # \"give me this data as a pandas DataFrame\", so we can accept\n # DataFrame objects from other libraries\n wide_data = pd.DataFrame(data, copy=True)\n\n # At this point we should reduce the dataframe to numeric cols\n numeric_cols = [\n k for k, v in wide_data.items() if variable_type(v) == \"numeric\"\n ]\n wide_data = wide_data[numeric_cols]\n\n # Now melt the data to long form\n melt_kws = {\"var_name\": \"@columns\", \"value_name\": \"@values\"}\n use_index = \"@index\" in self.wide_structure.values()\n if use_index:\n melt_kws[\"id_vars\"] = \"@index\"\n try:\n orig_categories = wide_data.columns.categories\n orig_ordered = wide_data.columns.ordered\n wide_data.columns = wide_data.columns.add_categories(\"@index\")\n except AttributeError:\n category_columns = False\n else:\n category_columns = True\n wide_data[\"@index\"] = wide_data.index.to_series()\n\n plot_data = wide_data.melt(**melt_kws)\n\n if use_index and category_columns:\n plot_data[\"@columns\"] = pd.Categorical(plot_data[\"@columns\"],\n orig_categories,\n orig_ordered)\n\n # Assign names corresponding to plot semantics\n for var, attr in self.wide_structure.items():\n plot_data[var] = plot_data[attr]\n\n # Define the variable names\n variables = {}\n for var, attr in self.wide_structure.items():\n obj = getattr(wide_data, attr[1:])\n variables[var] = getattr(obj, \"name\", None)\n\n # Remove redundant columns from plot_data\n plot_data = plot_data[list(variables)]\n\n return plot_data, variables\n\n def _assign_variables_longform(self, data=None, **kwargs):\n \"\"\"Define plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data : dict-like collection of vectors\n Input data where variable names map to vector values.\n kwargs : variable -> data mappings\n Keys are seaborn variables (x, y, hue, ...) and values are vectors\n in any format that can construct a :class:`pandas.DataFrame` or\n names of columns or index levels in ``data``.\n\n Returns\n -------\n plot_data : :class:`pandas.DataFrame`\n Long-form data object mapping seaborn variables (x, y, hue, ...)\n to data vectors.\n variables : dict\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in ``data``.\n\n \"\"\"\n plot_data = {}\n variables = {}\n\n # Data is optional; all variables can be defined as vectors\n if data is None:\n data = {}\n\n # TODO should we try a data.to_dict() or similar here to more\n # generally accept objects with that interface?\n # Note that dict(df) also works for pandas, and gives us what we\n # want, whereas DataFrame.to_dict() gives a nested dict instead of\n # a dict of series.\n\n # Variables can also be extracted from the index attribute\n # TODO is this the most general way to enable it?\n # There is no index.to_dict on multiindex, unfortunately\n try:\n index = data.index.to_frame()\n except AttributeError:\n index = {}\n\n # The caller will determine the order of variables in plot_data\n for key, val in kwargs.items():\n\n # First try to treat the argument as a key for the data collection.\n # But be flexible about what can be used as a key.\n # Usually it will be a string, but allow numbers or tuples too when\n # taking from the main data object. Only allow strings to reference\n # fields in the index, because otherwise there is too much ambiguity.\n try:\n val_as_data_key = (\n val in data\n or (isinstance(val, (str, bytes)) and val in index)\n )\n except (KeyError, TypeError):\n val_as_data_key = False\n\n if val_as_data_key:\n\n # We know that __getitem__ will work\n\n if val in data:\n plot_data[key] = data[val]\n elif val in index:\n plot_data[key] = index[val]\n variables[key] = val\n\n elif isinstance(val, (str, bytes)):\n\n # This looks like a column name but we don't know what it means!\n\n err = f\"Could not interpret value `{val}` for parameter `{key}`\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, assume the value is itself data\n\n # Raise when data object is present and a vector can't matched\n if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series):\n if np.ndim(val) and len(data) != len(val):\n val_cls = val.__class__.__name__\n err = (\n f\"Length of {val_cls} vectors must match length of `data`\"\n f\" when both are used, but `data` has length {len(data)}\"\n f\" and the vector passed to `{key}` has length {len(val)}.\"\n )\n raise ValueError(err)\n\n plot_data[key] = val\n\n # Try to infer the name of the variable\n variables[key] = getattr(val, \"name\", None)\n\n # Construct a tidy plot DataFrame. This will convert a number of\n # types automatically, aligning on index in case of pandas objects\n plot_data = pd.DataFrame(plot_data)\n\n # Reduce the variables dictionary to fields with valid data\n variables = {\n var: name\n for var, name in variables.items()\n if plot_data[var].notnull().any()\n }\n\n return plot_data, variables\n\n def iter_data(\n self, grouping_vars=None, *,\n reverse=False, from_comp_data=False,\n by_facet=True, allow_empty=False, dropna=True,\n ):\n \"\"\"Generator for getting subsets of data defined by semantic variables.\n\n Also injects \"col\" and \"row\" into grouping semantics.\n\n Parameters\n ----------\n grouping_vars : string or list of strings\n Semantic variables that define the subsets of data.\n reverse : bool\n If True, reverse the order of iteration.\n from_comp_data : bool\n If True, use self.comp_data rather than self.plot_data\n by_facet : bool\n If True, add faceting variables to the set of grouping variables.\n allow_empty : bool\n If True, yield an empty dataframe when no observations exist for\n combinations of grouping variables.\n dropna : bool\n If True, remove rows with missing data.\n\n Yields\n ------\n sub_vars : dict\n Keys are semantic names, values are the level of that semantic.\n sub_data : :class:`pandas.DataFrame`\n Subset of ``plot_data`` for this combination of semantic values.\n\n \"\"\"\n # TODO should this default to using all (non x/y?) semantics?\n # or define grouping vars somewhere?\n if grouping_vars is None:\n grouping_vars = []\n elif isinstance(grouping_vars, str):\n grouping_vars = [grouping_vars]\n elif isinstance(grouping_vars, tuple):\n grouping_vars = list(grouping_vars)\n\n # Always insert faceting variables\n if by_facet:\n facet_vars = {\"col\", \"row\"}\n grouping_vars.extend(\n facet_vars & set(self.variables) - set(grouping_vars)\n )\n\n # Reduce to the semantics used in this plot\n grouping_vars = [\n var for var in grouping_vars if var in self.variables\n ]\n\n if from_comp_data:\n data = self.comp_data\n else:\n data = self.plot_data\n\n if dropna:\n data = data.dropna()\n\n levels = self.var_levels.copy()\n if from_comp_data:\n for axis in {\"x\", \"y\"} & set(grouping_vars):\n if self.var_types[axis] == \"categorical\":\n if self._var_ordered[axis]:\n # If the axis is ordered, then the axes in a possible\n # facet grid are by definition \"shared\", or there is a\n # single axis with a unique cat -> idx mapping.\n # So we can just take the first converter object.\n converter = self.converters[axis].iloc[0]\n levels[axis] = converter.convert_units(levels[axis])\n else:\n # Otherwise, the mappings may not be unique, but we can\n # use the unique set of index values in comp_data.\n levels[axis] = np.sort(data[axis].unique())\n elif self.var_types[axis] == \"datetime\":\n levels[axis] = mpl.dates.date2num(levels[axis])\n elif self.var_types[axis] == \"numeric\" and self._log_scaled(axis):\n levels[axis] = np.log10(levels[axis])\n\n if grouping_vars:\n\n grouped_data = data.groupby(\n grouping_vars, sort=False, as_index=False\n )\n\n grouping_keys = []\n for var in grouping_vars:\n grouping_keys.append(levels.get(var, []))\n\n iter_keys = itertools.product(*grouping_keys)\n if reverse:\n iter_keys = reversed(list(iter_keys))\n\n for key in iter_keys:\n\n # Pandas fails with singleton tuple inputs\n pd_key = key[0] if len(key) == 1 else key\n\n try:\n data_subset = grouped_data.get_group(pd_key)\n except KeyError:\n # XXX we are adding this to allow backwards compatibility\n # with the empty artists that old categorical plots would\n # add (before 0.12), which we may decide to break, in which\n # case this option could be removed\n data_subset = data.loc[[]]\n\n if data_subset.empty and not allow_empty:\n continue\n\n sub_vars = dict(zip(grouping_vars, key))\n\n yield sub_vars, data_subset.copy()\n\n else:\n\n yield {}, data.copy()\n\n @property\n def comp_data(self):\n \"\"\"Dataframe with numeric x and y, after unit conversion and log scaling.\"\"\"\n if not hasattr(self, \"ax\"):\n # Probably a good idea, but will need a bunch of tests updated\n # Most of these tests should just use the external interface\n # Then this can be re-enabled.\n # raise AttributeError(\"No Axes attached to plotter\")\n return self.plot_data\n\n if not hasattr(self, \"_comp_data\"):\n\n comp_data = (\n self.plot_data\n .copy(deep=False)\n .drop([\"x\", \"y\"], axis=1, errors=\"ignore\")\n )\n\n for var in \"yx\":\n if var not in self.variables:\n continue\n\n parts = []\n grouped = self.plot_data[var].groupby(self.converters[var], sort=False)\n for converter, orig in grouped:\n with pd.option_context('mode.use_inf_as_null', True):\n orig = orig.dropna()\n if var in self.var_levels:\n # TODO this should happen in some centralized location\n # it is similar to GH2419, but more complicated because\n # supporting `order` in categorical plots is tricky\n orig = orig[orig.isin(self.var_levels[var])]\n comp = pd.to_numeric(converter.convert_units(orig))\n if converter.get_scale() == \"log\":\n comp = np.log10(comp)\n parts.append(pd.Series(comp, orig.index, name=orig.name))\n if parts:\n comp_col = pd.concat(parts)\n else:\n comp_col = pd.Series(dtype=float, name=var)\n comp_data.insert(0, var, comp_col)\n\n self._comp_data = comp_data\n\n return self._comp_data\n\n def _get_axes(self, sub_vars):\n \"\"\"Return an Axes object based on existence of row/col variables.\"\"\"\n row = sub_vars.get(\"row\", None)\n col = sub_vars.get(\"col\", None)\n if row is not None and col is not None:\n return self.facets.axes_dict[(row, col)]\n elif row is not None:\n return self.facets.axes_dict[row]\n elif col is not None:\n return self.facets.axes_dict[col]\n elif self.ax is None:\n return self.facets.ax\n else:\n return self.ax\n\n def _attach(\n self,\n obj,\n allowed_types=None,\n log_scale=None,\n ):\n \"\"\"Associate the plotter with an Axes manager and initialize its units.\n\n Parameters\n ----------\n obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid`\n Structural object that we will eventually plot onto.\n allowed_types : str or list of str\n If provided, raise when either the x or y variable does not have\n one of the declared seaborn types.\n log_scale : bool, number, or pair of bools or numbers\n If not False, set the axes to use log scaling, with the given\n base or defaulting to 10. If a tuple, interpreted as separate\n arguments for the x and y axes.\n\n \"\"\"\n from .axisgrid import FacetGrid\n if isinstance(obj, FacetGrid):\n self.ax = None\n self.facets = obj\n ax_list = obj.axes.flatten()\n if obj.col_names is not None:\n self.var_levels[\"col\"] = obj.col_names\n if obj.row_names is not None:\n self.var_levels[\"row\"] = obj.row_names\n else:\n self.ax = obj\n self.facets = None\n ax_list = [obj]\n\n # Identify which \"axis\" variables we have defined\n axis_variables = set(\"xy\").intersection(self.variables)\n\n # -- Verify the types of our x and y variables here.\n # This doesn't really make complete sense being here here, but it's a fine\n # place for it, given the current system.\n # (Note that for some plots, there might be more complicated restrictions)\n # e.g. the categorical plots have their own check that as specific to the\n # non-categorical axis.\n if allowed_types is None:\n allowed_types = [\"numeric\", \"datetime\", \"categorical\"]\n elif isinstance(allowed_types, str):\n allowed_types = [allowed_types]\n\n for var in axis_variables:\n var_type = self.var_types[var]\n if var_type not in allowed_types:\n err = (\n f\"The {var} variable is {var_type}, but one of \"\n f\"{allowed_types} is required\"\n )\n raise TypeError(err)\n\n # -- Get axis objects for each row in plot_data for type conversions and scaling\n\n facet_dim = {\"x\": \"col\", \"y\": \"row\"}\n\n self.converters = {}\n for var in axis_variables:\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n\n converter = pd.Series(index=self.plot_data.index, name=var, dtype=object)\n share_state = getattr(self.facets, f\"_share{var}\", True)\n\n # Simplest cases are that we have a single axes, all axes are shared,\n # or sharing is only on the orthogonal facet dimension. In these cases,\n # all datapoints get converted the same way, so use the first axis\n if share_state is True or share_state == facet_dim[other_var]:\n converter.loc[:] = getattr(ax_list[0], f\"{var}axis\")\n\n else:\n\n # Next simplest case is when no axes are shared, and we can\n # use the axis objects within each facet\n if share_state is False:\n for axes_vars, axes_data in self.iter_data():\n ax = self._get_axes(axes_vars)\n converter.loc[axes_data.index] = getattr(ax, f\"{var}axis\")\n\n # In the more complicated case, the axes are shared within each\n # \"file\" of the facetgrid. In that case, we need to subset the data\n # for that file and assign it the first axis in the slice of the grid\n else:\n\n names = getattr(self.facets, f\"{share_state}_names\")\n for i, level in enumerate(names):\n idx = (i, 0) if share_state == \"row\" else (0, i)\n axis = getattr(self.facets.axes[idx], f\"{var}axis\")\n converter.loc[self.plot_data[share_state] == level] = axis\n\n # Store the converter vector, which we use elsewhere (e.g comp_data)\n self.converters[var] = converter\n\n # Now actually update the matplotlib objects to do the conversion we want\n grouped = self.plot_data[var].groupby(self.converters[var], sort=False)\n for converter, seed_data in grouped:\n if self.var_types[var] == \"categorical\":\n if self._var_ordered[var]:\n order = self.var_levels[var]\n else:\n order = None\n seed_data = categorical_order(seed_data, order)\n converter.update_units(seed_data)\n\n # -- Set numerical axis scales\n\n # First unpack the log_scale argument\n if log_scale is None:\n scalex = scaley = False\n else:\n # Allow single value or x, y tuple\n try:\n scalex, scaley = log_scale\n except TypeError:\n scalex = log_scale if \"x\" in self.variables else False\n scaley = log_scale if \"y\" in self.variables else False\n\n # Now use it\n for axis, scale in zip(\"xy\", (scalex, scaley)):\n if scale:\n for ax in ax_list:\n set_scale = getattr(ax, f\"set_{axis}scale\")\n if scale is True:\n set_scale(\"log\")\n else:\n if Version(mpl.__version__) >= Version(\"3.3\"):\n set_scale(\"log\", base=scale)\n else:\n set_scale(\"log\", **{f\"base{axis}\": scale})\n\n # For categorical y, we want the \"first\" level to be at the top of the axis\n if self.var_types.get(\"y\", None) == \"categorical\":\n for ax in ax_list:\n try:\n ax.yaxis.set_inverted(True)\n except AttributeError: # mpl < 3.1\n if not ax.yaxis_inverted():\n ax.invert_yaxis()\n\n # TODO -- Add axes labels\n\n def _log_scaled(self, axis):\n \"\"\"Return True if specified axis is log scaled on all attached axes.\"\"\"\n if not hasattr(self, \"ax\"):\n return False\n\n if self.ax is None:\n axes_list = self.facets.axes.flatten()\n else:\n axes_list = [self.ax]\n\n log_scaled = []\n for ax in axes_list:\n data_axis = getattr(ax, f\"{axis}axis\")\n log_scaled.append(data_axis.get_scale() == \"log\")\n\n if any(log_scaled) and not all(log_scaled):\n raise RuntimeError(\"Axis scaling is not consistent\")\n\n return any(log_scaled)\n\n def _add_axis_labels(self, ax, default_x=\"\", default_y=\"\"):\n \"\"\"Add axis labels if not present, set visibility to match ticklabels.\"\"\"\n # TODO ax could default to None and use attached axes if present\n # but what to do about the case of facets? Currently using FacetGrid's\n # set_axis_labels method, which doesn't add labels to the interior even\n # when the axes are not shared. Maybe that makes sense?\n if not ax.get_xlabel():\n x_visible = any(t.get_visible() for t in ax.get_xticklabels())\n ax.set_xlabel(self.variables.get(\"x\", default_x), visible=x_visible)\n if not ax.get_ylabel():\n y_visible = any(t.get_visible() for t in ax.get_yticklabels())\n ax.set_ylabel(self.variables.get(\"y\", default_y), visible=y_visible)\n\n # XXX If the scale_* methods are going to modify the plot_data structure, they\n # can't be called twice. That means that if they are called twice, they should\n # raise. Alternatively, we could store an original version of plot_data and each\n # time they are called they operate on the store, not the current state.\n\n def scale_native(self, axis, *args, **kwargs):\n\n # Default, defer to matplotlib\n\n raise NotImplementedError\n\n def scale_numeric(self, axis, *args, **kwargs):\n\n # Feels needed to completeness, what should it do?\n # Perhaps handle log scaling? Set the ticker/formatter/limits?\n\n raise NotImplementedError\n\n def scale_datetime(self, axis, *args, **kwargs):\n\n # Use pd.to_datetime to convert strings or numbers to datetime objects\n # Note, use day-resolution for numeric->datetime to match matplotlib\n\n raise NotImplementedError\n\n def scale_categorical(self, axis, order=None, formatter=None):\n \"\"\"\n Enforce categorical (fixed-scale) rules for the data on given axis.\n\n Parameters\n ----------\n axis : \"x\" or \"y\"\n Axis of the plot to operate on.\n order : list\n Order that unique values should appear in.\n formatter : callable\n Function mapping values to a string representation.\n\n Returns\n -------\n self\n\n \"\"\"\n # This method both modifies the internal representation of the data\n # (converting it to string) and sets some attributes on self. It might be\n # a good idea to have a separate object attached to self that contains the\n # information in those attributes (i.e. whether to enforce variable order\n # across facets, the order to use) similar to the SemanticMapping objects\n # we have for semantic variables. That object could also hold the converter\n # objects that get used, if we can decouple those from an existing axis\n # (cf. https://github.com/matplotlib/matplotlib/issues/19229).\n # There are some interactions with faceting information that would need\n # to be thought through, since the converts to use depend on facets.\n # If we go that route, these methods could become \"borrowed\" methods similar\n # to what happens with the alternate semantic mapper constructors, although\n # that approach is kind of fussy and confusing.\n\n # TODO this method could also set the grid state? Since we like to have no\n # grid on the categorical axis by default. Again, a case where we'll need to\n # store information until we use it, so best to have a way to collect the\n # attributes that this method sets.\n\n # TODO if we are going to set visual properties of the axes with these methods,\n # then we could do the steps currently in CategoricalPlotter._adjust_cat_axis\n\n # TODO another, and distinct idea, is to expose a cut= param here\n\n _check_argument(\"axis\", [\"x\", \"y\"], axis)\n\n # Categorical plots can be \"univariate\" in which case they get an anonymous\n # category label on the opposite axis.\n if axis not in self.variables:\n self.variables[axis] = None\n self.var_types[axis] = \"categorical\"\n self.plot_data[axis] = \"\"\n\n # If the \"categorical\" variable has a numeric type, sort the rows so that\n # the default result from categorical_order has those values sorted after\n # they have been coerced to strings. The reason for this is so that later\n # we can get facet-wise orders that are correct.\n # XXX Should this also sort datetimes?\n # It feels more consistent, but technically will be a default change\n # If so, should also change categorical_order to behave that way\n if self.var_types[axis] == \"numeric\":\n self.plot_data = self.plot_data.sort_values(axis, kind=\"mergesort\")\n\n # Now get a reference to the categorical data vector\n cat_data = self.plot_data[axis]\n\n # Get the initial categorical order, which we do before string\n # conversion to respect the original types of the order list.\n # Track whether the order is given explicitly so that we can know\n # whether or not to use the order constructed here downstream\n self._var_ordered[axis] = order is not None or cat_data.dtype.name == \"category\"\n order = pd.Index(categorical_order(cat_data, order))\n\n # Then convert data to strings. This is because in matplotlib,\n # \"categorical\" data really mean \"string\" data, so doing this artists\n # will be drawn on the categorical axis with a fixed scale.\n # TODO implement formatter here; check that it returns strings?\n if formatter is not None:\n cat_data = cat_data.map(formatter)\n order = order.map(formatter)\n else:\n cat_data = cat_data.astype(str)\n order = order.astype(str)\n\n # Update the levels list with the type-converted order variable\n self.var_levels[axis] = order\n\n # Now ensure that seaborn will use categorical rules internally\n self.var_types[axis] = \"categorical\"\n\n # Put the string-typed categorical vector back into the plot_data structure\n self.plot_data[axis] = cat_data\n\n return self"},{"col":4,"comment":"Return True at least one of x or y is defined.","endLoc":666,"header":"@property\n def has_xy_data(self)","id":800,"name":"has_xy_data","nodeType":"Function","startLoc":663,"text":"@property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n return bool({\"x\", \"y\"} & set(self.variables))"},{"col":0,"comment":"null","endLoc":906,"header":"def _make_logit_transforms(base: float = None) -> TransFuncs","id":802,"name":"_make_logit_transforms","nodeType":"Function","startLoc":894,"text":"def _make_logit_transforms(base: float = None) -> TransFuncs:\n\n log, exp = _make_log_transforms(base)\n\n def logit(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return log(x) - log(1 - x)\n\n def expit(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return exp(x) / (1 + exp(x))\n\n return logit, expit"},{"fileName":"kde_ridgeplot.py","filePath":"examples","id":803,"nodeType":"File","text":"\"\"\"\nOverlapping densities ('ridge plot')\n====================================\n\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_theme(style=\"white\", rc={\"axes.facecolor\": (0, 0, 0, 0)})\n\n# Create the data\nrs = np.random.RandomState(1979)\nx = rs.randn(500)\ng = np.tile(list(\"ABCDEFGHIJ\"), 50)\ndf = pd.DataFrame(dict(x=x, g=g))\nm = df.g.map(ord)\ndf[\"x\"] += m\n\n# Initialize the FacetGrid object\npal = sns.cubehelix_palette(10, rot=-.25, light=.7)\ng = sns.FacetGrid(df, row=\"g\", hue=\"g\", aspect=15, height=.5, palette=pal)\n\n# Draw the densities in a few steps\ng.map(sns.kdeplot, \"x\",\n bw_adjust=.5, clip_on=False,\n fill=True, alpha=1, linewidth=1.5)\ng.map(sns.kdeplot, \"x\", clip_on=False, color=\"w\", lw=2, bw_adjust=.5)\n\n# passing color=None to refline() uses the hue mapping\ng.refline(y=0, linewidth=2, linestyle=\"-\", color=None, clip_on=False)\n\n\n# Define and use a simple function to label the plot in axes coordinates\ndef label(x, color, label):\n ax = plt.gca()\n ax.text(0, .2, label, fontweight=\"bold\", color=color,\n ha=\"left\", va=\"center\", transform=ax.transAxes)\n\n\ng.map(label, \"x\")\n\n# Set the subplots to overlap\ng.figure.subplots_adjust(hspace=-.25)\n\n# Remove axes details that don't play well with overlap\ng.set_titles(\"\")\ng.set(yticks=[], ylabel=\"\")\ng.despine(bottom=True, left=True)\n"},{"col":0,"comment":"null","endLoc":39,"header":"def label(x, color, label)","id":804,"name":"label","nodeType":"Function","startLoc":36,"text":"def label(x, color, label):\n ax = plt.gca()\n ax.text(0, .2, label, fontweight=\"bold\", color=color,\n ha=\"left\", va=\"center\", transform=ax.transAxes)"},{"attributeType":"null","col":16,"comment":"null","endLoc":7,"id":805,"name":"np","nodeType":"Attribute","startLoc":7,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":8,"id":806,"name":"pd","nodeType":"Attribute","startLoc":8,"text":"pd"},{"attributeType":"null","col":18,"comment":"null","endLoc":9,"id":807,"name":"sns","nodeType":"Attribute","startLoc":9,"text":"sns"},{"attributeType":"null","col":28,"comment":"null","endLoc":10,"id":808,"name":"plt","nodeType":"Attribute","startLoc":10,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":809,"name":"rs","nodeType":"Attribute","startLoc":14,"text":"rs"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":810,"name":"x","nodeType":"Attribute","startLoc":15,"text":"x"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":811,"name":"g","nodeType":"Attribute","startLoc":16,"text":"g"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":812,"name":"df","nodeType":"Attribute","startLoc":17,"text":"df"},{"id":813,"name":"JointGrid.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Calling the constructor initializes the figure, but it does not plot anything:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The simplest plotting method, :meth:`JointGrid.plot` accepts a pair of functions (one for the joint axes and one for both marginal axes):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot(sns.scatterplot, sns.histplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The :meth:`JointGrid.plot` function also accepts additional keyword arguments, but it passes them to both functions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot(sns.scatterplot, sns.histplot, alpha=.7, edgecolor=\\\".2\\\", linewidth=.5)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If you need to pass different keyword arguments to each function, you'll have to invoke :meth:`JointGrid.plot_joint` and :meth:`JointGrid.plot_marginals`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot_joint(sns.scatterplot, s=100, alpha=.5)\\n\",\n \"g.plot_marginals(sns.histplot, kde=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can also set up the grid without assigning any data:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can then plot by accessing the ``ax_joint``, ``ax_marg_x``, and ``ax_marg_y`` attributes, which are :class:`matplotlib.axes.Axes` objects:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid()\\n\",\n \"x, y = penguins[\\\"bill_length_mm\\\"], penguins[\\\"bill_depth_mm\\\"]\\n\",\n \"sns.scatterplot(x=x, y=y, ec=\\\"b\\\", fc=\\\"none\\\", s=100, linewidth=1.5, ax=g.ax_joint)\\n\",\n \"sns.histplot(x=x, fill=False, linewidth=2, ax=g.ax_marg_x)\\n\",\n \"sns.kdeplot(y=y, linewidth=2, ax=g.ax_marg_y)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The plotting methods can use any seaborn functions that accept ``x`` and ``y`` variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot(sns.regplot, sns.boxplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If the functions accept a ``hue`` variable, you can use it by assigning ``hue`` when you call the constructor:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\")\\n\",\n \"g.plot(sns.scatterplot, sns.histplot)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Horizontal and/or vertical reference lines can be added to the joint and/or marginal axes using :meth:`JointGrid.refline`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.JointGrid(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot(sns.scatterplot, sns.histplot)\\n\",\n \"g.refline(x=45, y=16)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The figure will always be square (unless you resize it at the matplotlib layer), but its overall size and layout are configurable. The size is controlled by the ``height`` parameter. The relative ratio between the joint and marginal axes is controlled by ``ratio``, and the amount of space between the plots is controlled by ``space``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.JointGrid(height=4, ratio=2, space=.05)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, the ticks on the density axis of the marginal plots are turned off, but this is configurable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.JointGrid(marginal_ticks=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Limits on the two data axes (which are shared across plots) can also be defined when setting up the figure:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.JointGrid(xlim=(-2, 5), ylim=(0, 10))\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"col":4,"comment":"Property interface to ordered list of variables levels.\n\n Each time it's accessed, it updates the var_levels dictionary with the\n list of levels in the current semantic mappers. But it also allows the\n dictionary to persist, so it can be used to set levels by a key. This is\n used to track the list of col/row levels using an attached FacetGrid\n object, but it's kind of messy and ideally fixed by improving the\n faceting logic so it interfaces better with the modern approach to\n tracking plot variables.\n\n ","endLoc":687,"header":"@property\n def var_levels(self)","id":815,"name":"var_levels","nodeType":"Function","startLoc":668,"text":"@property\n def var_levels(self):\n \"\"\"Property interface to ordered list of variables levels.\n\n Each time it's accessed, it updates the var_levels dictionary with the\n list of levels in the current semantic mappers. But it also allows the\n dictionary to persist, so it can be used to set levels by a key. This is\n used to track the list of col/row levels using an attached FacetGrid\n object, but it's kind of messy and ideally fixed by improving the\n faceting logic so it interfaces better with the modern approach to\n tracking plot variables.\n\n \"\"\"\n for var in self.variables:\n try:\n map_obj = getattr(self, f\"_{var}_map\")\n self._var_levels[var] = map_obj.levels\n except AttributeError:\n pass\n return self._var_levels"},{"id":816,"name":"objects.Plot.limit.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1888667e-8761-4c32-9510-68e08e64f21d\",\n \"metadata\": {},\n \"source\": [\n \"By default, plot limits are automatically set to provide a small margin around the data (controlled by :meth:`Plot.theme` parameters `axes.xmargin` and `axes.ymargin`):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"25ec46d9-3c60-4962-b182-a2b2c8310305\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(x=[1, 2, 3], y=[1, 3, 2]).add(so.Line(marker=\\\"o\\\"))\\n\",\n \"p\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5f5c19d8-4104-4df0-ae45-9a8ac96d024e\",\n \"metadata\": {},\n \"source\": [\n \"Pass a `min`/`max` tuple to pin the limits at specific values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"804388c5-5efa-4cfb-92d8-97fdf838ae5e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.limit(x=(0, 4), y=(-1, 6))\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"49634203-4c77-42ae-abc1-b182671f305e\",\n \"metadata\": {},\n \"source\": [\n \"Reversing the `min`/`max` values will invert the axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6ea1c82c-a9bc-43cc-ba75-5ee28923b8f2\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.limit(y=(4, 0))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"9bb25c70-3960-4a81-891c-2bd299e7b24f\",\n \"metadata\": {},\n \"source\": [\n \"Use `None` for either side to maintain the default value:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d0566ba8-707c-4808-9a76-525ccaef7a42\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.limit(y=(0, None))\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"fefc2b45-3510-4cd7-9de9-4806d71fc4c1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"Generator for getting subsets of data defined by semantic variables.\n\n Also injects \"col\" and \"row\" into grouping semantics.\n\n Parameters\n ----------\n grouping_vars : string or list of strings\n Semantic variables that define the subsets of data.\n reverse : bool\n If True, reverse the order of iteration.\n from_comp_data : bool\n If True, use self.comp_data rather than self.plot_data\n by_facet : bool\n If True, add faceting variables to the set of grouping variables.\n allow_empty : bool\n If True, yield an empty dataframe when no observations exist for\n combinations of grouping variables.\n dropna : bool\n If True, remove rows with missing data.\n\n Yields\n ------\n sub_vars : dict\n Keys are semantic names, values are the level of that semantic.\n sub_data : :class:`pandas.DataFrame`\n Subset of ``plot_data`` for this combination of semantic values.\n\n ","endLoc":1092,"header":"def iter_data(\n self, grouping_vars=None, *,\n reverse=False, from_comp_data=False,\n by_facet=True, allow_empty=False, dropna=True,\n )","id":817,"name":"iter_data","nodeType":"Function","startLoc":973,"text":"def iter_data(\n self, grouping_vars=None, *,\n reverse=False, from_comp_data=False,\n by_facet=True, allow_empty=False, dropna=True,\n ):\n \"\"\"Generator for getting subsets of data defined by semantic variables.\n\n Also injects \"col\" and \"row\" into grouping semantics.\n\n Parameters\n ----------\n grouping_vars : string or list of strings\n Semantic variables that define the subsets of data.\n reverse : bool\n If True, reverse the order of iteration.\n from_comp_data : bool\n If True, use self.comp_data rather than self.plot_data\n by_facet : bool\n If True, add faceting variables to the set of grouping variables.\n allow_empty : bool\n If True, yield an empty dataframe when no observations exist for\n combinations of grouping variables.\n dropna : bool\n If True, remove rows with missing data.\n\n Yields\n ------\n sub_vars : dict\n Keys are semantic names, values are the level of that semantic.\n sub_data : :class:`pandas.DataFrame`\n Subset of ``plot_data`` for this combination of semantic values.\n\n \"\"\"\n # TODO should this default to using all (non x/y?) semantics?\n # or define grouping vars somewhere?\n if grouping_vars is None:\n grouping_vars = []\n elif isinstance(grouping_vars, str):\n grouping_vars = [grouping_vars]\n elif isinstance(grouping_vars, tuple):\n grouping_vars = list(grouping_vars)\n\n # Always insert faceting variables\n if by_facet:\n facet_vars = {\"col\", \"row\"}\n grouping_vars.extend(\n facet_vars & set(self.variables) - set(grouping_vars)\n )\n\n # Reduce to the semantics used in this plot\n grouping_vars = [\n var for var in grouping_vars if var in self.variables\n ]\n\n if from_comp_data:\n data = self.comp_data\n else:\n data = self.plot_data\n\n if dropna:\n data = data.dropna()\n\n levels = self.var_levels.copy()\n if from_comp_data:\n for axis in {\"x\", \"y\"} & set(grouping_vars):\n if self.var_types[axis] == \"categorical\":\n if self._var_ordered[axis]:\n # If the axis is ordered, then the axes in a possible\n # facet grid are by definition \"shared\", or there is a\n # single axis with a unique cat -> idx mapping.\n # So we can just take the first converter object.\n converter = self.converters[axis].iloc[0]\n levels[axis] = converter.convert_units(levels[axis])\n else:\n # Otherwise, the mappings may not be unique, but we can\n # use the unique set of index values in comp_data.\n levels[axis] = np.sort(data[axis].unique())\n elif self.var_types[axis] == \"datetime\":\n levels[axis] = mpl.dates.date2num(levels[axis])\n elif self.var_types[axis] == \"numeric\" and self._log_scaled(axis):\n levels[axis] = np.log10(levels[axis])\n\n if grouping_vars:\n\n grouped_data = data.groupby(\n grouping_vars, sort=False, as_index=False\n )\n\n grouping_keys = []\n for var in grouping_vars:\n grouping_keys.append(levels.get(var, []))\n\n iter_keys = itertools.product(*grouping_keys)\n if reverse:\n iter_keys = reversed(list(iter_keys))\n\n for key in iter_keys:\n\n # Pandas fails with singleton tuple inputs\n pd_key = key[0] if len(key) == 1 else key\n\n try:\n data_subset = grouped_data.get_group(pd_key)\n except KeyError:\n # XXX we are adding this to allow backwards compatibility\n # with the empty artists that old categorical plots would\n # add (before 0.12), which we may decide to break, in which\n # case this option could be removed\n data_subset = data.loc[[]]\n\n if data_subset.empty and not allow_empty:\n continue\n\n sub_vars = dict(zip(grouping_vars, key))\n\n yield sub_vars, data_subset.copy()\n\n else:\n\n yield {}, data.copy()"},{"id":818,"name":"objects.Bar.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"penguins = load_dataset(\\\"penguins\\\")\\n\",\n \"flights = load_dataset(\\\"flights\\\").query(\\\"year == 1960\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4e817cdd-09a3-4cf6-8602-e9665607bfe1\",\n \"metadata\": {},\n \"source\": [\n \"The mark draws discrete bars from a baseline to provided values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5a4e5ba1-50ce-4060-8eb7-f17fee9080c0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(flights[\\\"month\\\"], flights[\\\"passengers\\\"]).add(so.Bar())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"252cf7b2-7fc8-4085-8174-0126743d8a08\",\n \"metadata\": {},\n \"source\": [\n \"The bars are oriented depending on the x/y variable types and the `orient` parameter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"81dbbc81-178a-46dd-9acf-2c57d2a7e315\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(flights[\\\"passengers\\\"], flights[\\\"month\\\"]).add(so.Bar())\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"6fddeceb-25b9-4fc1-bae0-4cc4cb612674\",\n \"metadata\": {},\n \"source\": [\n \"A common usecase will be drawing histograms on a variable with a nominal scale:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"08604543-c681-4cd3-943e-b57c0f863b2e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(penguins, x=\\\"species\\\").add(so.Bar(), so.Hist())\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"8b9af978-fdb0-46aa-9cf9-d3e49e38b344\",\n \"metadata\": {},\n \"source\": [\n \"When mapping additional variables, the bars will overlap by default:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"297f7fef-7c31-40dd-ac68-e0ce7f131528\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(penguins, x=\\\"species\\\", color=\\\"sex\\\").add(so.Bar(), so.Hist())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"cd9b7b4a-3150-42b5-b1a8-1c5950ca8703\",\n \"metadata\": {},\n \"source\": [\n \"Apply a move transform, such as a :class:`Dodge` or :class:`Stack` to resolve them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a13c7594-737c-4215-b2a2-e59fc2d033c3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(penguins, x=\\\"species\\\", color=\\\"sex\\\").add(so.Bar(), so.Hist(), so.Dodge())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f5f44a6b-610a-4523-a7c2-39c804a60520\",\n \"metadata\": {},\n \"source\": [\n \"A number of properties can be mapped or set:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e5cbf5a9-effb-4550-bdaf-c266dc69d3f0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(\\n\",\n \" penguins, x=\\\"species\\\",\\n\",\n \" color=\\\"sex\\\", alpha=\\\"sex\\\", edgestyle=\\\"sex\\\",\\n\",\n \" )\\n\",\n \" .add(so.Bar(edgewidth=2), so.Hist(), so.Dodge(\\\"fill\\\"))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"539144d9-75bc-4eb0-8fed-ca57b516b6d3\",\n \"metadata\": {},\n \"source\": [\n \"Combine with :class:`Range` to plot an estimate with errorbars:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"89233c4a-38e7-4807-b3b4-3b4540ffcf56\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, \\\"body_mass_g\\\", \\\"species\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Bar(alpha=.5), so.Agg(), so.Dodge())\\n\",\n \" .add(so.Range(), so.Est(errorbar=\\\"sd\\\"), so.Dodge())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4f6a97a0-2d92-4fd5-ad98-b4299bda1b6b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"regression_marginals.py","filePath":"examples","id":819,"nodeType":"File","text":"\"\"\"\nLinear regression with marginal distributions\n=============================================\n\n_thumb: .65, .65\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"darkgrid\")\n\ntips = sns.load_dataset(\"tips\")\ng = sns.jointplot(x=\"total_bill\", y=\"tip\", data=tips,\n kind=\"reg\", truncate=False,\n xlim=(0, 60), ylim=(0, 12),\n color=\"m\", height=7)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":820,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":821,"name":"tips","nodeType":"Attribute","startLoc":10,"text":"tips"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":822,"name":"g","nodeType":"Attribute","startLoc":11,"text":"g"},{"col":0,"comment":"","endLoc":6,"header":"regression_marginals.py#","id":823,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nLinear regression with marginal distributions\n=============================================\n\n_thumb: .65, .65\n\"\"\"\n\nsns.set_theme(style=\"darkgrid\")\n\ntips = sns.load_dataset(\"tips\")\n\ng = sns.jointplot(x=\"total_bill\", y=\"tip\", data=tips,\n kind=\"reg\", truncate=False,\n xlim=(0, 60), ylim=(0, 12),\n color=\"m\", height=7)"},{"col":0,"comment":"null","endLoc":2339,"header":"def jointplot(\n data=None, *, x=None, y=None, hue=None, kind=\"scatter\",\n height=6, ratio=5, space=.2, dropna=False, xlim=None, ylim=None,\n color=None, palette=None, hue_order=None, hue_norm=None, marginal_ticks=False,\n joint_kws=None, marginal_kws=None,\n **kwargs\n)","id":824,"name":"jointplot","nodeType":"Function","startLoc":2179,"text":"def jointplot(\n data=None, *, x=None, y=None, hue=None, kind=\"scatter\",\n height=6, ratio=5, space=.2, dropna=False, xlim=None, ylim=None,\n color=None, palette=None, hue_order=None, hue_norm=None, marginal_ticks=False,\n joint_kws=None, marginal_kws=None,\n **kwargs\n):\n # Avoid circular imports\n from .relational import scatterplot\n from .regression import regplot, residplot\n from .distributions import histplot, kdeplot, _freedman_diaconis_bins\n\n if kwargs.pop(\"ax\", None) is not None:\n msg = \"Ignoring `ax`; jointplot is a figure-level function.\"\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Set up empty default kwarg dicts\n joint_kws = {} if joint_kws is None else joint_kws.copy()\n joint_kws.update(kwargs)\n marginal_kws = {} if marginal_kws is None else marginal_kws.copy()\n\n # Handle deprecations of distplot-specific kwargs\n distplot_keys = [\n \"rug\", \"fit\", \"hist_kws\", \"norm_hist\" \"hist_kws\", \"rug_kws\",\n ]\n unused_keys = []\n for key in distplot_keys:\n if key in marginal_kws:\n unused_keys.append(key)\n marginal_kws.pop(key)\n if unused_keys and kind != \"kde\":\n msg = (\n \"The marginal plotting function has changed to `histplot`,\"\n \" which does not accept the following argument(s): {}.\"\n ).format(\", \".join(unused_keys))\n warnings.warn(msg, UserWarning)\n\n # Validate the plot kind\n plot_kinds = [\"scatter\", \"hist\", \"hex\", \"kde\", \"reg\", \"resid\"]\n _check_argument(\"kind\", plot_kinds, kind)\n\n # Raise early if using `hue` with a kind that does not support it\n if hue is not None and kind in [\"hex\", \"reg\", \"resid\"]:\n msg = (\n f\"Use of `hue` with `kind='{kind}'` is not currently supported.\"\n )\n raise ValueError(msg)\n\n # Make a colormap based off the plot color\n # (Currently used only for kind=\"hex\")\n if color is None:\n color = \"C0\"\n color_rgb = mpl.colors.colorConverter.to_rgb(color)\n colors = [utils.set_hls_values(color_rgb, l=l) # noqa\n for l in np.linspace(1, 0, 12)]\n cmap = blend_palette(colors, as_cmap=True)\n\n # Matplotlib's hexbin plot is not na-robust\n if kind == \"hex\":\n dropna = True\n\n # Initialize the JointGrid object\n grid = JointGrid(\n data=data, x=x, y=y, hue=hue,\n palette=palette, hue_order=hue_order, hue_norm=hue_norm,\n dropna=dropna, height=height, ratio=ratio, space=space,\n xlim=xlim, ylim=ylim, marginal_ticks=marginal_ticks,\n )\n\n if grid.hue is not None:\n marginal_kws.setdefault(\"legend\", False)\n\n # Plot the data using the grid\n if kind.startswith(\"scatter\"):\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(scatterplot, **joint_kws)\n\n if grid.hue is None:\n marg_func = histplot\n else:\n marg_func = kdeplot\n marginal_kws.setdefault(\"warn_singular\", False)\n marginal_kws.setdefault(\"fill\", True)\n\n marginal_kws.setdefault(\"color\", color)\n grid.plot_marginals(marg_func, **marginal_kws)\n\n elif kind.startswith(\"hist\"):\n\n # TODO process pair parameters for bins, etc. and pass\n # to both joint and marginal plots\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(histplot, **joint_kws)\n\n marginal_kws.setdefault(\"kde\", False)\n marginal_kws.setdefault(\"color\", color)\n\n marg_x_kws = marginal_kws.copy()\n marg_y_kws = marginal_kws.copy()\n\n pair_keys = \"bins\", \"binwidth\", \"binrange\"\n for key in pair_keys:\n if isinstance(joint_kws.get(key), tuple):\n x_val, y_val = joint_kws[key]\n marg_x_kws.setdefault(key, x_val)\n marg_y_kws.setdefault(key, y_val)\n\n histplot(data=data, x=x, hue=hue, **marg_x_kws, ax=grid.ax_marg_x)\n histplot(data=data, y=y, hue=hue, **marg_y_kws, ax=grid.ax_marg_y)\n\n elif kind.startswith(\"kde\"):\n\n joint_kws.setdefault(\"color\", color)\n joint_kws.setdefault(\"warn_singular\", False)\n grid.plot_joint(kdeplot, **joint_kws)\n\n marginal_kws.setdefault(\"color\", color)\n if \"fill\" in joint_kws:\n marginal_kws.setdefault(\"fill\", joint_kws[\"fill\"])\n\n grid.plot_marginals(kdeplot, **marginal_kws)\n\n elif kind.startswith(\"hex\"):\n\n x_bins = min(_freedman_diaconis_bins(grid.x), 50)\n y_bins = min(_freedman_diaconis_bins(grid.y), 50)\n gridsize = int(np.mean([x_bins, y_bins]))\n\n joint_kws.setdefault(\"gridsize\", gridsize)\n joint_kws.setdefault(\"cmap\", cmap)\n grid.plot_joint(plt.hexbin, **joint_kws)\n\n marginal_kws.setdefault(\"kde\", False)\n marginal_kws.setdefault(\"color\", color)\n grid.plot_marginals(histplot, **marginal_kws)\n\n elif kind.startswith(\"reg\"):\n\n marginal_kws.setdefault(\"color\", color)\n marginal_kws.setdefault(\"kde\", True)\n grid.plot_marginals(histplot, **marginal_kws)\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(regplot, **joint_kws)\n\n elif kind.startswith(\"resid\"):\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(residplot, **joint_kws)\n\n x, y = grid.ax_joint.collections[0].get_offsets().T\n marginal_kws.setdefault(\"color\", color)\n histplot(x=x, hue=hue, ax=grid.ax_marg_x, **marginal_kws)\n histplot(y=y, hue=hue, ax=grid.ax_marg_y, **marginal_kws)\n\n # Make the main axes active in the matplotlib state machine\n plt.sca(grid.ax_joint)\n\n return grid"},{"attributeType":"null","col":0,"comment":"null","endLoc":18,"id":825,"name":"m","nodeType":"Attribute","startLoc":18,"text":"m"},{"col":0,"comment":"Independently manipulate the h, l, or s channels of a color.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n h, l, s : floats between 0 and 1, or None\n new values for each channel in hls space\n\n Returns\n -------\n new_color : rgb tuple\n new color code in RGB tuple representation\n\n ","endLoc":244,"header":"def set_hls_values(color, h=None, l=None, s=None)","id":826,"name":"set_hls_values","nodeType":"Function","startLoc":220,"text":"def set_hls_values(color, h=None, l=None, s=None): # noqa\n \"\"\"Independently manipulate the h, l, or s channels of a color.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n h, l, s : floats between 0 and 1, or None\n new values for each channel in hls space\n\n Returns\n -------\n new_color : rgb tuple\n new color code in RGB tuple representation\n\n \"\"\"\n # Get an RGB tuple representation\n rgb = to_rgb(color)\n vals = list(colorsys.rgb_to_hls(*rgb))\n for i, val in enumerate([h, l, s]):\n if val is not None:\n vals[i] = val\n\n rgb = colorsys.hls_to_rgb(*vals)\n return rgb"},{"col":0,"comment":"null","endLoc":951,"header":"def _make_symlog_transforms(c: float = 1, base: float = 10) -> TransFuncs","id":827,"name":"_make_symlog_transforms","nodeType":"Function","startLoc":934,"text":"def _make_symlog_transforms(c: float = 1, base: float = 10) -> TransFuncs:\n\n # From https://iopscience.iop.org/article/10.1088/0957-0233/24/2/027001\n\n # Note: currently not using base because we only get\n # one parameter from the string, and are using c (this is consistent with d3)\n\n log, exp = _make_log_transforms(base)\n\n def symlog(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return np.sign(x) * log(1 + np.abs(np.divide(x, c)))\n\n def symexp(x):\n with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n return np.sign(x) * c * (exp(np.abs(x)) - 1)\n\n return symlog, symexp"},{"col":0,"comment":"null","endLoc":973,"header":"def _make_power_transforms(exp: float) -> TransFuncs","id":828,"name":"_make_power_transforms","nodeType":"Function","startLoc":965,"text":"def _make_power_transforms(exp: float) -> TransFuncs:\n\n def forward(x):\n return np.sign(x) * np.power(np.abs(x), exp)\n\n def inverse(x):\n return np.sign(x) * np.power(np.abs(x), 1 / exp)\n\n return forward, inverse"},{"col":0,"comment":"null","endLoc":962,"header":"def _make_sqrt_transforms() -> TransFuncs","id":829,"name":"_make_sqrt_transforms","nodeType":"Function","startLoc":954,"text":"def _make_sqrt_transforms() -> TransFuncs:\n\n def sqrt(x):\n return np.sign(x) * np.sqrt(np.abs(x))\n\n def square(x):\n return np.sign(x) * np.square(x)\n\n return sqrt, square"},{"fileName":"subplots.py","filePath":"seaborn/_core","id":830,"nodeType":"File","text":"from __future__ import annotations\nfrom collections.abc import Generator\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.axes import Axes\nfrom matplotlib.figure import Figure\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING: # TODO move to seaborn._core.typing?\n from seaborn._core.plot import FacetSpec, PairSpec\n from matplotlib.figure import SubFigure\n\n\nclass Subplots:\n \"\"\"\n Interface for creating and using matplotlib subplots based on seaborn parameters.\n\n Parameters\n ----------\n subplot_spec : dict\n Keyword args for :meth:`matplotlib.figure.Figure.subplots`.\n facet_spec : dict\n Parameters that control subplot faceting.\n pair_spec : dict\n Parameters that control subplot pairing.\n data : PlotData\n Data used to define figure setup.\n\n \"\"\"\n def __init__(\n self,\n subplot_spec: dict, # TODO define as TypedDict\n facet_spec: FacetSpec,\n pair_spec: PairSpec,\n ):\n\n self.subplot_spec = subplot_spec\n\n self._check_dimension_uniqueness(facet_spec, pair_spec)\n self._determine_grid_dimensions(facet_spec, pair_spec)\n self._handle_wrapping(facet_spec, pair_spec)\n self._determine_axis_sharing(pair_spec)\n\n def _check_dimension_uniqueness(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Reject specs that pair and facet on (or wrap to) same figure dimension.\"\"\"\n err = None\n\n facet_vars = facet_spec.get(\"variables\", {})\n\n if facet_spec.get(\"wrap\") and {\"col\", \"row\"} <= set(facet_vars):\n err = \"Cannot wrap facets when specifying both `col` and `row`.\"\n elif (\n pair_spec.get(\"wrap\")\n and pair_spec.get(\"cross\", True)\n and len(pair_spec.get(\"structure\", {}).get(\"x\", [])) > 1\n and len(pair_spec.get(\"structure\", {}).get(\"y\", [])) > 1\n ):\n err = \"Cannot wrap subplots when pairing on both `x` and `y`.\"\n\n collisions = {\"x\": [\"columns\", \"rows\"], \"y\": [\"rows\", \"columns\"]}\n for pair_axis, (multi_dim, wrap_dim) in collisions.items():\n if pair_axis not in pair_spec.get(\"structure\", {}):\n continue\n elif multi_dim[:3] in facet_vars:\n err = f\"Cannot facet the {multi_dim} while pairing on `{pair_axis}``.\"\n elif wrap_dim[:3] in facet_vars and facet_spec.get(\"wrap\"):\n err = f\"Cannot wrap the {wrap_dim} while pairing on `{pair_axis}``.\"\n elif wrap_dim[:3] in facet_vars and pair_spec.get(\"wrap\"):\n err = f\"Cannot wrap the {multi_dim} while faceting the {wrap_dim}.\"\n\n if err is not None:\n raise RuntimeError(err) # TODO what err class? Define PlotSpecError?\n\n def _determine_grid_dimensions(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Parse faceting and pairing information to define figure structure.\"\"\"\n self.grid_dimensions: dict[str, list] = {}\n for dim, axis in zip([\"col\", \"row\"], [\"x\", \"y\"]):\n\n facet_vars = facet_spec.get(\"variables\", {})\n if dim in facet_vars:\n self.grid_dimensions[dim] = facet_spec[\"structure\"][dim]\n elif axis in pair_spec.get(\"structure\", {}):\n self.grid_dimensions[dim] = [\n None for _ in pair_spec.get(\"structure\", {})[axis]\n ]\n else:\n self.grid_dimensions[dim] = [None]\n\n self.subplot_spec[f\"n{dim}s\"] = len(self.grid_dimensions[dim])\n\n if not pair_spec.get(\"cross\", True):\n self.subplot_spec[\"nrows\"] = 1\n\n self.n_subplots = self.subplot_spec[\"ncols\"] * self.subplot_spec[\"nrows\"]\n\n def _handle_wrapping(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Update figure structure parameters based on facet/pair wrapping.\"\"\"\n self.wrap = wrap = facet_spec.get(\"wrap\") or pair_spec.get(\"wrap\")\n if not wrap:\n return\n\n wrap_dim = \"row\" if self.subplot_spec[\"nrows\"] > 1 else \"col\"\n flow_dim = {\"row\": \"col\", \"col\": \"row\"}[wrap_dim]\n n_subplots = self.subplot_spec[f\"n{wrap_dim}s\"]\n flow = int(np.ceil(n_subplots / wrap))\n\n if wrap < self.subplot_spec[f\"n{wrap_dim}s\"]:\n self.subplot_spec[f\"n{wrap_dim}s\"] = wrap\n self.subplot_spec[f\"n{flow_dim}s\"] = flow\n self.n_subplots = n_subplots\n self.wrap_dim = wrap_dim\n\n def _determine_axis_sharing(self, pair_spec: PairSpec) -> None:\n \"\"\"Update subplot spec with default or specified axis sharing parameters.\"\"\"\n axis_to_dim = {\"x\": \"col\", \"y\": \"row\"}\n key: str\n val: str | bool\n for axis in \"xy\":\n key = f\"share{axis}\"\n # Always use user-specified value, if present\n if key not in self.subplot_spec:\n if axis in pair_spec.get(\"structure\", {}):\n # Paired axes are shared along one dimension by default\n if self.wrap is None and pair_spec.get(\"cross\", True):\n val = axis_to_dim[axis]\n else:\n val = False\n else:\n # This will pick up faceted plots, as well as single subplot\n # figures, where the value doesn't really matter\n val = True\n self.subplot_spec[key] = val\n\n def init_figure(\n self,\n pair_spec: PairSpec,\n pyplot: bool = False,\n figure_kws: dict | None = None,\n target: Axes | Figure | SubFigure = None,\n ) -> Figure:\n \"\"\"Initialize matplotlib objects and add seaborn-relevant metadata.\"\"\"\n # TODO reduce need to pass pair_spec here?\n\n if figure_kws is None:\n figure_kws = {}\n\n if isinstance(target, mpl.axes.Axes):\n\n if max(self.subplot_spec[\"nrows\"], self.subplot_spec[\"ncols\"]) > 1:\n err = \" \".join([\n \"Cannot create multiple subplots after calling `Plot.on` with\",\n f\"a {mpl.axes.Axes} object.\",\n ])\n try:\n err += f\" You may want to use a {mpl.figure.SubFigure} instead.\"\n except AttributeError: # SubFigure added in mpl 3.4\n pass\n raise RuntimeError(err)\n\n self._subplot_list = [{\n \"ax\": target,\n \"left\": True,\n \"right\": True,\n \"top\": True,\n \"bottom\": True,\n \"col\": None,\n \"row\": None,\n \"x\": \"x\",\n \"y\": \"y\",\n }]\n self._figure = target.figure\n return self._figure\n\n elif (\n hasattr(mpl.figure, \"SubFigure\") # Added in mpl 3.4\n and isinstance(target, mpl.figure.SubFigure)\n ):\n figure = target.figure\n elif isinstance(target, mpl.figure.Figure):\n figure = target\n else:\n if pyplot:\n figure = plt.figure(**figure_kws)\n else:\n figure = mpl.figure.Figure(**figure_kws)\n target = figure\n self._figure = figure\n\n axs = target.subplots(**self.subplot_spec, squeeze=False)\n\n if self.wrap:\n # Remove unused Axes and flatten the rest into a (2D) vector\n axs_flat = axs.ravel({\"col\": \"C\", \"row\": \"F\"}[self.wrap_dim])\n axs, extra = np.split(axs_flat, [self.n_subplots])\n for ax in extra:\n ax.remove()\n if self.wrap_dim == \"col\":\n axs = axs[np.newaxis, :]\n else:\n axs = axs[:, np.newaxis]\n\n # Get i, j coordinates for each Axes object\n # Note that i, j are with respect to faceting/pairing,\n # not the subplot grid itself, (which only matters in the case of wrapping).\n iter_axs: np.ndenumerate | zip\n if not pair_spec.get(\"cross\", True):\n indices = np.arange(self.n_subplots)\n iter_axs = zip(zip(indices, indices), axs.flat)\n else:\n iter_axs = np.ndenumerate(axs)\n\n self._subplot_list = []\n for (i, j), ax in iter_axs:\n\n info = {\"ax\": ax}\n\n nrows, ncols = self.subplot_spec[\"nrows\"], self.subplot_spec[\"ncols\"]\n if not self.wrap:\n info[\"left\"] = j % ncols == 0\n info[\"right\"] = (j + 1) % ncols == 0\n info[\"top\"] = i == 0\n info[\"bottom\"] = i == nrows - 1\n elif self.wrap_dim == \"col\":\n info[\"left\"] = j % ncols == 0\n info[\"right\"] = ((j + 1) % ncols == 0) or ((j + 1) == self.n_subplots)\n info[\"top\"] = j < ncols\n info[\"bottom\"] = j >= (self.n_subplots - ncols)\n elif self.wrap_dim == \"row\":\n info[\"left\"] = i < nrows\n info[\"right\"] = i >= self.n_subplots - nrows\n info[\"top\"] = i % nrows == 0\n info[\"bottom\"] = ((i + 1) % nrows == 0) or ((i + 1) == self.n_subplots)\n\n if not pair_spec.get(\"cross\", True):\n info[\"top\"] = j < ncols\n info[\"bottom\"] = j >= self.n_subplots - ncols\n\n for dim in [\"row\", \"col\"]:\n idx = {\"row\": i, \"col\": j}[dim]\n info[dim] = self.grid_dimensions[dim][idx]\n\n for axis in \"xy\":\n\n idx = {\"x\": j, \"y\": i}[axis]\n if axis in pair_spec.get(\"structure\", {}):\n key = f\"{axis}{idx}\"\n else:\n key = axis\n info[axis] = key\n\n self._subplot_list.append(info)\n\n return figure\n\n def __iter__(self) -> Generator[dict, None, None]: # TODO TypedDict?\n \"\"\"Yield each subplot dictionary with Axes object and metadata.\"\"\"\n yield from self._subplot_list\n\n def __len__(self) -> int:\n \"\"\"Return the number of subplots in this figure.\"\"\"\n return len(self._subplot_list)\n"},{"className":"Generator","col":0,"comment":"null","endLoc":461,"id":831,"nodeType":"Class","startLoc":440,"text":"class Generator(Iterator[_YieldT_co], Generic[_YieldT_co, _SendT_contra, _ReturnT_co]):\n def __next__(self) -> _YieldT_co: ...\n @abstractmethod\n def send(self, value: _SendT_contra, /) -> _YieldT_co: ...\n @overload\n @abstractmethod\n def throw(\n self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /\n ) -> _YieldT_co: ...\n @overload\n @abstractmethod\n def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ...\n def close(self) -> None: ...\n def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ...\n @property\n def gi_code(self) -> CodeType: ...\n @property\n def gi_frame(self) -> FrameType: ...\n @property\n def gi_running(self) -> bool: ...\n @property\n def gi_yieldfrom(self) -> Generator[Any, Any, Any] | None: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":832,"name":"pal","nodeType":"Attribute","startLoc":22,"text":"pal"},{"col":4,"comment":"null","endLoc":441,"header":"def __next__(self) -> _YieldT_co","id":833,"name":"__next__","nodeType":"Function","startLoc":441,"text":"def __next__(self) -> _YieldT_co: ..."},{"col":4,"comment":"null","endLoc":443,"header":"@abstractmethod\n def send(self, value: _SendT_contra, /) -> _YieldT_co","id":834,"name":"send","nodeType":"Function","startLoc":442,"text":"@abstractmethod\n def send(self, value: _SendT_contra, /) -> _YieldT_co: ..."},{"col":4,"comment":"null","endLoc":448,"header":"@overload\n @abstractmethod\n def throw(\n self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /\n ) -> _YieldT_co","id":835,"name":"throw","nodeType":"Function","startLoc":444,"text":"@overload\n @abstractmethod\n def throw(\n self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /\n ) -> _YieldT_co: ..."},{"col":4,"comment":"null","endLoc":451,"header":"@overload\n @abstractmethod\n def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co","id":836,"name":"throw","nodeType":"Function","startLoc":449,"text":"@overload\n @abstractmethod\n def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ..."},{"col":4,"comment":"null","endLoc":452,"header":"def close(self) -> None","id":837,"name":"close","nodeType":"Function","startLoc":452,"text":"def close(self) -> None: ..."},{"col":4,"comment":"null","endLoc":453,"header":"def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]","id":838,"name":"__iter__","nodeType":"Function","startLoc":453,"text":"def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ..."},{"col":4,"comment":"null","endLoc":455,"header":"@property\n def gi_code(self) -> CodeType","id":839,"name":"gi_code","nodeType":"Function","startLoc":454,"text":"@property\n def gi_code(self) -> CodeType: ..."},{"col":4,"comment":"null","endLoc":457,"header":"@property\n def gi_frame(self) -> FrameType","id":840,"name":"gi_frame","nodeType":"Function","startLoc":456,"text":"@property\n def gi_frame(self) -> FrameType: ..."},{"col":4,"comment":"null","endLoc":459,"header":"@property\n def gi_running(self) -> bool","id":841,"name":"gi_running","nodeType":"Function","startLoc":458,"text":"@property\n def gi_running(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":461,"header":"@property\n def gi_yieldfrom(self) -> Generator[Any, Any, Any] | None","id":842,"name":"gi_yieldfrom","nodeType":"Function","startLoc":460,"text":"@property\n def gi_yieldfrom(self) -> Generator[Any, Any, Any] | None: ..."},{"className":"FacetSpec","col":0,"comment":"null","endLoc":78,"id":843,"nodeType":"Class","startLoc":74,"text":"class FacetSpec(TypedDict, total=False):\n\n variables: dict[str, VariableSpec]\n structure: dict[str, list[str]]\n wrap: int | None"},{"attributeType":"FacetGrid","col":0,"comment":"null","endLoc":23,"id":844,"name":"g","nodeType":"Attribute","startLoc":23,"text":"g"},{"col":0,"comment":"","endLoc":6,"header":"kde_ridgeplot.py#","id":845,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nOverlapping densities ('ridge plot')\n====================================\n\n\n\"\"\"\n\nsns.set_theme(style=\"white\", rc={\"axes.facecolor\": (0, 0, 0, 0)})\n\nrs = np.random.RandomState(1979)\n\nx = rs.randn(500)\n\ng = np.tile(list(\"ABCDEFGHIJ\"), 50)\n\ndf = pd.DataFrame(dict(x=x, g=g))\n\nm = df.g.map(ord)\n\ndf[\"x\"] += m\n\npal = sns.cubehelix_palette(10, rot=-.25, light=.7)\n\ng = sns.FacetGrid(df, row=\"g\", hue=\"g\", aspect=15, height=.5, palette=pal)\n\ng.map(sns.kdeplot, \"x\",\n bw_adjust=.5, clip_on=False,\n fill=True, alpha=1, linewidth=1.5)\n\ng.map(sns.kdeplot, \"x\", clip_on=False, color=\"w\", lw=2, bw_adjust=.5)\n\ng.refline(y=0, linewidth=2, linestyle=\"-\", color=None, clip_on=False)\n\ng.map(label, \"x\")\n\ng.figure.subplots_adjust(hspace=-.25)\n\ng.set_titles(\"\")\n\ng.set(yticks=[], ylabel=\"\")\n\ng.despine(bottom=True, left=True)"},{"col":4,"comment":"Add a reference line(s) to each facet.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s). Pass ``color=None`` to\n use ``hue`` mapping.\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`FacetGrid` instance\n Returns ``self`` for easy method chaining.\n\n ","endLoc":1062,"header":"def refline(self, *, x=None, y=None, color='.5', linestyle='--', **line_kws)","id":846,"name":"refline","nodeType":"Function","startLoc":1030,"text":"def refline(self, *, x=None, y=None, color='.5', linestyle='--', **line_kws):\n \"\"\"Add a reference line(s) to each facet.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s). Pass ``color=None`` to\n use ``hue`` mapping.\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`FacetGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n line_kws['color'] = color\n line_kws['linestyle'] = linestyle\n\n if x is not None:\n self.map(plt.axvline, x=x, **line_kws)\n\n if y is not None:\n self.map(plt.axhline, y=y, **line_kws)\n\n return self"},{"col":4,"comment":"Return True if specified axis is log scaled on all attached axes.","endLoc":1319,"header":"def _log_scaled(self, axis)","id":847,"name":"_log_scaled","nodeType":"Function","startLoc":1301,"text":"def _log_scaled(self, axis):\n \"\"\"Return True if specified axis is log scaled on all attached axes.\"\"\"\n if not hasattr(self, \"ax\"):\n return False\n\n if self.ax is None:\n axes_list = self.facets.axes.flatten()\n else:\n axes_list = [self.ax]\n\n log_scaled = []\n for ax in axes_list:\n data_axis = getattr(ax, f\"{axis}axis\")\n log_scaled.append(data_axis.get_scale() == \"log\")\n\n if any(log_scaled) and not all(log_scaled):\n raise RuntimeError(\"Axis scaling is not consistent\")\n\n return any(log_scaled)"},{"col":4,"comment":"Add labels to the left and bottom Axes.","endLoc":1662,"header":"def _add_axis_labels(self)","id":848,"name":"_add_axis_labels","nodeType":"Function","startLoc":1657,"text":"def _add_axis_labels(self):\n \"\"\"Add labels to the left and bottom Axes.\"\"\"\n for ax, label in zip(self.axes[-1, :], self.x_vars):\n ax.set_xlabel(label)\n for ax, label in zip(self.axes[:, 0], self.y_vars):\n ax.set_ylabel(label)"},{"col":4,"comment":"Determine colors when the hue variable is quantitative.","endLoc":288,"header":"def numeric_mapping(self, data, palette, norm)","id":849,"name":"numeric_mapping","nodeType":"Function","startLoc":247,"text":"def numeric_mapping(self, data, palette, norm):\n \"\"\"Determine colors when the hue variable is quantitative.\"\"\"\n if isinstance(palette, dict):\n\n # The presence of a norm object overrides a dictionary of hues\n # in specifying a numeric mapping, so we need to process it here.\n levels = list(sorted(palette))\n colors = [palette[k] for k in sorted(palette)]\n cmap = mpl.colors.ListedColormap(colors)\n lookup_table = palette.copy()\n\n else:\n\n # The levels are the sorted unique values in the data\n levels = list(np.sort(remove_na(data.unique())))\n\n # --- Sort out the colormap to use from the palette argument\n\n # Default numeric palette is our default cubehelix palette\n # TODO do we want to do something complicated to ensure contrast?\n palette = \"ch:\" if palette is None else palette\n\n if isinstance(palette, mpl.colors.Colormap):\n cmap = palette\n else:\n cmap = color_palette(palette, as_cmap=True)\n\n # Now sort out the data normalization\n if norm is None:\n norm = mpl.colors.Normalize()\n elif isinstance(norm, tuple):\n norm = mpl.colors.Normalize(*norm)\n elif not isinstance(norm, mpl.colors.Normalize):\n err = \"``hue_norm`` must be None, tuple, or Normalize object.\"\n raise ValueError(err)\n\n if not norm.scaled():\n norm(np.asarray(data.dropna()))\n\n lookup_table = dict(zip(levels, cmap(norm(levels))))\n\n return levels, lookup_table, norm, cmap"},{"fileName":"structured_heatmap.py","filePath":"examples","id":850,"nodeType":"File","text":"\"\"\"\nDiscovering structure in heatmap data\n=====================================\n\n_thumb: .3, .25\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\nsns.set_theme()\n\n# Load the brain networks example dataset\ndf = sns.load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n\n# Select a subset of the networks\nused_networks = [1, 5, 6, 7, 8, 12, 13, 17]\nused_columns = (df.columns.get_level_values(\"network\")\n .astype(int)\n .isin(used_networks))\ndf = df.loc[:, used_columns]\n\n# Create a categorical palette to identify the networks\nnetwork_pal = sns.husl_palette(8, s=.45)\nnetwork_lut = dict(zip(map(str, used_networks), network_pal))\n\n# Convert the palette to vectors that will be drawn on the side of the matrix\nnetworks = df.columns.get_level_values(\"network\")\nnetwork_colors = pd.Series(networks, index=df.columns).map(network_lut)\n\n# Draw the full plot\ng = sns.clustermap(df.corr(), center=0, cmap=\"vlag\",\n row_colors=network_colors, col_colors=network_colors,\n dendrogram_ratio=(.1, .2),\n cbar_pos=(.02, .32, .03, .2),\n linewidths=.75, figsize=(12, 13))\n\ng.ax_row_dendrogram.remove()\n"},{"attributeType":"null","col":17,"comment":"null","endLoc":7,"id":851,"name":"pd","nodeType":"Attribute","startLoc":7,"text":"pd"},{"attributeType":"dict","col":4,"comment":"null","endLoc":76,"id":852,"name":"variables","nodeType":"Attribute","startLoc":76,"text":"variables"},{"attributeType":"dict","col":4,"comment":"null","endLoc":77,"id":853,"name":"structure","nodeType":"Attribute","startLoc":77,"text":"structure"},{"attributeType":"int | None","col":4,"comment":"null","endLoc":78,"id":854,"name":"wrap","nodeType":"Attribute","startLoc":78,"text":"wrap"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":855,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":856,"name":"df","nodeType":"Attribute","startLoc":12,"text":"df"},{"className":"PairSpec","col":0,"comment":"null","endLoc":86,"id":857,"nodeType":"Class","startLoc":81,"text":"class PairSpec(TypedDict, total=False):\n\n variables: dict[str, VariableSpec]\n structure: dict[str, list[str]]\n cross: bool\n wrap: int | None"},{"attributeType":"dict","col":4,"comment":"null","endLoc":83,"id":858,"name":"variables","nodeType":"Attribute","startLoc":83,"text":"variables"},{"attributeType":"dict","col":4,"comment":"null","endLoc":84,"id":859,"name":"structure","nodeType":"Attribute","startLoc":84,"text":"structure"},{"attributeType":"bool","col":4,"comment":"null","endLoc":85,"id":860,"name":"cross","nodeType":"Attribute","startLoc":85,"text":"cross"},{"attributeType":"int | None","col":4,"comment":"null","endLoc":86,"id":861,"name":"wrap","nodeType":"Attribute","startLoc":86,"text":"wrap"},{"className":"Subplots","col":0,"comment":"\n Interface for creating and using matplotlib subplots based on seaborn parameters.\n\n Parameters\n ----------\n subplot_spec : dict\n Keyword args for :meth:`matplotlib.figure.Figure.subplots`.\n facet_spec : dict\n Parameters that control subplot faceting.\n pair_spec : dict\n Parameters that control subplot pairing.\n data : PlotData\n Data used to define figure setup.\n\n ","endLoc":269,"id":862,"nodeType":"Class","startLoc":16,"text":"class Subplots:\n \"\"\"\n Interface for creating and using matplotlib subplots based on seaborn parameters.\n\n Parameters\n ----------\n subplot_spec : dict\n Keyword args for :meth:`matplotlib.figure.Figure.subplots`.\n facet_spec : dict\n Parameters that control subplot faceting.\n pair_spec : dict\n Parameters that control subplot pairing.\n data : PlotData\n Data used to define figure setup.\n\n \"\"\"\n def __init__(\n self,\n subplot_spec: dict, # TODO define as TypedDict\n facet_spec: FacetSpec,\n pair_spec: PairSpec,\n ):\n\n self.subplot_spec = subplot_spec\n\n self._check_dimension_uniqueness(facet_spec, pair_spec)\n self._determine_grid_dimensions(facet_spec, pair_spec)\n self._handle_wrapping(facet_spec, pair_spec)\n self._determine_axis_sharing(pair_spec)\n\n def _check_dimension_uniqueness(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Reject specs that pair and facet on (or wrap to) same figure dimension.\"\"\"\n err = None\n\n facet_vars = facet_spec.get(\"variables\", {})\n\n if facet_spec.get(\"wrap\") and {\"col\", \"row\"} <= set(facet_vars):\n err = \"Cannot wrap facets when specifying both `col` and `row`.\"\n elif (\n pair_spec.get(\"wrap\")\n and pair_spec.get(\"cross\", True)\n and len(pair_spec.get(\"structure\", {}).get(\"x\", [])) > 1\n and len(pair_spec.get(\"structure\", {}).get(\"y\", [])) > 1\n ):\n err = \"Cannot wrap subplots when pairing on both `x` and `y`.\"\n\n collisions = {\"x\": [\"columns\", \"rows\"], \"y\": [\"rows\", \"columns\"]}\n for pair_axis, (multi_dim, wrap_dim) in collisions.items():\n if pair_axis not in pair_spec.get(\"structure\", {}):\n continue\n elif multi_dim[:3] in facet_vars:\n err = f\"Cannot facet the {multi_dim} while pairing on `{pair_axis}``.\"\n elif wrap_dim[:3] in facet_vars and facet_spec.get(\"wrap\"):\n err = f\"Cannot wrap the {wrap_dim} while pairing on `{pair_axis}``.\"\n elif wrap_dim[:3] in facet_vars and pair_spec.get(\"wrap\"):\n err = f\"Cannot wrap the {multi_dim} while faceting the {wrap_dim}.\"\n\n if err is not None:\n raise RuntimeError(err) # TODO what err class? Define PlotSpecError?\n\n def _determine_grid_dimensions(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Parse faceting and pairing information to define figure structure.\"\"\"\n self.grid_dimensions: dict[str, list] = {}\n for dim, axis in zip([\"col\", \"row\"], [\"x\", \"y\"]):\n\n facet_vars = facet_spec.get(\"variables\", {})\n if dim in facet_vars:\n self.grid_dimensions[dim] = facet_spec[\"structure\"][dim]\n elif axis in pair_spec.get(\"structure\", {}):\n self.grid_dimensions[dim] = [\n None for _ in pair_spec.get(\"structure\", {})[axis]\n ]\n else:\n self.grid_dimensions[dim] = [None]\n\n self.subplot_spec[f\"n{dim}s\"] = len(self.grid_dimensions[dim])\n\n if not pair_spec.get(\"cross\", True):\n self.subplot_spec[\"nrows\"] = 1\n\n self.n_subplots = self.subplot_spec[\"ncols\"] * self.subplot_spec[\"nrows\"]\n\n def _handle_wrapping(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Update figure structure parameters based on facet/pair wrapping.\"\"\"\n self.wrap = wrap = facet_spec.get(\"wrap\") or pair_spec.get(\"wrap\")\n if not wrap:\n return\n\n wrap_dim = \"row\" if self.subplot_spec[\"nrows\"] > 1 else \"col\"\n flow_dim = {\"row\": \"col\", \"col\": \"row\"}[wrap_dim]\n n_subplots = self.subplot_spec[f\"n{wrap_dim}s\"]\n flow = int(np.ceil(n_subplots / wrap))\n\n if wrap < self.subplot_spec[f\"n{wrap_dim}s\"]:\n self.subplot_spec[f\"n{wrap_dim}s\"] = wrap\n self.subplot_spec[f\"n{flow_dim}s\"] = flow\n self.n_subplots = n_subplots\n self.wrap_dim = wrap_dim\n\n def _determine_axis_sharing(self, pair_spec: PairSpec) -> None:\n \"\"\"Update subplot spec with default or specified axis sharing parameters.\"\"\"\n axis_to_dim = {\"x\": \"col\", \"y\": \"row\"}\n key: str\n val: str | bool\n for axis in \"xy\":\n key = f\"share{axis}\"\n # Always use user-specified value, if present\n if key not in self.subplot_spec:\n if axis in pair_spec.get(\"structure\", {}):\n # Paired axes are shared along one dimension by default\n if self.wrap is None and pair_spec.get(\"cross\", True):\n val = axis_to_dim[axis]\n else:\n val = False\n else:\n # This will pick up faceted plots, as well as single subplot\n # figures, where the value doesn't really matter\n val = True\n self.subplot_spec[key] = val\n\n def init_figure(\n self,\n pair_spec: PairSpec,\n pyplot: bool = False,\n figure_kws: dict | None = None,\n target: Axes | Figure | SubFigure = None,\n ) -> Figure:\n \"\"\"Initialize matplotlib objects and add seaborn-relevant metadata.\"\"\"\n # TODO reduce need to pass pair_spec here?\n\n if figure_kws is None:\n figure_kws = {}\n\n if isinstance(target, mpl.axes.Axes):\n\n if max(self.subplot_spec[\"nrows\"], self.subplot_spec[\"ncols\"]) > 1:\n err = \" \".join([\n \"Cannot create multiple subplots after calling `Plot.on` with\",\n f\"a {mpl.axes.Axes} object.\",\n ])\n try:\n err += f\" You may want to use a {mpl.figure.SubFigure} instead.\"\n except AttributeError: # SubFigure added in mpl 3.4\n pass\n raise RuntimeError(err)\n\n self._subplot_list = [{\n \"ax\": target,\n \"left\": True,\n \"right\": True,\n \"top\": True,\n \"bottom\": True,\n \"col\": None,\n \"row\": None,\n \"x\": \"x\",\n \"y\": \"y\",\n }]\n self._figure = target.figure\n return self._figure\n\n elif (\n hasattr(mpl.figure, \"SubFigure\") # Added in mpl 3.4\n and isinstance(target, mpl.figure.SubFigure)\n ):\n figure = target.figure\n elif isinstance(target, mpl.figure.Figure):\n figure = target\n else:\n if pyplot:\n figure = plt.figure(**figure_kws)\n else:\n figure = mpl.figure.Figure(**figure_kws)\n target = figure\n self._figure = figure\n\n axs = target.subplots(**self.subplot_spec, squeeze=False)\n\n if self.wrap:\n # Remove unused Axes and flatten the rest into a (2D) vector\n axs_flat = axs.ravel({\"col\": \"C\", \"row\": \"F\"}[self.wrap_dim])\n axs, extra = np.split(axs_flat, [self.n_subplots])\n for ax in extra:\n ax.remove()\n if self.wrap_dim == \"col\":\n axs = axs[np.newaxis, :]\n else:\n axs = axs[:, np.newaxis]\n\n # Get i, j coordinates for each Axes object\n # Note that i, j are with respect to faceting/pairing,\n # not the subplot grid itself, (which only matters in the case of wrapping).\n iter_axs: np.ndenumerate | zip\n if not pair_spec.get(\"cross\", True):\n indices = np.arange(self.n_subplots)\n iter_axs = zip(zip(indices, indices), axs.flat)\n else:\n iter_axs = np.ndenumerate(axs)\n\n self._subplot_list = []\n for (i, j), ax in iter_axs:\n\n info = {\"ax\": ax}\n\n nrows, ncols = self.subplot_spec[\"nrows\"], self.subplot_spec[\"ncols\"]\n if not self.wrap:\n info[\"left\"] = j % ncols == 0\n info[\"right\"] = (j + 1) % ncols == 0\n info[\"top\"] = i == 0\n info[\"bottom\"] = i == nrows - 1\n elif self.wrap_dim == \"col\":\n info[\"left\"] = j % ncols == 0\n info[\"right\"] = ((j + 1) % ncols == 0) or ((j + 1) == self.n_subplots)\n info[\"top\"] = j < ncols\n info[\"bottom\"] = j >= (self.n_subplots - ncols)\n elif self.wrap_dim == \"row\":\n info[\"left\"] = i < nrows\n info[\"right\"] = i >= self.n_subplots - nrows\n info[\"top\"] = i % nrows == 0\n info[\"bottom\"] = ((i + 1) % nrows == 0) or ((i + 1) == self.n_subplots)\n\n if not pair_spec.get(\"cross\", True):\n info[\"top\"] = j < ncols\n info[\"bottom\"] = j >= self.n_subplots - ncols\n\n for dim in [\"row\", \"col\"]:\n idx = {\"row\": i, \"col\": j}[dim]\n info[dim] = self.grid_dimensions[dim][idx]\n\n for axis in \"xy\":\n\n idx = {\"x\": j, \"y\": i}[axis]\n if axis in pair_spec.get(\"structure\", {}):\n key = f\"{axis}{idx}\"\n else:\n key = axis\n info[axis] = key\n\n self._subplot_list.append(info)\n\n return figure\n\n def __iter__(self) -> Generator[dict, None, None]: # TODO TypedDict?\n \"\"\"Yield each subplot dictionary with Axes object and metadata.\"\"\"\n yield from self._subplot_list\n\n def __len__(self) -> int:\n \"\"\"Return the number of subplots in this figure.\"\"\"\n return len(self._subplot_list)"},{"col":4,"comment":"null","endLoc":44,"header":"def __init__(\n self,\n subplot_spec: dict, # TODO define as TypedDict\n facet_spec: FacetSpec,\n pair_spec: PairSpec,\n )","id":863,"name":"__init__","nodeType":"Function","startLoc":32,"text":"def __init__(\n self,\n subplot_spec: dict, # TODO define as TypedDict\n facet_spec: FacetSpec,\n pair_spec: PairSpec,\n ):\n\n self.subplot_spec = subplot_spec\n\n self._check_dimension_uniqueness(facet_spec, pair_spec)\n self._determine_grid_dimensions(facet_spec, pair_spec)\n self._handle_wrapping(facet_spec, pair_spec)\n self._determine_axis_sharing(pair_spec)"},{"col":4,"comment":"Reject specs that pair and facet on (or wrap to) same figure dimension.","endLoc":76,"header":"def _check_dimension_uniqueness(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None","id":864,"name":"_check_dimension_uniqueness","nodeType":"Function","startLoc":46,"text":"def _check_dimension_uniqueness(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Reject specs that pair and facet on (or wrap to) same figure dimension.\"\"\"\n err = None\n\n facet_vars = facet_spec.get(\"variables\", {})\n\n if facet_spec.get(\"wrap\") and {\"col\", \"row\"} <= set(facet_vars):\n err = \"Cannot wrap facets when specifying both `col` and `row`.\"\n elif (\n pair_spec.get(\"wrap\")\n and pair_spec.get(\"cross\", True)\n and len(pair_spec.get(\"structure\", {}).get(\"x\", [])) > 1\n and len(pair_spec.get(\"structure\", {}).get(\"y\", [])) > 1\n ):\n err = \"Cannot wrap subplots when pairing on both `x` and `y`.\"\n\n collisions = {\"x\": [\"columns\", \"rows\"], \"y\": [\"rows\", \"columns\"]}\n for pair_axis, (multi_dim, wrap_dim) in collisions.items():\n if pair_axis not in pair_spec.get(\"structure\", {}):\n continue\n elif multi_dim[:3] in facet_vars:\n err = f\"Cannot facet the {multi_dim} while pairing on `{pair_axis}``.\"\n elif wrap_dim[:3] in facet_vars and facet_spec.get(\"wrap\"):\n err = f\"Cannot wrap the {wrap_dim} while pairing on `{pair_axis}``.\"\n elif wrap_dim[:3] in facet_vars and pair_spec.get(\"wrap\"):\n err = f\"Cannot wrap the {multi_dim} while faceting the {wrap_dim}.\"\n\n if err is not None:\n raise RuntimeError(err) # TODO what err class? Define PlotSpecError?"},{"col":4,"comment":"null","endLoc":1761,"header":"def __init__(\n self, data=None, *,\n x=None, y=None, hue=None,\n height=6, ratio=5, space=.2,\n palette=None, hue_order=None, hue_norm=None,\n dropna=False, xlim=None, ylim=None, marginal_ticks=False,\n )","id":865,"name":"__init__","nodeType":"Function","startLoc":1681,"text":"def __init__(\n self, data=None, *,\n x=None, y=None, hue=None,\n height=6, ratio=5, space=.2,\n palette=None, hue_order=None, hue_norm=None,\n dropna=False, xlim=None, ylim=None, marginal_ticks=False,\n ):\n\n # Set up the subplot grid\n f = plt.figure(figsize=(height, height))\n gs = plt.GridSpec(ratio + 1, ratio + 1)\n\n ax_joint = f.add_subplot(gs[1:, :-1])\n ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint)\n ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint)\n\n self._figure = f\n self.ax_joint = ax_joint\n self.ax_marg_x = ax_marg_x\n self.ax_marg_y = ax_marg_y\n\n # Turn off tick visibility for the measure axis on the marginal plots\n plt.setp(ax_marg_x.get_xticklabels(), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(), visible=False)\n plt.setp(ax_marg_x.get_xticklabels(minor=True), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(minor=True), visible=False)\n\n # Turn off the ticks on the density axis for the marginal plots\n if not marginal_ticks:\n plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(minor=True), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(minor=True), visible=False)\n ax_marg_x.yaxis.grid(False)\n ax_marg_y.xaxis.grid(False)\n\n # Process the input variables\n p = VectorPlotter(data=data, variables=dict(x=x, y=y, hue=hue))\n plot_data = p.plot_data.loc[:, p.plot_data.notna().any()]\n\n # Possibly drop NA\n if dropna:\n plot_data = plot_data.dropna()\n\n def get_var(var):\n vector = plot_data.get(var, None)\n if vector is not None:\n vector = vector.rename(p.variables.get(var, None))\n return vector\n\n self.x = get_var(\"x\")\n self.y = get_var(\"y\")\n self.hue = get_var(\"hue\")\n\n for axis in \"xy\":\n name = p.variables.get(axis, None)\n if name is not None:\n getattr(ax_joint, f\"set_{axis}label\")(name)\n\n if xlim is not None:\n ax_joint.set_xlim(xlim)\n if ylim is not None:\n ax_joint.set_ylim(ylim)\n\n # Store the semantic mapping parameters for axes-level functions\n self._hue_params = dict(palette=palette, hue_order=hue_order, hue_norm=hue_norm)\n\n # Make the grid look nice\n utils.despine(f)\n if not marginal_ticks:\n utils.despine(ax=ax_marg_x, left=True)\n utils.despine(ax=ax_marg_y, bottom=True)\n for axes in [ax_marg_x, ax_marg_y]:\n for axis in [axes.xaxis, axes.yaxis]:\n axis.label.set_visible(False)\n f.tight_layout()\n f.subplots_adjust(hspace=space, wspace=space)"},{"attributeType":"list","col":0,"comment":"null","endLoc":15,"id":866,"name":"used_networks","nodeType":"Attribute","startLoc":15,"text":"used_networks"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":867,"name":"used_columns","nodeType":"Attribute","startLoc":16,"text":"used_columns"},{"fileName":"palette_choices.py","filePath":"examples","id":868,"nodeType":"File","text":"\"\"\"\nColor palette choices\n=====================\n\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_theme(style=\"white\", context=\"talk\")\nrs = np.random.RandomState(8)\n\n# Set up the matplotlib figure\nf, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7, 5), sharex=True)\n\n# Generate some sequential data\nx = np.array(list(\"ABCDEFGHIJ\"))\ny1 = np.arange(1, 11)\nsns.barplot(x=x, y=y1, palette=\"rocket\", ax=ax1)\nax1.axhline(0, color=\"k\", clip_on=False)\nax1.set_ylabel(\"Sequential\")\n\n# Center the data to make it diverging\ny2 = y1 - 5.5\nsns.barplot(x=x, y=y2, palette=\"vlag\", ax=ax2)\nax2.axhline(0, color=\"k\", clip_on=False)\nax2.set_ylabel(\"Diverging\")\n\n# Randomly reorder the data to make it qualitative\ny3 = rs.choice(y1, len(y1), replace=False)\nsns.barplot(x=x, y=y3, palette=\"deep\", ax=ax3)\nax3.axhline(0, color=\"k\", clip_on=False)\nax3.set_ylabel(\"Qualitative\")\n\n# Finalize the plot\nsns.despine(bottom=True)\nplt.setp(f.axes, yticks=[])\nplt.tight_layout(h_pad=2)\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":6,"id":869,"name":"np","nodeType":"Attribute","startLoc":6,"text":"np"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":871,"name":"df","nodeType":"Attribute","startLoc":19,"text":"df"},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":872,"name":"network_pal","nodeType":"Attribute","startLoc":22,"text":"network_pal"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":873,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":874,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":875,"name":"rs","nodeType":"Attribute","startLoc":10,"text":"rs"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":876,"name":"f","nodeType":"Attribute","startLoc":13,"text":"f"},{"attributeType":"null","col":4,"comment":"null","endLoc":13,"id":877,"name":"ax1","nodeType":"Attribute","startLoc":13,"text":"ax1"},{"attributeType":"null","col":9,"comment":"null","endLoc":13,"id":878,"name":"ax2","nodeType":"Attribute","startLoc":13,"text":"ax2"},{"attributeType":"dict","col":0,"comment":"null","endLoc":23,"id":879,"name":"network_lut","nodeType":"Attribute","startLoc":23,"text":"network_lut"},{"attributeType":"null","col":14,"comment":"null","endLoc":13,"id":880,"name":"ax3","nodeType":"Attribute","startLoc":13,"text":"ax3"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":881,"name":"x","nodeType":"Attribute","startLoc":16,"text":"x"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":882,"name":"y1","nodeType":"Attribute","startLoc":17,"text":"y1"},{"attributeType":"tuple | str | None","col":4,"comment":"null","endLoc":313,"id":884,"name":"values","nodeType":"Attribute","startLoc":313,"text":"values"},{"attributeType":"tuple | None","col":4,"comment":"null","endLoc":314,"id":885,"name":"norm","nodeType":"Attribute","startLoc":314,"text":"norm"},{"className":"Continuous","col":0,"comment":"\n A numeric scale supporting norms and functional transforms.\n ","endLoc":645,"id":886,"nodeType":"Class","startLoc":414,"text":"@dataclass\nclass Continuous(ContinuousBase):\n \"\"\"\n A numeric scale supporting norms and functional transforms.\n \"\"\"\n values: tuple | str | None = None\n trans: str | TransFuncs | None = None\n\n # TODO Add this to deal with outliers?\n # outside: Literal[\"keep\", \"drop\", \"clip\"] = \"keep\"\n\n _priority: ClassVar[int] = 1\n\n def tick(\n self,\n locator: Locator | None = None, *,\n at: Sequence[float] = None,\n upto: int | None = None,\n count: int | None = None,\n every: float | None = None,\n between: tuple[float, float] | None = None,\n minor: int | None = None,\n ) -> Continuous:\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n at : sequence of floats\n Place ticks at these specific locations (in data units).\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n count : int\n Choose exactly this number of ticks, bounded by `between` or axis limits.\n every : float\n Choose locations at this interval of separation (in data units).\n between : pair of floats\n Bound upper / lower ticks when using `every` or `count`.\n minor : int\n Number of unlabeled ticks to draw between labeled \"major\" ticks.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n # Input checks\n if locator is not None and not isinstance(locator, Locator):\n raise TypeError(\n f\"Tick locator must be an instance of {Locator!r}, \"\n f\"not {type(locator)!r}.\"\n )\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n if log_base or symlog_thresh:\n if count is not None and between is None:\n raise RuntimeError(\"`count` requires `between` with log transform.\")\n if every is not None:\n raise RuntimeError(\"`every` not supported with log transform.\")\n\n new = copy(self)\n new._tick_params = {\n \"locator\": locator,\n \"at\": at,\n \"upto\": upto,\n \"count\": count,\n \"every\": every,\n \"between\": between,\n \"minor\": minor,\n }\n return new\n\n def label(\n self,\n formatter: Formatter | None = None, *,\n like: str | Callable | None = None,\n base: int | None = None,\n unit: str | None = None,\n ) -> Continuous:\n \"\"\"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n like : str or callable\n Either a format pattern (e.g., `\".2f\"`), a format string with fields named\n `x` and/or `pos` (e.g., `\"${x:.2f}\"`), or a callable that consumes a number\n and returns a string.\n base : number\n Use log formatter (with scientific notation) having this value as the base.\n unit : str or (str, str) tuple\n Use SI prefixes with these units (e.g., with `unit=\"g\"`, a tick value\n of 5000 will appear as `5 kg`). When a tuple, the first element gives the\n separator between the number and unit.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n \"\"\"\n # Input checks\n if formatter is not None and not isinstance(formatter, Formatter):\n raise TypeError(\n f\"Label formatter must be an instance of {Formatter!r}, \"\n f\"not {type(formatter)!r}\"\n )\n if like is not None and not (isinstance(like, str) or callable(like)):\n msg = f\"`like` must be a string or callable, not {type(like).__name__}.\"\n raise TypeError(msg)\n\n new = copy(self)\n new._label_params = {\n \"formatter\": formatter,\n \"like\": like,\n \"base\": base,\n \"unit\": unit,\n }\n return new\n\n def _parse_for_log_params(\n self, trans: str | TransFuncs | None\n ) -> tuple[float | None, float | None]:\n\n log_base = symlog_thresh = None\n if isinstance(trans, str):\n m = re.match(r\"^log(\\d*)\", trans)\n if m is not None:\n log_base = float(m[1] or 10)\n m = re.match(r\"symlog(\\d*)\", trans)\n if m is not None:\n symlog_thresh = float(m[1] or 1)\n return log_base, symlog_thresh\n\n def _get_locators(self, locator, at, upto, count, every, between, minor):\n\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n\n if locator is not None:\n major_locator = locator\n\n elif upto is not None:\n if log_base:\n major_locator = LogLocator(base=log_base, numticks=upto)\n else:\n major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10])\n\n elif count is not None:\n if between is None:\n # This is rarely useful (unless you are setting limits)\n major_locator = LinearLocator(count)\n else:\n if log_base or symlog_thresh:\n forward, inverse = self._get_transform()\n lo, hi = forward(between)\n ticks = inverse(np.linspace(lo, hi, num=count))\n else:\n ticks = np.linspace(*between, num=count)\n major_locator = FixedLocator(ticks)\n\n elif every is not None:\n if between is None:\n major_locator = MultipleLocator(every)\n else:\n lo, hi = between\n ticks = np.arange(lo, hi + every, every)\n major_locator = FixedLocator(ticks)\n\n elif at is not None:\n major_locator = FixedLocator(at)\n\n else:\n if log_base:\n major_locator = LogLocator(log_base)\n elif symlog_thresh:\n major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10)\n else:\n major_locator = AutoLocator()\n\n if minor is None:\n minor_locator = LogLocator(log_base, subs=None) if log_base else None\n else:\n if log_base:\n subs = np.linspace(0, log_base, minor + 2)[1:-1]\n minor_locator = LogLocator(log_base, subs=subs)\n else:\n minor_locator = AutoMinorLocator(minor + 1)\n\n return major_locator, minor_locator\n\n def _get_formatter(self, locator, formatter, like, base, unit):\n\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n if base is None:\n if symlog_thresh:\n log_base = 10\n base = log_base\n\n if formatter is not None:\n return formatter\n\n if like is not None:\n if isinstance(like, str):\n if \"{x\" in like or \"{pos\" in like:\n fmt = like\n else:\n fmt = f\"{{x:{like}}}\"\n formatter = StrMethodFormatter(fmt)\n else:\n formatter = FuncFormatter(like)\n\n elif base is not None:\n # We could add other log options if necessary\n formatter = LogFormatterSciNotation(base)\n\n elif unit is not None:\n if isinstance(unit, tuple):\n sep, unit = unit\n elif not unit:\n sep = \"\"\n else:\n sep = \" \"\n formatter = EngFormatter(unit, sep=sep)\n\n else:\n formatter = ScalarFormatter()\n\n return formatter"},{"col":4,"comment":"\n Configure the selection of ticks for the scale's axis or legend.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n at : sequence of floats\n Place ticks at these specific locations (in data units).\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n count : int\n Choose exactly this number of ticks, bounded by `between` or axis limits.\n every : float\n Choose locations at this interval of separation (in data units).\n between : pair of floats\n Bound upper / lower ticks when using `every` or `count`.\n minor : int\n Number of unlabeled ticks to draw between labeled \"major\" ticks.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n ","endLoc":486,"header":"def tick(\n self,\n locator: Locator | None = None, *,\n at: Sequence[float] = None,\n upto: int | None = None,\n count: int | None = None,\n every: float | None = None,\n between: tuple[float, float] | None = None,\n minor: int | None = None,\n ) -> Continuous","id":887,"name":"tick","nodeType":"Function","startLoc":427,"text":"def tick(\n self,\n locator: Locator | None = None, *,\n at: Sequence[float] = None,\n upto: int | None = None,\n count: int | None = None,\n every: float | None = None,\n between: tuple[float, float] | None = None,\n minor: int | None = None,\n ) -> Continuous:\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n at : sequence of floats\n Place ticks at these specific locations (in data units).\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n count : int\n Choose exactly this number of ticks, bounded by `between` or axis limits.\n every : float\n Choose locations at this interval of separation (in data units).\n between : pair of floats\n Bound upper / lower ticks when using `every` or `count`.\n minor : int\n Number of unlabeled ticks to draw between labeled \"major\" ticks.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n # Input checks\n if locator is not None and not isinstance(locator, Locator):\n raise TypeError(\n f\"Tick locator must be an instance of {Locator!r}, \"\n f\"not {type(locator)!r}.\"\n )\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n if log_base or symlog_thresh:\n if count is not None and between is None:\n raise RuntimeError(\"`count` requires `between` with log transform.\")\n if every is not None:\n raise RuntimeError(\"`every` not supported with log transform.\")\n\n new = copy(self)\n new._tick_params = {\n \"locator\": locator,\n \"at\": at,\n \"upto\": upto,\n \"count\": count,\n \"every\": every,\n \"between\": between,\n \"minor\": minor,\n }\n return new"},{"col":4,"comment":"An array of the :class:`matplotlib.axes.Axes` objects in the grid.","endLoc":1069,"header":"@property\n def axes(self)","id":888,"name":"axes","nodeType":"Function","startLoc":1066,"text":"@property\n def axes(self):\n \"\"\"An array of the :class:`matplotlib.axes.Axes` objects in the grid.\"\"\"\n return self._axes"},{"col":4,"comment":"The :class:`matplotlib.axes.Axes` when no faceting variables are assigned.","endLoc":1080,"header":"@property\n def ax(self)","id":889,"name":"ax","nodeType":"Function","startLoc":1071,"text":"@property\n def ax(self):\n \"\"\"The :class:`matplotlib.axes.Axes` when no faceting variables are assigned.\"\"\"\n if self.axes.shape == (1, 1):\n return self.axes[0, 0]\n else:\n err = (\n \"Use the `.axes` attribute when facet variables are assigned.\"\n )\n raise AttributeError(err)"},{"col":4,"comment":"null","endLoc":550,"header":"def _parse_for_log_params(\n self, trans: str | TransFuncs | None\n ) -> tuple[float | None, float | None]","id":890,"name":"_parse_for_log_params","nodeType":"Function","startLoc":538,"text":"def _parse_for_log_params(\n self, trans: str | TransFuncs | None\n ) -> tuple[float | None, float | None]:\n\n log_base = symlog_thresh = None\n if isinstance(trans, str):\n m = re.match(r\"^log(\\d*)\", trans)\n if m is not None:\n log_base = float(m[1] or 10)\n m = re.match(r\"symlog(\\d*)\", trans)\n if m is not None:\n symlog_thresh = float(m[1] or 1)\n return log_base, symlog_thresh"},{"col":4,"comment":"A mapping of facet names to corresponding :class:`matplotlib.axes.Axes`.\n\n If only one of ``row`` or ``col`` is assigned, each key is a string\n representing a level of that variable. If both facet dimensions are\n assigned, each key is a ``({row_level}, {col_level})`` tuple.\n\n ","endLoc":1091,"header":"@property\n def axes_dict(self)","id":892,"name":"axes_dict","nodeType":"Function","startLoc":1082,"text":"@property\n def axes_dict(self):\n \"\"\"A mapping of facet names to corresponding :class:`matplotlib.axes.Axes`.\n\n If only one of ``row`` or ``col`` is assigned, each key is a string\n representing a level of that variable. If both facet dimensions are\n assigned, each key is a ``({row_level}, {col_level})`` tuple.\n\n \"\"\"\n return self._axes_dict"},{"col":4,"comment":"Return a flat array of the inner axes.","endLoc":1111,"header":"@property\n def _inner_axes(self)","id":893,"name":"_inner_axes","nodeType":"Function","startLoc":1095,"text":"@property\n def _inner_axes(self):\n \"\"\"Return a flat array of the inner axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, 1:].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i % self._ncol\n and i < (self._ncol * (self._nrow - 1))\n and i < (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat"},{"attributeType":"float","col":0,"comment":"null","endLoc":23,"id":895,"name":"y2","nodeType":"Attribute","startLoc":23,"text":"y2"},{"attributeType":"null","col":0,"comment":"null","endLoc":29,"id":896,"name":"y3","nodeType":"Attribute","startLoc":29,"text":"y3"},{"col":0,"comment":"","endLoc":5,"header":"palette_choices.py#","id":897,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nColor palette choices\n=====================\n\n\"\"\"\n\nsns.set_theme(style=\"white\", context=\"talk\")\n\nrs = np.random.RandomState(8)\n\nf, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7, 5), sharex=True)\n\nx = np.array(list(\"ABCDEFGHIJ\"))\n\ny1 = np.arange(1, 11)\n\nsns.barplot(x=x, y=y1, palette=\"rocket\", ax=ax1)\n\nax1.axhline(0, color=\"k\", clip_on=False)\n\nax1.set_ylabel(\"Sequential\")\n\ny2 = y1 - 5.5\n\nsns.barplot(x=x, y=y2, palette=\"vlag\", ax=ax2)\n\nax2.axhline(0, color=\"k\", clip_on=False)\n\nax2.set_ylabel(\"Diverging\")\n\ny3 = rs.choice(y1, len(y1), replace=False)\n\nsns.barplot(x=x, y=y3, palette=\"deep\", ax=ax3)\n\nax3.axhline(0, color=\"k\", clip_on=False)\n\nax3.set_ylabel(\"Qualitative\")\n\nsns.despine(bottom=True)\n\nplt.setp(f.axes, yticks=[])\n\nplt.tight_layout(h_pad=2)"},{"col":4,"comment":"Return a flat array of the left column of axes.","endLoc":1123,"header":"@property\n def _left_axes(self)","id":898,"name":"_left_axes","nodeType":"Function","startLoc":1113,"text":"@property\n def _left_axes(self):\n \"\"\"Return a flat array of the left column of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 0].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if not i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat"},{"col":0,"comment":"null","endLoc":2762,"header":"def barplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True, ci=\"deprecated\",\n ax=None,\n **kwargs,\n)","id":899,"name":"barplot","nodeType":"Function","startLoc":2737,"text":"def barplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True, ci=\"deprecated\",\n ax=None,\n **kwargs,\n):\n\n errorbar = utils._deprecate_ci(errorbar, ci)\n\n # Be backwards compatible with len passed directly, which\n # does not work in Series.agg (maybe a pandas bug?)\n if estimator is len:\n estimator = \"size\"\n\n plotter = _BarPlotter(x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation,\n width, errcolor, errwidth, capsize, dodge)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax"},{"col":4,"comment":"Determine ticks and ticklabels that minimize overlap.","endLoc":292,"header":"def _auto_ticks(self, ax, labels, axis)","id":903,"name":"_auto_ticks","nodeType":"Function","startLoc":278,"text":"def _auto_ticks(self, ax, labels, axis):\n \"\"\"Determine ticks and ticklabels that minimize overlap.\"\"\"\n transform = ax.figure.dpi_scale_trans.inverted()\n bbox = ax.get_window_extent().transformed(transform)\n size = [bbox.width, bbox.height][axis]\n axis = [ax.xaxis, ax.yaxis][axis]\n tick, = axis.set_ticks([0])\n fontsize = tick.label1.get_size()\n max_ticks = int(size // (fontsize / 72))\n if max_ticks < 1:\n return [], []\n tick_every = len(labels) // max_ticks + 1\n tick_every = 1 if tick_every == 0 else tick_every\n ticks, labels = self._skip_ticks(labels, tick_every)\n return ticks, labels"},{"col":0,"comment":"Calculate number of hist bins using Freedman-Diaconis rule.","endLoc":2402,"header":"def _freedman_diaconis_bins(a)","id":904,"name":"_freedman_diaconis_bins","nodeType":"Function","startLoc":2390,"text":"def _freedman_diaconis_bins(a):\n \"\"\"Calculate number of hist bins using Freedman-Diaconis rule.\"\"\"\n # From https://stats.stackexchange.com/questions/798/\n a = np.asarray(a)\n if len(a) < 2:\n return 1\n iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25]))\n h = 2 * iqr / (len(a) ** (1 / 3))\n # fall back to sqrt(a) bins if iqr is 0\n if h == 0:\n return int(np.sqrt(a.size))\n else:\n return int(np.ceil((a.max() - a.min()) / h))"},{"col":4,"comment":"Initialize the plotter.","endLoc":1540,"header":"def __init__(self, x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation, width,\n errcolor, errwidth, capsize, dodge)","id":905,"name":"__init__","nodeType":"Function","startLoc":1525,"text":"def __init__(self, x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation, width,\n errcolor, errwidth, capsize, dodge):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient,\n order, hue_order, units)\n self.establish_colors(color, palette, saturation)\n self.estimate_statistic(estimator, errorbar, n_boot, seed)\n\n self.dodge = dodge\n self.width = width\n\n self.errcolor = errcolor\n self.errwidth = errwidth\n self.capsize = capsize"},{"col":4,"comment":"Convert input specification into a common representation.","endLoc":628,"header":"def establish_variables(self, x=None, y=None, hue=None, data=None,\n orient=None, order=None, hue_order=None,\n units=None)","id":906,"name":"establish_variables","nodeType":"Function","startLoc":425,"text":"def establish_variables(self, x=None, y=None, hue=None, data=None,\n orient=None, order=None, hue_order=None,\n units=None):\n \"\"\"Convert input specification into a common representation.\"\"\"\n # Option 1:\n # We are plotting a wide-form dataset\n # -----------------------------------\n if x is None and y is None:\n\n # Do a sanity check on the inputs\n if hue is not None:\n error = \"Cannot use `hue` without `x` and `y`\"\n raise ValueError(error)\n\n # No hue grouping with wide inputs\n plot_hues = None\n hue_title = None\n hue_names = None\n\n # No statistical units with wide inputs\n plot_units = None\n\n # We also won't get a axes labels here\n value_label = None\n group_label = None\n\n # Option 1a:\n # The input data is a Pandas DataFrame\n # ------------------------------------\n\n if isinstance(data, pd.DataFrame):\n\n # Order the data correctly\n if order is None:\n order = []\n # Reduce to just numeric columns\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n order.append(col)\n plot_data = data[order]\n group_names = order\n group_label = data.columns.name\n\n # Convert to a list of arrays, the common representation\n iter_data = plot_data.items()\n plot_data = [np.asarray(s, float) for k, s in iter_data]\n\n # Option 1b:\n # The input data is an array or list\n # ----------------------------------\n\n else:\n\n # We can't reorder the data\n if order is not None:\n error = \"Input data must be a pandas object to reorder\"\n raise ValueError(error)\n\n # The input data is an array\n if hasattr(data, \"shape\"):\n if len(data.shape) == 1:\n if np.isscalar(data[0]):\n plot_data = [data]\n else:\n plot_data = list(data)\n elif len(data.shape) == 2:\n nr, nc = data.shape\n if nr == 1 or nc == 1:\n plot_data = [data.ravel()]\n else:\n plot_data = [data[:, i] for i in range(nc)]\n else:\n error = (\"Input `data` can have no \"\n \"more than 2 dimensions\")\n raise ValueError(error)\n\n # Check if `data` is None to let us bail out here (for testing)\n elif data is None:\n plot_data = [[]]\n\n # The input data is a flat list\n elif np.isscalar(data[0]):\n plot_data = [data]\n\n # The input data is a nested list\n # This will catch some things that might fail later\n # but exhaustive checks are hard\n else:\n plot_data = data\n\n # Convert to a list of arrays, the common representation\n plot_data = [np.asarray(d, float) for d in plot_data]\n\n # The group names will just be numeric indices\n group_names = list(range(len(plot_data)))\n\n # Figure out the plotting orientation\n orient = \"h\" if str(orient).startswith(\"h\") else \"v\"\n\n # Option 2:\n # We are plotting a long-form dataset\n # -----------------------------------\n\n else:\n\n # See if we need to get variables from `data`\n if data is not None:\n x = data.get(x, x)\n y = data.get(y, y)\n hue = data.get(hue, hue)\n units = data.get(units, units)\n\n # Validate the inputs\n for var in [x, y, hue, units]:\n if isinstance(var, str):\n err = f\"Could not interpret input '{var}'\"\n raise ValueError(err)\n\n # Figure out the plotting orientation\n orient = infer_orient(\n x, y, orient, require_numeric=self.require_numeric\n )\n\n # Option 2a:\n # We are plotting a single set of data\n # ------------------------------------\n if x is None or y is None:\n\n # Determine where the data are\n vals = y if x is None else x\n\n # Put them into the common representation\n plot_data = [np.asarray(vals)]\n\n # Get a label for the value axis\n if hasattr(vals, \"name\"):\n value_label = vals.name\n else:\n value_label = None\n\n # This plot will not have group labels or hue nesting\n groups = None\n group_label = None\n group_names = []\n plot_hues = None\n hue_names = None\n hue_title = None\n plot_units = None\n\n # Option 2b:\n # We are grouping the data values by another variable\n # ---------------------------------------------------\n else:\n\n # Determine which role each variable will play\n if orient == \"v\":\n vals, groups = y, x\n else:\n vals, groups = x, y\n\n # Get the categorical axis label\n group_label = None\n if hasattr(groups, \"name\"):\n group_label = groups.name\n\n # Get the order on the categorical axis\n group_names = categorical_order(groups, order)\n\n # Group the numeric data\n plot_data, value_label = self._group_longform(vals, groups,\n group_names)\n\n # Now handle the hue levels for nested ordering\n if hue is None:\n plot_hues = None\n hue_title = None\n hue_names = None\n else:\n\n # Get the order of the hue levels\n hue_names = categorical_order(hue, hue_order)\n\n # Group the hue data\n plot_hues, hue_title = self._group_longform(hue, groups,\n group_names)\n\n # Now handle the units for nested observations\n if units is None:\n plot_units = None\n else:\n plot_units, _ = self._group_longform(units, groups,\n group_names)\n\n # Assign object attributes\n # ------------------------\n self.orient = orient\n self.plot_data = plot_data\n self.group_label = group_label\n self.value_label = value_label\n self.group_names = group_names\n self.plot_hues = plot_hues\n self.hue_title = hue_title\n self.hue_names = hue_names\n self.plot_units = plot_units"},{"col":4,"comment":"Return a flat array of axes that aren't on the left column.","endLoc":1135,"header":"@property\n def _not_left_axes(self)","id":907,"name":"_not_left_axes","nodeType":"Function","startLoc":1125,"text":"@property\n def _not_left_axes(self):\n \"\"\"Return a flat array of axes that aren't on the left column.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 1:].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat"},{"col":4,"comment":"Return a flat array of the bottom row of axes.","endLoc":1152,"header":"@property\n def _bottom_axes(self)","id":908,"name":"_bottom_axes","nodeType":"Function","startLoc":1137,"text":"@property\n def _bottom_axes(self):\n \"\"\"Return a flat array of the bottom row of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i >= (self._ncol * (self._nrow - 1))\n or i >= (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat"},{"col":4,"comment":"Return a flat array of axes that aren't on the bottom row.","endLoc":1169,"header":"@property\n def _not_bottom_axes(self)","id":909,"name":"_not_bottom_axes","nodeType":"Function","startLoc":1154,"text":"@property\n def _not_bottom_axes(self):\n \"\"\"Return a flat array of axes that aren't on the bottom row.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i < (self._ncol * (self._nrow - 1))\n and i < (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat"},{"attributeType":"null","col":4,"comment":"null","endLoc":545,"id":910,"name":"__doc__","nodeType":"Attribute","startLoc":545,"text":"__init__.__doc__"},{"attributeType":"null","col":8,"comment":"null","endLoc":511,"id":911,"name":"_col_wrap","nodeType":"Attribute","startLoc":511,"text":"self._col_wrap"},{"attributeType":"null","col":8,"comment":"null","endLoc":497,"id":912,"name":"data","nodeType":"Attribute","startLoc":497,"text":"self.data"},{"id":913,"name":"set_style.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"practical-announcement\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"suffering-emerald\",\n \"metadata\": {},\n \"source\": [\n \"Call the function with the name of a seaborn style to set the default for all plots:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"collaborative-struggle\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"whitegrid\\\")\\n\",\n \"sns.barplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"defensive-surgery\",\n \"metadata\": {},\n \"source\": [\n \"You can also selectively override seaborn's default parameter values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"coastal-sydney\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"darkgrid\\\", {\\\"grid.color\\\": \\\".6\\\", \\\"grid.linestyle\\\": \\\":\\\"})\\n\",\n \"sns.lineplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"bright-october\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":516,"id":914,"name":"_x_var","nodeType":"Attribute","startLoc":516,"text":"self._x_var"},{"attributeType":"null","col":8,"comment":"null","endLoc":415,"id":915,"name":"_n_facets","nodeType":"Attribute","startLoc":415,"text":"self._n_facets"},{"attributeType":"null","col":8,"comment":"null","endLoc":507,"id":916,"name":"_col_var","nodeType":"Attribute","startLoc":507,"text":"self._col_var"},{"attributeType":"null","col":8,"comment":"null","endLoc":521,"id":917,"name":"_not_na","nodeType":"Attribute","startLoc":521,"text":"self._not_na"},{"id":918,"name":"residplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"776f8271-21ed-4707-a1ad-09d8c63ae95a\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"mpg = sns.load_dataset(\\\"mpg\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"85717971-adc9-45b0-9c4b-3f022d96179c\",\n \"metadata\": {},\n \"source\": [\n \"Pass `x` and `y` to see a scatter plot of the residuals after fitting a simple regression model:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5aea4655-fb51-4b51-b41d-4769de50e956\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.residplot(data=mpg, x=\\\"weight\\\", y=\\\"displacement\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"175b6287-9240-493f-94bc-9d18258e952b\",\n \"metadata\": {},\n \"source\": [\n \"Structure in the residual plot can reveal a violation of linear regression assumptions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"39aa84c2-d623-44be-9b0b-746f52b55fd4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.residplot(data=mpg, x=\\\"horsepower\\\", y=\\\"mpg\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"bd9641e4-8df5-4751-b261-6443888fbbfe\",\n \"metadata\": {},\n \"source\": [\n \"Remove higher-order trends to test whether that stabilizes the residuals:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"03a68199-1272-464b-8b85-7a309c22a4a6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.residplot(data=mpg, x=\\\"horsepower\\\", y=\\\"mpg\\\", order=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b17750af-0393-4c53-8057-bf95d0de821a\",\n \"metadata\": {},\n \"source\": [\n \"Adding a LOWESS curve can help reveal or emphasize structure:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"494359bd-47b2-426e-9c35-14b5351eec93\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.residplot(data=mpg, x=\\\"horsepower\\\", y=\\\"mpg\\\", lowess=True, line_kws=dict(color=\\\"r\\\"))\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"part_whole_bars.py","filePath":"examples","id":919,"nodeType":"File","text":"\"\"\"\nHorizontal bar plots\n====================\n\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_theme(style=\"whitegrid\")\n\n# Initialize the matplotlib figure\nf, ax = plt.subplots(figsize=(6, 15))\n\n# Load the example car crash dataset\ncrashes = sns.load_dataset(\"car_crashes\").sort_values(\"total\", ascending=False)\n\n# Plot the total crashes\nsns.set_color_codes(\"pastel\")\nsns.barplot(x=\"total\", y=\"abbrev\", data=crashes,\n label=\"Total\", color=\"b\")\n\n# Plot the crashes where alcohol was involved\nsns.set_color_codes(\"muted\")\nsns.barplot(x=\"alcohol\", y=\"abbrev\", data=crashes,\n label=\"Alcohol-involved\", color=\"b\")\n\n# Add a legend and informative axis label\nax.legend(ncol=2, loc=\"lower right\", frameon=True)\nax.set(xlim=(0, 24), ylabel=\"\",\n xlabel=\"Automobile collisions per billion miles\")\nsns.despine(left=True, bottom=True)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":6,"id":920,"name":"sns","nodeType":"Attribute","startLoc":6,"text":"sns"},{"col":4,"comment":"Determine colors when the hue mapping is categorical.","endLoc":245,"header":"def categorical_mapping(self, data, palette, order)","id":921,"name":"categorical_mapping","nodeType":"Function","startLoc":213,"text":"def categorical_mapping(self, data, palette, order):\n \"\"\"Determine colors when the hue mapping is categorical.\"\"\"\n # -- Identify the order and name of the levels\n\n levels = categorical_order(data, order)\n n_colors = len(levels)\n\n # -- Identify the set of colors to use\n\n if isinstance(palette, dict):\n\n missing = set(levels) - set(palette)\n if any(missing):\n err = \"The palette dictionary is missing keys: {}\"\n raise ValueError(err.format(missing))\n\n lookup_table = palette\n\n else:\n\n if palette is None:\n if n_colors <= len(get_color_cycle()):\n colors = color_palette(None, n_colors)\n else:\n colors = color_palette(\"husl\", n_colors)\n elif isinstance(palette, list):\n colors = self._check_list_length(levels, palette, \"palette\")\n else:\n colors = color_palette(palette, n_colors)\n\n lookup_table = dict(zip(levels, colors))\n\n return levels, lookup_table"},{"attributeType":"null","col":28,"comment":"null","endLoc":7,"id":922,"name":"plt","nodeType":"Attribute","startLoc":7,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":923,"name":"f","nodeType":"Attribute","startLoc":11,"text":"f"},{"attributeType":"null","col":8,"comment":"null","endLoc":518,"id":924,"name":"_sharex","nodeType":"Attribute","startLoc":518,"text":"self._sharex"},{"attributeType":"null","col":3,"comment":"null","endLoc":11,"id":925,"name":"ax","nodeType":"Attribute","startLoc":11,"text":"ax"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":926,"name":"crashes","nodeType":"Attribute","startLoc":14,"text":"crashes"},{"col":0,"comment":"","endLoc":5,"header":"part_whole_bars.py#","id":927,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nHorizontal bar plots\n====================\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\nf, ax = plt.subplots(figsize=(6, 15))\n\ncrashes = sns.load_dataset(\"car_crashes\").sort_values(\"total\", ascending=False)\n\nsns.set_color_codes(\"pastel\")\n\nsns.barplot(x=\"total\", y=\"abbrev\", data=crashes,\n label=\"Total\", color=\"b\")\n\nsns.set_color_codes(\"muted\")\n\nsns.barplot(x=\"alcohol\", y=\"abbrev\", data=crashes,\n label=\"Alcohol-involved\", color=\"b\")\n\nax.legend(ncol=2, loc=\"lower right\", frameon=True)\n\nax.set(xlim=(0, 24), ylabel=\"\",\n xlabel=\"Automobile collisions per billion miles\")\n\nsns.despine(left=True, bottom=True)"},{"col":4,"comment":"Get the color for a single value, using colormap to interpolate.","endLoc":196,"header":"def _lookup_single(self, key)","id":928,"name":"_lookup_single","nodeType":"Function","startLoc":170,"text":"def _lookup_single(self, key):\n \"\"\"Get the color for a single value, using colormap to interpolate.\"\"\"\n try:\n # Use a value that's in the original data vector\n value = self.lookup_table[key]\n except KeyError:\n\n if self.norm is None:\n # Currently we only get here in scatterplot with hue_order,\n # because scatterplot does not consider hue a grouping variable\n # So unused hue levels are in the data, but not the lookup table\n return (0, 0, 0, 0)\n\n # Use the colormap to interpolate between existing datapoints\n # (e.g. in the context of making a continuous legend)\n try:\n normed = self.norm(key)\n except TypeError as err:\n if np.isnan(key):\n value = (0, 0, 0, 0)\n else:\n raise err\n else:\n if np.ma.is_masked(normed):\n normed = np.nan\n value = self.cmap(normed)\n return value"},{"attributeType":"null","col":8,"comment":"null","endLoc":519,"id":929,"name":"_sharey","nodeType":"Attribute","startLoc":519,"text":"self._sharey"},{"col":4,"comment":"Parse faceting and pairing information to define figure structure.","endLoc":100,"header":"def _determine_grid_dimensions(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None","id":930,"name":"_determine_grid_dimensions","nodeType":"Function","startLoc":78,"text":"def _determine_grid_dimensions(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Parse faceting and pairing information to define figure structure.\"\"\"\n self.grid_dimensions: dict[str, list] = {}\n for dim, axis in zip([\"col\", \"row\"], [\"x\", \"y\"]):\n\n facet_vars = facet_spec.get(\"variables\", {})\n if dim in facet_vars:\n self.grid_dimensions[dim] = facet_spec[\"structure\"][dim]\n elif axis in pair_spec.get(\"structure\", {}):\n self.grid_dimensions[dim] = [\n None for _ in pair_spec.get(\"structure\", {})[axis]\n ]\n else:\n self.grid_dimensions[dim] = [None]\n\n self.subplot_spec[f\"n{dim}s\"] = len(self.grid_dimensions[dim])\n\n if not pair_spec.get(\"cross\", True):\n self.subplot_spec[\"nrows\"] = 1\n\n self.n_subplots = self.subplot_spec[\"ncols\"] * self.subplot_spec[\"nrows\"]"},{"col":4,"comment":"Update figure structure parameters based on facet/pair wrapping.","endLoc":119,"header":"def _handle_wrapping(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None","id":931,"name":"_handle_wrapping","nodeType":"Function","startLoc":102,"text":"def _handle_wrapping(\n self, facet_spec: FacetSpec, pair_spec: PairSpec\n ) -> None:\n \"\"\"Update figure structure parameters based on facet/pair wrapping.\"\"\"\n self.wrap = wrap = facet_spec.get(\"wrap\") or pair_spec.get(\"wrap\")\n if not wrap:\n return\n\n wrap_dim = \"row\" if self.subplot_spec[\"nrows\"] > 1 else \"col\"\n flow_dim = {\"row\": \"col\", \"col\": \"row\"}[wrap_dim]\n n_subplots = self.subplot_spec[f\"n{wrap_dim}s\"]\n flow = int(np.ceil(n_subplots / wrap))\n\n if wrap < self.subplot_spec[f\"n{wrap_dim}s\"]:\n self.subplot_spec[f\"n{wrap_dim}s\"] = wrap\n self.subplot_spec[f\"n{flow_dim}s\"] = flow\n self.n_subplots = n_subplots\n self.wrap_dim = wrap_dim"},{"col":4,"comment":"Update subplot spec with default or specified axis sharing parameters.","endLoc":140,"header":"def _determine_axis_sharing(self, pair_spec: PairSpec) -> None","id":932,"name":"_determine_axis_sharing","nodeType":"Function","startLoc":121,"text":"def _determine_axis_sharing(self, pair_spec: PairSpec) -> None:\n \"\"\"Update subplot spec with default or specified axis sharing parameters.\"\"\"\n axis_to_dim = {\"x\": \"col\", \"y\": \"row\"}\n key: str\n val: str | bool\n for axis in \"xy\":\n key = f\"share{axis}\"\n # Always use user-specified value, if present\n if key not in self.subplot_spec:\n if axis in pair_spec.get(\"structure\", {}):\n # Paired axes are shared along one dimension by default\n if self.wrap is None and pair_spec.get(\"cross\", True):\n val = axis_to_dim[axis]\n else:\n val = False\n else:\n # This will pick up faceted plots, as well as single subplot\n # figures, where the value doesn't really matter\n val = True\n self.subplot_spec[key] = val"},{"col":4,"comment":"Initialize matplotlib objects and add seaborn-relevant metadata.","endLoc":261,"header":"def init_figure(\n self,\n pair_spec: PairSpec,\n pyplot: bool = False,\n figure_kws: dict | None = None,\n target: Axes | Figure | SubFigure = None,\n ) -> Figure","id":933,"name":"init_figure","nodeType":"Function","startLoc":142,"text":"def init_figure(\n self,\n pair_spec: PairSpec,\n pyplot: bool = False,\n figure_kws: dict | None = None,\n target: Axes | Figure | SubFigure = None,\n ) -> Figure:\n \"\"\"Initialize matplotlib objects and add seaborn-relevant metadata.\"\"\"\n # TODO reduce need to pass pair_spec here?\n\n if figure_kws is None:\n figure_kws = {}\n\n if isinstance(target, mpl.axes.Axes):\n\n if max(self.subplot_spec[\"nrows\"], self.subplot_spec[\"ncols\"]) > 1:\n err = \" \".join([\n \"Cannot create multiple subplots after calling `Plot.on` with\",\n f\"a {mpl.axes.Axes} object.\",\n ])\n try:\n err += f\" You may want to use a {mpl.figure.SubFigure} instead.\"\n except AttributeError: # SubFigure added in mpl 3.4\n pass\n raise RuntimeError(err)\n\n self._subplot_list = [{\n \"ax\": target,\n \"left\": True,\n \"right\": True,\n \"top\": True,\n \"bottom\": True,\n \"col\": None,\n \"row\": None,\n \"x\": \"x\",\n \"y\": \"y\",\n }]\n self._figure = target.figure\n return self._figure\n\n elif (\n hasattr(mpl.figure, \"SubFigure\") # Added in mpl 3.4\n and isinstance(target, mpl.figure.SubFigure)\n ):\n figure = target.figure\n elif isinstance(target, mpl.figure.Figure):\n figure = target\n else:\n if pyplot:\n figure = plt.figure(**figure_kws)\n else:\n figure = mpl.figure.Figure(**figure_kws)\n target = figure\n self._figure = figure\n\n axs = target.subplots(**self.subplot_spec, squeeze=False)\n\n if self.wrap:\n # Remove unused Axes and flatten the rest into a (2D) vector\n axs_flat = axs.ravel({\"col\": \"C\", \"row\": \"F\"}[self.wrap_dim])\n axs, extra = np.split(axs_flat, [self.n_subplots])\n for ax in extra:\n ax.remove()\n if self.wrap_dim == \"col\":\n axs = axs[np.newaxis, :]\n else:\n axs = axs[:, np.newaxis]\n\n # Get i, j coordinates for each Axes object\n # Note that i, j are with respect to faceting/pairing,\n # not the subplot grid itself, (which only matters in the case of wrapping).\n iter_axs: np.ndenumerate | zip\n if not pair_spec.get(\"cross\", True):\n indices = np.arange(self.n_subplots)\n iter_axs = zip(zip(indices, indices), axs.flat)\n else:\n iter_axs = np.ndenumerate(axs)\n\n self._subplot_list = []\n for (i, j), ax in iter_axs:\n\n info = {\"ax\": ax}\n\n nrows, ncols = self.subplot_spec[\"nrows\"], self.subplot_spec[\"ncols\"]\n if not self.wrap:\n info[\"left\"] = j % ncols == 0\n info[\"right\"] = (j + 1) % ncols == 0\n info[\"top\"] = i == 0\n info[\"bottom\"] = i == nrows - 1\n elif self.wrap_dim == \"col\":\n info[\"left\"] = j % ncols == 0\n info[\"right\"] = ((j + 1) % ncols == 0) or ((j + 1) == self.n_subplots)\n info[\"top\"] = j < ncols\n info[\"bottom\"] = j >= (self.n_subplots - ncols)\n elif self.wrap_dim == \"row\":\n info[\"left\"] = i < nrows\n info[\"right\"] = i >= self.n_subplots - nrows\n info[\"top\"] = i % nrows == 0\n info[\"bottom\"] = ((i + 1) % nrows == 0) or ((i + 1) == self.n_subplots)\n\n if not pair_spec.get(\"cross\", True):\n info[\"top\"] = j < ncols\n info[\"bottom\"] = j >= self.n_subplots - ncols\n\n for dim in [\"row\", \"col\"]:\n idx = {\"row\": i, \"col\": j}[dim]\n info[dim] = self.grid_dimensions[dim][idx]\n\n for axis in \"xy\":\n\n idx = {\"x\": j, \"y\": i}[axis]\n if axis in pair_spec.get(\"structure\", {}):\n key = f\"{axis}{idx}\"\n else:\n key = axis\n info[axis] = key\n\n self._subplot_list.append(info)\n\n return figure"},{"fileName":"joint_histogram.py","filePath":"examples","id":934,"nodeType":"File","text":"\"\"\"\nJoint and marginal histograms\n=============================\n\n_thumb: .52, .505\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\n\n# Load the planets dataset and initialize the figure\nplanets = sns.load_dataset(\"planets\")\ng = sns.JointGrid(data=planets, x=\"year\", y=\"distance\", marginal_ticks=True)\n\n# Set a log scaling on the y axis\ng.ax_joint.set(yscale=\"log\")\n\n# Create an inset legend for the histogram colorbar\ncax = g.figure.add_axes([.15, .55, .02, .2])\n\n# Add the joint and marginal histogram plots\ng.plot_joint(\n sns.histplot, discrete=(True, False),\n cmap=\"light:#03012d\", pmax=.8, cbar=True, cbar_ax=cax\n)\ng.plot_marginals(sns.histplot, element=\"step\", color=\"#03012d\")\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":935,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"null","col":8,"comment":"null","endLoc":520,"id":936,"name":"_dropna","nodeType":"Attribute","startLoc":520,"text":"self._dropna"},{"attributeType":"None","col":4,"comment":"null","endLoc":98,"id":937,"name":"palette","nodeType":"Attribute","startLoc":98,"text":"palette"},{"attributeType":"None","col":4,"comment":"null","endLoc":101,"id":938,"name":"norm","nodeType":"Attribute","startLoc":101,"text":"norm"},{"attributeType":"None","col":4,"comment":"null","endLoc":104,"id":939,"name":"cmap","nodeType":"Attribute","startLoc":104,"text":"cmap"},{"attributeType":"str","col":12,"comment":"null","endLoc":163,"id":940,"name":"map_type","nodeType":"Attribute","startLoc":163,"text":"self.map_type"},{"attributeType":"null","col":8,"comment":"null","endLoc":514,"id":941,"name":"_legend_out","nodeType":"Attribute","startLoc":514,"text":"self._legend_out"},{"attributeType":"dict | dict","col":12,"comment":"null","endLoc":164,"id":942,"name":"lookup_table","nodeType":"Attribute","startLoc":164,"text":"self.lookup_table"},{"attributeType":"null","col":8,"comment":"null","endLoc":517,"id":943,"name":"_y_var","nodeType":"Attribute","startLoc":517,"text":"self._y_var"},{"attributeType":"null","col":8,"comment":"null","endLoc":493,"id":944,"name":"_legend","nodeType":"Attribute","startLoc":493,"text":"self._legend"},{"attributeType":"None | str","col":12,"comment":"null","endLoc":168,"id":945,"name":"cmap","nodeType":"Attribute","startLoc":168,"text":"self.cmap"},{"attributeType":"null","col":12,"comment":"null","endLoc":165,"id":946,"name":"palette","nodeType":"Attribute","startLoc":165,"text":"self.palette"},{"attributeType":"null","col":8,"comment":"null","endLoc":498,"id":947,"name":"row_names","nodeType":"Attribute","startLoc":498,"text":"self.row_names"},{"attributeType":"null","col":8,"comment":"null","endLoc":499,"id":948,"name":"col_names","nodeType":"Attribute","startLoc":499,"text":"self.col_names"},{"attributeType":"null","col":8,"comment":"null","endLoc":512,"id":949,"name":"_hue_var","nodeType":"Attribute","startLoc":512,"text":"self._hue_var"},{"attributeType":"list | list | list","col":12,"comment":"null","endLoc":166,"id":950,"name":"levels","nodeType":"Attribute","startLoc":166,"text":"self.levels"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":951,"name":"planets","nodeType":"Attribute","startLoc":12,"text":"planets"},{"attributeType":"None","col":12,"comment":"null","endLoc":167,"id":952,"name":"norm","nodeType":"Attribute","startLoc":167,"text":"self.norm"},{"className":"SizeMapping","col":0,"comment":"Mapping that sets artist sizes according to data values.","endLoc":510,"id":953,"nodeType":"Class","startLoc":291,"text":"@share_init_params_with_map\nclass SizeMapping(SemanticMapping):\n \"\"\"Mapping that sets artist sizes according to data values.\"\"\"\n # An object that normalizes data values to [0, 1] range\n norm = None\n\n def __init__(\n self, plotter, sizes=None, order=None, norm=None,\n ):\n \"\"\"Map the levels of the `size` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"size\", pd.Series(dtype=float))\n\n if data.notna().any():\n\n map_type = self.infer_map_type(\n norm, sizes, plotter.var_types[\"size\"]\n )\n\n # --- Option 1: numeric mapping\n\n if map_type == \"numeric\":\n\n levels, lookup_table, norm, size_range = self.numeric_mapping(\n data, sizes, norm,\n )\n\n # --- Option 2: categorical mapping\n\n elif map_type == \"categorical\":\n\n levels, lookup_table = self.categorical_mapping(\n data, sizes, order,\n )\n size_range = None\n\n # --- Option 3: datetime mapping\n\n # TODO this needs an actual implementation\n else:\n\n levels, lookup_table = self.categorical_mapping(\n # Casting data to list to handle differences in the way\n # pandas and numpy represent datetime64 data\n list(data), sizes, order,\n )\n size_range = None\n\n self.map_type = map_type\n self.levels = levels\n self.norm = norm\n self.sizes = sizes\n self.size_range = size_range\n self.lookup_table = lookup_table\n\n def infer_map_type(self, norm, sizes, var_type):\n\n if norm is not None:\n map_type = \"numeric\"\n elif isinstance(sizes, (dict, list)):\n map_type = \"categorical\"\n else:\n map_type = var_type\n\n return map_type\n\n def _lookup_single(self, key):\n\n try:\n value = self.lookup_table[key]\n except KeyError:\n normed = self.norm(key)\n if np.ma.is_masked(normed):\n normed = np.nan\n value = self.size_range[0] + normed * np.ptp(self.size_range)\n return value\n\n def categorical_mapping(self, data, sizes, order):\n\n levels = categorical_order(data, order)\n\n if isinstance(sizes, dict):\n\n # Dict inputs map existing data values to the size attribute\n missing = set(levels) - set(sizes)\n if any(missing):\n err = f\"Missing sizes for the following levels: {missing}\"\n raise ValueError(err)\n lookup_table = sizes.copy()\n\n elif isinstance(sizes, list):\n\n # List inputs give size values in the same order as the levels\n sizes = self._check_list_length(levels, sizes, \"sizes\")\n lookup_table = dict(zip(levels, sizes))\n\n else:\n\n if isinstance(sizes, tuple):\n\n # Tuple input sets the min, max size values\n if len(sizes) != 2:\n err = \"A `sizes` tuple must have only 2 values\"\n raise ValueError(err)\n\n elif sizes is not None:\n\n err = f\"Value for `sizes` not understood: {sizes}\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, we need to get the min, max size values from\n # the plotter object we are attached to.\n\n # TODO this is going to cause us trouble later, because we\n # want to restructure things so that the plotter is generic\n # across the visual representation of the data. But at this\n # point, we don't know the visual representation. Likely we\n # want to change the logic of this Mapping so that it gives\n # points on a normalized range that then gets un-normalized\n # when we know what we're drawing. But given the way the\n # package works now, this way is cleanest.\n sizes = self.plotter._default_size_range\n\n # For categorical sizes, use regularly-spaced linear steps\n # between the minimum and maximum sizes. Then reverse the\n # ramp so that the largest value is used for the first entry\n # in size_order, etc. This is because \"ordered\" categories\n # are often though to go in decreasing priority.\n sizes = np.linspace(*sizes, len(levels))[::-1]\n lookup_table = dict(zip(levels, sizes))\n\n return levels, lookup_table\n\n def numeric_mapping(self, data, sizes, norm):\n\n if isinstance(sizes, dict):\n # The presence of a norm object overrides a dictionary of sizes\n # in specifying a numeric mapping, so we need to process it\n # dictionary here\n levels = list(np.sort(list(sizes)))\n size_values = sizes.values()\n size_range = min(size_values), max(size_values)\n\n else:\n\n # The levels here will be the unique values in the data\n levels = list(np.sort(remove_na(data.unique())))\n\n if isinstance(sizes, tuple):\n\n # For numeric inputs, the size can be parametrized by\n # the minimum and maximum artist values to map to. The\n # norm object that gets set up next specifies how to\n # do the mapping.\n\n if len(sizes) != 2:\n err = \"A `sizes` tuple must have only 2 values\"\n raise ValueError(err)\n\n size_range = sizes\n\n elif sizes is not None:\n\n err = f\"Value for `sizes` not understood: {sizes}\"\n raise ValueError(err)\n\n else:\n\n # When not provided, we get the size range from the plotter\n # object we are attached to. See the note in the categorical\n # method about how this is suboptimal for future development.\n size_range = self.plotter._default_size_range\n\n # Now that we know the minimum and maximum sizes that will get drawn,\n # we need to map the data values that we have into that range. We will\n # use a matplotlib Normalize class, which is typically used for numeric\n # color mapping but works fine here too. It takes data values and maps\n # them into a [0, 1] interval, potentially nonlinear-ly.\n\n if norm is None:\n # Default is a linear function between the min and max data values\n norm = mpl.colors.Normalize()\n elif isinstance(norm, tuple):\n # It is also possible to give different limits in data space\n norm = mpl.colors.Normalize(*norm)\n elif not isinstance(norm, mpl.colors.Normalize):\n err = f\"Value for size `norm` parameter not understood: {norm}\"\n raise ValueError(err)\n else:\n # If provided with Normalize object, copy it so we can modify\n norm = copy(norm)\n\n # Set the mapping so all output values are in [0, 1]\n norm.clip = True\n\n # If the input range is not set, use the full range of the data\n if not norm.scaled():\n norm(levels)\n\n # Map from data values to [0, 1] range\n sizes_scaled = norm(levels)\n\n # Now map from the scaled range into the artist units\n if isinstance(sizes, dict):\n lookup_table = sizes\n else:\n lo, hi = size_range\n sizes = lo + sizes_scaled * (hi - lo)\n lookup_table = dict(zip(levels, sizes))\n\n return levels, lookup_table, norm, size_range"},{"col":4,"comment":"Map the levels of the `size` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n ","endLoc":351,"header":"def __init__(\n self, plotter, sizes=None, order=None, norm=None,\n )","id":954,"name":"__init__","nodeType":"Function","startLoc":297,"text":"def __init__(\n self, plotter, sizes=None, order=None, norm=None,\n ):\n \"\"\"Map the levels of the `size` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"size\", pd.Series(dtype=float))\n\n if data.notna().any():\n\n map_type = self.infer_map_type(\n norm, sizes, plotter.var_types[\"size\"]\n )\n\n # --- Option 1: numeric mapping\n\n if map_type == \"numeric\":\n\n levels, lookup_table, norm, size_range = self.numeric_mapping(\n data, sizes, norm,\n )\n\n # --- Option 2: categorical mapping\n\n elif map_type == \"categorical\":\n\n levels, lookup_table = self.categorical_mapping(\n data, sizes, order,\n )\n size_range = None\n\n # --- Option 3: datetime mapping\n\n # TODO this needs an actual implementation\n else:\n\n levels, lookup_table = self.categorical_mapping(\n # Casting data to list to handle differences in the way\n # pandas and numpy represent datetime64 data\n list(data), sizes, order,\n )\n size_range = None\n\n self.map_type = map_type\n self.levels = levels\n self.norm = norm\n self.sizes = sizes\n self.size_range = size_range\n self.lookup_table = lookup_table"},{"id":955,"name":"categorical.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _categorical_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Visualizing categorical data\\n\",\n \"============================\\n\",\n \" \\n\",\n \"In the :ref:`relational plot tutorial ` we saw how to use different visual representations to show the relationship between multiple variables in a dataset. In the examples, we focused on cases where the main relationship was between two numerical variables. If one of the main variables is \\\"categorical\\\" (divided into discrete groups) it may be helpful to use a more specialized approach to visualization.\\n\",\n \"\\n\",\n \"In seaborn, there are several different ways to visualize a relationship involving categorical data. Similar to the relationship between :func:`relplot` and either :func:`scatterplot` or :func:`lineplot`, there are two ways to make these plots. There are a number of axes-level functions for plotting categorical data in different ways and a figure-level interface, :func:`catplot`, that gives unified higher-level access to them.\\n\",\n \"\\n\",\n \"It's helpful to think of the different categorical plot kinds as belonging to three different families, which we'll discuss in detail below. They are:\\n\",\n \"\\n\",\n \"Categorical scatterplots:\\n\",\n \"\\n\",\n \"- :func:`stripplot` (with ``kind=\\\"strip\\\"``; the default)\\n\",\n \"- :func:`swarmplot` (with ``kind=\\\"swarm\\\"``)\\n\",\n \"\\n\",\n \"Categorical distribution plots:\\n\",\n \"\\n\",\n \"- :func:`boxplot` (with ``kind=\\\"box\\\"``)\\n\",\n \"- :func:`violinplot` (with ``kind=\\\"violin\\\"``)\\n\",\n \"- :func:`boxenplot` (with ``kind=\\\"boxen\\\"``)\\n\",\n \"\\n\",\n \"Categorical estimate plots:\\n\",\n \"\\n\",\n \"- :func:`pointplot` (with ``kind=\\\"point\\\"``)\\n\",\n \"- :func:`barplot` (with ``kind=\\\"bar\\\"``)\\n\",\n \"- :func:`countplot` (with ``kind=\\\"count\\\"``)\\n\",\n \"\\n\",\n \"These families represent the data using different levels of granularity. When deciding which to use, you'll have to think about the question that you want to answer. The unified API makes it easy to switch between different kinds and see your data from several perspectives.\\n\",\n \"\\n\",\n \"In this tutorial, we'll mostly focus on the figure-level interface, :func:`catplot`. Remember that this function is a higher-level interface each of the functions above, so we'll reference them when we show each kind of plot, keeping the more verbose kind-specific API documentation at hand.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"sns.set_theme(style=\\\"ticks\\\", color_codes=True)\\n\",\n \"np.random.seed(sum(map(ord, \\\"categorical\\\")))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Categorical scatterplots\\n\",\n \"------------------------\\n\",\n \"\\n\",\n \"The default representation of the data in :func:`catplot` uses a scatterplot. There are actually two different categorical scatter plots in seaborn. They take different approaches to resolving the main challenge in representing categorical data with a scatter plot, which is that all of the points belonging to one category would fall on the same position along the axis corresponding to the categorical variable. The approach used by :func:`stripplot`, which is the default \\\"kind\\\" in :func:`catplot` is to adjust the positions of points on the categorical axis with a small amount of random \\\"jitter\\\":\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The ``jitter`` parameter controls the magnitude of jitter or disables it altogether:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", jitter=False)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The second approach adjusts the points along the categorical axis using an algorithm that prevents them from overlapping. It can give a better representation of the distribution of observations, although it only works well for relatively small datasets. This kind of plot is sometimes called a \\\"beeswarm\\\" and is drawn in seaborn by :func:`swarmplot`, which is activated by setting ``kind=\\\"swarm\\\"`` in :func:`catplot`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", kind=\\\"swarm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Similar to the relational plots, it's possible to add another dimension to a categorical plot by using a ``hue`` semantic. (The categorical plots do not currently support ``size`` or ``style`` semantics). Each different categorical plotting function handles the ``hue`` semantic differently. For the scatter plots, it is only necessary to change the color of the points:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"sex\\\", kind=\\\"swarm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Unlike with numerical data, it is not always obvious how to order the levels of the categorical variable along its axis. In general, the seaborn categorical plotting functions try to infer the order of categories from the data. If your data have a pandas ``Categorical`` datatype, then the default order of the categories can be set there. If the variable passed to the categorical axis looks numerical, the levels will be sorted. But the data are still treated as categorical and drawn at ordinal positions on the categorical axes (specifically, at 0, 1, ...) even when numbers are used to label them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips.query(\\\"size != 3\\\"), x=\\\"size\\\", y=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The other option for choosing a default ordering is to take the levels of the category as they appear in the dataset. The ordering can also be controlled on a plot-specific basis using the ``order`` parameter. This can be important when drawing multiple categorical plots in the same figure, which we'll see more of below:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"smoker\\\", y=\\\"tip\\\", order=[\\\"No\\\", \\\"Yes\\\"])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"We've referred to the idea of \\\"categorical axis\\\". In these examples, that's always corresponded to the horizontal axis. But it's often helpful to put the categorical variable on the vertical axis (particularly when the category names are relatively long or there are many categories). To do this, swap the assignment of variables to axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"time\\\", kind=\\\"swarm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Comparing distributions\\n\",\n \"-----------------------\\n\",\n \"\\n\",\n \"As the size of the dataset grows, categorical scatter plots become limited in the information they can provide about the distribution of values within each category. When this happens, there are several approaches for summarizing the distributional information in ways that facilitate easy comparisons across the category levels.\\n\",\n \"\\n\",\n \"Boxplots\\n\",\n \"^^^^^^^^\\n\",\n \"\\n\",\n \"The first is the familiar :func:`boxplot`. This kind of plot shows the three quartile values of the distribution along with extreme values. The \\\"whiskers\\\" extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. This means that each value in the boxplot corresponds to an actual observation in the data.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", kind=\\\"box\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When adding a ``hue`` semantic, the box for each level of the semantic variable is moved along the categorical axis so they don't overlap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"smoker\\\", kind=\\\"box\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This behavior is called \\\"dodging\\\" and is turned on by default because it is assumed that the semantic variable is nested within the main categorical variable. If that's not the case, you can disable the dodging:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips[\\\"weekend\\\"] = tips[\\\"day\\\"].isin([\\\"Sat\\\", \\\"Sun\\\"])\\n\",\n \"sns.catplot(\\n\",\n \" data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"weekend\\\",\\n\",\n \" kind=\\\"box\\\", dodge=False,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A related function, :func:`boxenplot`, draws a plot that is similar to a box plot but optimized for showing more information about the shape of the distribution. It is best suited for larger datasets:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"diamonds = sns.load_dataset(\\\"diamonds\\\")\\n\",\n \"sns.catplot(\\n\",\n \" data=diamonds.sort_values(\\\"color\\\"),\\n\",\n \" x=\\\"color\\\", y=\\\"price\\\", kind=\\\"boxen\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Violinplots\\n\",\n \"^^^^^^^^^^^\\n\",\n \"\\n\",\n \"A different approach is a :func:`violinplot`, which combines a boxplot with the kernel density estimation procedure described in the :ref:`distributions ` tutorial:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\", kind=\\\"violin\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This approach uses the kernel density estimate to provide a richer description of the distribution of values. Additionally, the quartile and whisker values from the boxplot are shown inside the violin. The downside is that, because the violinplot uses a KDE, there are some other parameters that may need tweaking, adding some complexity relative to the straightforward boxplot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\",\\n\",\n \" kind=\\\"violin\\\", bw=.15, cut=0,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to \\\"split\\\" the violins when the hue parameter has only two levels, which can allow for a more efficient use of space:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"sex\\\",\\n\",\n \" kind=\\\"violin\\\", split=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Finally, there are several options for the plot that is drawn on the interior of the violins, including ways to show each individual observation instead of the summary boxplot values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"sex\\\",\\n\",\n \" kind=\\\"violin\\\", inner=\\\"stick\\\", split=True, palette=\\\"pastel\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It can also be useful to combine :func:`swarmplot` or :func:`stripplot` with a box plot or violin plot to show each observation along with a summary of the distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.catplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", kind=\\\"violin\\\", inner=None)\\n\",\n \"sns.swarmplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", color=\\\"k\\\", size=3, ax=g.ax)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Estimating central tendency\\n\",\n \"---------------------------\\n\",\n \"\\n\",\n \"For other applications, rather than showing the distribution within each category, you might want to show an estimate of the central tendency of the values. Seaborn has two main ways to show this information. Importantly, the basic API for these functions is identical to that for the ones discussed above.\\n\",\n \"\\n\",\n \"Bar plots\\n\",\n \"^^^^^^^^^\\n\",\n \"\\n\",\n \"A familiar style of plot that accomplishes this goal is a bar plot. In seaborn, the :func:`barplot` function operates on a full dataset and applies a function to obtain the estimate (taking the mean by default). When there are multiple observations in each category, it also uses bootstrapping to compute a confidence interval around the estimate, which is plotted using error bars:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"titanic = sns.load_dataset(\\\"titanic\\\")\\n\",\n \"sns.catplot(data=titanic, x=\\\"sex\\\", y=\\\"survived\\\", hue=\\\"class\\\", kind=\\\"bar\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"The default error bars show 95% confidence intervals, but (starting in v0.12), it is possible to select from a number of other representations:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=titanic, x=\\\"age\\\", y=\\\"deck\\\", errorbar=(\\\"pi\\\", 95), kind=\\\"bar\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A special case for the bar plot is when you want to show the number of observations in each category rather than computing a statistic for a second variable. This is similar to a histogram over a categorical, rather than quantitative, variable. In seaborn, it's easy to do so with the :func:`countplot` function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=titanic, x=\\\"deck\\\", kind=\\\"count\\\", palette=\\\"ch:.25\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Both :func:`barplot` and :func:`countplot` can be invoked with all of the options discussed above, along with others that are demonstrated in the detailed documentation for each function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=titanic, y=\\\"deck\\\", hue=\\\"class\\\", kind=\\\"count\\\",\\n\",\n \" palette=\\\"pastel\\\", edgecolor=\\\".6\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Point plots\\n\",\n \"^^^^^^^^^^^\\n\",\n \"\\n\",\n \"An alternative style for visualizing the same information is offered by the :func:`pointplot` function. This function also encodes the value of the estimate with height on the other axis, but rather than showing a full bar, it plots the point estimate and confidence interval. Additionally, :func:`pointplot` connects points from the same ``hue`` category. This makes it easy to see how the main relationship is changing as a function of the hue semantic, because your eyes are quite good at picking up on differences of slopes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=titanic, x=\\\"sex\\\", y=\\\"survived\\\", hue=\\\"class\\\", kind=\\\"point\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"While the categorical functions lack the ``style`` semantic of the relational functions, it can still be a good idea to vary the marker and/or linestyle along with the hue to make figures that are maximally accessible and reproduce well in black and white:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=titanic, x=\\\"class\\\", y=\\\"survived\\\", hue=\\\"sex\\\",\\n\",\n \" palette={\\\"male\\\": \\\"g\\\", \\\"female\\\": \\\"m\\\"},\\n\",\n \" markers=[\\\"^\\\", \\\"o\\\"], linestyles=[\\\"-\\\", \\\"--\\\"],\\n\",\n \" kind=\\\"point\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Showing additional dimensions\\n\",\n \"-----------------------------\\n\",\n \"\\n\",\n \"Just like :func:`relplot`, the fact that :func:`catplot` is built on a :class:`FacetGrid` means that it is easy to add faceting variables to visualize higher-dimensional relationships:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=tips, x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"smoker\\\",\\n\",\n \" kind=\\\"swarm\\\", col=\\\"time\\\", aspect=.7,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"For further customization of the plot, you can use the methods on the :class:`FacetGrid` object that it returns:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.catplot(\\n\",\n \" data=titanic,\\n\",\n \" x=\\\"fare\\\", y=\\\"embark_town\\\", row=\\\"class\\\",\\n\",\n \" kind=\\\"box\\\", orient=\\\"h\\\",\\n\",\n \" sharex=False, margin_titles=True,\\n\",\n \" height=1.5, aspect=4,\\n\",\n \")\\n\",\n \"g.set(xlabel=\\\"Fare\\\", ylabel=\\\"\\\")\\n\",\n \"g.set_titles(row_template=\\\"{row_name} class\\\")\\n\",\n \"for ax in g.axes.flat:\\n\",\n \" ax.xaxis.set_major_formatter('${x:.0f}')\"\n ]\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":956,"name":"aesthetics.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _aesthetics_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Controlling figure aesthetics\\n\",\n \"=============================\\n\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Drawing attractive figures is important. When making figures for yourself, as you explore a dataset, it's nice to have plots that are pleasant to look at. Visualizations are also central to communicating quantitative insights to an audience, and in that setting it's even more necessary to have figures that catch the attention and draw a viewer in.\\n\",\n \"\\n\",\n \"Matplotlib is highly customizable, but it can be hard to know what settings to tweak to achieve an attractive plot. Seaborn comes with a number of customized themes and a high-level interface for controlling the look of matplotlib figures.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"%matplotlib inline\\n\",\n \"np.random.seed(sum(map(ord, \\\"aesthetics\\\")))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Let's define a simple function to plot some offset sine waves, which will help us see the different stylistic parameters we can tweak.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"def sinplot(n=10, flip=1):\\n\",\n \" x = np.linspace(0, 14, 100)\\n\",\n \" for i in range(1, n + 1):\\n\",\n \" plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This is what the plot looks like with matplotlib defaults:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To switch to seaborn defaults, simply call the :func:`set_theme` function.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_theme()\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"(Note that in versions of seaborn prior to 0.8, :func:`set_theme` was called on import. On later versions, it must be explicitly invoked).\\n\",\n \"\\n\",\n \"Seaborn splits matplotlib parameters into two independent groups. The first group sets the aesthetic style of the plot, and the second scales various elements of the figure so that it can be easily incorporated into different contexts.\\n\",\n \"\\n\",\n \"The interface for manipulating these parameters are two pairs of functions. To control the style, use the :func:`axes_style` and :func:`set_style` functions. To scale the plot, use the :func:`plotting_context` and :func:`set_context` functions. In both cases, the first function returns a dictionary of parameters and the second sets the matplotlib defaults.\\n\",\n \"\\n\",\n \".. _axes_style:\\n\",\n \"\\n\",\n \"Seaborn figure styles\\n\",\n \"---------------------\\n\",\n \"\\n\",\n \"There are five preset seaborn themes: ``darkgrid``, ``whitegrid``, ``dark``, ``white``, and ``ticks``. They are each suited to different applications and personal preferences. The default theme is ``darkgrid``. As mentioned above, the grid helps the plot serve as a lookup table for quantitative information, and the white-on grey helps to keep the grid from competing with lines that represent data. The ``whitegrid`` theme is similar, but it is better suited to plots with heavy data elements:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"whitegrid\\\")\\n\",\n \"data = np.random.normal(size=(20, 6)) + np.arange(6) / 2\\n\",\n \"sns.boxplot(data=data);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"For many plots, (especially for settings like talks, where you primarily want to use figures to provide impressions of patterns in the data), the grid is less necessary.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"dark\\\")\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"white\\\")\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Sometimes you might want to give a little extra structure to the plots, which is where ticks come in handy:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"ticks\\\")\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _remove_spines:\\n\",\n \"\\n\",\n \"Removing axes spines\\n\",\n \"--------------------\\n\",\n \"\\n\",\n \"Both the ``white`` and ``ticks`` styles can benefit from removing the top and right axes spines, which are not needed. The seaborn function :func:`despine` can be called to remove them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sinplot()\\n\",\n \"sns.despine()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Some plots benefit from offsetting the spines away from the data, which can also be done when calling :func:`despine`. When the ticks don't cover the whole range of the axis, the ``trim`` parameter will limit the range of the surviving spines.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f, ax = plt.subplots()\\n\",\n \"sns.violinplot(data=data)\\n\",\n \"sns.despine(offset=10, trim=True);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can also control which spines are removed with additional arguments to :func:`despine`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"whitegrid\\\")\\n\",\n \"sns.boxplot(data=data, palette=\\\"deep\\\")\\n\",\n \"sns.despine(left=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Temporarily setting figure style\\n\",\n \"--------------------------------\\n\",\n \"\\n\",\n \"Although it's easy to switch back and forth, you can also use the :func:`axes_style` function in a ``with`` statement to temporarily set plot parameters. This also allows you to make figures with differently-styled axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f = plt.figure(figsize=(6, 6))\\n\",\n \"gs = f.add_gridspec(2, 2)\\n\",\n \"\\n\",\n \"with sns.axes_style(\\\"darkgrid\\\"):\\n\",\n \" ax = f.add_subplot(gs[0, 0])\\n\",\n \" sinplot(6)\\n\",\n \" \\n\",\n \"with sns.axes_style(\\\"white\\\"):\\n\",\n \" ax = f.add_subplot(gs[0, 1])\\n\",\n \" sinplot(6)\\n\",\n \"\\n\",\n \"with sns.axes_style(\\\"ticks\\\"):\\n\",\n \" ax = f.add_subplot(gs[1, 0])\\n\",\n \" sinplot(6)\\n\",\n \"\\n\",\n \"with sns.axes_style(\\\"whitegrid\\\"):\\n\",\n \" ax = f.add_subplot(gs[1, 1])\\n\",\n \" sinplot(6)\\n\",\n \" \\n\",\n \"f.tight_layout()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Overriding elements of the seaborn styles\\n\",\n \"-----------------------------------------\\n\",\n \"\\n\",\n \"If you want to customize the seaborn styles, you can pass a dictionary of parameters to the ``rc`` argument of :func:`axes_style` and :func:`set_style`. Note that you can only override the parameters that are part of the style definition through this method. (However, the higher-level :func:`set_theme` function takes a dictionary of any matplotlib parameters).\\n\",\n \"\\n\",\n \"If you want to see what parameters are included, you can just call the function with no arguments, which will return the current settings:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.axes_style()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can then set different versions of these parameters:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_style(\\\"darkgrid\\\", {\\\"axes.facecolor\\\": \\\".9\\\"})\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _plotting_context:\\n\",\n \"\\n\",\n \"Scaling plot elements\\n\",\n \"---------------------\\n\",\n \"\\n\",\n \"A separate set of parameters control the scale of plot elements, which should let you use the same code to make plots that are suited for use in settings where larger or smaller plots are appropriate.\\n\",\n \"\\n\",\n \"First let's reset the default parameters by calling :func:`set_theme`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The four preset contexts, in order of relative size, are ``paper``, ``notebook``, ``talk``, and ``poster``. The ``notebook`` style is the default, and was used in the plots above.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"paper\\\")\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"talk\\\")\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"poster\\\")\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Most of what you now know about the style functions should transfer to the context functions.\\n\",\n \"\\n\",\n \"You can call :func:`set_context` with one of these names to set the parameters, and you can override the parameters by providing a dictionary of parameter values.\\n\",\n \"\\n\",\n \"You can also independently scale the size of the font elements when changing the context. (This option is also available through the top-level :func:`set` function).\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_context(\\\"notebook\\\", font_scale=1.5, rc={\\\"lines.linewidth\\\": 2.5})\\n\",\n \"sinplot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Similarly, you can temporarily control the scale of figures nested under a ``with`` statement.\\n\",\n \"\\n\",\n \"Both the style and the context can be quickly configured with the :func:`set` function. This function also sets the default color palette, but that will be covered in more detail in the :ref:`next section ` of the tutorial.\"\n ]\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"attributeType":"JointGrid","col":0,"comment":"null","endLoc":13,"id":957,"name":"g","nodeType":"Attribute","startLoc":13,"text":"g"},{"fileName":"grouped_violinplots.py","filePath":"examples","id":958,"nodeType":"File","text":"\"\"\"\nGrouped violinplots with split violins\n======================================\n\n_thumb: .44, .47\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the example tips dataset\ntips = sns.load_dataset(\"tips\")\n\n# Draw a nested violinplot and split the violins for easier comparison\nsns.violinplot(data=tips, x=\"day\", y=\"total_bill\", hue=\"smoker\",\n split=True, inner=\"quart\", linewidth=1,\n palette={\"Yes\": \"b\", \"No\": \".85\"})\nsns.despine(left=True)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":959,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"col":4,"comment":"null","endLoc":362,"header":"def infer_map_type(self, norm, sizes, var_type)","id":960,"name":"infer_map_type","nodeType":"Function","startLoc":353,"text":"def infer_map_type(self, norm, sizes, var_type):\n\n if norm is not None:\n map_type = \"numeric\"\n elif isinstance(sizes, (dict, list)):\n map_type = \"categorical\"\n else:\n map_type = var_type\n\n return map_type"},{"attributeType":"null","col":8,"comment":"null","endLoc":506,"id":961,"name":"_ncol","nodeType":"Attribute","startLoc":506,"text":"self._ncol"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":962,"name":"tips","nodeType":"Attribute","startLoc":11,"text":"tips"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":963,"name":"cax","nodeType":"Attribute","startLoc":19,"text":"cax"},{"col":0,"comment":"","endLoc":6,"header":"grouped_violinplots.py#","id":964,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nGrouped violinplots with split violins\n======================================\n\n_thumb: .44, .47\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ntips = sns.load_dataset(\"tips\")\n\nsns.violinplot(data=tips, x=\"day\", y=\"total_bill\", hue=\"smoker\",\n split=True, inner=\"quart\", linewidth=1,\n palette={\"Yes\": \"b\", \"No\": \".85\"})\n\nsns.despine(left=True)"},{"col":0,"comment":"null","endLoc":2313,"header":"def violinplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n bw=\"scott\", cut=2, scale=\"area\", scale_hue=True, gridsize=100,\n width=.8, inner=\"box\", split=False, dodge=True, orient=None,\n linewidth=None, color=None, palette=None, saturation=.75,\n ax=None, **kwargs,\n)","id":965,"name":"violinplot","nodeType":"Function","startLoc":2296,"text":"def violinplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n bw=\"scott\", cut=2, scale=\"area\", scale_hue=True, gridsize=100,\n width=.8, inner=\"box\", split=False, dodge=True, orient=None,\n linewidth=None, color=None, palette=None, saturation=.75,\n ax=None, **kwargs,\n):\n\n plotter = _ViolinPlotter(x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax)\n return ax"},{"col":4,"comment":"Draw the heatmap on the provided Axes.","endLoc":352,"header":"def plot(self, ax, cax, kws)","id":966,"name":"plot","nodeType":"Function","startLoc":294,"text":"def plot(self, ax, cax, kws):\n \"\"\"Draw the heatmap on the provided Axes.\"\"\"\n # Remove all the Axes spines\n despine(ax=ax, left=True, bottom=True)\n\n # setting vmin/vmax in addition to norm is deprecated\n # so avoid setting if norm is set\n if \"norm\" not in kws:\n kws.setdefault(\"vmin\", self.vmin)\n kws.setdefault(\"vmax\", self.vmax)\n\n # Draw the heatmap\n mesh = ax.pcolormesh(self.plot_data, cmap=self.cmap, **kws)\n\n # Set the axis limits\n ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0]))\n\n # Invert the y axis to show the plot in matrix form\n ax.invert_yaxis()\n\n # Possibly add a colorbar\n if self.cbar:\n cb = ax.figure.colorbar(mesh, cax, ax, **self.cbar_kws)\n cb.outline.set_linewidth(0)\n # If rasterized is passed to pcolormesh, also rasterize the\n # colorbar to avoid white lines on the PDF rendering\n if kws.get('rasterized', False):\n cb.solids.set_rasterized(True)\n\n # Add row and column labels\n if isinstance(self.xticks, str) and self.xticks == \"auto\":\n xticks, xticklabels = self._auto_ticks(ax, self.xticklabels, 0)\n else:\n xticks, xticklabels = self.xticks, self.xticklabels\n\n if isinstance(self.yticks, str) and self.yticks == \"auto\":\n yticks, yticklabels = self._auto_ticks(ax, self.yticklabels, 1)\n else:\n yticks, yticklabels = self.yticks, self.yticklabels\n\n ax.set(xticks=xticks, yticks=yticks)\n xtl = ax.set_xticklabels(xticklabels)\n ytl = ax.set_yticklabels(yticklabels, rotation=\"vertical\")\n plt.setp(ytl, va=\"center\") # GH2484\n\n # Possibly rotate them if they overlap\n _draw_figure(ax.figure)\n\n if axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n if axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n\n # Add the axis labels\n ax.set(xlabel=self.xlabel, ylabel=self.ylabel)\n\n # Annotate the cells with the formatted values\n if self.annot:\n self._annotate_heatmap(ax, mesh)"},{"attributeType":"null","col":8,"comment":"null","endLoc":513,"id":967,"name":"_colors","nodeType":"Attribute","startLoc":513,"text":"self._colors"},{"col":0,"comment":"","endLoc":7,"header":"joint_histogram.py#","id":968,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nJoint and marginal histograms\n=============================\n\n_thumb: .52, .505\n\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\nplanets = sns.load_dataset(\"planets\")\n\ng = sns.JointGrid(data=planets, x=\"year\", y=\"distance\", marginal_ticks=True)\n\ng.ax_joint.set(yscale=\"log\")\n\ncax = g.figure.add_axes([.15, .55, .02, .2])\n\ng.plot_joint(\n sns.histplot, discrete=(True, False),\n cmap=\"light:#03012d\", pmax=.8, cbar=True, cbar_ax=cax\n)\n\ng.plot_marginals(sns.histplot, element=\"step\", color=\"#03012d\")"},{"col":4,"comment":"null","endLoc":925,"header":"def __init__(self, x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation)","id":969,"name":"__init__","nodeType":"Function","startLoc":896,"text":"def __init__(self, x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n self.estimate_densities(bw, cut, scale, scale_hue, gridsize)\n\n self.gridsize = gridsize\n self.width = width\n self.dodge = dodge\n\n if inner is not None:\n if not any([inner.startswith(\"quart\"),\n inner.startswith(\"box\"),\n inner.startswith(\"stick\"),\n inner.startswith(\"point\")]):\n err = f\"Inner style '{inner}' not recognized\"\n raise ValueError(err)\n self.inner = inner\n\n if split and self.hue_names is not None and len(self.hue_names) != 2:\n msg = \"There must be exactly two hue levels to use `split`.'\"\n raise ValueError(msg)\n self.split = split\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth"},{"col":4,"comment":"Draw a bivariate plot on the joint axes of the grid.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y``. Otherwise,\n it must accept ``x`` and ``y`` vectors of data as the first two\n positional arguments, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, the function must\n accept ``hue`` as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n ","endLoc":1830,"header":"def plot_joint(self, func, **kwargs)","id":970,"name":"plot_joint","nodeType":"Function","startLoc":1796,"text":"def plot_joint(self, func, **kwargs):\n \"\"\"Draw a bivariate plot on the joint axes of the grid.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y``. Otherwise,\n it must accept ``x`` and ``y`` vectors of data as the first two\n positional arguments, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, the function must\n accept ``hue`` as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = self.ax_joint\n else:\n plt.sca(self.ax_joint)\n if self.hue is not None:\n kwargs[\"hue\"] = self.hue\n self._inject_kwargs(func, kwargs, self._hue_params)\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=self.x, y=self.y, **kwargs)\n else:\n func(self.x, self.y, **kwargs)\n\n return self"},{"attributeType":"null","col":8,"comment":"null","endLoc":515,"id":971,"name":"_legend_data","nodeType":"Attribute","startLoc":515,"text":"self._legend_data"},{"attributeType":"null","col":8,"comment":"null","endLoc":504,"id":972,"name":"_nrow","nodeType":"Attribute","startLoc":504,"text":"self._nrow"},{"attributeType":"null","col":8,"comment":"null","endLoc":500,"id":973,"name":"hue_names","nodeType":"Attribute","startLoc":500,"text":"self.hue_names"},{"attributeType":"function","col":8,"comment":"null","endLoc":492,"id":974,"name":"_axes_dict","nodeType":"Attribute","startLoc":492,"text":"self._axes_dict"},{"col":4,"comment":"Get a list of colors for the main component of the plots.","endLoc":712,"header":"def establish_colors(self, color, palette, saturation)","id":975,"name":"establish_colors","nodeType":"Function","startLoc":655,"text":"def establish_colors(self, color, palette, saturation):\n \"\"\"Get a list of colors for the main component of the plots.\"\"\"\n if self.hue_names is None:\n n_colors = len(self.plot_data)\n else:\n n_colors = len(self.hue_names)\n\n # Determine the main colors\n if color is None and palette is None:\n # Determine whether the current palette will have enough values\n # If not, we'll default to the husl palette so each is distinct\n current_palette = utils.get_color_cycle()\n if n_colors <= len(current_palette):\n colors = color_palette(n_colors=n_colors)\n else:\n colors = husl_palette(n_colors, l=.7) # noqa\n\n elif palette is None:\n # When passing a specific color, the interpretation depends\n # on whether there is a hue variable or not.\n # If so, we will make a blend palette so that the different\n # levels have some amount of variation.\n if self.hue_names is None:\n colors = [color] * n_colors\n else:\n if self.default_palette == \"light\":\n colors = light_palette(color, n_colors)\n elif self.default_palette == \"dark\":\n colors = dark_palette(color, n_colors)\n else:\n raise RuntimeError(\"No default palette specified\")\n else:\n\n # Let `palette` be a dict mapping level to color\n if isinstance(palette, dict):\n if self.hue_names is None:\n levels = self.group_names\n else:\n levels = self.hue_names\n palette = [palette[l] for l in levels]\n\n colors = color_palette(palette, n_colors)\n\n # Desaturate a bit because these are patches\n if saturation < 1:\n colors = color_palette(colors, desat=saturation)\n\n # Convert the colors to a common representations\n rgb_colors = color_palette(colors)\n\n # Determine the gray color to use for the lines framing the plot\n light_vals = [rgb_to_hls(*c)[1] for c in rgb_colors]\n lum = min(light_vals) * .6\n gray = mpl.colors.rgb2hex((lum, lum, lum))\n\n # Assign object attributes\n self.colors = rgb_colors\n self.gray = gray"},{"attributeType":"null","col":8,"comment":"null","endLoc":501,"id":976,"name":"hue_kws","nodeType":"Attribute","startLoc":501,"text":"self.hue_kws"},{"attributeType":"function","col":8,"comment":"null","endLoc":491,"id":977,"name":"_axes","nodeType":"Attribute","startLoc":491,"text":"self._axes"},{"col":4,"comment":"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n like : str or callable\n Either a format pattern (e.g., `\".2f\"`), a format string with fields named\n `x` and/or `pos` (e.g., `\"${x:.2f}\"`), or a callable that consumes a number\n and returns a string.\n base : number\n Use log formatter (with scientific notation) having this value as the base.\n unit : str or (str, str) tuple\n Use SI prefixes with these units (e.g., with `unit=\"g\"`, a tick value\n of 5000 will appear as `5 kg`). When a tuple, the first element gives the\n separator between the number and unit.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n ","endLoc":536,"header":"def label(\n self,\n formatter: Formatter | None = None, *,\n like: str | Callable | None = None,\n base: int | None = None,\n unit: str | None = None,\n ) -> Continuous","id":978,"name":"label","nodeType":"Function","startLoc":488,"text":"def label(\n self,\n formatter: Formatter | None = None, *,\n like: str | Callable | None = None,\n base: int | None = None,\n unit: str | None = None,\n ) -> Continuous:\n \"\"\"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n like : str or callable\n Either a format pattern (e.g., `\".2f\"`), a format string with fields named\n `x` and/or `pos` (e.g., `\"${x:.2f}\"`), or a callable that consumes a number\n and returns a string.\n base : number\n Use log formatter (with scientific notation) having this value as the base.\n unit : str or (str, str) tuple\n Use SI prefixes with these units (e.g., with `unit=\"g\"`, a tick value\n of 5000 will appear as `5 kg`). When a tuple, the first element gives the\n separator between the number and unit.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n \"\"\"\n # Input checks\n if formatter is not None and not isinstance(formatter, Formatter):\n raise TypeError(\n f\"Label formatter must be an instance of {Formatter!r}, \"\n f\"not {type(formatter)!r}\"\n )\n if like is not None and not (isinstance(like, str) or callable(like)):\n msg = f\"`like` must be a string or callable, not {type(like).__name__}.\"\n raise TypeError(msg)\n\n new = copy(self)\n new._label_params = {\n \"formatter\": formatter,\n \"like\": like,\n \"base\": base,\n \"unit\": unit,\n }\n return new"},{"attributeType":"null","col":8,"comment":"null","endLoc":510,"id":979,"name":"_margin_titles_texts","nodeType":"Attribute","startLoc":510,"text":"self._margin_titles_texts"},{"attributeType":"null","col":8,"comment":"null","endLoc":509,"id":980,"name":"_margin_titles","nodeType":"Attribute","startLoc":509,"text":"self._margin_titles"},{"attributeType":"function","col":8,"comment":"null","endLoc":490,"id":981,"name":"_figure","nodeType":"Attribute","startLoc":490,"text":"self._figure"},{"attributeType":"null","col":8,"comment":"null","endLoc":505,"id":982,"name":"_row_var","nodeType":"Attribute","startLoc":505,"text":"self._row_var"},{"attributeType":"null","col":0,"comment":"null","endLoc":304,"id":983,"name":"_facet_docs","nodeType":"Attribute","startLoc":304,"text":"_facet_docs"},{"className":"_LinearPlotter","col":0,"comment":"Base class for plotting relational data in tidy format.\n\n To get anything useful done you'll have to inherit from this, but setup\n code that can be abstracted out should be put here.\n\n ","endLoc":67,"id":984,"nodeType":"Class","startLoc":25,"text":"class _LinearPlotter:\n \"\"\"Base class for plotting relational data in tidy format.\n\n To get anything useful done you'll have to inherit from this, but setup\n code that can be abstracted out should be put here.\n\n \"\"\"\n def establish_variables(self, data, **kws):\n \"\"\"Extract variables from data or use directly.\"\"\"\n self.data = data\n\n # Validate the inputs\n any_strings = any([isinstance(v, str) for v in kws.values()])\n if any_strings and data is None:\n raise ValueError(\"Must pass `data` if using named variables.\")\n\n # Set the variables\n for var, val in kws.items():\n if isinstance(val, str):\n vector = data[val]\n elif isinstance(val, list):\n vector = np.asarray(val)\n else:\n vector = val\n if vector is not None and vector.shape != (1,):\n vector = np.squeeze(vector)\n if np.ndim(vector) > 1:\n err = \"regplot inputs must be 1d\"\n raise ValueError(err)\n setattr(self, var, vector)\n\n def dropna(self, *vars):\n \"\"\"Remove observations with missing data.\"\"\"\n vals = [getattr(self, var) for var in vars]\n vals = [v for v in vals if v is not None]\n not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1)\n for var in vars:\n val = getattr(self, var)\n if val is not None:\n setattr(self, var, val[not_na])\n\n def plot(self, ax):\n raise NotImplementedError"},{"col":4,"comment":"Extract variables from data or use directly.","endLoc":54,"header":"def establish_variables(self, data, **kws)","id":985,"name":"establish_variables","nodeType":"Function","startLoc":32,"text":"def establish_variables(self, data, **kws):\n \"\"\"Extract variables from data or use directly.\"\"\"\n self.data = data\n\n # Validate the inputs\n any_strings = any([isinstance(v, str) for v in kws.values()])\n if any_strings and data is None:\n raise ValueError(\"Must pass `data` if using named variables.\")\n\n # Set the variables\n for var, val in kws.items():\n if isinstance(val, str):\n vector = data[val]\n elif isinstance(val, list):\n vector = np.asarray(val)\n else:\n vector = val\n if vector is not None and vector.shape != (1,):\n vector = np.squeeze(vector)\n if np.ndim(vector) > 1:\n err = \"regplot inputs must be 1d\"\n raise ValueError(err)\n setattr(self, var, vector)"},{"col":4,"comment":"Find the support and density for all of the data.","endLoc":1050,"header":"def estimate_densities(self, bw, cut, scale, scale_hue, gridsize)","id":986,"name":"estimate_densities","nodeType":"Function","startLoc":927,"text":"def estimate_densities(self, bw, cut, scale, scale_hue, gridsize):\n \"\"\"Find the support and density for all of the data.\"\"\"\n # Initialize data structures to keep track of plotting data\n if self.hue_names is None:\n support = []\n density = []\n counts = np.zeros(len(self.plot_data))\n max_density = np.zeros(len(self.plot_data))\n else:\n support = [[] for _ in self.plot_data]\n density = [[] for _ in self.plot_data]\n size = len(self.group_names), len(self.hue_names)\n counts = np.zeros(size)\n max_density = np.zeros(size)\n\n for i, group_data in enumerate(self.plot_data):\n\n # Option 1: we have a single level of grouping\n # --------------------------------------------\n\n if self.plot_hues is None:\n\n # Strip missing datapoints\n kde_data = remove_na(group_data)\n\n # Handle special case of no data at this level\n if kde_data.size == 0:\n support.append(np.array([]))\n density.append(np.array([1.]))\n counts[i] = 0\n max_density[i] = 0\n continue\n\n # Handle special case of a single unique datapoint\n elif np.unique(kde_data).size == 1:\n support.append(np.unique(kde_data))\n density.append(np.array([1.]))\n counts[i] = 1\n max_density[i] = 0\n continue\n\n # Fit the KDE and get the used bandwidth size\n kde, bw_used = self.fit_kde(kde_data, bw)\n\n # Determine the support grid and get the density over it\n support_i = self.kde_support(kde_data, bw_used, cut, gridsize)\n density_i = kde.evaluate(support_i)\n\n # Update the data structures with these results\n support.append(support_i)\n density.append(density_i)\n counts[i] = kde_data.size\n max_density[i] = density_i.max()\n\n # Option 2: we have nested grouping by a hue variable\n # ---------------------------------------------------\n\n else:\n for j, hue_level in enumerate(self.hue_names):\n\n # Handle special case of no data at this category level\n if not group_data.size:\n support[i].append(np.array([]))\n density[i].append(np.array([1.]))\n counts[i, j] = 0\n max_density[i, j] = 0\n continue\n\n # Select out the observations for this hue level\n hue_mask = self.plot_hues[i] == hue_level\n\n # Strip missing datapoints\n kde_data = remove_na(group_data[hue_mask])\n\n # Handle special case of no data at this level\n if kde_data.size == 0:\n support[i].append(np.array([]))\n density[i].append(np.array([1.]))\n counts[i, j] = 0\n max_density[i, j] = 0\n continue\n\n # Handle special case of a single unique datapoint\n elif np.unique(kde_data).size == 1:\n support[i].append(np.unique(kde_data))\n density[i].append(np.array([1.]))\n counts[i, j] = 1\n max_density[i, j] = 0\n continue\n\n # Fit the KDE and get the used bandwidth size\n kde, bw_used = self.fit_kde(kde_data, bw)\n\n # Determine the support grid and get the density over it\n support_ij = self.kde_support(kde_data, bw_used,\n cut, gridsize)\n density_ij = kde.evaluate(support_ij)\n\n # Update the data structures with these results\n support[i].append(support_ij)\n density[i].append(density_ij)\n counts[i, j] = kde_data.size\n max_density[i, j] = density_ij.max()\n\n # Scale the height of the density curve.\n # For a violinplot the density is non-quantitative.\n # The objective here is to scale the curves relative to 1 so that\n # they can be multiplied by the width parameter during plotting.\n\n if scale == \"area\":\n self.scale_area(density, max_density, scale_hue)\n\n elif scale == \"width\":\n self.scale_width(density)\n\n elif scale == \"count\":\n self.scale_count(density, counts, scale_hue)\n\n else:\n raise ValueError(f\"scale method '{scale}' not recognized\")\n\n # Set object attributes that will be used while plotting\n self.support = support\n self.density = density"},{"col":4,"comment":"null","endLoc":606,"header":"def _get_locators(self, locator, at, upto, count, every, between, minor)","id":987,"name":"_get_locators","nodeType":"Function","startLoc":552,"text":"def _get_locators(self, locator, at, upto, count, every, between, minor):\n\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n\n if locator is not None:\n major_locator = locator\n\n elif upto is not None:\n if log_base:\n major_locator = LogLocator(base=log_base, numticks=upto)\n else:\n major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10])\n\n elif count is not None:\n if between is None:\n # This is rarely useful (unless you are setting limits)\n major_locator = LinearLocator(count)\n else:\n if log_base or symlog_thresh:\n forward, inverse = self._get_transform()\n lo, hi = forward(between)\n ticks = inverse(np.linspace(lo, hi, num=count))\n else:\n ticks = np.linspace(*between, num=count)\n major_locator = FixedLocator(ticks)\n\n elif every is not None:\n if between is None:\n major_locator = MultipleLocator(every)\n else:\n lo, hi = between\n ticks = np.arange(lo, hi + every, every)\n major_locator = FixedLocator(ticks)\n\n elif at is not None:\n major_locator = FixedLocator(at)\n\n else:\n if log_base:\n major_locator = LogLocator(log_base)\n elif symlog_thresh:\n major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10)\n else:\n major_locator = AutoLocator()\n\n if minor is None:\n minor_locator = LogLocator(log_base, subs=None) if log_base else None\n else:\n if log_base:\n subs = np.linspace(0, log_base, minor + 2)[1:-1]\n minor_locator = LogLocator(log_base, subs=subs)\n else:\n minor_locator = AutoMinorLocator(minor + 1)\n\n return major_locator, minor_locator"},{"col":4,"comment":"Group a long-form variable by another with correct order.","endLoc":653,"header":"def _group_longform(self, vals, grouper, order)","id":988,"name":"_group_longform","nodeType":"Function","startLoc":630,"text":"def _group_longform(self, vals, grouper, order):\n \"\"\"Group a long-form variable by another with correct order.\"\"\"\n # Ensure that the groupby will work\n if not isinstance(vals, pd.Series):\n if isinstance(grouper, pd.Series):\n index = grouper.index\n else:\n index = None\n vals = pd.Series(vals, index=index)\n\n # Group the val data\n grouped_vals = vals.groupby(grouper)\n out_data = []\n for g in order:\n try:\n g_vals = grouped_vals.get_group(g)\n except KeyError:\n g_vals = np.array([])\n out_data.append(g_vals)\n\n # Get the vals axis label\n label = vals.name\n\n return out_data, label"},{"col":4,"comment":"Add params to kws if they are accepted by func.","endLoc":1768,"header":"def _inject_kwargs(self, func, kws, params)","id":989,"name":"_inject_kwargs","nodeType":"Function","startLoc":1763,"text":"def _inject_kwargs(self, func, kws, params):\n \"\"\"Add params to kws if they are accepted by func.\"\"\"\n func_params = signature(func).parameters\n for key, val in params.items():\n if key in func_params:\n kws.setdefault(key, val)"},{"col":4,"comment":"null","endLoc":1087,"header":"def values(self) -> dict_values[_KT, _VT]","id":990,"name":"values","nodeType":"Function","startLoc":1087,"text":"def values(self) -> dict_values[_KT, _VT]: ..."},{"col":4,"comment":"Draw univariate plots on each marginal axes.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y`` and plot\n when only one of them is defined. Otherwise, it must accept a vector\n of data as the first positional argument and determine its orientation\n using the ``vertical`` parameter, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, it must accept ``hue``\n as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n ","endLoc":1891,"header":"def plot_marginals(self, func, **kwargs)","id":991,"name":"plot_marginals","nodeType":"Function","startLoc":1832,"text":"def plot_marginals(self, func, **kwargs):\n \"\"\"Draw univariate plots on each marginal axes.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y`` and plot\n when only one of them is defined. Otherwise, it must accept a vector\n of data as the first positional argument and determine its orientation\n using the ``vertical`` parameter, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, it must accept ``hue``\n as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n seaborn_func = (\n str(func.__module__).startswith(\"seaborn\")\n # deprecated distplot has a legacy API, special case it\n and not func.__name__ == \"distplot\"\n )\n func_params = signature(func).parameters\n kwargs = kwargs.copy()\n if self.hue is not None:\n kwargs[\"hue\"] = self.hue\n self._inject_kwargs(func, kwargs, self._hue_params)\n\n if \"legend\" in func_params:\n kwargs.setdefault(\"legend\", False)\n\n if \"orientation\" in func_params:\n # e.g. plt.hist\n orient_kw_x = {\"orientation\": \"vertical\"}\n orient_kw_y = {\"orientation\": \"horizontal\"}\n elif \"vertical\" in func_params:\n # e.g. sns.distplot (also how did this get backwards?)\n orient_kw_x = {\"vertical\": False}\n orient_kw_y = {\"vertical\": True}\n\n if seaborn_func:\n func(x=self.x, ax=self.ax_marg_x, **kwargs)\n else:\n plt.sca(self.ax_marg_x)\n func(self.x, **orient_kw_x, **kwargs)\n\n if seaborn_func:\n func(y=self.y, ax=self.ax_marg_y, **kwargs)\n else:\n plt.sca(self.ax_marg_y)\n func(self.y, **orient_kw_y, **kwargs)\n\n self.ax_marg_x.yaxis.get_label().set_visible(False)\n self.ax_marg_y.xaxis.get_label().set_visible(False)\n\n return self"},{"col":4,"comment":"null","endLoc":1492,"header":"def estimate_statistic(self, estimator, errorbar, n_boot, seed)","id":992,"name":"estimate_statistic","nodeType":"Function","startLoc":1438,"text":"def estimate_statistic(self, estimator, errorbar, n_boot, seed):\n\n if self.hue_names is None:\n statistic = []\n confint = []\n else:\n statistic = [[] for _ in self.plot_data]\n confint = [[] for _ in self.plot_data]\n\n var = {\"v\": \"y\", \"h\": \"x\"}[self.orient]\n\n agg = EstimateAggregator(estimator, errorbar, n_boot=n_boot, seed=seed)\n\n for i, group_data in enumerate(self.plot_data):\n\n # Option 1: we have a single layer of grouping\n # --------------------------------------------\n if self.plot_hues is None:\n\n df = pd.DataFrame({var: group_data})\n if self.plot_units is not None:\n df[\"units\"] = self.plot_units[i]\n\n res = agg(df, var)\n\n statistic.append(res[var])\n if errorbar is not None:\n confint.append((res[f\"{var}min\"], res[f\"{var}max\"]))\n\n # Option 2: we are grouping by a hue layer\n # ----------------------------------------\n\n else:\n for hue_level in self.hue_names:\n\n if not self.plot_hues[i].size:\n statistic[i].append(np.nan)\n if errorbar is not None:\n confint[i].append((np.nan, np.nan))\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n df = pd.DataFrame({var: group_data[hue_mask]})\n if self.plot_units is not None:\n df[\"units\"] = self.plot_units[i][hue_mask]\n\n res = agg(df, var)\n\n statistic[i].append(res[var])\n if errorbar is not None:\n confint[i].append((res[f\"{var}min\"], res[f\"{var}max\"]))\n\n # Save the resulting values for plotting\n self.statistic = np.array(statistic)\n self.confint = np.array(confint)"},{"attributeType":"str","col":8,"comment":"null","endLoc":160,"id":993,"name":"ylabel","nodeType":"Attribute","startLoc":160,"text":"self.ylabel"},{"col":4,"comment":"null","endLoc":645,"header":"def _get_formatter(self, locator, formatter, like, base, unit)","id":994,"name":"_get_formatter","nodeType":"Function","startLoc":608,"text":"def _get_formatter(self, locator, formatter, like, base, unit):\n\n log_base, symlog_thresh = self._parse_for_log_params(self.trans)\n if base is None:\n if symlog_thresh:\n log_base = 10\n base = log_base\n\n if formatter is not None:\n return formatter\n\n if like is not None:\n if isinstance(like, str):\n if \"{x\" in like or \"{pos\" in like:\n fmt = like\n else:\n fmt = f\"{{x:{like}}}\"\n formatter = StrMethodFormatter(fmt)\n else:\n formatter = FuncFormatter(like)\n\n elif base is not None:\n # We could add other log options if necessary\n formatter = LogFormatterSciNotation(base)\n\n elif unit is not None:\n if isinstance(unit, tuple):\n sep, unit = unit\n elif not unit:\n sep = \"\"\n else:\n sep = \" \"\n formatter = EngFormatter(unit, sep=sep)\n\n else:\n formatter = ScalarFormatter()\n\n return formatter"},{"col":4,"comment":"\n Data aggregator that produces an estimate and error bar interval.\n\n Parameters\n ----------\n estimator : callable or string\n Function (or method name) that maps a vector to a scalar.\n errorbar : string, (string, number) tuple, or callable\n Name of errorbar method (either \"ci\", \"pi\", \"se\", or \"sd\"), or a tuple\n with a method name and a level parameter, or a function that maps from a\n vector to a (min, max) interval.\n boot_kws\n Additional keywords are passed to bootstrap when error_method is \"ci\".\n\n ","endLoc":478,"header":"def __init__(self, estimator, errorbar=None, **boot_kws)","id":995,"name":"__init__","nodeType":"Function","startLoc":456,"text":"def __init__(self, estimator, errorbar=None, **boot_kws):\n \"\"\"\n Data aggregator that produces an estimate and error bar interval.\n\n Parameters\n ----------\n estimator : callable or string\n Function (or method name) that maps a vector to a scalar.\n errorbar : string, (string, number) tuple, or callable\n Name of errorbar method (either \"ci\", \"pi\", \"se\", or \"sd\"), or a tuple\n with a method name and a level parameter, or a function that maps from a\n vector to a (min, max) interval.\n boot_kws\n Additional keywords are passed to bootstrap when error_method is \"ci\".\n\n \"\"\"\n self.estimator = estimator\n\n method, level = _validate_errorbar_arg(errorbar)\n self.error_method = method\n self.error_level = level\n\n self.boot_kws = boot_kws"},{"col":0,"comment":"Check type and value of errorbar argument and assign default level.","endLoc":554,"header":"def _validate_errorbar_arg(arg)","id":996,"name":"_validate_errorbar_arg","nodeType":"Function","startLoc":526,"text":"def _validate_errorbar_arg(arg):\n \"\"\"Check type and value of errorbar argument and assign default level.\"\"\"\n DEFAULT_LEVELS = {\n \"ci\": 95,\n \"pi\": 95,\n \"se\": 1,\n \"sd\": 1,\n }\n\n usage = \"`errorbar` must be a callable, string, or (string, number) tuple\"\n\n if arg is None:\n return None, None\n elif callable(arg):\n return arg, None\n elif isinstance(arg, str):\n method = arg\n level = DEFAULT_LEVELS.get(method, None)\n else:\n try:\n method, level = arg\n except (ValueError, TypeError) as err:\n raise err.__class__(usage) from err\n\n _check_argument(\"errorbar\", list(DEFAULT_LEVELS), method)\n if level is not None and not isinstance(level, Number):\n raise TypeError(usage)\n\n return method, level"},{"attributeType":"{columns, index}","col":8,"comment":"null","endLoc":181,"id":997,"name":"data","nodeType":"Attribute","startLoc":181,"text":"self.data"},{"attributeType":"tuple | str | None","col":4,"comment":"null","endLoc":419,"id":998,"name":"values","nodeType":"Attribute","startLoc":419,"text":"values"},{"attributeType":"str | ((Any) -> Any, (Any) -> Any) | None","col":4,"comment":"null","endLoc":420,"id":999,"name":"trans","nodeType":"Attribute","startLoc":420,"text":"trans"},{"attributeType":"int","col":4,"comment":"null","endLoc":425,"id":1000,"name":"_priority","nodeType":"Attribute","startLoc":425,"text":"_priority"},{"className":"Temporal","col":0,"comment":"\n A scale for date/time data.\n ","endLoc":755,"id":1001,"nodeType":"Class","startLoc":648,"text":"@dataclass\nclass Temporal(ContinuousBase):\n \"\"\"\n A scale for date/time data.\n \"\"\"\n # TODO date: bool?\n # For when we only care about the time component, would affect\n # default formatter and norm conversion. Should also happen in\n # Property.default_scale. The alternative was having distinct\n # Calendric / Temporal scales, but that feels a bit fussy, and it\n # would get in the way of using first-letter shorthands because\n # Calendric and Continuous would collide. Still, we haven't implemented\n # those yet, and having a clear distinction betewen date(time) / time\n # may be more useful.\n\n trans = None\n\n _priority: ClassVar[int] = 2\n\n def tick(\n self, locator: Locator | None = None, *,\n upto: int | None = None,\n ) -> Temporal:\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n if locator is not None and not isinstance(locator, Locator):\n err = (\n f\"Tick locator must be an instance of {Locator!r}, \"\n f\"not {type(locator)!r}.\"\n )\n raise TypeError(err)\n\n new = copy(self)\n new._tick_params = {\"locator\": locator, \"upto\": upto}\n return new\n\n def label(\n self,\n formatter: Formatter | None = None, *,\n concise: bool = False,\n ) -> Temporal:\n \"\"\"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n concise : bool\n If True, use :class:`matplotlib.dates.ConciseDateFormatter` to make\n the tick labels as compact as possible.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n \"\"\"\n new = copy(self)\n new._label_params = {\"formatter\": formatter, \"concise\": concise}\n return new\n\n def _get_locators(self, locator, upto):\n\n if locator is not None:\n major_locator = locator\n elif upto is not None:\n major_locator = AutoDateLocator(minticks=2, maxticks=upto)\n\n else:\n major_locator = AutoDateLocator(minticks=2, maxticks=6)\n minor_locator = None\n\n return major_locator, minor_locator\n\n def _get_formatter(self, locator, formatter, concise):\n\n if formatter is not None:\n return formatter\n\n if concise:\n # TODO ideally we would have concise coordinate ticks,\n # but full semantic ticks. Is that possible?\n formatter = ConciseDateFormatter(locator)\n else:\n formatter = AutoDateFormatter(locator)\n\n return formatter"},{"col":4,"comment":"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n ","endLoc":699,"header":"def tick(\n self, locator: Locator | None = None, *,\n upto: int | None = None,\n ) -> Temporal","id":1002,"name":"tick","nodeType":"Function","startLoc":667,"text":"def tick(\n self, locator: Locator | None = None, *,\n upto: int | None = None,\n ) -> Temporal:\n \"\"\"\n Configure the selection of ticks for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n locator : :class:`matplotlib.ticker.Locator` subclass\n Pre-configured matplotlib locator; other parameters will not be used.\n upto : int\n Choose \"nice\" locations for ticks, but do not exceed this number.\n\n Returns\n -------\n scale\n Copy of self with new tick configuration.\n\n \"\"\"\n if locator is not None and not isinstance(locator, Locator):\n err = (\n f\"Tick locator must be an instance of {Locator!r}, \"\n f\"not {type(locator)!r}.\"\n )\n raise TypeError(err)\n\n new = copy(self)\n new._tick_params = {\"locator\": locator, \"upto\": upto}\n return new"},{"col":4,"comment":"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n concise : bool\n If True, use :class:`matplotlib.dates.ConciseDateFormatter` to make\n the tick labels as compact as possible.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n ","endLoc":728,"header":"def label(\n self,\n formatter: Formatter | None = None, *,\n concise: bool = False,\n ) -> Temporal","id":1003,"name":"label","nodeType":"Function","startLoc":701,"text":"def label(\n self,\n formatter: Formatter | None = None, *,\n concise: bool = False,\n ) -> Temporal:\n \"\"\"\n Configure the appearance of tick labels for the scale's axis or legend.\n\n .. note::\n This API is under construction and will be enhanced over time.\n\n Parameters\n ----------\n formatter : :class:`matplotlib.ticker.Formatter` subclass\n Pre-configured formatter to use; other parameters will be ignored.\n concise : bool\n If True, use :class:`matplotlib.dates.ConciseDateFormatter` to make\n the tick labels as compact as possible.\n\n Returns\n -------\n scale\n Copy of self with new label configuration.\n\n \"\"\"\n new = copy(self)\n new._label_params = {\"formatter\": formatter, \"concise\": concise}\n return new"},{"col":4,"comment":"null","endLoc":741,"header":"def _get_locators(self, locator, upto)","id":1004,"name":"_get_locators","nodeType":"Function","startLoc":730,"text":"def _get_locators(self, locator, upto):\n\n if locator is not None:\n major_locator = locator\n elif upto is not None:\n major_locator = AutoDateLocator(minticks=2, maxticks=upto)\n\n else:\n major_locator = AutoDateLocator(minticks=2, maxticks=6)\n minor_locator = None\n\n return major_locator, minor_locator"},{"col":4,"comment":"null","endLoc":755,"header":"def _get_formatter(self, locator, formatter, concise)","id":1005,"name":"_get_formatter","nodeType":"Function","startLoc":743,"text":"def _get_formatter(self, locator, formatter, concise):\n\n if formatter is not None:\n return formatter\n\n if concise:\n # TODO ideally we would have concise coordinate ticks,\n # but full semantic ticks. Is that possible?\n formatter = ConciseDateFormatter(locator)\n else:\n formatter = AutoDateFormatter(locator)\n\n return formatter"},{"attributeType":"None","col":4,"comment":"null","endLoc":663,"id":1006,"name":"trans","nodeType":"Attribute","startLoc":663,"text":"trans"},{"attributeType":"int","col":4,"comment":"null","endLoc":665,"id":1007,"name":"_priority","nodeType":"Attribute","startLoc":665,"text":"_priority"},{"col":4,"comment":"Estimate a KDE for a vector of data with flexible bandwidth.","endLoc":1065,"header":"def fit_kde(self, x, bw)","id":1008,"name":"fit_kde","nodeType":"Function","startLoc":1052,"text":"def fit_kde(self, x, bw):\n \"\"\"Estimate a KDE for a vector of data with flexible bandwidth.\"\"\"\n kde = gaussian_kde(x, bw)\n\n # Extract the numeric bandwidth from the KDE object\n bw_used = kde.factor\n\n # At this point, bw will be a numeric scale factor.\n # To get the actual bandwidth of the kernel, we multiple by the\n # unbiased standard deviation of the data, which we will use\n # elsewhere to compute the range of the support.\n bw_used = bw_used * x.std(ddof=1)\n\n return kde, bw_used"},{"className":"PseudoAxis","col":0,"comment":"\n Internal class implementing minimal interface equivalent to matplotlib Axis.\n\n Coordinate variables are typically scaled by attaching the Axis object from\n the figure where the plot will end up. Matplotlib has no similar concept of\n and axis for the other mappable variables (color, etc.), but to simplify the\n code, this object acts like an Axis and can be used to scale other variables.\n\n ","endLoc":879,"id":1009,"nodeType":"Class","startLoc":776,"text":"class PseudoAxis:\n \"\"\"\n Internal class implementing minimal interface equivalent to matplotlib Axis.\n\n Coordinate variables are typically scaled by attaching the Axis object from\n the figure where the plot will end up. Matplotlib has no similar concept of\n and axis for the other mappable variables (color, etc.), but to simplify the\n code, this object acts like an Axis and can be used to scale other variables.\n\n \"\"\"\n axis_name = \"\" # Matplotlib requirement but not actually used\n\n def __init__(self, scale):\n\n self.converter = None\n self.units = None\n self.scale = scale\n self.major = mpl.axis.Ticker()\n self.minor = mpl.axis.Ticker()\n\n # It appears that this needs to be initialized this way on matplotlib 3.1,\n # but not later versions. It is unclear whether there are any issues with it.\n self._data_interval = None, None\n\n scale.set_default_locators_and_formatters(self)\n # self.set_default_intervals() Is this ever needed?\n\n def set_view_interval(self, vmin, vmax):\n self._view_interval = vmin, vmax\n\n def get_view_interval(self):\n return self._view_interval\n\n # TODO do we want to distinguish view/data intervals? e.g. for a legend\n # we probably want to represent the full range of the data values, but\n # still norm the colormap. If so, we'll need to track data range separately\n # from the norm, which we currently don't do.\n\n def set_data_interval(self, vmin, vmax):\n self._data_interval = vmin, vmax\n\n def get_data_interval(self):\n return self._data_interval\n\n def get_tick_space(self):\n # TODO how to do this in a configurable / auto way?\n # Would be cool to have legend density adapt to figure size, etc.\n return 5\n\n def set_major_locator(self, locator):\n self.major.locator = locator\n locator.set_axis(self)\n\n def set_major_formatter(self, formatter):\n self.major.formatter = formatter\n formatter.set_axis(self)\n\n def set_minor_locator(self, locator):\n self.minor.locator = locator\n locator.set_axis(self)\n\n def set_minor_formatter(self, formatter):\n self.minor.formatter = formatter\n formatter.set_axis(self)\n\n def set_units(self, units):\n self.units = units\n\n def update_units(self, x):\n \"\"\"Pass units to the internal converter, potentially updating its mapping.\"\"\"\n self.converter = mpl.units.registry.get_converter(x)\n if self.converter is not None:\n self.converter.default_units(x, self)\n\n info = self.converter.axisinfo(self.units, self)\n\n if info is None:\n return\n if info.majloc is not None:\n self.set_major_locator(info.majloc)\n if info.majfmt is not None:\n self.set_major_formatter(info.majfmt)\n\n # This is in matplotlib method; do we need this?\n # self.set_default_intervals()\n\n def convert_units(self, x):\n \"\"\"Return a numeric representation of the input data.\"\"\"\n if np.issubdtype(np.asarray(x).dtype, np.number):\n return x\n elif self.converter is None:\n return x\n return self.converter.convert(x, self.units, self)\n\n def get_scale(self):\n # Note that matplotlib actually returns a string here!\n # (e.g., with a log scale, axis.get_scale() returns \"log\")\n # Currently we just hit it with minor ticks where it checks for\n # scale == \"log\". I'm not sure how you'd actually use log-scale\n # minor \"ticks\" in a legend context, so this is fine....\n return self.scale\n\n def get_majorticklocs(self):\n return self.major.locator()"},{"col":4,"comment":"null","endLoc":807,"header":"def get_view_interval(self)","id":1010,"name":"get_view_interval","nodeType":"Function","startLoc":806,"text":"def get_view_interval(self):\n return self._view_interval"},{"col":4,"comment":"null","endLoc":815,"header":"def set_data_interval(self, vmin, vmax)","id":1011,"name":"set_data_interval","nodeType":"Function","startLoc":814,"text":"def set_data_interval(self, vmin, vmax):\n self._data_interval = vmin, vmax"},{"col":4,"comment":"null","endLoc":818,"header":"def get_data_interval(self)","id":1012,"name":"get_data_interval","nodeType":"Function","startLoc":817,"text":"def get_data_interval(self):\n return self._data_interval"},{"col":4,"comment":"null","endLoc":823,"header":"def get_tick_space(self)","id":1013,"name":"get_tick_space","nodeType":"Function","startLoc":820,"text":"def get_tick_space(self):\n # TODO how to do this in a configurable / auto way?\n # Would be cool to have legend density adapt to figure size, etc.\n return 5"},{"col":4,"comment":"null","endLoc":835,"header":"def set_minor_locator(self, locator)","id":1014,"name":"set_minor_locator","nodeType":"Function","startLoc":833,"text":"def set_minor_locator(self, locator):\n self.minor.locator = locator\n locator.set_axis(self)"},{"col":4,"comment":"null","endLoc":839,"header":"def set_minor_formatter(self, formatter)","id":1015,"name":"set_minor_formatter","nodeType":"Function","startLoc":837,"text":"def set_minor_formatter(self, formatter):\n self.minor.formatter = formatter\n formatter.set_axis(self)"},{"col":4,"comment":"null","endLoc":842,"header":"def set_units(self, units)","id":1016,"name":"set_units","nodeType":"Function","startLoc":841,"text":"def set_units(self, units):\n self.units = units"},{"col":4,"comment":"null","endLoc":876,"header":"def get_scale(self)","id":1017,"name":"get_scale","nodeType":"Function","startLoc":870,"text":"def get_scale(self):\n # Note that matplotlib actually returns a string here!\n # (e.g., with a log scale, axis.get_scale() returns \"log\")\n # Currently we just hit it with minor ticks where it checks for\n # scale == \"log\". I'm not sure how you'd actually use log-scale\n # minor \"ticks\" in a legend context, so this is fine....\n return self.scale"},{"col":4,"comment":"null","endLoc":879,"header":"def get_majorticklocs(self)","id":1018,"name":"get_majorticklocs","nodeType":"Function","startLoc":878,"text":"def get_majorticklocs(self):\n return self.major.locator()"},{"attributeType":"str","col":4,"comment":"null","endLoc":786,"id":1019,"name":"axis_name","nodeType":"Attribute","startLoc":786,"text":"axis_name"},{"attributeType":"(Any, Any)","col":8,"comment":"null","endLoc":804,"id":1020,"name":"_view_interval","nodeType":"Attribute","startLoc":804,"text":"self._view_interval"},{"id":1021,"name":"boxplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"7edcf92f-6c11-4dc4-b684-118b3235d067\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"90798548-e999-4127-8191-ce01e252f305\",\n \"metadata\": {},\n \"source\": [\n \"Draw a single horizontal boxplot, assigning the data directly to the coordinate variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"80532f2c-0f34-456c-9d5c-673682385461\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"df = sns.load_dataset(\\\"titanic\\\")\\n\",\n \"sns.boxplot(x=df[\\\"age\\\"])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"98e6f351-2983-4edc-93e6-03b2d91ed5f1\",\n \"metadata\": {},\n \"source\": [\n \"Group by a categorical variable, referencing columns in a dataframe:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f1e0a6a4-151d-42d7-a098-ec9b91f20906\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxplot(data=df, x=\\\"age\\\", y=\\\"class\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"a4bebd98-9719-4279-b0b5-700ca0aa087d\",\n \"metadata\": {},\n \"source\": [\n \"Draw a vertical boxplot with nested grouping by two variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b8f74dc4-2b59-423a-90a7-dbf900c89251\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxplot(data=df, x=\\\"age\\\", y=\\\"class\\\", hue=\\\"alive\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"8b4a7418-d945-4ec6-90d2-8ec10c552a08\",\n \"metadata\": {},\n \"source\": [\n \"Control the order of the boxes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2a496593-7c12-4739-b3db-46b777599c65\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxplot(data=df, x=\\\"fare\\\", y=\\\"alive\\\", order=[\\\"yes\\\", \\\"no\\\"])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"4a5b57c0-7835-49c0-b899-012d3b112efc\",\n \"metadata\": {},\n \"source\": [\n \"Draw a box for multiple numeric columns:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a4ca0f44-be47-4014-9ac5-01c9b47c5bdc\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxplot(data=df[[\\\"age\\\", \\\"fare\\\"]], orient=\\\"h\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"d0e68414-2f63-442f-9d2e-24fc9ab1f5e3\",\n \"metadata\": {},\n \"source\": [\n \"Use a `hue` variable whithout changing the box width or position:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c242ee2b-22af-47f7-8de6-84e5ff95271f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxplot(data=df, x=\\\"fare\\\", y=\\\"deck\\\", hue=\\\"deck\\\", dodge=False)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"5dca0faa-96ec-4e64-a187-482a9d10a03b\",\n \"metadata\": {},\n \"source\": [\n \"Pass additional keyword arguments to matplotlib:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"66c81b6e-e7fb-46c5-aa7b-f001241569b0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxplot(\\n\",\n \" data=df, x=\\\"age\\\", y=\\\"class\\\",\\n\",\n \" notch=True, showcaps=False,\\n\",\n \" flierprops={\\\"marker\\\": \\\"x\\\"},\\n\",\n \" boxprops={\\\"facecolor\\\": (.4, .6, .8, .5)},\\n\",\n \" medianprops={\\\"color\\\": \\\"coral\\\"},\\n\",\n \")\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"attributeType":"{__len__} | list","col":25,"comment":"null","endLoc":153,"id":1022,"name":"yticklabels","nodeType":"Attribute","startLoc":153,"text":"self.yticklabels"},{"col":4,"comment":"Define a grid of support for the violin.","endLoc":1071,"header":"def kde_support(self, x, bw, cut, gridsize)","id":1023,"name":"kde_support","nodeType":"Function","startLoc":1067,"text":"def kde_support(self, x, bw, cut, gridsize):\n \"\"\"Define a grid of support for the violin.\"\"\"\n support_min = x.min() - bw * cut\n support_max = x.max() + bw * cut\n return np.linspace(support_min, support_max, gridsize)"},{"attributeType":"null","col":8,"comment":"null","endLoc":793,"id":1024,"name":"major","nodeType":"Attribute","startLoc":793,"text":"self.major"},{"attributeType":"null","col":8,"comment":"null","endLoc":794,"id":1025,"name":"minor","nodeType":"Attribute","startLoc":794,"text":"self.minor"},{"id":1026,"name":"v0.7.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.7.0 (January 2016)\n---------------------\n\nThis is a major release from 0.6. The main new feature is :func:`swarmplot` which implements the beeswarm approach for drawing categorical scatterplots. There are also some performance improvements, bug fixes, and updates for compatibility with new versions of dependencies.\n\n- Added the :func:`swarmplot` function, which draws beeswarm plots. These are categorical scatterplots, similar to those produced by :func:`stripplot`, but position of the points on the categorical axis is chosen to avoid overlapping points. See the :ref:`categorical plot tutorial ` for more information.\n\n- Changed some of the :func:`stripplot` defaults to be closer to :func:`swarmplot`. Points are now somewhat smaller, have no outlines, and are not split by default when using ``hue``. These settings remain customizable through function parameters.\n\n- Added an additional rule when determining category order in categorical plots. Now, when numeric variables are used in a categorical role, the default behavior is to sort the unique levels of the variable (i.e they will be in proper numerical order). This can still be overridden by the appropriate ``{*_}order`` parameter, and variables with a ``category`` datatype will still follow the category order even if the levels are strictly numerical.\n\n- Changed how :func:`stripplot` draws points when using ``hue`` nesting with ``split=False`` so that the different ``hue`` levels are not drawn strictly on top of each other.\n\n- Improve performance for large dendrograms in :func:`clustermap`.\n\n- Added ``font.size`` to the plotting context definition so that the default output from ``plt.text`` will be scaled appropriately.\n\n- Fixed a bug in :func:`clustermap` when ``fastcluster`` is not installed.\n\n- Fixed a bug in the zscore calculation in :func:`clustermap`.\n\n- Fixed a bug in :func:`distplot` where sometimes the default number of bins would not be an integer.\n\n- Fixed a bug in :func:`stripplot` where a legend item would not appear for a ``hue`` level if there were no observations in the first group of points.\n\n- Heatmap colorbars are now rasterized for better performance in vector plots.\n\n- Added workarounds for some matplotlib boxplot issues, such as strange colors of outlier points.\n\n- Added workarounds for an issue where violinplot edges would be missing or have random colors.\n\n- Added a workaround for an issue where only one :func:`heatmap` cell would be annotated on some matplotlib backends.\n\n- Fixed a bug on newer versions of matplotlib where a colormap would be erroneously applied to scatterplots with only three observations.\n\n- Updated seaborn for compatibility with matplotlib 1.5.\n\n- Added compatibility for various IPython (and Jupyter) versions in functions that use widgets.\n"},{"attributeType":"float | list","col":12,"comment":"null","endLoc":143,"id":1027,"name":"xticks","nodeType":"Attribute","startLoc":143,"text":"self.xticks"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":190,"id":1028,"name":"cbar_kws","nodeType":"Attribute","startLoc":190,"text":"self.cbar_kws"},{"attributeType":"None","col":8,"comment":"null","endLoc":790,"id":1029,"name":"converter","nodeType":"Attribute","startLoc":790,"text":"self.converter"},{"attributeType":"{set_default_locators_and_formatters}","col":8,"comment":"null","endLoc":792,"id":1030,"name":"scale","nodeType":"Attribute","startLoc":792,"text":"self.scale"},{"attributeType":"None","col":8,"comment":"null","endLoc":791,"id":1031,"name":"units","nodeType":"Attribute","startLoc":791,"text":"self.units"},{"attributeType":"null","col":8,"comment":"null","endLoc":208,"id":1032,"name":"vmin","nodeType":"Attribute","startLoc":208,"text":"self.vmin"},{"attributeType":"(None, None)","col":8,"comment":"null","endLoc":798,"id":1033,"name":"_data_interval","nodeType":"Attribute","startLoc":798,"text":"self._data_interval"},{"id":1034,"name":"Makefile","nodeType":"TextFile","path":"doc/_docstrings","text":"rst_files := $(patsubst %.ipynb,../docstrings/%.rst,$(wildcard *.ipynb))\n\ndocstrings: ${rst_files}\n\n../docstrings/%.rst: %.ipynb\n\t../tools/nb_to_doc.py $*.ipynb ../docstrings\n\t@cp -r ../docstrings/$*_files ../generated/\n\t@if [ -f ../generated/seaborn.$*.rst ]; then \\\n\t touch ../generated/seaborn.$*.rst; \\\n\t fi\n\nclean:\n\trm -rf ../docstrings\n"},{"col":4,"comment":"Scale the relative area under the KDE curve.\n\n This essentially preserves the \"standard\" KDE scaling, but the\n resulting maximum density will be 1 so that the curve can be\n properly multiplied by the violin width.\n\n ","endLoc":1093,"header":"def scale_area(self, density, max_density, scale_hue)","id":1035,"name":"scale_area","nodeType":"Function","startLoc":1073,"text":"def scale_area(self, density, max_density, scale_hue):\n \"\"\"Scale the relative area under the KDE curve.\n\n This essentially preserves the \"standard\" KDE scaling, but the\n resulting maximum density will be 1 so that the curve can be\n properly multiplied by the violin width.\n\n \"\"\"\n if self.hue_names is None:\n for d in density:\n if d.size > 1:\n d /= max_density.max()\n else:\n for i, group in enumerate(density):\n for d in group:\n if scale_hue:\n max = max_density[i].max()\n else:\n max = max_density.max()\n if d.size > 1:\n d /= max"},{"attributeType":"null","col":16,"comment":"null","endLoc":9,"id":1036,"name":"np","nodeType":"Attribute","startLoc":9,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":10,"id":1037,"name":"mpl","nodeType":"Attribute","startLoc":10,"text":"mpl"},{"attributeType":"tuple","col":4,"comment":"null","endLoc":44,"id":1038,"name":"TransFuncs","nodeType":"Attribute","startLoc":44,"text":"TransFuncs"},{"attributeType":"Sequence","col":4,"comment":"null","endLoc":50,"id":1039,"name":"Pipeline","nodeType":"Attribute","startLoc":50,"text":"Pipeline"},{"col":0,"comment":"","endLoc":1,"header":"scales.py#","id":1040,"name":"","nodeType":"Function","startLoc":1,"text":"if TYPE_CHECKING:\n from seaborn._core.properties import Property\n from numpy.typing import ArrayLike, NDArray\n\n TransFuncs = Tuple[\n Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]\n ]\n\n # TODO Reverting typing to Any as it was proving too complicated to\n # work out the right way to communicate the types to mypy. Revisit!\n Pipeline = Sequence[Optional[Callable[[Any], Any]]]"},{"attributeType":"bool","col":8,"comment":"null","endLoc":184,"id":1041,"name":"annot","nodeType":"Attribute","startLoc":184,"text":"self.annot"},{"attributeType":"null","col":8,"comment":"null","endLoc":187,"id":1042,"name":"fmt","nodeType":"Attribute","startLoc":187,"text":"self.fmt"},{"attributeType":"None","col":8,"comment":"null","endLoc":185,"id":1043,"name":"annot_data","nodeType":"Attribute","startLoc":185,"text":"self.annot_data"},{"attributeType":"float | list","col":12,"comment":"null","endLoc":153,"id":1044,"name":"yticks","nodeType":"Attribute","startLoc":153,"text":"self.yticks"},{"attributeType":"null","col":8,"comment":"null","endLoc":182,"id":1045,"name":"plot_data","nodeType":"Attribute","startLoc":182,"text":"self.plot_data"},{"col":4,"comment":"Scale each density curve to the same height.","endLoc":1103,"header":"def scale_width(self, density)","id":1046,"name":"scale_width","nodeType":"Function","startLoc":1095,"text":"def scale_width(self, density):\n \"\"\"Scale each density curve to the same height.\"\"\"\n if self.hue_names is None:\n for d in density:\n d /= d.max()\n else:\n for group in density:\n for d in group:\n d /= d.max()"},{"attributeType":"null","col":16,"comment":"null","endLoc":213,"id":1047,"name":"cmap","nodeType":"Attribute","startLoc":213,"text":"self.cmap"},{"attributeType":"{__len__} | list","col":25,"comment":"null","endLoc":143,"id":1048,"name":"xticklabels","nodeType":"Attribute","startLoc":143,"text":"self.xticklabels"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":188,"id":1049,"name":"annot_kws","nodeType":"Attribute","startLoc":188,"text":"self.annot_kws"},{"col":4,"comment":"Scale each density curve by the number of observations.","endLoc":1126,"header":"def scale_count(self, density, counts, scale_hue)","id":1050,"name":"scale_count","nodeType":"Function","startLoc":1105,"text":"def scale_count(self, density, counts, scale_hue):\n \"\"\"Scale each density curve by the number of observations.\"\"\"\n if self.hue_names is None:\n if counts.max() == 0:\n d = 0\n else:\n for count, d in zip(counts, density):\n d /= d.max()\n d *= count / counts.max()\n else:\n for i, group in enumerate(density):\n for j, d in enumerate(group):\n if counts[i].max() == 0:\n d = 0\n else:\n count = counts[i, j]\n if scale_hue:\n scaler = count / counts[i].max()\n else:\n scaler = count / counts.max()\n d /= d.max()\n d *= scaler"},{"attributeType":"str","col":8,"comment":"null","endLoc":159,"id":1051,"name":"xlabel","nodeType":"Attribute","startLoc":159,"text":"self.xlabel"},{"attributeType":"null","col":19,"comment":"null","endLoc":208,"id":1052,"name":"vmax","nodeType":"Attribute","startLoc":208,"text":"self.vmax"},{"attributeType":"null","col":8,"comment":"null","endLoc":189,"id":1053,"name":"cbar","nodeType":"Attribute","startLoc":189,"text":"self.cbar"},{"className":"_DendrogramPlotter","col":0,"comment":"Object for drawing tree of similarities between data rows/columns","endLoc":639,"id":1054,"nodeType":"Class","startLoc":463,"text":"class _DendrogramPlotter:\n \"\"\"Object for drawing tree of similarities between data rows/columns\"\"\"\n\n def __init__(self, data, linkage, metric, method, axis, label, rotate):\n \"\"\"Plot a dendrogram of the relationships between the columns of data\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n \"\"\"\n self.axis = axis\n if self.axis == 1:\n data = data.T\n\n if isinstance(data, pd.DataFrame):\n array = data.values\n else:\n array = np.asarray(data)\n data = pd.DataFrame(array)\n\n self.array = array\n self.data = data\n\n self.shape = self.data.shape\n self.metric = metric\n self.method = method\n self.axis = axis\n self.label = label\n self.rotate = rotate\n\n if linkage is None:\n self.linkage = self.calculated_linkage\n else:\n self.linkage = linkage\n self.dendrogram = self.calculate_dendrogram()\n\n # Dendrogram ends are always at multiples of 5, who knows why\n ticks = 10 * np.arange(self.data.shape[0]) + 5\n\n if self.label:\n ticklabels = _index_to_ticklabels(self.data.index)\n ticklabels = [ticklabels[i] for i in self.reordered_ind]\n if self.rotate:\n self.xticks = []\n self.yticks = ticks\n self.xticklabels = []\n\n self.yticklabels = ticklabels\n self.ylabel = _index_to_label(self.data.index)\n self.xlabel = ''\n else:\n self.xticks = ticks\n self.yticks = []\n self.xticklabels = ticklabels\n self.yticklabels = []\n self.ylabel = ''\n self.xlabel = _index_to_label(self.data.index)\n else:\n self.xticks, self.yticks = [], []\n self.yticklabels, self.xticklabels = [], []\n self.xlabel, self.ylabel = '', ''\n\n self.dependent_coord = self.dendrogram['dcoord']\n self.independent_coord = self.dendrogram['icoord']\n\n def _calculate_linkage_scipy(self):\n linkage = hierarchy.linkage(self.array, method=self.method,\n metric=self.metric)\n return linkage\n\n def _calculate_linkage_fastcluster(self):\n import fastcluster\n # Fastcluster has a memory-saving vectorized version, but only\n # with certain linkage methods, and mostly with euclidean metric\n # vector_methods = ('single', 'centroid', 'median', 'ward')\n euclidean_methods = ('centroid', 'median', 'ward')\n euclidean = self.metric == 'euclidean' and self.method in \\\n euclidean_methods\n if euclidean or self.method == 'single':\n return fastcluster.linkage_vector(self.array,\n method=self.method,\n metric=self.metric)\n else:\n linkage = fastcluster.linkage(self.array, method=self.method,\n metric=self.metric)\n return linkage\n\n @property\n def calculated_linkage(self):\n\n try:\n return self._calculate_linkage_fastcluster()\n except ImportError:\n if np.product(self.shape) >= 10000:\n msg = (\"Clustering large matrix with scipy. Installing \"\n \"`fastcluster` may give better performance.\")\n warnings.warn(msg)\n\n return self._calculate_linkage_scipy()\n\n def calculate_dendrogram(self):\n \"\"\"Calculates a dendrogram based on the linkage matrix\n\n Made a separate function, not a property because don't want to\n recalculate the dendrogram every time it is accessed.\n\n Returns\n -------\n dendrogram : dict\n Dendrogram dictionary as returned by scipy.cluster.hierarchy\n .dendrogram. The important key-value pairing is\n \"reordered_ind\" which indicates the re-ordering of the matrix\n \"\"\"\n return hierarchy.dendrogram(self.linkage, no_plot=True,\n color_threshold=-np.inf)\n\n @property\n def reordered_ind(self):\n \"\"\"Indices of the matrix, reordered by the dendrogram\"\"\"\n return self.dendrogram['leaves']\n\n def plot(self, ax, tree_kws):\n \"\"\"Plots a dendrogram of the similarities between data on the axes\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n Axes object upon which the dendrogram is plotted\n\n \"\"\"\n tree_kws = {} if tree_kws is None else tree_kws.copy()\n tree_kws.setdefault(\"linewidths\", .5)\n tree_kws.setdefault(\"colors\", tree_kws.pop(\"color\", (.2, .2, .2)))\n\n if self.rotate and self.axis == 0:\n coords = zip(self.dependent_coord, self.independent_coord)\n else:\n coords = zip(self.independent_coord, self.dependent_coord)\n lines = LineCollection([list(zip(x, y)) for x, y in coords],\n **tree_kws)\n\n ax.add_collection(lines)\n number_of_leaves = len(self.reordered_ind)\n max_dependent_coord = max(map(max, self.dependent_coord))\n\n if self.rotate:\n ax.yaxis.set_ticks_position('right')\n\n # Constants 10 and 1.05 come from\n # `scipy.cluster.hierarchy._plot_dendrogram`\n ax.set_ylim(0, number_of_leaves * 10)\n ax.set_xlim(0, max_dependent_coord * 1.05)\n\n ax.invert_xaxis()\n ax.invert_yaxis()\n else:\n # Constants 10 and 1.05 come from\n # `scipy.cluster.hierarchy._plot_dendrogram`\n ax.set_xlim(0, number_of_leaves * 10)\n ax.set_ylim(0, max_dependent_coord * 1.05)\n\n despine(ax=ax, bottom=True, left=True)\n\n ax.set(xticks=self.xticks, yticks=self.yticks,\n xlabel=self.xlabel, ylabel=self.ylabel)\n xtl = ax.set_xticklabels(self.xticklabels)\n ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical')\n\n # Force a draw of the plot to avoid matplotlib window error\n _draw_figure(ax.figure)\n\n if len(ytl) > 0 and axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n if len(xtl) > 0 and axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n return self"},{"col":4,"comment":"Plot a dendrogram of the relationships between the columns of data\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n ","endLoc":527,"header":"def __init__(self, data, linkage, metric, method, axis, label, rotate)","id":1055,"name":"__init__","nodeType":"Function","startLoc":466,"text":"def __init__(self, data, linkage, metric, method, axis, label, rotate):\n \"\"\"Plot a dendrogram of the relationships between the columns of data\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n \"\"\"\n self.axis = axis\n if self.axis == 1:\n data = data.T\n\n if isinstance(data, pd.DataFrame):\n array = data.values\n else:\n array = np.asarray(data)\n data = pd.DataFrame(array)\n\n self.array = array\n self.data = data\n\n self.shape = self.data.shape\n self.metric = metric\n self.method = method\n self.axis = axis\n self.label = label\n self.rotate = rotate\n\n if linkage is None:\n self.linkage = self.calculated_linkage\n else:\n self.linkage = linkage\n self.dendrogram = self.calculate_dendrogram()\n\n # Dendrogram ends are always at multiples of 5, who knows why\n ticks = 10 * np.arange(self.data.shape[0]) + 5\n\n if self.label:\n ticklabels = _index_to_ticklabels(self.data.index)\n ticklabels = [ticklabels[i] for i in self.reordered_ind]\n if self.rotate:\n self.xticks = []\n self.yticks = ticks\n self.xticklabels = []\n\n self.yticklabels = ticklabels\n self.ylabel = _index_to_label(self.data.index)\n self.xlabel = ''\n else:\n self.xticks = ticks\n self.yticks = []\n self.xticklabels = ticklabels\n self.yticklabels = []\n self.ylabel = ''\n self.xlabel = _index_to_label(self.data.index)\n else:\n self.xticks, self.yticks = [], []\n self.yticklabels, self.xticklabels = [], []\n self.xlabel, self.ylabel = '', ''\n\n self.dependent_coord = self.dendrogram['dcoord']\n self.independent_coord = self.dendrogram['icoord']"},{"col":4,"comment":"Calculates a dendrogram based on the linkage matrix\n\n Made a separate function, not a property because don't want to\n recalculate the dendrogram every time it is accessed.\n\n Returns\n -------\n dendrogram : dict\n Dendrogram dictionary as returned by scipy.cluster.hierarchy\n .dendrogram. The important key-value pairing is\n \"reordered_ind\" which indicates the re-ordering of the matrix\n ","endLoc":578,"header":"def calculate_dendrogram(self)","id":1056,"name":"calculate_dendrogram","nodeType":"Function","startLoc":564,"text":"def calculate_dendrogram(self):\n \"\"\"Calculates a dendrogram based on the linkage matrix\n\n Made a separate function, not a property because don't want to\n recalculate the dendrogram every time it is accessed.\n\n Returns\n -------\n dendrogram : dict\n Dendrogram dictionary as returned by scipy.cluster.hierarchy\n .dendrogram. The important key-value pairing is\n \"reordered_ind\" which indicates the re-ordering of the matrix\n \"\"\"\n return hierarchy.dendrogram(self.linkage, no_plot=True,\n color_threshold=-np.inf)"},{"col":4,"comment":"null","endLoc":532,"header":"def _calculate_linkage_scipy(self)","id":1057,"name":"_calculate_linkage_scipy","nodeType":"Function","startLoc":529,"text":"def _calculate_linkage_scipy(self):\n linkage = hierarchy.linkage(self.array, method=self.method,\n metric=self.metric)\n return linkage"},{"col":4,"comment":"null","endLoc":549,"header":"def _calculate_linkage_fastcluster(self)","id":1058,"name":"_calculate_linkage_fastcluster","nodeType":"Function","startLoc":534,"text":"def _calculate_linkage_fastcluster(self):\n import fastcluster\n # Fastcluster has a memory-saving vectorized version, but only\n # with certain linkage methods, and mostly with euclidean metric\n # vector_methods = ('single', 'centroid', 'median', 'ward')\n euclidean_methods = ('centroid', 'median', 'ward')\n euclidean = self.metric == 'euclidean' and self.method in \\\n euclidean_methods\n if euclidean or self.method == 'single':\n return fastcluster.linkage_vector(self.array,\n method=self.method,\n metric=self.metric)\n else:\n linkage = fastcluster.linkage(self.array, method=self.method,\n metric=self.metric)\n return linkage"},{"col":4,"comment":"Remove observations with missing data.","endLoc":64,"header":"def dropna(self, *vars)","id":1059,"name":"dropna","nodeType":"Function","startLoc":56,"text":"def dropna(self, *vars):\n \"\"\"Remove observations with missing data.\"\"\"\n vals = [getattr(self, var) for var in vars]\n vals = [v for v in vals if v is not None]\n not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1)\n for var in vars:\n val = getattr(self, var)\n if val is not None:\n setattr(self, var, val[not_na])"},{"col":4,"comment":"null","endLoc":67,"header":"def plot(self, ax)","id":1060,"name":"plot","nodeType":"Function","startLoc":66,"text":"def plot(self, ax):\n raise NotImplementedError"},{"attributeType":"null","col":8,"comment":"null","endLoc":34,"id":1061,"name":"data","nodeType":"Attribute","startLoc":34,"text":"self.data"},{"className":"_RegressionPlotter","col":0,"comment":"Plotter for numeric independent variables with regression model.\n\n This does the computations and drawing for the `regplot` function, and\n is thus also used indirectly by `lmplot`.\n ","endLoc":426,"id":1062,"nodeType":"Class","startLoc":70,"text":"class _RegressionPlotter(_LinearPlotter):\n \"\"\"Plotter for numeric independent variables with regression model.\n\n This does the computations and drawing for the `regplot` function, and\n is thus also used indirectly by `lmplot`.\n \"\"\"\n def __init__(self, x, y, data=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=False, dropna=True, x_jitter=None, y_jitter=None,\n color=None, label=None):\n\n # Set member attributes\n self.x_estimator = x_estimator\n self.ci = ci\n self.x_ci = ci if x_ci == \"ci\" else x_ci\n self.n_boot = n_boot\n self.seed = seed\n self.scatter = scatter\n self.fit_reg = fit_reg\n self.order = order\n self.logistic = logistic\n self.lowess = lowess\n self.robust = robust\n self.logx = logx\n self.truncate = truncate\n self.x_jitter = x_jitter\n self.y_jitter = y_jitter\n self.color = color\n self.label = label\n\n # Validate the regression options:\n if sum((order > 1, logistic, robust, lowess, logx)) > 1:\n raise ValueError(\"Mutually exclusive regression options.\")\n\n # Extract the data vals from the arguments or passed dataframe\n self.establish_variables(data, x=x, y=y, units=units,\n x_partial=x_partial, y_partial=y_partial)\n\n # Drop null observations\n if dropna:\n self.dropna(\"x\", \"y\", \"units\", \"x_partial\", \"y_partial\")\n\n # Regress nuisance variables out of the data\n if self.x_partial is not None:\n self.x = self.regress_out(self.x, self.x_partial)\n if self.y_partial is not None:\n self.y = self.regress_out(self.y, self.y_partial)\n\n # Possibly bin the predictor variable, which implies a point estimate\n if x_bins is not None:\n self.x_estimator = np.mean if x_estimator is None else x_estimator\n x_discrete, x_bins = self.bin_predictor(x_bins)\n self.x_discrete = x_discrete\n else:\n self.x_discrete = self.x\n\n # Disable regression in case of singleton inputs\n if len(self.x) <= 1:\n self.fit_reg = False\n\n # Save the range of the x variable for the grid later\n if self.fit_reg:\n self.x_range = self.x.min(), self.x.max()\n\n @property\n def scatter_data(self):\n \"\"\"Data where each observation is a point.\"\"\"\n x_j = self.x_jitter\n if x_j is None:\n x = self.x\n else:\n x = self.x + np.random.uniform(-x_j, x_j, len(self.x))\n\n y_j = self.y_jitter\n if y_j is None:\n y = self.y\n else:\n y = self.y + np.random.uniform(-y_j, y_j, len(self.y))\n\n return x, y\n\n @property\n def estimate_data(self):\n \"\"\"Data with a point estimate and CI for each discrete x value.\"\"\"\n x, y = self.x_discrete, self.y\n vals = sorted(np.unique(x))\n points, cis = [], []\n\n for val in vals:\n\n # Get the point estimate of the y variable\n _y = y[x == val]\n est = self.x_estimator(_y)\n points.append(est)\n\n # Compute the confidence interval for this estimate\n if self.x_ci is None:\n cis.append(None)\n else:\n units = None\n if self.x_ci == \"sd\":\n sd = np.std(_y)\n _ci = est - sd, est + sd\n else:\n if self.units is not None:\n units = self.units[x == val]\n boots = algo.bootstrap(_y,\n func=self.x_estimator,\n n_boot=self.n_boot,\n units=units,\n seed=self.seed)\n _ci = utils.ci(boots, self.x_ci)\n cis.append(_ci)\n\n return vals, points, cis\n\n def fit_regression(self, ax=None, x_range=None, grid=None):\n \"\"\"Fit the regression model.\"\"\"\n # Create the grid for the regression\n if grid is None:\n if self.truncate:\n x_min, x_max = self.x_range\n else:\n if ax is None:\n x_min, x_max = x_range\n else:\n x_min, x_max = ax.get_xlim()\n grid = np.linspace(x_min, x_max, 100)\n ci = self.ci\n\n # Fit the regression\n if self.order > 1:\n yhat, yhat_boots = self.fit_poly(grid, self.order)\n elif self.logistic:\n from statsmodels.genmod.generalized_linear_model import GLM\n from statsmodels.genmod.families import Binomial\n yhat, yhat_boots = self.fit_statsmodels(grid, GLM,\n family=Binomial())\n elif self.lowess:\n ci = None\n grid, yhat = self.fit_lowess()\n elif self.robust:\n from statsmodels.robust.robust_linear_model import RLM\n yhat, yhat_boots = self.fit_statsmodels(grid, RLM)\n elif self.logx:\n yhat, yhat_boots = self.fit_logx(grid)\n else:\n yhat, yhat_boots = self.fit_fast(grid)\n\n # Compute the confidence interval at each grid point\n if ci is None:\n err_bands = None\n else:\n err_bands = utils.ci(yhat_boots, ci, axis=0)\n\n return grid, yhat, err_bands\n\n def fit_fast(self, grid):\n \"\"\"Low-level regression and prediction using linear algebra.\"\"\"\n def reg_func(_x, _y):\n return np.linalg.pinv(_x).dot(_y)\n\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), grid]\n yhat = grid.dot(reg_func(X, y))\n if self.ci is None:\n return yhat, None\n\n beta_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed).T\n yhat_boots = grid.dot(beta_boots).T\n return yhat, yhat_boots\n\n def fit_poly(self, grid, order):\n \"\"\"Regression using numpy polyfit for higher-order trends.\"\"\"\n def reg_func(_x, _y):\n return np.polyval(np.polyfit(_x, _y, order), grid)\n\n x, y = self.x, self.y\n yhat = reg_func(x, y)\n if self.ci is None:\n return yhat, None\n\n yhat_boots = algo.bootstrap(x, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed)\n return yhat, yhat_boots\n\n def fit_statsmodels(self, grid, model, **kwargs):\n \"\"\"More general regression function using statsmodels objects.\"\"\"\n import statsmodels.genmod.generalized_linear_model as glm\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), grid]\n\n def reg_func(_x, _y):\n try:\n yhat = model(_y, _x, **kwargs).fit().predict(grid)\n except glm.PerfectSeparationError:\n yhat = np.empty(len(grid))\n yhat.fill(np.nan)\n return yhat\n\n yhat = reg_func(X, y)\n if self.ci is None:\n return yhat, None\n\n yhat_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed)\n return yhat, yhat_boots\n\n def fit_lowess(self):\n \"\"\"Fit a locally-weighted regression, which returns its own grid.\"\"\"\n from statsmodels.nonparametric.smoothers_lowess import lowess\n grid, yhat = lowess(self.y, self.x).T\n return grid, yhat\n\n def fit_logx(self, grid):\n \"\"\"Fit the model in log-space.\"\"\"\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), np.log(grid)]\n\n def reg_func(_x, _y):\n _x = np.c_[_x[:, 0], np.log(_x[:, 1])]\n return np.linalg.pinv(_x).dot(_y)\n\n yhat = grid.dot(reg_func(X, y))\n if self.ci is None:\n return yhat, None\n\n beta_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed).T\n yhat_boots = grid.dot(beta_boots).T\n return yhat, yhat_boots\n\n def bin_predictor(self, bins):\n \"\"\"Discretize a predictor by assigning value to closest bin.\"\"\"\n x = np.asarray(self.x)\n if np.isscalar(bins):\n percentiles = np.linspace(0, 100, bins + 2)[1:-1]\n bins = np.percentile(x, percentiles)\n else:\n bins = np.ravel(bins)\n\n dist = np.abs(np.subtract.outer(x, bins))\n x_binned = bins[np.argmin(dist, axis=1)].ravel()\n\n return x_binned, bins\n\n def regress_out(self, a, b):\n \"\"\"Regress b from a keeping a's original mean.\"\"\"\n a_mean = a.mean()\n a = a - a_mean\n b = b - b.mean()\n b = np.c_[b]\n a_prime = a - b.dot(np.linalg.pinv(b).dot(a))\n return np.asarray(a_prime + a_mean).reshape(a.shape)\n\n def plot(self, ax, scatter_kws, line_kws):\n \"\"\"Draw the full plot.\"\"\"\n # Insert the plot label into the correct set of keyword arguments\n if self.scatter:\n scatter_kws[\"label\"] = self.label\n else:\n line_kws[\"label\"] = self.label\n\n # Use the current color cycle state as a default\n if self.color is None:\n lines, = ax.plot([], [])\n color = lines.get_color()\n lines.remove()\n else:\n color = self.color\n\n # Ensure that color is hex to avoid matplotlib weirdness\n color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color))\n\n # Let color in keyword arguments override overall plot color\n scatter_kws.setdefault(\"color\", color)\n line_kws.setdefault(\"color\", color)\n\n # Draw the constituent plots\n if self.scatter:\n self.scatterplot(ax, scatter_kws)\n\n if self.fit_reg:\n self.lineplot(ax, line_kws)\n\n # Label the axes\n if hasattr(self.x, \"name\"):\n ax.set_xlabel(self.x.name)\n if hasattr(self.y, \"name\"):\n ax.set_ylabel(self.y.name)\n\n def scatterplot(self, ax, kws):\n \"\"\"Draw the data.\"\"\"\n # Treat the line-based markers specially, explicitly setting larger\n # linewidth than is provided by the seaborn style defaults.\n # This would ideally be handled better in matplotlib (i.e., distinguish\n # between edgewidth for solid glyphs and linewidth for line glyphs\n # but this should do for now.\n line_markers = [\"1\", \"2\", \"3\", \"4\", \"+\", \"x\", \"|\", \"_\"]\n if self.x_estimator is None:\n if \"marker\" in kws and kws[\"marker\"] in line_markers:\n lw = mpl.rcParams[\"lines.linewidth\"]\n else:\n lw = mpl.rcParams[\"lines.markeredgewidth\"]\n kws.setdefault(\"linewidths\", lw)\n\n if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4:\n kws.setdefault(\"alpha\", .8)\n\n x, y = self.scatter_data\n ax.scatter(x, y, **kws)\n else:\n # TODO abstraction\n ci_kws = {\"color\": kws[\"color\"]}\n if \"alpha\" in kws:\n ci_kws[\"alpha\"] = kws[\"alpha\"]\n ci_kws[\"linewidth\"] = mpl.rcParams[\"lines.linewidth\"] * 1.75\n kws.setdefault(\"s\", 50)\n\n xs, ys, cis = self.estimate_data\n if [ci for ci in cis if ci is not None]:\n for x, ci in zip(xs, cis):\n ax.plot([x, x], ci, **ci_kws)\n ax.scatter(xs, ys, **kws)\n\n def lineplot(self, ax, kws):\n \"\"\"Draw the model.\"\"\"\n # Fit the regression model\n grid, yhat, err_bands = self.fit_regression(ax)\n edges = grid[0], grid[-1]\n\n # Get set default aesthetics\n fill_color = kws[\"color\"]\n lw = kws.pop(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.5)\n kws.setdefault(\"linewidth\", lw)\n\n # Draw the regression line and confidence interval\n line, = ax.plot(grid, yhat, **kws)\n if not self.truncate:\n line.sticky_edges.x[:] = edges # Prevent mpl from adding margin\n if err_bands is not None:\n ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15)"},{"col":4,"comment":"null","endLoc":134,"header":"def __init__(self, x, y, data=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=False, dropna=True, x_jitter=None, y_jitter=None,\n color=None, label=None)","id":1063,"name":"__init__","nodeType":"Function","startLoc":76,"text":"def __init__(self, x, y, data=None, x_estimator=None, x_bins=None,\n x_ci=\"ci\", scatter=True, fit_reg=True, ci=95, n_boot=1000,\n units=None, seed=None, order=1, logistic=False, lowess=False,\n robust=False, logx=False, x_partial=None, y_partial=None,\n truncate=False, dropna=True, x_jitter=None, y_jitter=None,\n color=None, label=None):\n\n # Set member attributes\n self.x_estimator = x_estimator\n self.ci = ci\n self.x_ci = ci if x_ci == \"ci\" else x_ci\n self.n_boot = n_boot\n self.seed = seed\n self.scatter = scatter\n self.fit_reg = fit_reg\n self.order = order\n self.logistic = logistic\n self.lowess = lowess\n self.robust = robust\n self.logx = logx\n self.truncate = truncate\n self.x_jitter = x_jitter\n self.y_jitter = y_jitter\n self.color = color\n self.label = label\n\n # Validate the regression options:\n if sum((order > 1, logistic, robust, lowess, logx)) > 1:\n raise ValueError(\"Mutually exclusive regression options.\")\n\n # Extract the data vals from the arguments or passed dataframe\n self.establish_variables(data, x=x, y=y, units=units,\n x_partial=x_partial, y_partial=y_partial)\n\n # Drop null observations\n if dropna:\n self.dropna(\"x\", \"y\", \"units\", \"x_partial\", \"y_partial\")\n\n # Regress nuisance variables out of the data\n if self.x_partial is not None:\n self.x = self.regress_out(self.x, self.x_partial)\n if self.y_partial is not None:\n self.y = self.regress_out(self.y, self.y_partial)\n\n # Possibly bin the predictor variable, which implies a point estimate\n if x_bins is not None:\n self.x_estimator = np.mean if x_estimator is None else x_estimator\n x_discrete, x_bins = self.bin_predictor(x_bins)\n self.x_discrete = x_discrete\n else:\n self.x_discrete = self.x\n\n # Disable regression in case of singleton inputs\n if len(self.x) <= 1:\n self.fit_reg = False\n\n # Save the range of the x variable for the grid later\n if self.fit_reg:\n self.x_range = self.x.min(), self.x.max()"},{"col":4,"comment":"null","endLoc":562,"header":"@property\n def calculated_linkage(self)","id":1064,"name":"calculated_linkage","nodeType":"Function","startLoc":551,"text":"@property\n def calculated_linkage(self):\n\n try:\n return self._calculate_linkage_fastcluster()\n except ImportError:\n if np.product(self.shape) >= 10000:\n msg = (\"Clustering large matrix with scipy. Installing \"\n \"`fastcluster` may give better performance.\")\n warnings.warn(msg)\n\n return self._calculate_linkage_scipy()"},{"fileName":"cm.py","filePath":"seaborn","id":1065,"nodeType":"File","text":"from matplotlib import colors\nfrom seaborn._compat import register_colormap\n\n\n_rocket_lut = [\n [ 0.01060815, 0.01808215, 0.10018654],\n [ 0.01428972, 0.02048237, 0.10374486],\n [ 0.01831941, 0.0229766 , 0.10738511],\n [ 0.02275049, 0.02554464, 0.11108639],\n [ 0.02759119, 0.02818316, 0.11483751],\n [ 0.03285175, 0.03088792, 0.11863035],\n [ 0.03853466, 0.03365771, 0.12245873],\n [ 0.04447016, 0.03648425, 0.12631831],\n [ 0.05032105, 0.03936808, 0.13020508],\n [ 0.05611171, 0.04224835, 0.13411624],\n [ 0.0618531 , 0.04504866, 0.13804929],\n [ 0.06755457, 0.04778179, 0.14200206],\n [ 0.0732236 , 0.05045047, 0.14597263],\n [ 0.0788708 , 0.05305461, 0.14995981],\n [ 0.08450105, 0.05559631, 0.15396203],\n [ 0.09011319, 0.05808059, 0.15797687],\n [ 0.09572396, 0.06050127, 0.16200507],\n [ 0.10132312, 0.06286782, 0.16604287],\n [ 0.10692823, 0.06517224, 0.17009175],\n [ 0.1125315 , 0.06742194, 0.17414848],\n [ 0.11813947, 0.06961499, 0.17821272],\n [ 0.12375803, 0.07174938, 0.18228425],\n [ 0.12938228, 0.07383015, 0.18636053],\n [ 0.13501631, 0.07585609, 0.19044109],\n [ 0.14066867, 0.0778224 , 0.19452676],\n [ 0.14633406, 0.07973393, 0.1986151 ],\n [ 0.15201338, 0.08159108, 0.20270523],\n [ 0.15770877, 0.08339312, 0.20679668],\n [ 0.16342174, 0.0851396 , 0.21088893],\n [ 0.16915387, 0.08682996, 0.21498104],\n [ 0.17489524, 0.08848235, 0.2190294 ],\n [ 0.18065495, 0.09009031, 0.22303512],\n [ 0.18643324, 0.09165431, 0.22699705],\n [ 0.19223028, 0.09317479, 0.23091409],\n [ 0.19804623, 0.09465217, 0.23478512],\n [ 0.20388117, 0.09608689, 0.23860907],\n [ 0.20973515, 0.09747934, 0.24238489],\n [ 0.21560818, 0.09882993, 0.24611154],\n [ 0.22150014, 0.10013944, 0.2497868 ],\n [ 0.22741085, 0.10140876, 0.25340813],\n [ 0.23334047, 0.10263737, 0.25697736],\n [ 0.23928891, 0.10382562, 0.2604936 ],\n [ 0.24525608, 0.10497384, 0.26395596],\n [ 0.25124182, 0.10608236, 0.26736359],\n [ 0.25724602, 0.10715148, 0.27071569],\n [ 0.26326851, 0.1081815 , 0.27401148],\n [ 0.26930915, 0.1091727 , 0.2772502 ],\n [ 0.27536766, 0.11012568, 0.28043021],\n [ 0.28144375, 0.11104133, 0.2835489 ],\n [ 0.2875374 , 0.11191896, 0.28660853],\n [ 0.29364846, 0.11275876, 0.2896085 ],\n [ 0.29977678, 0.11356089, 0.29254823],\n [ 0.30592213, 0.11432553, 0.29542718],\n [ 0.31208435, 0.11505284, 0.29824485],\n [ 0.31826327, 0.1157429 , 0.30100076],\n [ 0.32445869, 0.11639585, 0.30369448],\n [ 0.33067031, 0.11701189, 0.30632563],\n [ 0.33689808, 0.11759095, 0.3088938 ],\n [ 0.34314168, 0.11813362, 0.31139721],\n [ 0.34940101, 0.11863987, 0.3138355 ],\n [ 0.355676 , 0.11910909, 0.31620996],\n [ 0.36196644, 0.1195413 , 0.31852037],\n [ 0.36827206, 0.11993653, 0.32076656],\n [ 0.37459292, 0.12029443, 0.32294825],\n [ 0.38092887, 0.12061482, 0.32506528],\n [ 0.38727975, 0.12089756, 0.3271175 ],\n [ 0.39364518, 0.12114272, 0.32910494],\n [ 0.40002537, 0.12134964, 0.33102734],\n [ 0.40642019, 0.12151801, 0.33288464],\n [ 0.41282936, 0.12164769, 0.33467689],\n [ 0.41925278, 0.12173833, 0.33640407],\n [ 0.42569057, 0.12178916, 0.33806605],\n [ 0.43214263, 0.12179973, 0.33966284],\n [ 0.43860848, 0.12177004, 0.34119475],\n [ 0.44508855, 0.12169883, 0.34266151],\n [ 0.45158266, 0.12158557, 0.34406324],\n [ 0.45809049, 0.12142996, 0.34540024],\n [ 0.46461238, 0.12123063, 0.34667231],\n [ 0.47114798, 0.12098721, 0.34787978],\n [ 0.47769736, 0.12069864, 0.34902273],\n [ 0.48426077, 0.12036349, 0.35010104],\n [ 0.49083761, 0.11998161, 0.35111537],\n [ 0.49742847, 0.11955087, 0.35206533],\n [ 0.50403286, 0.11907081, 0.35295152],\n [ 0.51065109, 0.11853959, 0.35377385],\n [ 0.51728314, 0.1179558 , 0.35453252],\n [ 0.52392883, 0.11731817, 0.35522789],\n [ 0.53058853, 0.11662445, 0.35585982],\n [ 0.53726173, 0.11587369, 0.35642903],\n [ 0.54394898, 0.11506307, 0.35693521],\n [ 0.5506426 , 0.11420757, 0.35737863],\n [ 0.55734473, 0.11330456, 0.35775059],\n [ 0.56405586, 0.11235265, 0.35804813],\n [ 0.57077365, 0.11135597, 0.35827146],\n [ 0.5774991 , 0.11031233, 0.35841679],\n [ 0.58422945, 0.10922707, 0.35848469],\n [ 0.59096382, 0.10810205, 0.35847347],\n [ 0.59770215, 0.10693774, 0.35838029],\n [ 0.60444226, 0.10573912, 0.35820487],\n [ 0.61118304, 0.10450943, 0.35794557],\n [ 0.61792306, 0.10325288, 0.35760108],\n [ 0.62466162, 0.10197244, 0.35716891],\n [ 0.63139686, 0.10067417, 0.35664819],\n [ 0.63812122, 0.09938212, 0.35603757],\n [ 0.64483795, 0.0980891 , 0.35533555],\n [ 0.65154562, 0.09680192, 0.35454107],\n [ 0.65824241, 0.09552918, 0.3536529 ],\n [ 0.66492652, 0.09428017, 0.3526697 ],\n [ 0.67159578, 0.09306598, 0.35159077],\n [ 0.67824099, 0.09192342, 0.3504148 ],\n [ 0.684863 , 0.09085633, 0.34914061],\n [ 0.69146268, 0.0898675 , 0.34776864],\n [ 0.69803757, 0.08897226, 0.3462986 ],\n [ 0.70457834, 0.0882129 , 0.34473046],\n [ 0.71108138, 0.08761223, 0.3430635 ],\n [ 0.7175507 , 0.08716212, 0.34129974],\n [ 0.72398193, 0.08688725, 0.33943958],\n [ 0.73035829, 0.0868623 , 0.33748452],\n [ 0.73669146, 0.08704683, 0.33543669],\n [ 0.74297501, 0.08747196, 0.33329799],\n [ 0.74919318, 0.08820542, 0.33107204],\n [ 0.75535825, 0.08919792, 0.32876184],\n [ 0.76145589, 0.09050716, 0.32637117],\n [ 0.76748424, 0.09213602, 0.32390525],\n [ 0.77344838, 0.09405684, 0.32136808],\n [ 0.77932641, 0.09634794, 0.31876642],\n [ 0.78513609, 0.09892473, 0.31610488],\n [ 0.79085854, 0.10184672, 0.313391 ],\n [ 0.7965014 , 0.10506637, 0.31063031],\n [ 0.80205987, 0.10858333, 0.30783 ],\n [ 0.80752799, 0.11239964, 0.30499738],\n [ 0.81291606, 0.11645784, 0.30213802],\n [ 0.81820481, 0.12080606, 0.29926105],\n [ 0.82341472, 0.12535343, 0.2963705 ],\n [ 0.82852822, 0.13014118, 0.29347474],\n [ 0.83355779, 0.13511035, 0.29057852],\n [ 0.83850183, 0.14025098, 0.2876878 ],\n [ 0.84335441, 0.14556683, 0.28480819],\n [ 0.84813096, 0.15099892, 0.281943 ],\n [ 0.85281737, 0.15657772, 0.27909826],\n [ 0.85742602, 0.1622583 , 0.27627462],\n [ 0.86196552, 0.16801239, 0.27346473],\n [ 0.86641628, 0.17387796, 0.27070818],\n [ 0.87079129, 0.17982114, 0.26797378],\n [ 0.87507281, 0.18587368, 0.26529697],\n [ 0.87925878, 0.19203259, 0.26268136],\n [ 0.8833417 , 0.19830556, 0.26014181],\n [ 0.88731387, 0.20469941, 0.25769539],\n [ 0.89116859, 0.21121788, 0.2553592 ],\n [ 0.89490337, 0.21785614, 0.25314362],\n [ 0.8985026 , 0.22463251, 0.25108745],\n [ 0.90197527, 0.23152063, 0.24918223],\n [ 0.90530097, 0.23854541, 0.24748098],\n [ 0.90848638, 0.24568473, 0.24598324],\n [ 0.911533 , 0.25292623, 0.24470258],\n [ 0.9144225 , 0.26028902, 0.24369359],\n [ 0.91717106, 0.26773821, 0.24294137],\n [ 0.91978131, 0.27526191, 0.24245973],\n [ 0.92223947, 0.28287251, 0.24229568],\n [ 0.92456587, 0.29053388, 0.24242622],\n [ 0.92676657, 0.29823282, 0.24285536],\n [ 0.92882964, 0.30598085, 0.24362274],\n [ 0.93078135, 0.31373977, 0.24468803],\n [ 0.93262051, 0.3215093 , 0.24606461],\n [ 0.93435067, 0.32928362, 0.24775328],\n [ 0.93599076, 0.33703942, 0.24972157],\n [ 0.93752831, 0.34479177, 0.25199928],\n [ 0.93899289, 0.35250734, 0.25452808],\n [ 0.94036561, 0.36020899, 0.25734661],\n [ 0.94167588, 0.36786594, 0.2603949 ],\n [ 0.94291042, 0.37549479, 0.26369821],\n [ 0.94408513, 0.3830811 , 0.26722004],\n [ 0.94520419, 0.39062329, 0.27094924],\n [ 0.94625977, 0.39813168, 0.27489742],\n [ 0.94727016, 0.4055909 , 0.27902322],\n [ 0.94823505, 0.41300424, 0.28332283],\n [ 0.94914549, 0.42038251, 0.28780969],\n [ 0.95001704, 0.42771398, 0.29244728],\n [ 0.95085121, 0.43500005, 0.29722817],\n [ 0.95165009, 0.44224144, 0.30214494],\n [ 0.9524044 , 0.44944853, 0.3072105 ],\n [ 0.95312556, 0.45661389, 0.31239776],\n [ 0.95381595, 0.46373781, 0.31769923],\n [ 0.95447591, 0.47082238, 0.32310953],\n [ 0.95510255, 0.47787236, 0.32862553],\n [ 0.95569679, 0.48489115, 0.33421404],\n [ 0.95626788, 0.49187351, 0.33985601],\n [ 0.95681685, 0.49882008, 0.34555431],\n [ 0.9573439 , 0.50573243, 0.35130912],\n [ 0.95784842, 0.51261283, 0.35711942],\n [ 0.95833051, 0.51946267, 0.36298589],\n [ 0.95879054, 0.52628305, 0.36890904],\n [ 0.95922872, 0.53307513, 0.3748895 ],\n [ 0.95964538, 0.53983991, 0.38092784],\n [ 0.96004345, 0.54657593, 0.3870292 ],\n [ 0.96042097, 0.55328624, 0.39319057],\n [ 0.96077819, 0.55997184, 0.39941173],\n [ 0.9611152 , 0.5666337 , 0.40569343],\n [ 0.96143273, 0.57327231, 0.41203603],\n [ 0.96173392, 0.57988594, 0.41844491],\n [ 0.96201757, 0.58647675, 0.42491751],\n [ 0.96228344, 0.59304598, 0.43145271],\n [ 0.96253168, 0.5995944 , 0.43805131],\n [ 0.96276513, 0.60612062, 0.44471698],\n [ 0.96298491, 0.6126247 , 0.45145074],\n [ 0.96318967, 0.61910879, 0.45824902],\n [ 0.96337949, 0.6255736 , 0.46511271],\n [ 0.96355923, 0.63201624, 0.47204746],\n [ 0.96372785, 0.63843852, 0.47905028],\n [ 0.96388426, 0.64484214, 0.4861196 ],\n [ 0.96403203, 0.65122535, 0.4932578 ],\n [ 0.96417332, 0.65758729, 0.50046894],\n [ 0.9643063 , 0.66393045, 0.5077467 ],\n [ 0.96443322, 0.67025402, 0.51509334],\n [ 0.96455845, 0.67655564, 0.52251447],\n [ 0.96467922, 0.68283846, 0.53000231],\n [ 0.96479861, 0.68910113, 0.53756026],\n [ 0.96492035, 0.69534192, 0.5451917 ],\n [ 0.96504223, 0.7015636 , 0.5528892 ],\n [ 0.96516917, 0.70776351, 0.5606593 ],\n [ 0.96530224, 0.71394212, 0.56849894],\n [ 0.96544032, 0.72010124, 0.57640375],\n [ 0.96559206, 0.72623592, 0.58438387],\n [ 0.96575293, 0.73235058, 0.59242739],\n [ 0.96592829, 0.73844258, 0.60053991],\n [ 0.96612013, 0.74451182, 0.60871954],\n [ 0.96632832, 0.75055966, 0.61696136],\n [ 0.96656022, 0.75658231, 0.62527295],\n [ 0.96681185, 0.76258381, 0.63364277],\n [ 0.96709183, 0.76855969, 0.64207921],\n [ 0.96739773, 0.77451297, 0.65057302],\n [ 0.96773482, 0.78044149, 0.65912731],\n [ 0.96810471, 0.78634563, 0.66773889],\n [ 0.96850919, 0.79222565, 0.6764046 ],\n [ 0.96893132, 0.79809112, 0.68512266],\n [ 0.96935926, 0.80395415, 0.69383201],\n [ 0.9698028 , 0.80981139, 0.70252255],\n [ 0.97025511, 0.81566605, 0.71120296],\n [ 0.97071849, 0.82151775, 0.71987163],\n [ 0.97120159, 0.82736371, 0.72851999],\n [ 0.97169389, 0.83320847, 0.73716071],\n [ 0.97220061, 0.83905052, 0.74578903],\n [ 0.97272597, 0.84488881, 0.75440141],\n [ 0.97327085, 0.85072354, 0.76299805],\n [ 0.97383206, 0.85655639, 0.77158353],\n [ 0.97441222, 0.86238689, 0.78015619],\n [ 0.97501782, 0.86821321, 0.78871034],\n [ 0.97564391, 0.87403763, 0.79725261],\n [ 0.97628674, 0.87986189, 0.8057883 ],\n [ 0.97696114, 0.88568129, 0.81430324],\n [ 0.97765722, 0.89149971, 0.82280948],\n [ 0.97837585, 0.89731727, 0.83130786],\n [ 0.97912374, 0.90313207, 0.83979337],\n [ 0.979891 , 0.90894778, 0.84827858],\n [ 0.98067764, 0.91476465, 0.85676611],\n [ 0.98137749, 0.92061729, 0.86536915]\n]\n\n\n_mako_lut = [\n [ 0.04503935, 0.01482344, 0.02092227],\n [ 0.04933018, 0.01709292, 0.02535719],\n [ 0.05356262, 0.01950702, 0.03018802],\n [ 0.05774337, 0.02205989, 0.03545515],\n [ 0.06188095, 0.02474764, 0.04115287],\n [ 0.06598247, 0.0275665 , 0.04691409],\n [ 0.07005374, 0.03051278, 0.05264306],\n [ 0.07409947, 0.03358324, 0.05834631],\n [ 0.07812339, 0.03677446, 0.06403249],\n [ 0.08212852, 0.0400833 , 0.06970862],\n [ 0.08611731, 0.04339148, 0.07538208],\n [ 0.09009161, 0.04664706, 0.08105568],\n [ 0.09405308, 0.04985685, 0.08673591],\n [ 0.09800301, 0.05302279, 0.09242646],\n [ 0.10194255, 0.05614641, 0.09813162],\n [ 0.10587261, 0.05922941, 0.103854 ],\n [ 0.1097942 , 0.06227277, 0.10959847],\n [ 0.11370826, 0.06527747, 0.11536893],\n [ 0.11761516, 0.06824548, 0.12116393],\n [ 0.12151575, 0.07117741, 0.12698763],\n [ 0.12541095, 0.07407363, 0.1328442 ],\n [ 0.12930083, 0.07693611, 0.13873064],\n [ 0.13317849, 0.07976988, 0.14465095],\n [ 0.13701138, 0.08259683, 0.15060265],\n [ 0.14079223, 0.08542126, 0.15659379],\n [ 0.14452486, 0.08824175, 0.16262484],\n [ 0.14820351, 0.09106304, 0.16869476],\n [ 0.15183185, 0.09388372, 0.17480366],\n [ 0.15540398, 0.09670855, 0.18094993],\n [ 0.15892417, 0.09953561, 0.18713384],\n [ 0.16238588, 0.10236998, 0.19335329],\n [ 0.16579435, 0.10520905, 0.19960847],\n [ 0.16914226, 0.10805832, 0.20589698],\n [ 0.17243586, 0.11091443, 0.21221911],\n [ 0.17566717, 0.11378321, 0.21857219],\n [ 0.17884322, 0.11666074, 0.2249565 ],\n [ 0.18195582, 0.11955283, 0.23136943],\n [ 0.18501213, 0.12245547, 0.23781116],\n [ 0.18800459, 0.12537395, 0.24427914],\n [ 0.19093944, 0.1283047 , 0.25077369],\n [ 0.19381092, 0.13125179, 0.25729255],\n [ 0.19662307, 0.13421303, 0.26383543],\n [ 0.19937337, 0.13719028, 0.27040111],\n [ 0.20206187, 0.14018372, 0.27698891],\n [ 0.20469116, 0.14319196, 0.28359861],\n [ 0.20725547, 0.14621882, 0.29022775],\n [ 0.20976258, 0.14925954, 0.29687795],\n [ 0.21220409, 0.15231929, 0.30354703],\n [ 0.21458611, 0.15539445, 0.31023563],\n [ 0.21690827, 0.15848519, 0.31694355],\n [ 0.21916481, 0.16159489, 0.32366939],\n [ 0.2213631 , 0.16471913, 0.33041431],\n [ 0.22349947, 0.1678599 , 0.33717781],\n [ 0.2255714 , 0.1710185 , 0.34395925],\n [ 0.22758415, 0.17419169, 0.35075983],\n [ 0.22953569, 0.17738041, 0.35757941],\n [ 0.23142077, 0.18058733, 0.3644173 ],\n [ 0.2332454 , 0.18380872, 0.37127514],\n [ 0.2350092 , 0.18704459, 0.3781528 ],\n [ 0.23670785, 0.190297 , 0.38504973],\n [ 0.23834119, 0.19356547, 0.39196711],\n [ 0.23991189, 0.19684817, 0.39890581],\n [ 0.24141903, 0.20014508, 0.4058667 ],\n [ 0.24286214, 0.20345642, 0.4128484 ],\n [ 0.24423453, 0.20678459, 0.41985299],\n [ 0.24554109, 0.21012669, 0.42688124],\n [ 0.2467815 , 0.21348266, 0.43393244],\n [ 0.24795393, 0.21685249, 0.4410088 ],\n [ 0.24905614, 0.22023618, 0.448113 ],\n [ 0.25007383, 0.22365053, 0.45519562],\n [ 0.25098926, 0.22710664, 0.46223892],\n [ 0.25179696, 0.23060342, 0.46925447],\n [ 0.25249346, 0.23414353, 0.47623196],\n [ 0.25307401, 0.23772973, 0.48316271],\n [ 0.25353152, 0.24136961, 0.49001976],\n [ 0.25386167, 0.24506548, 0.49679407],\n [ 0.25406082, 0.2488164 , 0.50348932],\n [ 0.25412435, 0.25262843, 0.51007843],\n [ 0.25404842, 0.25650743, 0.51653282],\n [ 0.25383134, 0.26044852, 0.52286845],\n [ 0.2534705 , 0.26446165, 0.52903422],\n [ 0.25296722, 0.2685428 , 0.53503572],\n [ 0.2523226 , 0.27269346, 0.54085315],\n [ 0.25153974, 0.27691629, 0.54645752],\n [ 0.25062402, 0.28120467, 0.55185939],\n [ 0.24958205, 0.28556371, 0.55701246],\n [ 0.24842386, 0.28998148, 0.56194601],\n [ 0.24715928, 0.29446327, 0.56660884],\n [ 0.24580099, 0.29899398, 0.57104399],\n [ 0.24436202, 0.30357852, 0.57519929],\n [ 0.24285591, 0.30819938, 0.57913247],\n [ 0.24129828, 0.31286235, 0.58278615],\n [ 0.23970131, 0.3175495 , 0.5862272 ],\n [ 0.23807973, 0.32226344, 0.58941872],\n [ 0.23644557, 0.32699241, 0.59240198],\n [ 0.2348113 , 0.33173196, 0.59518282],\n [ 0.23318874, 0.33648036, 0.59775543],\n [ 0.2315855 , 0.34122763, 0.60016456],\n [ 0.23001121, 0.34597357, 0.60240251],\n [ 0.2284748 , 0.35071512, 0.6044784 ],\n [ 0.22698081, 0.35544612, 0.60642528],\n [ 0.22553305, 0.36016515, 0.60825252],\n [ 0.22413977, 0.36487341, 0.60994938],\n [ 0.22280246, 0.36956728, 0.61154118],\n [ 0.22152555, 0.37424409, 0.61304472],\n [ 0.22030752, 0.37890437, 0.61446646],\n [ 0.2191538 , 0.38354668, 0.61581561],\n [ 0.21806257, 0.38817169, 0.61709794],\n [ 0.21703799, 0.39277882, 0.61831922],\n [ 0.21607792, 0.39736958, 0.61948028],\n [ 0.21518463, 0.40194196, 0.62059763],\n [ 0.21435467, 0.40649717, 0.62167507],\n [ 0.21358663, 0.41103579, 0.62271724],\n [ 0.21288172, 0.41555771, 0.62373011],\n [ 0.21223835, 0.42006355, 0.62471794],\n [ 0.21165312, 0.42455441, 0.62568371],\n [ 0.21112526, 0.42903064, 0.6266318 ],\n [ 0.21065161, 0.43349321, 0.62756504],\n [ 0.21023306, 0.43794288, 0.62848279],\n [ 0.20985996, 0.44238227, 0.62938329],\n [ 0.20951045, 0.44680966, 0.63030696],\n [ 0.20916709, 0.45122981, 0.63124483],\n [ 0.20882976, 0.45564335, 0.63219599],\n [ 0.20849798, 0.46005094, 0.63315928],\n [ 0.20817199, 0.46445309, 0.63413391],\n [ 0.20785149, 0.46885041, 0.63511876],\n [ 0.20753716, 0.47324327, 0.63611321],\n [ 0.20722876, 0.47763224, 0.63711608],\n [ 0.20692679, 0.48201774, 0.63812656],\n [ 0.20663156, 0.48640018, 0.63914367],\n [ 0.20634336, 0.49078002, 0.64016638],\n [ 0.20606303, 0.49515755, 0.6411939 ],\n [ 0.20578999, 0.49953341, 0.64222457],\n [ 0.20552612, 0.50390766, 0.64325811],\n [ 0.20527189, 0.50828072, 0.64429331],\n [ 0.20502868, 0.51265277, 0.64532947],\n [ 0.20479718, 0.51702417, 0.64636539],\n [ 0.20457804, 0.52139527, 0.64739979],\n [ 0.20437304, 0.52576622, 0.64843198],\n [ 0.20418396, 0.53013715, 0.64946117],\n [ 0.20401238, 0.53450825, 0.65048638],\n [ 0.20385896, 0.53887991, 0.65150606],\n [ 0.20372653, 0.54325208, 0.65251978],\n [ 0.20361709, 0.5476249 , 0.6535266 ],\n [ 0.20353258, 0.55199854, 0.65452542],\n [ 0.20347472, 0.55637318, 0.655515 ],\n [ 0.20344718, 0.56074869, 0.65649508],\n [ 0.20345161, 0.56512531, 0.65746419],\n [ 0.20349089, 0.56950304, 0.65842151],\n [ 0.20356842, 0.57388184, 0.65936642],\n [ 0.20368663, 0.57826181, 0.66029768],\n [ 0.20384884, 0.58264293, 0.6612145 ],\n [ 0.20405904, 0.58702506, 0.66211645],\n [ 0.20431921, 0.59140842, 0.66300179],\n [ 0.20463464, 0.59579264, 0.66387079],\n [ 0.20500731, 0.60017798, 0.66472159],\n [ 0.20544449, 0.60456387, 0.66555409],\n [ 0.20596097, 0.60894927, 0.66636568],\n [ 0.20654832, 0.61333521, 0.66715744],\n [ 0.20721003, 0.61772167, 0.66792838],\n [ 0.20795035, 0.62210845, 0.66867802],\n [ 0.20877302, 0.62649546, 0.66940555],\n [ 0.20968223, 0.63088252, 0.6701105 ],\n [ 0.21068163, 0.63526951, 0.67079211],\n [ 0.21177544, 0.63965621, 0.67145005],\n [ 0.21298582, 0.64404072, 0.67208182],\n [ 0.21430361, 0.64842404, 0.67268861],\n [ 0.21572716, 0.65280655, 0.67326978],\n [ 0.21726052, 0.65718791, 0.6738255 ],\n [ 0.21890636, 0.66156803, 0.67435491],\n [ 0.220668 , 0.66594665, 0.67485792],\n [ 0.22255447, 0.67032297, 0.67533374],\n [ 0.22458372, 0.67469531, 0.67578061],\n [ 0.22673713, 0.67906542, 0.67620044],\n [ 0.22901625, 0.6834332 , 0.67659251],\n [ 0.23142316, 0.68779836, 0.67695703],\n [ 0.23395924, 0.69216072, 0.67729378],\n [ 0.23663857, 0.69651881, 0.67760151],\n [ 0.23946645, 0.70087194, 0.67788018],\n [ 0.24242624, 0.70522162, 0.67813088],\n [ 0.24549008, 0.70957083, 0.67835215],\n [ 0.24863372, 0.71392166, 0.67854868],\n [ 0.25187832, 0.71827158, 0.67872193],\n [ 0.25524083, 0.72261873, 0.67887024],\n [ 0.25870947, 0.72696469, 0.67898912],\n [ 0.26229238, 0.73130855, 0.67907645],\n [ 0.26604085, 0.73564353, 0.67914062],\n [ 0.26993099, 0.73997282, 0.67917264],\n [ 0.27397488, 0.74429484, 0.67917096],\n [ 0.27822463, 0.74860229, 0.67914468],\n [ 0.28264201, 0.75290034, 0.67907959],\n [ 0.2873016 , 0.75717817, 0.67899164],\n [ 0.29215894, 0.76144162, 0.67886578],\n [ 0.29729823, 0.76567816, 0.67871894],\n [ 0.30268199, 0.76989232, 0.67853896],\n [ 0.30835665, 0.77407636, 0.67833512],\n [ 0.31435139, 0.77822478, 0.67811118],\n [ 0.3206671 , 0.78233575, 0.67786729],\n [ 0.32733158, 0.78640315, 0.67761027],\n [ 0.33437168, 0.79042043, 0.67734882],\n [ 0.34182112, 0.79437948, 0.67709394],\n [ 0.34968889, 0.79827511, 0.67685638],\n [ 0.35799244, 0.80210037, 0.67664969],\n [ 0.36675371, 0.80584651, 0.67649539],\n [ 0.3759816 , 0.80950627, 0.67641393],\n [ 0.38566792, 0.81307432, 0.67642947],\n [ 0.39579804, 0.81654592, 0.67656899],\n [ 0.40634556, 0.81991799, 0.67686215],\n [ 0.41730243, 0.82318339, 0.67735255],\n [ 0.4285828 , 0.82635051, 0.6780564 ],\n [ 0.44012728, 0.82942353, 0.67900049],\n [ 0.45189421, 0.83240398, 0.68021733],\n [ 0.46378379, 0.83530763, 0.6817062 ],\n [ 0.47573199, 0.83814472, 0.68347352],\n [ 0.48769865, 0.84092197, 0.68552698],\n [ 0.49962354, 0.84365379, 0.68783929],\n [ 0.5114027 , 0.8463718 , 0.69029789],\n [ 0.52301693, 0.84908401, 0.69288545],\n [ 0.53447549, 0.85179048, 0.69561066],\n [ 0.54578602, 0.8544913 , 0.69848331],\n [ 0.55695565, 0.85718723, 0.70150427],\n [ 0.56798832, 0.85987893, 0.70468261],\n [ 0.57888639, 0.86256715, 0.70802931],\n [ 0.5896541 , 0.8652532 , 0.71154204],\n [ 0.60028928, 0.86793835, 0.71523675],\n [ 0.61079441, 0.87062438, 0.71910895],\n [ 0.62116633, 0.87331311, 0.72317003],\n [ 0.63140509, 0.87600675, 0.72741689],\n [ 0.64150735, 0.87870746, 0.73185717],\n [ 0.65147219, 0.8814179 , 0.73648495],\n [ 0.66129632, 0.8841403 , 0.74130658],\n [ 0.67097934, 0.88687758, 0.74631123],\n [ 0.68051833, 0.88963189, 0.75150483],\n [ 0.68991419, 0.89240612, 0.75687187],\n [ 0.69916533, 0.89520211, 0.76241714],\n [ 0.70827373, 0.89802257, 0.76812286],\n [ 0.71723995, 0.90086891, 0.77399039],\n [ 0.72606665, 0.90374337, 0.7800041 ],\n [ 0.73475675, 0.90664718, 0.78615802],\n [ 0.74331358, 0.90958151, 0.79244474],\n [ 0.75174143, 0.91254787, 0.79884925],\n [ 0.76004473, 0.91554656, 0.80536823],\n [ 0.76827704, 0.91856549, 0.81196513],\n [ 0.77647029, 0.921603 , 0.81855729],\n [ 0.78462009, 0.92466151, 0.82514119],\n [ 0.79273542, 0.92773848, 0.83172131],\n [ 0.8008109 , 0.93083672, 0.83829355],\n [ 0.80885107, 0.93395528, 0.84485982],\n [ 0.81685878, 0.9370938 , 0.85142101],\n [ 0.82483206, 0.94025378, 0.8579751 ],\n [ 0.83277661, 0.94343371, 0.86452477],\n [ 0.84069127, 0.94663473, 0.87106853],\n [ 0.84857662, 0.9498573 , 0.8776059 ],\n [ 0.8564431 , 0.95309792, 0.88414253],\n [ 0.86429066, 0.95635719, 0.89067759],\n [ 0.87218969, 0.95960708, 0.89725384]\n]\n\n\n_vlag_lut = [\n [ 0.13850039, 0.41331206, 0.74052025],\n [ 0.15077609, 0.41762684, 0.73970427],\n [ 0.16235219, 0.4219191 , 0.7389667 ],\n [ 0.1733322 , 0.42619024, 0.73832537],\n [ 0.18382538, 0.43044226, 0.73776764],\n [ 0.19394034, 0.4346772 , 0.73725867],\n [ 0.20367115, 0.43889576, 0.73685314],\n [ 0.21313625, 0.44310003, 0.73648045],\n [ 0.22231173, 0.44729079, 0.73619681],\n [ 0.23125148, 0.45146945, 0.73597803],\n [ 0.23998101, 0.45563715, 0.7358223 ],\n [ 0.24853358, 0.45979489, 0.73571524],\n [ 0.25691416, 0.4639437 , 0.73566943],\n [ 0.26513894, 0.46808455, 0.73568319],\n [ 0.27322194, 0.47221835, 0.73575497],\n [ 0.28117543, 0.47634598, 0.73588332],\n [ 0.28901021, 0.48046826, 0.73606686],\n [ 0.2967358 , 0.48458597, 0.73630433],\n [ 0.30436071, 0.48869986, 0.73659451],\n [ 0.3118955 , 0.49281055, 0.73693255],\n [ 0.31935389, 0.49691847, 0.73730851],\n [ 0.32672701, 0.5010247 , 0.73774013],\n [ 0.33402607, 0.50512971, 0.73821941],\n [ 0.34125337, 0.50923419, 0.73874905],\n [ 0.34840921, 0.51333892, 0.73933402],\n [ 0.35551826, 0.51744353, 0.73994642],\n [ 0.3625676 , 0.52154929, 0.74060763],\n [ 0.36956356, 0.52565656, 0.74131327],\n [ 0.37649902, 0.52976642, 0.74207698],\n [ 0.38340273, 0.53387791, 0.74286286],\n [ 0.39025859, 0.53799253, 0.7436962 ],\n [ 0.39706821, 0.54211081, 0.744578 ],\n [ 0.40384046, 0.54623277, 0.74549872],\n [ 0.41058241, 0.55035849, 0.74645094],\n [ 0.41728385, 0.55448919, 0.74745174],\n [ 0.42395178, 0.55862494, 0.74849357],\n [ 0.4305964 , 0.56276546, 0.74956387],\n [ 0.4372044 , 0.56691228, 0.75068412],\n [ 0.4437909 , 0.57106468, 0.75183427],\n [ 0.45035117, 0.5752235 , 0.75302312],\n [ 0.45687824, 0.57938983, 0.75426297],\n [ 0.46339713, 0.58356191, 0.75551816],\n [ 0.46988778, 0.58774195, 0.75682037],\n [ 0.47635605, 0.59192986, 0.75816245],\n [ 0.48281101, 0.5961252 , 0.75953212],\n [ 0.4892374 , 0.60032986, 0.76095418],\n [ 0.49566225, 0.60454154, 0.76238852],\n [ 0.50206137, 0.60876307, 0.76387371],\n [ 0.50845128, 0.61299312, 0.76538551],\n [ 0.5148258 , 0.61723272, 0.76693475],\n [ 0.52118385, 0.62148236, 0.76852436],\n [ 0.52753571, 0.62574126, 0.77013939],\n [ 0.53386831, 0.63001125, 0.77180152],\n [ 0.54020159, 0.63429038, 0.7734803 ],\n [ 0.54651272, 0.63858165, 0.77521306],\n [ 0.55282975, 0.64288207, 0.77695608],\n [ 0.55912585, 0.64719519, 0.77875327],\n [ 0.56542599, 0.65151828, 0.78056551],\n [ 0.57170924, 0.65585426, 0.78242747],\n [ 0.57799572, 0.6602009 , 0.78430751],\n [ 0.58426817, 0.66456073, 0.78623458],\n [ 0.590544 , 0.66893178, 0.78818117],\n [ 0.59680758, 0.67331643, 0.79017369],\n [ 0.60307553, 0.67771273, 0.79218572],\n [ 0.60934065, 0.68212194, 0.79422987],\n [ 0.61559495, 0.68654548, 0.7963202 ],\n [ 0.62185554, 0.69098125, 0.79842918],\n [ 0.62810662, 0.69543176, 0.80058381],\n [ 0.63436425, 0.69989499, 0.80275812],\n [ 0.64061445, 0.70437326, 0.80497621],\n [ 0.6468706 , 0.70886488, 0.80721641],\n [ 0.65312213, 0.7133717 , 0.80949719],\n [ 0.65937818, 0.71789261, 0.81180392],\n [ 0.66563334, 0.72242871, 0.81414642],\n [ 0.67189155, 0.72697967, 0.81651872],\n [ 0.67815314, 0.73154569, 0.81892097],\n [ 0.68441395, 0.73612771, 0.82136094],\n [ 0.69068321, 0.74072452, 0.82382353],\n [ 0.69694776, 0.7453385 , 0.82633199],\n [ 0.70322431, 0.74996721, 0.8288583 ],\n [ 0.70949595, 0.75461368, 0.83143221],\n [ 0.7157774 , 0.75927574, 0.83402904],\n [ 0.72206299, 0.76395461, 0.83665922],\n [ 0.72835227, 0.76865061, 0.8393242 ],\n [ 0.73465238, 0.7733628 , 0.84201224],\n [ 0.74094862, 0.77809393, 0.84474951],\n [ 0.74725683, 0.78284158, 0.84750915],\n [ 0.75357103, 0.78760701, 0.85030217],\n [ 0.75988961, 0.79239077, 0.85313207],\n [ 0.76621987, 0.79719185, 0.85598668],\n [ 0.77255045, 0.8020125 , 0.85888658],\n [ 0.77889241, 0.80685102, 0.86181298],\n [ 0.78524572, 0.81170768, 0.86476656],\n [ 0.79159841, 0.81658489, 0.86776906],\n [ 0.79796459, 0.82148036, 0.8707962 ],\n [ 0.80434168, 0.82639479, 0.87385315],\n [ 0.8107221 , 0.83132983, 0.87695392],\n [ 0.81711301, 0.8362844 , 0.88008641],\n [ 0.82351479, 0.84125863, 0.88325045],\n [ 0.82992772, 0.84625263, 0.88644594],\n [ 0.83634359, 0.85126806, 0.8896878 ],\n [ 0.84277295, 0.85630293, 0.89295721],\n [ 0.84921192, 0.86135782, 0.89626076],\n [ 0.85566206, 0.866432 , 0.89959467],\n [ 0.86211514, 0.87152627, 0.90297183],\n [ 0.86857483, 0.87663856, 0.90638248],\n [ 0.87504231, 0.88176648, 0.90981938],\n [ 0.88151194, 0.88690782, 0.91328493],\n [ 0.88797938, 0.89205857, 0.91677544],\n [ 0.89443865, 0.89721298, 0.9202854 ],\n [ 0.90088204, 0.90236294, 0.92380601],\n [ 0.90729768, 0.90749778, 0.92732797],\n [ 0.91367037, 0.91260329, 0.93083814],\n [ 0.91998105, 0.91766106, 0.93431861],\n [ 0.92620596, 0.92264789, 0.93774647],\n [ 0.93231683, 0.9275351 , 0.94109192],\n [ 0.93827772, 0.9322888 , 0.94432312],\n [ 0.94404755, 0.93686925, 0.94740137],\n [ 0.94958284, 0.94123072, 0.95027696],\n [ 0.95482682, 0.9453245 , 0.95291103],\n [ 0.9597248 , 0.94909728, 0.95525103],\n [ 0.96422552, 0.95249273, 0.95723271],\n [ 0.96826161, 0.95545812, 0.95882188],\n [ 0.97178458, 0.95793984, 0.95995705],\n [ 0.97474105, 0.95989142, 0.96059997],\n [ 0.97708604, 0.96127366, 0.96071853],\n [ 0.97877855, 0.96205832, 0.96030095],\n [ 0.97978484, 0.96222949, 0.95935496],\n [ 0.9805997 , 0.96155216, 0.95813083],\n [ 0.98152619, 0.95993719, 0.95639322],\n [ 0.9819726 , 0.95766608, 0.95399269],\n [ 0.98191855, 0.9547873 , 0.95098107],\n [ 0.98138514, 0.95134771, 0.94740644],\n [ 0.98040845, 0.94739906, 0.94332125],\n [ 0.97902107, 0.94300131, 0.93878672],\n [ 0.97729348, 0.93820409, 0.93385135],\n [ 0.9752533 , 0.933073 , 0.92858252],\n [ 0.97297834, 0.92765261, 0.92302309],\n [ 0.97049104, 0.92200317, 0.91723505],\n [ 0.96784372, 0.91616744, 0.91126063],\n [ 0.96507281, 0.91018664, 0.90514124],\n [ 0.96222034, 0.90409203, 0.89890756],\n [ 0.9593079 , 0.89791478, 0.89259122],\n [ 0.95635626, 0.89167908, 0.88621654],\n [ 0.95338303, 0.88540373, 0.87980238],\n [ 0.95040174, 0.87910333, 0.87336339],\n [ 0.94742246, 0.87278899, 0.86691076],\n [ 0.94445249, 0.86646893, 0.86045277],\n [ 0.94150476, 0.86014606, 0.85399191],\n [ 0.93857394, 0.85382798, 0.84753642],\n [ 0.93566206, 0.84751766, 0.84108935],\n [ 0.93277194, 0.8412164 , 0.83465197],\n [ 0.92990106, 0.83492672, 0.82822708],\n [ 0.92704736, 0.82865028, 0.82181656],\n [ 0.92422703, 0.82238092, 0.81541333],\n [ 0.92142581, 0.81612448, 0.80902415],\n [ 0.91864501, 0.80988032, 0.80264838],\n [ 0.91587578, 0.80365187, 0.79629001],\n [ 0.9131367 , 0.79743115, 0.78994 ],\n [ 0.91041602, 0.79122265, 0.78360361],\n [ 0.90771071, 0.78502727, 0.77728196],\n [ 0.90501581, 0.77884674, 0.7709771 ],\n [ 0.90235365, 0.77267117, 0.76467793],\n [ 0.8997019 , 0.76650962, 0.75839484],\n [ 0.89705346, 0.76036481, 0.752131 ],\n [ 0.89444021, 0.75422253, 0.74587047],\n [ 0.89183355, 0.74809474, 0.73962689],\n [ 0.88923216, 0.74198168, 0.73340061],\n [ 0.88665892, 0.73587283, 0.72717995],\n [ 0.88408839, 0.72977904, 0.72097718],\n [ 0.88153537, 0.72369332, 0.71478461],\n [ 0.87899389, 0.7176179 , 0.70860487],\n [ 0.87645157, 0.71155805, 0.7024439 ],\n [ 0.8739399 , 0.70549893, 0.6962854 ],\n [ 0.87142626, 0.6994551 , 0.69014561],\n [ 0.8689268 , 0.69341868, 0.68401597],\n [ 0.86643562, 0.687392 , 0.67789917],\n [ 0.86394434, 0.68137863, 0.67179927],\n [ 0.86147586, 0.67536728, 0.665704 ],\n [ 0.85899928, 0.66937226, 0.6596292 ],\n [ 0.85654668, 0.66337773, 0.6535577 ],\n [ 0.85408818, 0.65739772, 0.64750494],\n [ 0.85164413, 0.65142189, 0.64145983],\n [ 0.84920091, 0.6454565 , 0.63542932],\n [ 0.84676427, 0.63949827, 0.62941 ],\n [ 0.84433231, 0.63354773, 0.62340261],\n [ 0.84190106, 0.62760645, 0.61740899],\n [ 0.83947935, 0.62166951, 0.61142404],\n [ 0.8370538 , 0.61574332, 0.60545478],\n [ 0.83463975, 0.60981951, 0.59949247],\n [ 0.83221877, 0.60390724, 0.593547 ],\n [ 0.82980985, 0.59799607, 0.58760751],\n [ 0.82740268, 0.59209095, 0.58167944],\n [ 0.82498638, 0.5861973 , 0.57576866],\n [ 0.82258181, 0.5803034 , 0.56986307],\n [ 0.82016611, 0.57442123, 0.56397539],\n [ 0.81776305, 0.56853725, 0.55809173],\n [ 0.81534551, 0.56266602, 0.55222741],\n [ 0.81294293, 0.55679056, 0.5463651 ],\n [ 0.81052113, 0.55092973, 0.54052443],\n [ 0.80811509, 0.54506305, 0.53468464],\n [ 0.80568952, 0.53921036, 0.52886622],\n [ 0.80327506, 0.53335335, 0.52305077],\n [ 0.80084727, 0.52750583, 0.51725256],\n [ 0.79842217, 0.5216578 , 0.51146173],\n [ 0.79599382, 0.51581223, 0.50568155],\n [ 0.79355781, 0.50997127, 0.49991444],\n [ 0.79112596, 0.50412707, 0.49415289],\n [ 0.78867442, 0.49829386, 0.48841129],\n [ 0.7862306 , 0.49245398, 0.48267247],\n [ 0.7837687 , 0.48662309, 0.47695216],\n [ 0.78130809, 0.4807883 , 0.47123805],\n [ 0.77884467, 0.47495151, 0.46553236],\n [ 0.77636283, 0.46912235, 0.45984473],\n [ 0.77388383, 0.46328617, 0.45416141],\n [ 0.77138912, 0.45745466, 0.44849398],\n [ 0.76888874, 0.45162042, 0.44283573],\n [ 0.76638802, 0.44577901, 0.43718292],\n [ 0.76386116, 0.43994762, 0.43155211],\n [ 0.76133542, 0.43410655, 0.42592523],\n [ 0.75880631, 0.42825801, 0.42030488],\n [ 0.75624913, 0.42241905, 0.41470727],\n [ 0.7536919 , 0.41656866, 0.40911347],\n [ 0.75112748, 0.41071104, 0.40352792],\n [ 0.74854331, 0.40485474, 0.3979589 ],\n [ 0.74594723, 0.39899309, 0.39240088],\n [ 0.74334332, 0.39312199, 0.38685075],\n [ 0.74073277, 0.38723941, 0.3813074 ],\n [ 0.73809409, 0.38136133, 0.37578553],\n [ 0.73544692, 0.37547129, 0.37027123],\n [ 0.73278943, 0.36956954, 0.36476549],\n [ 0.73011829, 0.36365761, 0.35927038],\n [ 0.72743485, 0.35773314, 0.35378465],\n [ 0.72472722, 0.35180504, 0.34831662],\n [ 0.72200473, 0.34586421, 0.34285937],\n [ 0.71927052, 0.33990649, 0.33741033],\n [ 0.71652049, 0.33393396, 0.33197219],\n [ 0.71375362, 0.32794602, 0.32654545],\n [ 0.71096951, 0.32194148, 0.32113016],\n [ 0.70816772, 0.31591904, 0.31572637],\n [ 0.70534784, 0.30987734, 0.31033414],\n [ 0.70250944, 0.30381489, 0.30495353],\n [ 0.69965211, 0.2977301 , 0.2995846 ],\n [ 0.6967754 , 0.29162126, 0.29422741],\n [ 0.69388446, 0.28548074, 0.28887769],\n [ 0.69097561, 0.2793096 , 0.28353795],\n [ 0.68803513, 0.27311993, 0.27821876],\n [ 0.6850794 , 0.26689144, 0.27290694],\n [ 0.682108 , 0.26062114, 0.26760246],\n [ 0.67911013, 0.2543177 , 0.26231367],\n [ 0.67609393, 0.24796818, 0.25703372],\n [ 0.67305921, 0.24156846, 0.25176238],\n [ 0.67000176, 0.23511902, 0.24650278],\n [ 0.66693423, 0.22859879, 0.24124404],\n [ 0.6638441 , 0.22201742, 0.2359961 ],\n [ 0.66080672, 0.21526712, 0.23069468]\n]\n\n\n_icefire_lut = [\n [ 0.73936227, 0.90443867, 0.85757238],\n [ 0.72888063, 0.89639109, 0.85488394],\n [ 0.71834255, 0.88842162, 0.8521605 ],\n [ 0.70773866, 0.88052939, 0.849422 ],\n [ 0.69706215, 0.87271313, 0.84668315],\n [ 0.68629021, 0.86497329, 0.84398721],\n [ 0.67543654, 0.85730617, 0.84130969],\n [ 0.66448539, 0.84971123, 0.83868005],\n [ 0.65342679, 0.84218728, 0.83611512],\n [ 0.64231804, 0.83471867, 0.83358584],\n [ 0.63117745, 0.827294 , 0.83113431],\n [ 0.62000484, 0.81991069, 0.82876741],\n [ 0.60879435, 0.81256797, 0.82648905],\n [ 0.59754118, 0.80526458, 0.82430414],\n [ 0.58624247, 0.79799884, 0.82221573],\n [ 0.57489525, 0.7907688 , 0.82022901],\n [ 0.56349779, 0.78357215, 0.81834861],\n [ 0.55204294, 0.77640827, 0.81657563],\n [ 0.54052516, 0.76927562, 0.81491462],\n [ 0.52894085, 0.76217215, 0.81336913],\n [ 0.51728854, 0.75509528, 0.81194156],\n [ 0.50555676, 0.74804469, 0.81063503],\n [ 0.49373871, 0.7410187 , 0.80945242],\n [ 0.48183174, 0.73401449, 0.80839675],\n [ 0.46982587, 0.72703075, 0.80747097],\n [ 0.45770893, 0.72006648, 0.80667756],\n [ 0.44547249, 0.71311941, 0.80601991],\n [ 0.43318643, 0.70617126, 0.80549278],\n [ 0.42110294, 0.69916972, 0.80506683],\n [ 0.40925101, 0.69211059, 0.80473246],\n [ 0.3976693 , 0.68498786, 0.80448272],\n [ 0.38632002, 0.67781125, 0.80431024],\n [ 0.37523981, 0.67057537, 0.80420832],\n [ 0.36442578, 0.66328229, 0.80417474],\n [ 0.35385939, 0.65593699, 0.80420591],\n [ 0.34358916, 0.64853177, 0.8043 ],\n [ 0.33355526, 0.64107876, 0.80445484],\n [ 0.32383062, 0.63356578, 0.80467091],\n [ 0.31434372, 0.62600624, 0.8049475 ],\n [ 0.30516161, 0.618389 , 0.80528692],\n [ 0.29623491, 0.61072284, 0.80569021],\n [ 0.28759072, 0.60300319, 0.80616055],\n [ 0.27923924, 0.59522877, 0.80669803],\n [ 0.27114651, 0.5874047 , 0.80730545],\n [ 0.26337153, 0.57952055, 0.80799113],\n [ 0.25588696, 0.57157984, 0.80875922],\n [ 0.248686 , 0.56358255, 0.80961366],\n [ 0.24180668, 0.55552289, 0.81055123],\n [ 0.23526251, 0.54739477, 0.8115939 ],\n [ 0.22921445, 0.53918506, 0.81267292],\n [ 0.22397687, 0.53086094, 0.8137141 ],\n [ 0.21977058, 0.52241482, 0.81457651],\n [ 0.21658989, 0.51384321, 0.81528511],\n [ 0.21452772, 0.50514155, 0.81577278],\n [ 0.21372783, 0.49630865, 0.81589566],\n [ 0.21409503, 0.48734861, 0.81566163],\n [ 0.2157176 , 0.47827123, 0.81487615],\n [ 0.21842857, 0.46909168, 0.81351614],\n [ 0.22211705, 0.45983212, 0.81146983],\n [ 0.22665681, 0.45052233, 0.80860217],\n [ 0.23176013, 0.44119137, 0.80494325],\n [ 0.23727775, 0.43187704, 0.80038017],\n [ 0.24298285, 0.42261123, 0.79493267],\n [ 0.24865068, 0.41341842, 0.78869164],\n [ 0.25423116, 0.40433127, 0.78155831],\n [ 0.25950239, 0.39535521, 0.77376848],\n [ 0.2644736 , 0.38651212, 0.76524809],\n [ 0.26901584, 0.37779582, 0.75621942],\n [ 0.27318141, 0.36922056, 0.746605 ],\n [ 0.27690355, 0.3607736 , 0.73659374],\n [ 0.28023585, 0.35244234, 0.72622103],\n [ 0.28306009, 0.34438449, 0.71500731],\n [ 0.28535896, 0.33660243, 0.70303975],\n [ 0.28708711, 0.32912157, 0.69034504],\n [ 0.28816354, 0.32200604, 0.67684067],\n [ 0.28862749, 0.31519824, 0.66278813],\n [ 0.28847904, 0.30869064, 0.6482815 ],\n [ 0.28770912, 0.30250126, 0.63331265],\n [ 0.28640325, 0.29655509, 0.61811374],\n [ 0.28458943, 0.29082155, 0.60280913],\n [ 0.28233561, 0.28527482, 0.58742866],\n [ 0.27967038, 0.2798938 , 0.57204225],\n [ 0.27665361, 0.27465357, 0.55667809],\n [ 0.27332564, 0.2695165 , 0.54145387],\n [ 0.26973851, 0.26447054, 0.52634916],\n [ 0.2659204 , 0.25949691, 0.511417 ],\n [ 0.26190145, 0.25458123, 0.49668768],\n [ 0.2577151 , 0.24971691, 0.48214874],\n [ 0.25337618, 0.24490494, 0.46778758],\n [ 0.24890842, 0.24013332, 0.45363816],\n [ 0.24433654, 0.23539226, 0.4397245 ],\n [ 0.23967922, 0.23067729, 0.4260591 ],\n [ 0.23495608, 0.22598894, 0.41262952],\n [ 0.23018113, 0.22132414, 0.39945577],\n [ 0.22534609, 0.21670847, 0.38645794],\n [ 0.22048761, 0.21211723, 0.37372555],\n [ 0.2156198 , 0.20755389, 0.36125301],\n [ 0.21074637, 0.20302717, 0.34903192],\n [ 0.20586893, 0.19855368, 0.33701661],\n [ 0.20101757, 0.19411573, 0.32529173],\n [ 0.19619947, 0.18972425, 0.31383846],\n [ 0.19140726, 0.18540157, 0.30260777],\n [ 0.1866769 , 0.1811332 , 0.29166583],\n [ 0.18201285, 0.17694992, 0.28088776],\n [ 0.17745228, 0.17282141, 0.27044211],\n [ 0.17300684, 0.16876921, 0.26024893],\n [ 0.16868273, 0.16479861, 0.25034479],\n [ 0.16448691, 0.16091728, 0.24075373],\n [ 0.16043195, 0.15714351, 0.23141745],\n [ 0.15652427, 0.15348248, 0.22238175],\n [ 0.15277065, 0.14994111, 0.21368395],\n [ 0.14918274, 0.14653431, 0.20529486],\n [ 0.14577095, 0.14327403, 0.19720829],\n [ 0.14254381, 0.14016944, 0.18944326],\n [ 0.13951035, 0.13723063, 0.18201072],\n [ 0.13667798, 0.13446606, 0.17493774],\n [ 0.13405762, 0.13188822, 0.16820842],\n [ 0.13165767, 0.12950667, 0.16183275],\n [ 0.12948748, 0.12733187, 0.15580631],\n [ 0.12755435, 0.1253723 , 0.15014098],\n [ 0.12586516, 0.12363617, 0.1448459 ],\n [ 0.12442647, 0.12213143, 0.13992571],\n [ 0.12324241, 0.12086419, 0.13539995],\n [ 0.12232067, 0.11984278, 0.13124644],\n [ 0.12166209, 0.11907077, 0.12749671],\n [ 0.12126982, 0.11855309, 0.12415079],\n [ 0.12114244, 0.11829179, 0.1212385 ],\n [ 0.12127766, 0.11828837, 0.11878534],\n [ 0.12284806, 0.1179729 , 0.11772022],\n [ 0.12619498, 0.11721796, 0.11770203],\n [ 0.129968 , 0.11663788, 0.11792377],\n [ 0.13410011, 0.11625146, 0.11839138],\n [ 0.13855459, 0.11606618, 0.11910584],\n [ 0.14333775, 0.11607038, 0.1200606 ],\n [ 0.148417 , 0.11626929, 0.12125453],\n [ 0.15377389, 0.11666192, 0.12268364],\n [ 0.15941427, 0.11723486, 0.12433911],\n [ 0.16533376, 0.11797856, 0.12621303],\n [ 0.17152547, 0.11888403, 0.12829735],\n [ 0.17797765, 0.11994436, 0.13058435],\n [ 0.18468769, 0.12114722, 0.13306426],\n [ 0.19165663, 0.12247737, 0.13572616],\n [ 0.19884415, 0.12394381, 0.1385669 ],\n [ 0.20627181, 0.12551883, 0.14157124],\n [ 0.21394877, 0.12718055, 0.14472604],\n [ 0.22184572, 0.12893119, 0.14802579],\n [ 0.22994394, 0.13076731, 0.15146314],\n [ 0.23823937, 0.13267611, 0.15502793],\n [ 0.24676041, 0.13462172, 0.15870321],\n [ 0.25546457, 0.13661751, 0.16248722],\n [ 0.26433628, 0.13865956, 0.16637301],\n [ 0.27341345, 0.14070412, 0.17034221],\n [ 0.28264773, 0.14277192, 0.1743957 ],\n [ 0.29202272, 0.14486161, 0.17852793],\n [ 0.30159648, 0.14691224, 0.1827169 ],\n [ 0.31129002, 0.14897583, 0.18695213],\n [ 0.32111555, 0.15103351, 0.19119629],\n [ 0.33107961, 0.1530674 , 0.19543758],\n [ 0.34119892, 0.15504762, 0.1996803 ],\n [ 0.35142388, 0.15701131, 0.20389086],\n [ 0.36178937, 0.1589124 , 0.20807639],\n [ 0.37229381, 0.16073993, 0.21223189],\n [ 0.38288348, 0.16254006, 0.2163249 ],\n [ 0.39359592, 0.16426336, 0.22036577],\n [ 0.40444332, 0.16588767, 0.22434027],\n [ 0.41537995, 0.16745325, 0.2282297 ],\n [ 0.42640867, 0.16894939, 0.23202755],\n [ 0.43754706, 0.17034847, 0.23572899],\n [ 0.44878564, 0.1716535 , 0.23932344],\n [ 0.4601126 , 0.17287365, 0.24278607],\n [ 0.47151732, 0.17401641, 0.24610337],\n [ 0.48300689, 0.17506676, 0.2492737 ],\n [ 0.49458302, 0.17601892, 0.25227688],\n [ 0.50623876, 0.17687777, 0.255096 ],\n [ 0.5179623 , 0.17765528, 0.2577162 ],\n [ 0.52975234, 0.17835232, 0.2601134 ],\n [ 0.54159776, 0.17898292, 0.26226847],\n [ 0.55348804, 0.17956232, 0.26416003],\n [ 0.56541729, 0.18010175, 0.26575971],\n [ 0.57736669, 0.180631 , 0.26704888],\n [ 0.58932081, 0.18117827, 0.26800409],\n [ 0.60127582, 0.18175888, 0.26858488],\n [ 0.61319563, 0.1824336 , 0.2687872 ],\n [ 0.62506376, 0.18324015, 0.26858301],\n [ 0.63681202, 0.18430173, 0.26795276],\n [ 0.64842603, 0.18565472, 0.26689463],\n [ 0.65988195, 0.18734638, 0.26543435],\n [ 0.67111966, 0.18948885, 0.26357955],\n [ 0.68209194, 0.19216636, 0.26137175],\n [ 0.69281185, 0.19535326, 0.25887063],\n [ 0.70335022, 0.19891271, 0.25617971],\n [ 0.71375229, 0.20276438, 0.25331365],\n [ 0.72401436, 0.20691287, 0.25027366],\n [ 0.73407638, 0.21145051, 0.24710661],\n [ 0.74396983, 0.21631913, 0.24380715],\n [ 0.75361506, 0.22163653, 0.24043996],\n [ 0.7630579 , 0.22731637, 0.23700095],\n [ 0.77222228, 0.23346231, 0.23356628],\n [ 0.78115441, 0.23998404, 0.23013825],\n [ 0.78979746, 0.24694858, 0.22678822],\n [ 0.79819286, 0.25427223, 0.22352658],\n [ 0.80630444, 0.26198807, 0.22040877],\n [ 0.81417437, 0.27001406, 0.21744645],\n [ 0.82177364, 0.27837336, 0.21468316],\n [ 0.82915955, 0.28696963, 0.21210766],\n [ 0.83628628, 0.2958499 , 0.20977813],\n [ 0.84322168, 0.30491136, 0.20766435],\n [ 0.84995458, 0.31415945, 0.2057863 ],\n [ 0.85648867, 0.32358058, 0.20415327],\n [ 0.86286243, 0.33312058, 0.20274969],\n [ 0.86908321, 0.34276705, 0.20157271],\n [ 0.87512876, 0.3525416 , 0.20064949],\n [ 0.88100349, 0.36243385, 0.19999078],\n [ 0.8866469 , 0.37249496, 0.1997976 ],\n [ 0.89203964, 0.38273475, 0.20013431],\n [ 0.89713496, 0.39318156, 0.20121514],\n [ 0.90195099, 0.40380687, 0.20301555],\n [ 0.90648379, 0.41460191, 0.20558847],\n [ 0.9106967 , 0.42557857, 0.20918529],\n [ 0.91463791, 0.43668557, 0.21367954],\n [ 0.91830723, 0.44790913, 0.21916352],\n [ 0.92171507, 0.45922856, 0.22568002],\n [ 0.92491786, 0.4705936 , 0.23308207],\n [ 0.92790792, 0.48200153, 0.24145932],\n [ 0.93073701, 0.49341219, 0.25065486],\n [ 0.93343918, 0.5048017 , 0.26056148],\n [ 0.93602064, 0.51616486, 0.27118485],\n [ 0.93850535, 0.52748892, 0.28242464],\n [ 0.94092933, 0.53875462, 0.29416042],\n [ 0.94330011, 0.5499628 , 0.30634189],\n [ 0.94563159, 0.56110987, 0.31891624],\n [ 0.94792955, 0.57219822, 0.33184256],\n [ 0.95020929, 0.5832232 , 0.34508419],\n [ 0.95247324, 0.59419035, 0.35859866],\n [ 0.95471709, 0.60510869, 0.37236035],\n [ 0.95698411, 0.61595766, 0.38629631],\n [ 0.95923863, 0.62676473, 0.40043317],\n [ 0.9615041 , 0.6375203 , 0.41474106],\n [ 0.96371553, 0.64826619, 0.42928335],\n [ 0.96591497, 0.65899621, 0.44380444],\n [ 0.96809871, 0.66971662, 0.45830232],\n [ 0.9702495 , 0.6804394 , 0.47280492],\n [ 0.9723881 , 0.69115622, 0.48729272],\n [ 0.97450723, 0.70187358, 0.50178034],\n [ 0.9766108 , 0.712592 , 0.51626837],\n [ 0.97871716, 0.72330511, 0.53074053],\n [ 0.98082222, 0.73401769, 0.54520694],\n [ 0.9829001 , 0.74474445, 0.5597019 ],\n [ 0.98497466, 0.75547635, 0.57420239],\n [ 0.98705581, 0.76621129, 0.58870185],\n [ 0.98913325, 0.77695637, 0.60321626],\n [ 0.99119918, 0.78771716, 0.61775821],\n [ 0.9932672 , 0.79848979, 0.63231691],\n [ 0.99535958, 0.80926704, 0.64687278],\n [ 0.99740544, 0.82008078, 0.66150571],\n [ 0.9992197 , 0.83100723, 0.6764127 ]\n]\n\n\n_flare_lut = [\n [0.92907237, 0.68878959, 0.50411509],\n [0.92891402, 0.68494686, 0.50173994],\n [0.92864754, 0.68116207, 0.4993754],\n [0.92836112, 0.67738527, 0.49701572],\n [0.9280599, 0.67361354, 0.49466044],\n [0.92775569, 0.66983999, 0.49230866],\n [0.9274375, 0.66607098, 0.48996097],\n [0.927111, 0.66230315, 0.48761688],\n [0.92677996, 0.6585342, 0.485276],\n [0.92644317, 0.65476476, 0.48293832],\n [0.92609759, 0.65099658, 0.48060392],\n [0.925747, 0.64722729, 0.47827244],\n [0.92539502, 0.64345456, 0.47594352],\n [0.92503106, 0.6396848, 0.47361782],\n [0.92466877, 0.6359095, 0.47129427],\n [0.92429828, 0.63213463, 0.46897349],\n [0.92392172, 0.62835879, 0.46665526],\n [0.92354597, 0.62457749, 0.46433898],\n [0.9231622, 0.6207962, 0.46202524],\n [0.92277222, 0.61701365, 0.45971384],\n [0.92237978, 0.61322733, 0.45740444],\n [0.92198615, 0.60943622, 0.45509686],\n [0.92158735, 0.60564276, 0.45279137],\n [0.92118373, 0.60184659, 0.45048789],\n [0.92077582, 0.59804722, 0.44818634],\n [0.92036413, 0.59424414, 0.44588663],\n [0.91994924, 0.5904368, 0.44358868],\n [0.91952943, 0.58662619, 0.4412926],\n [0.91910675, 0.58281075, 0.43899817],\n [0.91868096, 0.57899046, 0.4367054],\n [0.91825103, 0.57516584, 0.43441436],\n [0.91781857, 0.57133556, 0.43212486],\n [0.9173814, 0.56750099, 0.4298371],\n [0.91694139, 0.56366058, 0.42755089],\n [0.91649756, 0.55981483, 0.42526631],\n [0.91604942, 0.55596387, 0.42298339],\n [0.9155979, 0.55210684, 0.42070204],\n [0.9151409, 0.54824485, 0.4184247],\n [0.91466138, 0.54438817, 0.41617858],\n [0.91416896, 0.54052962, 0.41396347],\n [0.91366559, 0.53666778, 0.41177769],\n [0.91315173, 0.53280208, 0.40962196],\n [0.91262605, 0.52893336, 0.40749715],\n [0.91208866, 0.52506133, 0.40540404],\n [0.91153952, 0.52118582, 0.40334346],\n [0.91097732, 0.51730767, 0.4013163],\n [0.910403, 0.51342591, 0.39932342],\n [0.90981494, 0.50954168, 0.39736571],\n [0.90921368, 0.5056543, 0.39544411],\n [0.90859797, 0.50176463, 0.39355952],\n [0.90796841, 0.49787195, 0.39171297],\n [0.90732341, 0.4939774, 0.38990532],\n [0.90666382, 0.49008006, 0.38813773],\n [0.90598815, 0.486181, 0.38641107],\n [0.90529624, 0.48228017, 0.38472641],\n [0.90458808, 0.47837738, 0.38308489],\n [0.90386248, 0.47447348, 0.38148746],\n [0.90311921, 0.4705685, 0.37993524],\n [0.90235809, 0.46666239, 0.37842943],\n [0.90157824, 0.46275577, 0.37697105],\n [0.90077904, 0.45884905, 0.37556121],\n [0.89995995, 0.45494253, 0.37420106],\n [0.89912041, 0.4510366, 0.37289175],\n [0.8982602, 0.44713126, 0.37163458],\n [0.89737819, 0.44322747, 0.37043052],\n [0.89647387, 0.43932557, 0.36928078],\n [0.89554477, 0.43542759, 0.36818855],\n [0.89458871, 0.4315354, 0.36715654],\n [0.89360794, 0.42764714, 0.36618273],\n [0.89260152, 0.42376366, 0.36526813],\n [0.8915687, 0.41988565, 0.36441384],\n [0.89050882, 0.41601371, 0.36362102],\n [0.8894159, 0.41215334, 0.36289639],\n [0.888292, 0.40830288, 0.36223756],\n [0.88713784, 0.40446193, 0.36164328],\n [0.88595253, 0.40063149, 0.36111438],\n [0.88473115, 0.39681635, 0.3606566],\n [0.88347246, 0.39301805, 0.36027074],\n [0.88217931, 0.38923439, 0.35995244],\n [0.880851, 0.38546632, 0.35970244],\n [0.87947728, 0.38172422, 0.35953127],\n [0.87806542, 0.37800172, 0.35942941],\n [0.87661509, 0.37429964, 0.35939659],\n [0.87511668, 0.37062819, 0.35944178],\n [0.87357554, 0.36698279, 0.35955811],\n [0.87199254, 0.3633634, 0.35974223],\n [0.87035691, 0.35978174, 0.36000516],\n [0.86867647, 0.35623087, 0.36033559],\n [0.86694949, 0.35271349, 0.36073358],\n [0.86516775, 0.34923921, 0.36120624],\n [0.86333996, 0.34580008, 0.36174113],\n [0.86145909, 0.3424046, 0.36234402],\n [0.85952586, 0.33905327, 0.36301129],\n [0.85754536, 0.33574168, 0.36373567],\n [0.855514, 0.33247568, 0.36451271],\n [0.85344392, 0.32924217, 0.36533344],\n [0.8513284, 0.32604977, 0.36620106],\n [0.84916723, 0.32289973, 0.36711424],\n [0.84696243, 0.31979068, 0.36806976],\n [0.84470627, 0.31673295, 0.36907066],\n [0.84240761, 0.31371695, 0.37010969],\n [0.84005337, 0.31075974, 0.37119284],\n [0.83765537, 0.30784814, 0.3723105],\n [0.83520234, 0.30499724, 0.37346726],\n [0.83270291, 0.30219766, 0.37465552],\n [0.83014895, 0.29946081, 0.37587769],\n [0.82754694, 0.29677989, 0.37712733],\n [0.82489111, 0.29416352, 0.37840532],\n [0.82218644, 0.29160665, 0.37970606],\n [0.81942908, 0.28911553, 0.38102921],\n [0.81662276, 0.28668665, 0.38236999],\n [0.81376555, 0.28432371, 0.383727],\n [0.81085964, 0.28202508, 0.38509649],\n [0.8079055, 0.27979128, 0.38647583],\n [0.80490309, 0.27762348, 0.3878626],\n [0.80185613, 0.2755178, 0.38925253],\n [0.79876118, 0.27347974, 0.39064559],\n [0.79562644, 0.27149928, 0.39203532],\n [0.79244362, 0.2695883, 0.39342447],\n [0.78922456, 0.26773176, 0.3948046],\n [0.78596161, 0.26594053, 0.39617873],\n [0.7826624, 0.26420493, 0.39754146],\n [0.77932717, 0.26252522, 0.39889102],\n [0.77595363, 0.2609049, 0.4002279],\n [0.77254999, 0.25933319, 0.40154704],\n [0.76911107, 0.25781758, 0.40284959],\n [0.76564158, 0.25635173, 0.40413341],\n [0.76214598, 0.25492998, 0.40539471],\n [0.75861834, 0.25356035, 0.40663694],\n [0.75506533, 0.25223402, 0.40785559],\n [0.75148963, 0.2509473, 0.40904966],\n [0.74788835, 0.24970413, 0.41022028],\n [0.74426345, 0.24850191, 0.41136599],\n [0.74061927, 0.24733457, 0.41248516],\n [0.73695678, 0.24620072, 0.41357737],\n [0.73327278, 0.24510469, 0.41464364],\n [0.72957096, 0.24404127, 0.4156828],\n [0.72585394, 0.24300672, 0.41669383],\n [0.7221226, 0.24199971, 0.41767651],\n [0.71837612, 0.24102046, 0.41863486],\n [0.71463236, 0.24004289, 0.41956983],\n [0.7108932, 0.23906316, 0.42048681],\n [0.70715842, 0.23808142, 0.42138647],\n [0.70342811, 0.2370976, 0.42226844],\n [0.69970218, 0.23611179, 0.42313282],\n [0.69598055, 0.2351247, 0.42397678],\n [0.69226314, 0.23413578, 0.42480327],\n [0.68854988, 0.23314511, 0.42561234],\n [0.68484064, 0.23215279, 0.42640419],\n [0.68113541, 0.23115942, 0.42717615],\n [0.67743412, 0.23016472, 0.42792989],\n [0.67373662, 0.22916861, 0.42866642],\n [0.67004287, 0.22817117, 0.42938576],\n [0.66635279, 0.22717328, 0.43008427],\n [0.66266621, 0.22617435, 0.43076552],\n [0.65898313, 0.22517434, 0.43142956],\n [0.65530349, 0.22417381, 0.43207427],\n [0.65162696, 0.22317307, 0.4327001],\n [0.64795375, 0.22217149, 0.43330852],\n [0.64428351, 0.22116972, 0.43389854],\n [0.64061624, 0.22016818, 0.43446845],\n [0.63695183, 0.21916625, 0.43502123],\n [0.63329016, 0.21816454, 0.43555493],\n [0.62963102, 0.2171635, 0.43606881],\n [0.62597451, 0.21616235, 0.43656529],\n [0.62232019, 0.21516239, 0.43704153],\n [0.61866821, 0.21416307, 0.43749868],\n [0.61501835, 0.21316435, 0.43793808],\n [0.61137029, 0.21216761, 0.4383556],\n [0.60772426, 0.2111715, 0.43875552],\n [0.60407977, 0.21017746, 0.43913439],\n [0.60043678, 0.20918503, 0.43949412],\n [0.59679524, 0.20819447, 0.43983393],\n [0.59315487, 0.20720639, 0.44015254],\n [0.58951566, 0.20622027, 0.44045213],\n [0.58587715, 0.20523751, 0.44072926],\n [0.5822395, 0.20425693, 0.44098758],\n [0.57860222, 0.20328034, 0.44122241],\n [0.57496549, 0.20230637, 0.44143805],\n [0.57132875, 0.20133689, 0.4416298],\n [0.56769215, 0.20037071, 0.44180142],\n [0.5640552, 0.19940936, 0.44194923],\n [0.56041794, 0.19845221, 0.44207535],\n [0.55678004, 0.1975, 0.44217824],\n [0.55314129, 0.19655316, 0.44225723],\n [0.54950166, 0.19561118, 0.44231412],\n [0.54585987, 0.19467771, 0.44234111],\n [0.54221157, 0.19375869, 0.44233698],\n [0.5385549, 0.19285696, 0.44229959],\n [0.5348913, 0.19197036, 0.44222958],\n [0.53122177, 0.1910974, 0.44212735],\n [0.52754464, 0.19024042, 0.44199159],\n [0.52386353, 0.18939409, 0.44182449],\n [0.52017476, 0.18856368, 0.44162345],\n [0.51648277, 0.18774266, 0.44139128],\n [0.51278481, 0.18693492, 0.44112605],\n [0.50908361, 0.18613639, 0.4408295],\n [0.50537784, 0.18534893, 0.44050064],\n [0.50166912, 0.18457008, 0.44014054],\n [0.49795686, 0.18380056, 0.43974881],\n [0.49424218, 0.18303865, 0.43932623],\n [0.49052472, 0.18228477, 0.43887255],\n [0.48680565, 0.1815371, 0.43838867],\n [0.48308419, 0.18079663, 0.43787408],\n [0.47936222, 0.18006056, 0.43733022],\n [0.47563799, 0.17933127, 0.43675585],\n [0.47191466, 0.17860416, 0.43615337],\n [0.46818879, 0.17788392, 0.43552047],\n [0.46446454, 0.17716458, 0.43486036],\n [0.46073893, 0.17645017, 0.43417097],\n [0.45701462, 0.17573691, 0.43345429],\n [0.45329097, 0.17502549, 0.43271025],\n [0.44956744, 0.17431649, 0.4319386],\n [0.44584668, 0.17360625, 0.43114133],\n [0.44212538, 0.17289906, 0.43031642],\n [0.43840678, 0.17219041, 0.42946642],\n [0.43469046, 0.17148074, 0.42859124],\n [0.4309749, 0.17077192, 0.42769008],\n [0.42726297, 0.17006003, 0.42676519],\n [0.42355299, 0.16934709, 0.42581586],\n [0.41984535, 0.16863258, 0.42484219],\n [0.41614149, 0.16791429, 0.42384614],\n [0.41244029, 0.16719372, 0.42282661],\n [0.40874177, 0.16647061, 0.42178429],\n [0.40504765, 0.16574261, 0.42072062],\n [0.401357, 0.16501079, 0.41963528],\n [0.397669, 0.16427607, 0.418528],\n [0.39398585, 0.16353554, 0.41740053],\n [0.39030735, 0.16278924, 0.41625344],\n [0.3866314, 0.16203977, 0.41508517],\n [0.38295904, 0.16128519, 0.41389849],\n [0.37928736, 0.16052483, 0.41270599],\n [0.37562649, 0.15974704, 0.41151182],\n [0.37197803, 0.15895049, 0.41031532],\n [0.36833779, 0.15813871, 0.40911916],\n [0.36470944, 0.15730861, 0.40792149],\n [0.36109117, 0.15646169, 0.40672362],\n [0.35748213, 0.15559861, 0.40552633],\n [0.353885, 0.15471714, 0.40432831],\n [0.35029682, 0.15381967, 0.4031316],\n [0.34671861, 0.1529053, 0.40193587],\n [0.34315191, 0.15197275, 0.40074049],\n [0.33959331, 0.15102466, 0.3995478],\n [0.33604378, 0.15006017, 0.39835754],\n [0.33250529, 0.14907766, 0.39716879],\n [0.32897621, 0.14807831, 0.39598285],\n [0.3254559, 0.14706248, 0.39480044],\n [0.32194567, 0.14602909, 0.39362106],\n [0.31844477, 0.14497857, 0.39244549],\n [0.31494974, 0.14391333, 0.39127626],\n [0.31146605, 0.14282918, 0.39011024],\n [0.30798857, 0.1417297, 0.38895105],\n [0.30451661, 0.14061515, 0.38779953],\n [0.30105136, 0.13948445, 0.38665531],\n [0.2975886, 0.1383403, 0.38552159],\n [0.29408557, 0.13721193, 0.38442775]\n]\n\n\n_crest_lut = [\n [0.6468274, 0.80289262, 0.56592265],\n [0.64233318, 0.80081141, 0.56639461],\n [0.63791969, 0.7987162, 0.56674976],\n [0.6335316, 0.79661833, 0.56706128],\n [0.62915226, 0.7945212, 0.56735066],\n [0.62477862, 0.79242543, 0.56762143],\n [0.62042003, 0.79032918, 0.56786129],\n [0.61606327, 0.78823508, 0.56808666],\n [0.61171322, 0.78614216, 0.56829092],\n [0.60736933, 0.78405055, 0.56847436],\n [0.60302658, 0.78196121, 0.56864272],\n [0.59868708, 0.77987374, 0.56879289],\n [0.59435366, 0.77778758, 0.56892099],\n [0.59001953, 0.77570403, 0.56903477],\n [0.58568753, 0.77362254, 0.56913028],\n [0.58135593, 0.77154342, 0.56920908],\n [0.57702623, 0.76946638, 0.56926895],\n [0.57269165, 0.76739266, 0.5693172],\n [0.56835934, 0.76532092, 0.56934507],\n [0.56402533, 0.76325185, 0.56935664],\n [0.55968429, 0.76118643, 0.56935732],\n [0.55534159, 0.75912361, 0.56934052],\n [0.55099572, 0.75706366, 0.56930743],\n [0.54664626, 0.75500662, 0.56925799],\n [0.54228969, 0.75295306, 0.56919546],\n [0.53792417, 0.75090328, 0.56912118],\n [0.53355172, 0.74885687, 0.5690324],\n [0.52917169, 0.74681387, 0.56892926],\n [0.52478243, 0.74477453, 0.56881287],\n [0.52038338, 0.74273888, 0.56868323],\n [0.5159739, 0.74070697, 0.56854039],\n [0.51155269, 0.73867895, 0.56838507],\n [0.50711872, 0.73665492, 0.56821764],\n [0.50267118, 0.73463494, 0.56803826],\n [0.49822926, 0.73261388, 0.56785146],\n [0.49381422, 0.73058524, 0.56767484],\n [0.48942421, 0.72854938, 0.56751036],\n [0.48505993, 0.72650623, 0.56735752],\n [0.48072207, 0.72445575, 0.56721583],\n [0.4764113, 0.72239788, 0.56708475],\n [0.47212827, 0.72033258, 0.56696376],\n [0.46787361, 0.71825983, 0.56685231],\n [0.46364792, 0.71617961, 0.56674986],\n [0.45945271, 0.71409167, 0.56665625],\n [0.45528878, 0.71199595, 0.56657103],\n [0.45115557, 0.70989276, 0.5664931],\n [0.44705356, 0.70778212, 0.56642189],\n [0.44298321, 0.70566406, 0.56635683],\n [0.43894492, 0.70353863, 0.56629734],\n [0.43493911, 0.70140588, 0.56624286],\n [0.43096612, 0.69926587, 0.5661928],\n [0.42702625, 0.69711868, 0.56614659],\n [0.42311977, 0.69496438, 0.56610368],\n [0.41924689, 0.69280308, 0.56606355],\n [0.41540778, 0.69063486, 0.56602564],\n [0.41160259, 0.68845984, 0.56598944],\n [0.40783143, 0.68627814, 0.56595436],\n [0.40409434, 0.68408988, 0.56591994],\n [0.40039134, 0.68189518, 0.56588564],\n [0.39672238, 0.6796942, 0.56585103],\n [0.39308781, 0.67748696, 0.56581581],\n [0.38949137, 0.67527276, 0.56578084],\n [0.38592889, 0.67305266, 0.56574422],\n [0.38240013, 0.67082685, 0.56570561],\n [0.37890483, 0.66859548, 0.56566462],\n [0.37544276, 0.66635871, 0.56562081],\n [0.37201365, 0.66411673, 0.56557372],\n [0.36861709, 0.6618697, 0.5655231],\n [0.36525264, 0.65961782, 0.56546873],\n [0.36191986, 0.65736125, 0.56541032],\n [0.35861935, 0.65509998, 0.56534768],\n [0.35535621, 0.65283302, 0.56528211],\n [0.35212361, 0.65056188, 0.56521171],\n [0.34892097, 0.64828676, 0.56513633],\n [0.34574785, 0.64600783, 0.56505539],\n [0.34260357, 0.64372528, 0.5649689],\n [0.33948744, 0.64143931, 0.56487679],\n [0.33639887, 0.6391501, 0.56477869],\n [0.33334501, 0.63685626, 0.56467661],\n [0.33031952, 0.63455911, 0.564569],\n [0.3273199, 0.63225924, 0.56445488],\n [0.32434526, 0.62995682, 0.56433457],\n [0.32139487, 0.62765201, 0.56420795],\n [0.31846807, 0.62534504, 0.56407446],\n [0.3155731, 0.62303426, 0.56393695],\n [0.31270304, 0.62072111, 0.56379321],\n [0.30985436, 0.61840624, 0.56364307],\n [0.30702635, 0.61608984, 0.56348606],\n [0.30421803, 0.61377205, 0.56332267],\n [0.30143611, 0.61145167, 0.56315419],\n [0.29867863, 0.60912907, 0.56298054],\n [0.29593872, 0.60680554, 0.56280022],\n [0.29321538, 0.60448121, 0.56261376],\n [0.2905079, 0.60215628, 0.56242036],\n [0.28782827, 0.5998285, 0.56222366],\n [0.28516521, 0.59749996, 0.56202093],\n [0.28251558, 0.59517119, 0.56181204],\n [0.27987847, 0.59284232, 0.56159709],\n [0.27726216, 0.59051189, 0.56137785],\n [0.27466434, 0.58818027, 0.56115433],\n [0.2720767, 0.58584893, 0.56092486],\n [0.26949829, 0.58351797, 0.56068983],\n [0.26693801, 0.58118582, 0.56045121],\n [0.26439366, 0.57885288, 0.56020858],\n [0.26185616, 0.57652063, 0.55996077],\n [0.25932459, 0.57418919, 0.55970795],\n [0.25681303, 0.57185614, 0.55945297],\n [0.25431024, 0.56952337, 0.55919385],\n [0.25180492, 0.56719255, 0.5589305],\n [0.24929311, 0.56486397, 0.5586654],\n [0.24678356, 0.56253666, 0.55839491],\n [0.24426587, 0.56021153, 0.55812473],\n [0.24174022, 0.55788852, 0.55785448],\n [0.23921167, 0.55556705, 0.55758211],\n [0.23668315, 0.55324675, 0.55730676],\n [0.23414742, 0.55092825, 0.55703167],\n [0.23160473, 0.54861143, 0.5567573],\n [0.22905996, 0.54629572, 0.55648168],\n [0.22651648, 0.54398082, 0.5562029],\n [0.22396709, 0.54166721, 0.55592542],\n [0.22141221, 0.53935481, 0.55564885],\n [0.21885269, 0.53704347, 0.55537294],\n [0.21629986, 0.53473208, 0.55509319],\n [0.21374297, 0.53242154, 0.5548144],\n [0.21118255, 0.53011166, 0.55453708],\n [0.2086192, 0.52780237, 0.55426067],\n [0.20605624, 0.52549322, 0.55398479],\n [0.20350004, 0.5231837, 0.55370601],\n [0.20094292, 0.52087429, 0.55342884],\n [0.19838567, 0.51856489, 0.55315283],\n [0.19582911, 0.51625531, 0.55287818],\n [0.19327413, 0.51394542, 0.55260469],\n [0.19072933, 0.51163448, 0.5523289],\n [0.18819045, 0.50932268, 0.55205372],\n [0.18565609, 0.50701014, 0.55177937],\n [0.18312739, 0.50469666, 0.55150597],\n [0.18060561, 0.50238204, 0.55123374],\n [0.178092, 0.50006616, 0.55096224],\n [0.17558808, 0.49774882, 0.55069118],\n [0.17310341, 0.49542924, 0.5504176],\n [0.17063111, 0.49310789, 0.55014445],\n [0.1681728, 0.49078458, 0.54987159],\n [0.1657302, 0.48845913, 0.54959882],\n [0.16330517, 0.48613135, 0.54932605],\n [0.16089963, 0.48380104, 0.54905306],\n [0.15851561, 0.48146803, 0.54877953],\n [0.15615526, 0.47913212, 0.54850526],\n [0.15382083, 0.47679313, 0.54822991],\n [0.15151471, 0.47445087, 0.54795318],\n [0.14924112, 0.47210502, 0.54767411],\n [0.1470032, 0.46975537, 0.54739226],\n [0.14480101, 0.46740187, 0.54710832],\n [0.14263736, 0.46504434, 0.54682188],\n [0.14051521, 0.46268258, 0.54653253],\n [0.13843761, 0.46031639, 0.54623985],\n [0.13640774, 0.45794558, 0.5459434],\n [0.13442887, 0.45556994, 0.54564272],\n [0.1325044, 0.45318928, 0.54533736],\n [0.13063777, 0.4508034, 0.54502674],\n [0.12883252, 0.44841211, 0.5447104],\n [0.12709242, 0.44601517, 0.54438795],\n [0.1254209, 0.44361244, 0.54405855],\n [0.12382162, 0.44120373, 0.54372156],\n [0.12229818, 0.43878887, 0.54337634],\n [0.12085453, 0.4363676, 0.54302253],\n [0.11949938, 0.43393955, 0.54265715],\n [0.11823166, 0.43150478, 0.54228104],\n [0.11705496, 0.42906306, 0.54189388],\n [0.115972, 0.42661431, 0.54149449],\n [0.11498598, 0.42415835, 0.54108222],\n [0.11409965, 0.42169502, 0.54065622],\n [0.11331533, 0.41922424, 0.5402155],\n [0.11263542, 0.41674582, 0.53975931],\n [0.1120615, 0.4142597, 0.53928656],\n [0.11159738, 0.41176567, 0.53879549],\n [0.11125248, 0.40926325, 0.53828203],\n [0.11101698, 0.40675289, 0.53774864],\n [0.11089152, 0.40423445, 0.53719455],\n [0.11085121, 0.4017095, 0.53662425],\n [0.11087217, 0.39917938, 0.53604354],\n [0.11095515, 0.39664394, 0.53545166],\n [0.11110676, 0.39410282, 0.53484509],\n [0.11131735, 0.39155635, 0.53422678],\n [0.11158595, 0.38900446, 0.53359634],\n [0.11191139, 0.38644711, 0.5329534],\n [0.11229224, 0.38388426, 0.53229748],\n [0.11273683, 0.38131546, 0.53162393],\n [0.11323438, 0.37874109, 0.53093619],\n [0.11378271, 0.37616112, 0.53023413],\n [0.11437992, 0.37357557, 0.52951727],\n [0.11502681, 0.37098429, 0.52878396],\n [0.11572661, 0.36838709, 0.52803124],\n [0.11646936, 0.36578429, 0.52726234],\n [0.11725299, 0.3631759, 0.52647685],\n [0.1180755, 0.36056193, 0.52567436],\n [0.1189438, 0.35794203, 0.5248497],\n [0.11984752, 0.35531657, 0.52400649],\n [0.1207833, 0.35268564, 0.52314492],\n [0.12174895, 0.35004927, 0.52226461],\n [0.12274959, 0.34740723, 0.52136104],\n [0.12377809, 0.34475975, 0.52043639],\n [0.12482961, 0.34210702, 0.51949179],\n [0.125902, 0.33944908, 0.51852688],\n [0.12699998, 0.33678574, 0.51753708],\n [0.12811691, 0.33411727, 0.51652464],\n [0.12924811, 0.33144384, 0.51549084],\n [0.13039157, 0.32876552, 0.51443538],\n [0.13155228, 0.32608217, 0.51335321],\n [0.13272282, 0.32339407, 0.51224759],\n [0.13389954, 0.32070138, 0.51111946],\n [0.13508064, 0.31800419, 0.50996862],\n [0.13627149, 0.31530238, 0.50878942],\n [0.13746376, 0.31259627, 0.50758645],\n [0.13865499, 0.30988598, 0.50636017],\n [0.13984364, 0.30717161, 0.50511042],\n [0.14103515, 0.30445309, 0.50383119],\n [0.14222093, 0.30173071, 0.50252813],\n [0.14339946, 0.2990046, 0.50120127],\n [0.14456941, 0.29627483, 0.49985054],\n [0.14573579, 0.29354139, 0.49847009],\n [0.14689091, 0.29080452, 0.49706566],\n [0.1480336, 0.28806432, 0.49563732],\n [0.1491628, 0.28532086, 0.49418508],\n [0.15028228, 0.28257418, 0.49270402],\n [0.15138673, 0.27982444, 0.49119848],\n [0.15247457, 0.27707172, 0.48966925],\n [0.15354487, 0.2743161, 0.48811641],\n [0.15459955, 0.27155765, 0.4865371],\n [0.15563716, 0.26879642, 0.4849321],\n [0.1566572, 0.26603191, 0.48330429],\n [0.15765823, 0.26326032, 0.48167456],\n [0.15862147, 0.26048295, 0.48005785],\n [0.15954301, 0.25770084, 0.47845341],\n [0.16043267, 0.25491144, 0.4768626],\n [0.16129262, 0.25211406, 0.4752857],\n [0.1621119, 0.24931169, 0.47372076],\n [0.16290577, 0.24649998, 0.47217025],\n [0.16366819, 0.24368054, 0.47063302],\n [0.1644021, 0.24085237, 0.46910949],\n [0.16510882, 0.2380149, 0.46759982],\n [0.16579015, 0.23516739, 0.46610429],\n [0.1664433, 0.2323105, 0.46462219],\n [0.16707586, 0.22944155, 0.46315508],\n [0.16768475, 0.22656122, 0.46170223],\n [0.16826815, 0.22366984, 0.46026308],\n [0.16883174, 0.22076514, 0.45883891],\n [0.16937589, 0.21784655, 0.45742976],\n [0.16990129, 0.21491339, 0.45603578],\n [0.1704074, 0.21196535, 0.45465677],\n [0.17089473, 0.20900176, 0.4532928],\n [0.17136819, 0.20602012, 0.45194524],\n [0.17182683, 0.20302012, 0.45061386],\n [0.17227059, 0.20000106, 0.44929865],\n [0.17270583, 0.19695949, 0.44800165],\n [0.17313804, 0.19389201, 0.44672488],\n [0.17363177, 0.19076859, 0.44549087]\n]\n\n\n_lut_dict = dict(\n rocket=_rocket_lut,\n mako=_mako_lut,\n icefire=_icefire_lut,\n vlag=_vlag_lut,\n flare=_flare_lut,\n crest=_crest_lut,\n\n)\n\nfor _name, _lut in _lut_dict.items():\n\n _cmap = colors.ListedColormap(_lut, _name)\n locals()[_name] = _cmap\n\n _cmap_r = colors.ListedColormap(_lut[::-1], _name + \"_r\")\n locals()[_name + \"_r\"] = _cmap_r\n\n register_colormap(_name, _cmap)\n register_colormap(_name + \"_r\", _cmap_r)\n\ndel colors, register_colormap\n"},{"attributeType":"list","col":0,"comment":"null","endLoc":5,"id":1066,"name":"_rocket_lut","nodeType":"Attribute","startLoc":5,"text":"_rocket_lut"},{"col":4,"comment":"Regress b from a keeping a's original mean.","endLoc":338,"header":"def regress_out(self, a, b)","id":1067,"name":"regress_out","nodeType":"Function","startLoc":331,"text":"def regress_out(self, a, b):\n \"\"\"Regress b from a keeping a's original mean.\"\"\"\n a_mean = a.mean()\n a = a - a_mean\n b = b - b.mean()\n b = np.c_[b]\n a_prime = a - b.dot(np.linalg.pinv(b).dot(a))\n return np.asarray(a_prime + a_mean).reshape(a.shape)"},{"attributeType":"list","col":0,"comment":"null","endLoc":265,"id":1068,"name":"_mako_lut","nodeType":"Attribute","startLoc":265,"text":"_mako_lut"},{"col":4,"comment":"Discretize a predictor by assigning value to closest bin.","endLoc":329,"header":"def bin_predictor(self, bins)","id":1069,"name":"bin_predictor","nodeType":"Function","startLoc":317,"text":"def bin_predictor(self, bins):\n \"\"\"Discretize a predictor by assigning value to closest bin.\"\"\"\n x = np.asarray(self.x)\n if np.isscalar(bins):\n percentiles = np.linspace(0, 100, bins + 2)[1:-1]\n bins = np.percentile(x, percentiles)\n else:\n bins = np.ravel(bins)\n\n dist = np.abs(np.subtract.outer(x, bins))\n x_binned = bins[np.argmin(dist, axis=1)].ravel()\n\n return x_binned, bins"},{"col":4,"comment":"Indices of the matrix, reordered by the dendrogram","endLoc":583,"header":"@property\n def reordered_ind(self)","id":1070,"name":"reordered_ind","nodeType":"Function","startLoc":580,"text":"@property\n def reordered_ind(self):\n \"\"\"Indices of the matrix, reordered by the dendrogram\"\"\"\n return self.dendrogram['leaves']"},{"col":4,"comment":"Plots a dendrogram of the similarities between data on the axes\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n Axes object upon which the dendrogram is plotted\n\n ","endLoc":639,"header":"def plot(self, ax, tree_kws)","id":1071,"name":"plot","nodeType":"Function","startLoc":585,"text":"def plot(self, ax, tree_kws):\n \"\"\"Plots a dendrogram of the similarities between data on the axes\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n Axes object upon which the dendrogram is plotted\n\n \"\"\"\n tree_kws = {} if tree_kws is None else tree_kws.copy()\n tree_kws.setdefault(\"linewidths\", .5)\n tree_kws.setdefault(\"colors\", tree_kws.pop(\"color\", (.2, .2, .2)))\n\n if self.rotate and self.axis == 0:\n coords = zip(self.dependent_coord, self.independent_coord)\n else:\n coords = zip(self.independent_coord, self.dependent_coord)\n lines = LineCollection([list(zip(x, y)) for x, y in coords],\n **tree_kws)\n\n ax.add_collection(lines)\n number_of_leaves = len(self.reordered_ind)\n max_dependent_coord = max(map(max, self.dependent_coord))\n\n if self.rotate:\n ax.yaxis.set_ticks_position('right')\n\n # Constants 10 and 1.05 come from\n # `scipy.cluster.hierarchy._plot_dendrogram`\n ax.set_ylim(0, number_of_leaves * 10)\n ax.set_xlim(0, max_dependent_coord * 1.05)\n\n ax.invert_xaxis()\n ax.invert_yaxis()\n else:\n # Constants 10 and 1.05 come from\n # `scipy.cluster.hierarchy._plot_dendrogram`\n ax.set_xlim(0, number_of_leaves * 10)\n ax.set_ylim(0, max_dependent_coord * 1.05)\n\n despine(ax=ax, bottom=True, left=True)\n\n ax.set(xticks=self.xticks, yticks=self.yticks,\n xlabel=self.xlabel, ylabel=self.ylabel)\n xtl = ax.set_xticklabels(self.xticklabels)\n ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical')\n\n # Force a draw of the plot to avoid matplotlib window error\n _draw_figure(ax.figure)\n\n if len(ytl) > 0 and axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n if len(xtl) > 0 and axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n return self"},{"attributeType":"list","col":0,"comment":"null","endLoc":525,"id":1072,"name":"_vlag_lut","nodeType":"Attribute","startLoc":525,"text":"_vlag_lut"},{"col":4,"comment":"Dataframe with numeric x and y, after unit conversion and log scaling.","endLoc":1138,"header":"@property\n def comp_data(self)","id":1073,"name":"comp_data","nodeType":"Function","startLoc":1094,"text":"@property\n def comp_data(self):\n \"\"\"Dataframe with numeric x and y, after unit conversion and log scaling.\"\"\"\n if not hasattr(self, \"ax\"):\n # Probably a good idea, but will need a bunch of tests updated\n # Most of these tests should just use the external interface\n # Then this can be re-enabled.\n # raise AttributeError(\"No Axes attached to plotter\")\n return self.plot_data\n\n if not hasattr(self, \"_comp_data\"):\n\n comp_data = (\n self.plot_data\n .copy(deep=False)\n .drop([\"x\", \"y\"], axis=1, errors=\"ignore\")\n )\n\n for var in \"yx\":\n if var not in self.variables:\n continue\n\n parts = []\n grouped = self.plot_data[var].groupby(self.converters[var], sort=False)\n for converter, orig in grouped:\n with pd.option_context('mode.use_inf_as_null', True):\n orig = orig.dropna()\n if var in self.var_levels:\n # TODO this should happen in some centralized location\n # it is similar to GH2419, but more complicated because\n # supporting `order` in categorical plots is tricky\n orig = orig[orig.isin(self.var_levels[var])]\n comp = pd.to_numeric(converter.convert_units(orig))\n if converter.get_scale() == \"log\":\n comp = np.log10(comp)\n parts.append(pd.Series(comp, orig.index, name=orig.name))\n if parts:\n comp_col = pd.concat(parts)\n else:\n comp_col = pd.Series(dtype=float, name=var)\n comp_data.insert(0, var, comp_col)\n\n self._comp_data = comp_data\n\n return self._comp_data"},{"col":4,"comment":"Data where each observation is a point.","endLoc":151,"header":"@property\n def scatter_data(self)","id":1074,"name":"scatter_data","nodeType":"Function","startLoc":136,"text":"@property\n def scatter_data(self):\n \"\"\"Data where each observation is a point.\"\"\"\n x_j = self.x_jitter\n if x_j is None:\n x = self.x\n else:\n x = self.x + np.random.uniform(-x_j, x_j, len(self.x))\n\n y_j = self.y_jitter\n if y_j is None:\n y = self.y\n else:\n y = self.y + np.random.uniform(-y_j, y_j, len(self.y))\n\n return x, y"},{"col":4,"comment":"Data with a point estimate and CI for each discrete x value.","endLoc":186,"header":"@property\n def estimate_data(self)","id":1075,"name":"estimate_data","nodeType":"Function","startLoc":153,"text":"@property\n def estimate_data(self):\n \"\"\"Data with a point estimate and CI for each discrete x value.\"\"\"\n x, y = self.x_discrete, self.y\n vals = sorted(np.unique(x))\n points, cis = [], []\n\n for val in vals:\n\n # Get the point estimate of the y variable\n _y = y[x == val]\n est = self.x_estimator(_y)\n points.append(est)\n\n # Compute the confidence interval for this estimate\n if self.x_ci is None:\n cis.append(None)\n else:\n units = None\n if self.x_ci == \"sd\":\n sd = np.std(_y)\n _ci = est - sd, est + sd\n else:\n if self.units is not None:\n units = self.units[x == val]\n boots = algo.bootstrap(_y,\n func=self.x_estimator,\n n_boot=self.n_boot,\n units=units,\n seed=self.seed)\n _ci = utils.ci(boots, self.x_ci)\n cis.append(_ci)\n\n return vals, points, cis"},{"col":4,"comment":"Return an Axes object based on existence of row/col variables.","endLoc":1153,"header":"def _get_axes(self, sub_vars)","id":1076,"name":"_get_axes","nodeType":"Function","startLoc":1140,"text":"def _get_axes(self, sub_vars):\n \"\"\"Return an Axes object based on existence of row/col variables.\"\"\"\n row = sub_vars.get(\"row\", None)\n col = sub_vars.get(\"col\", None)\n if row is not None and col is not None:\n return self.facets.axes_dict[(row, col)]\n elif row is not None:\n return self.facets.axes_dict[row]\n elif col is not None:\n return self.facets.axes_dict[col]\n elif self.ax is None:\n return self.facets.ax\n else:\n return self.ax"},{"col":4,"comment":"Associate the plotter with an Axes manager and initialize its units.\n\n Parameters\n ----------\n obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid`\n Structural object that we will eventually plot onto.\n allowed_types : str or list of str\n If provided, raise when either the x or y variable does not have\n one of the declared seaborn types.\n log_scale : bool, number, or pair of bools or numbers\n If not False, set the axes to use log scaling, with the given\n base or defaulting to 10. If a tuple, interpreted as separate\n arguments for the x and y axes.\n\n ","endLoc":1299,"header":"def _attach(\n self,\n obj,\n allowed_types=None,\n log_scale=None,\n )","id":1077,"name":"_attach","nodeType":"Function","startLoc":1155,"text":"def _attach(\n self,\n obj,\n allowed_types=None,\n log_scale=None,\n ):\n \"\"\"Associate the plotter with an Axes manager and initialize its units.\n\n Parameters\n ----------\n obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid`\n Structural object that we will eventually plot onto.\n allowed_types : str or list of str\n If provided, raise when either the x or y variable does not have\n one of the declared seaborn types.\n log_scale : bool, number, or pair of bools or numbers\n If not False, set the axes to use log scaling, with the given\n base or defaulting to 10. If a tuple, interpreted as separate\n arguments for the x and y axes.\n\n \"\"\"\n from .axisgrid import FacetGrid\n if isinstance(obj, FacetGrid):\n self.ax = None\n self.facets = obj\n ax_list = obj.axes.flatten()\n if obj.col_names is not None:\n self.var_levels[\"col\"] = obj.col_names\n if obj.row_names is not None:\n self.var_levels[\"row\"] = obj.row_names\n else:\n self.ax = obj\n self.facets = None\n ax_list = [obj]\n\n # Identify which \"axis\" variables we have defined\n axis_variables = set(\"xy\").intersection(self.variables)\n\n # -- Verify the types of our x and y variables here.\n # This doesn't really make complete sense being here here, but it's a fine\n # place for it, given the current system.\n # (Note that for some plots, there might be more complicated restrictions)\n # e.g. the categorical plots have their own check that as specific to the\n # non-categorical axis.\n if allowed_types is None:\n allowed_types = [\"numeric\", \"datetime\", \"categorical\"]\n elif isinstance(allowed_types, str):\n allowed_types = [allowed_types]\n\n for var in axis_variables:\n var_type = self.var_types[var]\n if var_type not in allowed_types:\n err = (\n f\"The {var} variable is {var_type}, but one of \"\n f\"{allowed_types} is required\"\n )\n raise TypeError(err)\n\n # -- Get axis objects for each row in plot_data for type conversions and scaling\n\n facet_dim = {\"x\": \"col\", \"y\": \"row\"}\n\n self.converters = {}\n for var in axis_variables:\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n\n converter = pd.Series(index=self.plot_data.index, name=var, dtype=object)\n share_state = getattr(self.facets, f\"_share{var}\", True)\n\n # Simplest cases are that we have a single axes, all axes are shared,\n # or sharing is only on the orthogonal facet dimension. In these cases,\n # all datapoints get converted the same way, so use the first axis\n if share_state is True or share_state == facet_dim[other_var]:\n converter.loc[:] = getattr(ax_list[0], f\"{var}axis\")\n\n else:\n\n # Next simplest case is when no axes are shared, and we can\n # use the axis objects within each facet\n if share_state is False:\n for axes_vars, axes_data in self.iter_data():\n ax = self._get_axes(axes_vars)\n converter.loc[axes_data.index] = getattr(ax, f\"{var}axis\")\n\n # In the more complicated case, the axes are shared within each\n # \"file\" of the facetgrid. In that case, we need to subset the data\n # for that file and assign it the first axis in the slice of the grid\n else:\n\n names = getattr(self.facets, f\"{share_state}_names\")\n for i, level in enumerate(names):\n idx = (i, 0) if share_state == \"row\" else (0, i)\n axis = getattr(self.facets.axes[idx], f\"{var}axis\")\n converter.loc[self.plot_data[share_state] == level] = axis\n\n # Store the converter vector, which we use elsewhere (e.g comp_data)\n self.converters[var] = converter\n\n # Now actually update the matplotlib objects to do the conversion we want\n grouped = self.plot_data[var].groupby(self.converters[var], sort=False)\n for converter, seed_data in grouped:\n if self.var_types[var] == \"categorical\":\n if self._var_ordered[var]:\n order = self.var_levels[var]\n else:\n order = None\n seed_data = categorical_order(seed_data, order)\n converter.update_units(seed_data)\n\n # -- Set numerical axis scales\n\n # First unpack the log_scale argument\n if log_scale is None:\n scalex = scaley = False\n else:\n # Allow single value or x, y tuple\n try:\n scalex, scaley = log_scale\n except TypeError:\n scalex = log_scale if \"x\" in self.variables else False\n scaley = log_scale if \"y\" in self.variables else False\n\n # Now use it\n for axis, scale in zip(\"xy\", (scalex, scaley)):\n if scale:\n for ax in ax_list:\n set_scale = getattr(ax, f\"set_{axis}scale\")\n if scale is True:\n set_scale(\"log\")\n else:\n if Version(mpl.__version__) >= Version(\"3.3\"):\n set_scale(\"log\", base=scale)\n else:\n set_scale(\"log\", **{f\"base{axis}\": scale})\n\n # For categorical y, we want the \"first\" level to be at the top of the axis\n if self.var_types.get(\"y\", None) == \"categorical\":\n for ax in ax_list:\n try:\n ax.yaxis.set_inverted(True)\n except AttributeError: # mpl < 3.1\n if not ax.yaxis_inverted():\n ax.invert_yaxis()\n\n # TODO -- Add axes labels"},{"attributeType":"list","col":0,"comment":"null","endLoc":785,"id":1078,"name":"_icefire_lut","nodeType":"Attribute","startLoc":785,"text":"_icefire_lut"},{"fileName":"test_matrix.py","filePath":"tests","id":1080,"nodeType":"File","text":"import tempfile\nimport copy\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ntry:\n from scipy.spatial import distance\n from scipy.cluster import hierarchy\n _no_scipy = False\nexcept ImportError:\n _no_scipy = True\n\ntry:\n import fastcluster\n assert fastcluster\n _no_fastcluster = False\nexcept ImportError:\n _no_fastcluster = True\n\nimport numpy.testing as npt\ntry:\n import pandas.testing as pdt\nexcept ImportError:\n import pandas.util.testing as pdt\nimport pytest\n\nfrom seaborn import matrix as mat\nfrom seaborn import color_palette\nfrom seaborn._compat import get_colormap\nfrom seaborn._testing import assert_colors_equal\n\n\nclass TestHeatmap:\n rs = np.random.RandomState(sum(map(ord, \"heatmap\")))\n\n x_norm = rs.randn(4, 8)\n letters = pd.Series([\"A\", \"B\", \"C\", \"D\"], name=\"letters\")\n df_norm = pd.DataFrame(x_norm, index=letters)\n\n x_unif = rs.rand(20, 13)\n df_unif = pd.DataFrame(x_unif)\n\n default_kws = dict(vmin=None, vmax=None, cmap=None, center=None,\n robust=False, annot=False, fmt=\".2f\", annot_kws=None,\n cbar=True, cbar_kws=None, mask=None)\n\n def test_ndarray_input(self):\n\n p = mat._HeatMapper(self.x_norm, **self.default_kws)\n npt.assert_array_equal(p.plot_data, self.x_norm)\n pdt.assert_frame_equal(p.data, pd.DataFrame(self.x_norm))\n\n npt.assert_array_equal(p.xticklabels, np.arange(8))\n npt.assert_array_equal(p.yticklabels, np.arange(4))\n\n assert p.xlabel == \"\"\n assert p.ylabel == \"\"\n\n def test_df_input(self):\n\n p = mat._HeatMapper(self.df_norm, **self.default_kws)\n npt.assert_array_equal(p.plot_data, self.x_norm)\n pdt.assert_frame_equal(p.data, self.df_norm)\n\n npt.assert_array_equal(p.xticklabels, np.arange(8))\n npt.assert_array_equal(p.yticklabels, self.letters.values)\n\n assert p.xlabel == \"\"\n assert p.ylabel == \"letters\"\n\n def test_df_multindex_input(self):\n\n df = self.df_norm.copy()\n index = pd.MultiIndex.from_tuples([(\"A\", 1), (\"B\", 2),\n (\"C\", 3), (\"D\", 4)],\n names=[\"letter\", \"number\"])\n index.name = \"letter-number\"\n df.index = index\n\n p = mat._HeatMapper(df, **self.default_kws)\n\n combined_tick_labels = [\"A-1\", \"B-2\", \"C-3\", \"D-4\"]\n npt.assert_array_equal(p.yticklabels, combined_tick_labels)\n assert p.ylabel == \"letter-number\"\n\n p = mat._HeatMapper(df.T, **self.default_kws)\n\n npt.assert_array_equal(p.xticklabels, combined_tick_labels)\n assert p.xlabel == \"letter-number\"\n\n @pytest.mark.parametrize(\"dtype\", [float, np.int64, object])\n def test_mask_input(self, dtype):\n kws = self.default_kws.copy()\n\n mask = self.x_norm > 0\n kws['mask'] = mask\n data = self.x_norm.astype(dtype)\n p = mat._HeatMapper(data, **kws)\n plot_data = np.ma.masked_where(mask, data)\n\n npt.assert_array_equal(p.plot_data, plot_data)\n\n def test_mask_limits(self):\n \"\"\"Make sure masked cells are not used to calculate extremes\"\"\"\n\n kws = self.default_kws.copy()\n\n mask = self.x_norm > 0\n kws['mask'] = mask\n p = mat._HeatMapper(self.x_norm, **kws)\n\n assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()\n assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()\n\n mask = self.x_norm < 0\n kws['mask'] = mask\n p = mat._HeatMapper(self.x_norm, **kws)\n\n assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()\n assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()\n\n def test_default_vlims(self):\n\n p = mat._HeatMapper(self.df_unif, **self.default_kws)\n assert p.vmin == self.x_unif.min()\n assert p.vmax == self.x_unif.max()\n\n def test_robust_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"robust\"] = True\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == np.percentile(self.x_unif, 2)\n assert p.vmax == np.percentile(self.x_unif, 98)\n\n def test_custom_sequential_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"vmin\"] = 0\n kws[\"vmax\"] = 1\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == 0\n assert p.vmax == 1\n\n def test_custom_diverging_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"vmin\"] = -4\n kws[\"vmax\"] = 5\n kws[\"center\"] = 0\n p = mat._HeatMapper(self.df_norm, **kws)\n\n assert p.vmin == -4\n assert p.vmax == 5\n\n def test_array_with_nans(self):\n\n x1 = self.rs.rand(10, 10)\n nulls = np.zeros(10) * np.nan\n x2 = np.c_[x1, nulls]\n\n m1 = mat._HeatMapper(x1, **self.default_kws)\n m2 = mat._HeatMapper(x2, **self.default_kws)\n\n assert m1.vmin == m2.vmin\n assert m1.vmax == m2.vmax\n\n def test_mask(self):\n\n df = pd.DataFrame(data={'a': [1, 1, 1],\n 'b': [2, np.nan, 2],\n 'c': [3, 3, np.nan]})\n\n kws = self.default_kws.copy()\n kws[\"mask\"] = np.isnan(df.values)\n\n m = mat._HeatMapper(df, **kws)\n\n npt.assert_array_equal(np.isnan(m.plot_data.data),\n m.plot_data.mask)\n\n def test_custom_cmap(self):\n\n kws = self.default_kws.copy()\n kws[\"cmap\"] = \"BuGn\"\n p = mat._HeatMapper(self.df_unif, **kws)\n assert p.cmap == mpl.cm.BuGn\n\n def test_centered_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"center\"] = .5\n\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == self.df_unif.values.min()\n assert p.vmax == self.df_unif.values.max()\n\n def test_default_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n cvals = np.linspace(0, 1, 9)\n npt.assert_array_almost_equal(fc, cmap(cvals), 2)\n\n def test_custom_vlim_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], vmin=0, cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n npt.assert_array_almost_equal(fc, cmap(vals), 2)\n\n def test_custom_center_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], center=.5, cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n npt.assert_array_almost_equal(fc, cmap(vals), 2)\n\n def test_cmap_with_properties(self):\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_bad(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(\n cmap(np.ma.masked_invalid([np.nan])),\n hm.cmap(np.ma.masked_invalid([np.nan])))\n\n kws[\"center\"] = 0.5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(\n cmap(np.ma.masked_invalid([np.nan])),\n hm.cmap(np.ma.masked_invalid([np.nan])))\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_under(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws[\"center\"] = .5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_over(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws[\"center\"] = .5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(np.inf), hm.cmap(np.inf))\n\n def test_ticklabels_off(self):\n kws = self.default_kws.copy()\n kws['xticklabels'] = False\n kws['yticklabels'] = False\n p = mat._HeatMapper(self.df_norm, **kws)\n assert p.xticklabels == []\n assert p.yticklabels == []\n\n def test_custom_ticklabels(self):\n kws = self.default_kws.copy()\n xticklabels = list('iheartheatmaps'[:self.df_norm.shape[1]])\n yticklabels = list('heatmapsarecool'[:self.df_norm.shape[0]])\n kws['xticklabels'] = xticklabels\n kws['yticklabels'] = yticklabels\n p = mat._HeatMapper(self.df_norm, **kws)\n assert p.xticklabels == xticklabels\n assert p.yticklabels == yticklabels\n\n def test_custom_ticklabel_interval(self):\n\n kws = self.default_kws.copy()\n xstep, ystep = 2, 3\n kws['xticklabels'] = xstep\n kws['yticklabels'] = ystep\n p = mat._HeatMapper(self.df_norm, **kws)\n\n nx, ny = self.df_norm.T.shape\n npt.assert_array_equal(p.xticks, np.arange(0, nx, xstep) + .5)\n npt.assert_array_equal(p.yticks, np.arange(0, ny, ystep) + .5)\n npt.assert_array_equal(p.xticklabels,\n self.df_norm.columns[0:nx:xstep])\n npt.assert_array_equal(p.yticklabels,\n self.df_norm.index[0:ny:ystep])\n\n def test_heatmap_annotation(self):\n\n ax = mat.heatmap(self.df_norm, annot=True, fmt=\".1f\",\n annot_kws={\"fontsize\": 14})\n for val, text in zip(self.x_norm.flat, ax.texts):\n assert text.get_text() == f\"{val:.1f}\"\n assert text.get_fontsize() == 14\n\n def test_heatmap_annotation_overwrite_kws(self):\n\n annot_kws = dict(color=\"0.3\", va=\"bottom\", ha=\"left\")\n ax = mat.heatmap(self.df_norm, annot=True, fmt=\".1f\",\n annot_kws=annot_kws)\n for text in ax.texts:\n assert text.get_color() == \"0.3\"\n assert text.get_ha() == \"left\"\n assert text.get_va() == \"bottom\"\n\n def test_heatmap_annotation_with_mask(self):\n\n df = pd.DataFrame(data={'a': [1, 1, 1],\n 'b': [2, np.nan, 2],\n 'c': [3, 3, np.nan]})\n mask = np.isnan(df.values)\n df_masked = np.ma.masked_where(mask, df)\n ax = mat.heatmap(df, annot=True, fmt='.1f', mask=mask)\n assert len(df_masked.compressed()) == len(ax.texts)\n for val, text in zip(df_masked.compressed(), ax.texts):\n assert f\"{val:.1f}\" == text.get_text()\n\n def test_heatmap_annotation_mesh_colors(self):\n\n ax = mat.heatmap(self.df_norm, annot=True)\n mesh = ax.collections[0]\n assert len(mesh.get_facecolors()) == self.df_norm.values.size\n\n plt.close(\"all\")\n\n def test_heatmap_annotation_other_data(self):\n annot_data = self.df_norm + 10\n\n ax = mat.heatmap(self.df_norm, annot=annot_data, fmt=\".1f\",\n annot_kws={\"fontsize\": 14})\n\n for val, text in zip(annot_data.values.flat, ax.texts):\n assert text.get_text() == f\"{val:.1f}\"\n assert text.get_fontsize() == 14\n\n def test_heatmap_annotation_different_shapes(self):\n\n annot_data = self.df_norm.iloc[:-1]\n with pytest.raises(ValueError):\n mat.heatmap(self.df_norm, annot=annot_data)\n\n def test_heatmap_annotation_with_limited_ticklabels(self):\n ax = mat.heatmap(self.df_norm, fmt=\".2f\", annot=True,\n xticklabels=False, yticklabels=False)\n for val, text in zip(self.x_norm.flat, ax.texts):\n assert text.get_text() == f\"{val:.2f}\"\n\n def test_heatmap_cbar(self):\n\n f = plt.figure()\n mat.heatmap(self.df_norm)\n assert len(f.axes) == 2\n plt.close(f)\n\n f = plt.figure()\n mat.heatmap(self.df_norm, cbar=False)\n assert len(f.axes) == 1\n plt.close(f)\n\n f, (ax1, ax2) = plt.subplots(2)\n mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2)\n assert len(f.axes) == 2\n plt.close(f)\n\n @pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_heatmap_axes(self):\n\n ax = mat.heatmap(self.df_norm)\n\n xtl = [int(l.get_text()) for l in ax.get_xticklabels()]\n assert xtl == list(self.df_norm.columns)\n ytl = [l.get_text() for l in ax.get_yticklabels()]\n assert ytl == list(self.df_norm.index)\n\n assert ax.get_xlabel() == \"\"\n assert ax.get_ylabel() == \"letters\"\n\n assert ax.get_xlim() == (0, 8)\n assert ax.get_ylim() == (4, 0)\n\n def test_heatmap_ticklabel_rotation(self):\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.heatmap(self.df_norm, xticklabels=1, yticklabels=1, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 0\n\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 90\n\n plt.close(f)\n\n df = self.df_norm.copy()\n df.columns = [str(c) * 10 for c in df.columns]\n df.index = [i * 10 for i in df.index]\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.heatmap(df, xticklabels=1, yticklabels=1, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 90\n\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 0\n\n plt.close(f)\n\n def test_heatmap_inner_lines(self):\n\n c = (0, 0, 1, 1)\n ax = mat.heatmap(self.df_norm, linewidths=2, linecolor=c)\n mesh = ax.collections[0]\n assert mesh.get_linewidths()[0] == 2\n assert tuple(mesh.get_edgecolor()[0]) == c\n\n def test_square_aspect(self):\n\n ax = mat.heatmap(self.df_norm, square=True)\n obs_aspect = ax.get_aspect()\n # mpl>3.3 returns 1 for setting \"equal\" aspect\n # so test for the two possible equal outcomes\n assert obs_aspect == \"equal\" or obs_aspect == 1\n\n def test_mask_validation(self):\n\n mask = mat._matrix_mask(self.df_norm, None)\n assert mask.shape == self.df_norm.shape\n assert mask.values.sum() == 0\n\n with pytest.raises(ValueError):\n bad_array_mask = self.rs.randn(3, 6) > 0\n mat._matrix_mask(self.df_norm, bad_array_mask)\n\n with pytest.raises(ValueError):\n bad_df_mask = pd.DataFrame(self.rs.randn(4, 8) > 0)\n mat._matrix_mask(self.df_norm, bad_df_mask)\n\n def test_missing_data_mask(self):\n\n data = pd.DataFrame(np.arange(4, dtype=float).reshape(2, 2))\n data.loc[0, 0] = np.nan\n mask = mat._matrix_mask(data, None)\n npt.assert_array_equal(mask, [[True, False], [False, False]])\n\n mask_in = np.array([[False, True], [False, False]])\n mask_out = mat._matrix_mask(data, mask_in)\n npt.assert_array_equal(mask_out, [[True, True], [False, False]])\n\n def test_cbar_ticks(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2,\n cbar_kws=dict(drawedges=True))\n assert len(ax2.collections) == 2\n\n\n@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\nclass TestDendrogram:\n\n rs = np.random.RandomState(sum(map(ord, \"dendrogram\")))\n\n default_kws = dict(linkage=None, metric='euclidean', method='single',\n axis=1, label=True, rotate=False)\n\n x_norm = rs.randn(4, 8) + np.arange(8)\n x_norm = (x_norm.T + np.arange(4)).T\n letters = pd.Series([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"],\n name=\"letters\")\n\n df_norm = pd.DataFrame(x_norm, columns=letters)\n\n if not _no_scipy:\n if _no_fastcluster:\n x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')\n x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')\n else:\n x_norm_linkage = fastcluster.linkage_vector(x_norm.T,\n metric='euclidean',\n method='single')\n\n x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,\n color_threshold=-np.inf)\n x_norm_leaves = x_norm_dendrogram['leaves']\n df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])\n\n def test_ndarray_input(self):\n p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)\n npt.assert_array_equal(p.array.T, self.x_norm)\n pdt.assert_frame_equal(p.data.T, pd.DataFrame(self.x_norm))\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)\n\n npt.assert_array_equal(p.xticklabels, self.x_norm_leaves)\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel is None\n assert p.ylabel == ''\n\n def test_df_input(self):\n p = mat._DendrogramPlotter(self.df_norm, **self.default_kws)\n npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))\n pdt.assert_frame_equal(p.data.T, self.df_norm)\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.xticklabels,\n np.asarray(self.df_norm.columns)[\n self.x_norm_leaves])\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel == 'letters'\n assert p.ylabel == ''\n\n def test_df_multindex_input(self):\n\n df = self.df_norm.copy()\n index = pd.MultiIndex.from_tuples([(\"A\", 1), (\"B\", 2),\n (\"C\", 3), (\"D\", 4)],\n names=[\"letter\", \"number\"])\n index.name = \"letter-number\"\n df.index = index\n kws = self.default_kws.copy()\n kws['label'] = True\n\n p = mat._DendrogramPlotter(df.T, **kws)\n\n xticklabels = [\"A-1\", \"B-2\", \"C-3\", \"D-4\"]\n xticklabels = [xticklabels[i] for i in p.reordered_ind]\n npt.assert_array_equal(p.xticklabels, xticklabels)\n npt.assert_array_equal(p.yticklabels, [])\n assert p.xlabel == \"letter-number\"\n\n def test_axis0_input(self):\n kws = self.default_kws.copy()\n kws['axis'] = 0\n p = mat._DendrogramPlotter(self.df_norm.T, **kws)\n\n npt.assert_array_equal(p.array, np.asarray(self.df_norm.T))\n pdt.assert_frame_equal(p.data, self.df_norm.T)\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.xticklabels, self.df_norm_leaves)\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel == 'letters'\n assert p.ylabel == ''\n\n def test_rotate_input(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))\n pdt.assert_frame_equal(p.data.T, self.df_norm)\n\n npt.assert_array_equal(p.xticklabels, [])\n npt.assert_array_equal(p.yticklabels, self.df_norm_leaves)\n\n assert p.xlabel == ''\n assert p.ylabel == 'letters'\n\n def test_rotate_axis0_input(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n kws['axis'] = 0\n p = mat._DendrogramPlotter(self.df_norm.T, **kws)\n\n npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)\n\n def test_custom_linkage(self):\n kws = self.default_kws.copy()\n\n try:\n import fastcluster\n\n linkage = fastcluster.linkage_vector(self.x_norm, method='single',\n metric='euclidean')\n except ImportError:\n d = distance.pdist(self.x_norm, metric='euclidean')\n linkage = hierarchy.linkage(d, method='single')\n dendrogram = hierarchy.dendrogram(linkage, no_plot=True,\n color_threshold=-np.inf)\n kws['linkage'] = linkage\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n\n npt.assert_array_equal(p.linkage, linkage)\n assert p.dendrogram == dendrogram\n\n def test_label_false(self):\n kws = self.default_kws.copy()\n kws['label'] = False\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n assert p.xticks == []\n assert p.yticks == []\n assert p.xticklabels == []\n assert p.yticklabels == []\n assert p.xlabel == \"\"\n assert p.ylabel == \"\"\n\n def test_linkage_scipy(self):\n p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)\n\n scipy_linkage = p._calculate_linkage_scipy()\n\n from scipy.spatial import distance\n from scipy.cluster import hierarchy\n\n dists = distance.pdist(self.x_norm.T,\n metric=self.default_kws['metric'])\n linkage = hierarchy.linkage(dists, method=self.default_kws['method'])\n\n npt.assert_array_equal(scipy_linkage, linkage)\n\n @pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_other_method(self):\n import fastcluster\n\n kws = self.default_kws.copy()\n kws['method'] = 'average'\n linkage = fastcluster.linkage(self.x_norm.T, method='average',\n metric='euclidean')\n p = mat._DendrogramPlotter(self.x_norm, **kws)\n npt.assert_array_equal(p.linkage, linkage)\n\n @pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_non_euclidean(self):\n import fastcluster\n\n kws = self.default_kws.copy()\n kws['metric'] = 'cosine'\n kws['method'] = 'average'\n linkage = fastcluster.linkage(self.x_norm.T, method=kws['method'],\n metric=kws['metric'])\n p = mat._DendrogramPlotter(self.x_norm, **kws)\n npt.assert_array_equal(p.linkage, linkage)\n\n def test_dendrogram_plot(self):\n d = mat.dendrogram(self.x_norm, **self.default_kws)\n\n ax = plt.gca()\n xlim = ax.get_xlim()\n # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy\n xmax = len(d.reordered_ind) * 10\n\n assert xlim[0] == 0\n assert xlim[1] == xmax\n\n assert len(ax.collections[0].get_paths()) == len(d.dependent_coord)\n\n @pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_dendrogram_rotate(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n\n d = mat.dendrogram(self.x_norm, **kws)\n\n ax = plt.gca()\n ylim = ax.get_ylim()\n\n # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy\n ymax = len(d.reordered_ind) * 10\n\n # Since y axis is inverted, ylim is (80, 0)\n # and therefore not (0, 80) as usual:\n assert ylim[1] == 0\n assert ylim[0] == ymax\n\n def test_dendrogram_ticklabel_rotation(self):\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(self.df_norm, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 0\n\n plt.close(f)\n\n df = self.df_norm.copy()\n df.columns = [str(c) * 10 for c in df.columns]\n df.index = [i * 10 for i in df.index]\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(df, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 90\n\n plt.close(f)\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(df.T, axis=0, rotate=True)\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 0\n plt.close(f)\n\n\n@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\nclass TestClustermap:\n\n rs = np.random.RandomState(sum(map(ord, \"clustermap\")))\n\n x_norm = rs.randn(4, 8) + np.arange(8)\n x_norm = (x_norm.T + np.arange(4)).T\n letters = pd.Series([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"],\n name=\"letters\")\n\n df_norm = pd.DataFrame(x_norm, columns=letters)\n\n default_kws = dict(pivot_kws=None, z_score=None, standard_scale=None,\n figsize=(10, 10), row_colors=None, col_colors=None,\n dendrogram_ratio=.2, colors_ratio=.03,\n cbar_pos=(0, .8, .05, .2))\n\n default_plot_kws = dict(metric='euclidean', method='average',\n colorbar_kws=None,\n row_cluster=True, col_cluster=True,\n row_linkage=None, col_linkage=None,\n tree_kws=None)\n\n row_colors = color_palette('Set2', df_norm.shape[0])\n col_colors = color_palette('Dark2', df_norm.shape[1])\n\n if not _no_scipy:\n if _no_fastcluster:\n x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')\n x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')\n else:\n x_norm_linkage = fastcluster.linkage_vector(x_norm.T,\n metric='euclidean',\n method='single')\n\n x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,\n color_threshold=-np.inf)\n x_norm_leaves = x_norm_dendrogram['leaves']\n df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])\n\n def test_ndarray_input(self):\n cg = mat.ClusterGrid(self.x_norm, **self.default_kws)\n pdt.assert_frame_equal(cg.data, pd.DataFrame(self.x_norm))\n assert len(cg.fig.axes) == 4\n assert cg.ax_row_colors is None\n assert cg.ax_col_colors is None\n\n def test_df_input(self):\n cg = mat.ClusterGrid(self.df_norm, **self.default_kws)\n pdt.assert_frame_equal(cg.data, self.df_norm)\n\n def test_corr_df_input(self):\n df = self.df_norm.corr()\n cg = mat.ClusterGrid(df, **self.default_kws)\n cg.plot(**self.default_plot_kws)\n diag = cg.data2d.values[np.diag_indices_from(cg.data2d)]\n npt.assert_array_almost_equal(diag, np.ones(cg.data2d.shape[0]))\n\n def test_pivot_input(self):\n df_norm = self.df_norm.copy()\n df_norm.index.name = 'numbers'\n df_long = pd.melt(df_norm.reset_index(), var_name='letters',\n id_vars='numbers')\n kws = self.default_kws.copy()\n kws['pivot_kws'] = dict(index='numbers', columns='letters',\n values='value')\n cg = mat.ClusterGrid(df_long, **kws)\n\n pdt.assert_frame_equal(cg.data2d, df_norm)\n\n def test_colors_input(self):\n kws = self.default_kws.copy()\n\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, self.row_colors)\n npt.assert_array_equal(cg.col_colors, self.col_colors)\n\n assert len(cg.fig.axes) == 6\n\n def test_categorical_colors_input(self):\n kws = self.default_kws.copy()\n\n row_colors = pd.Series(self.row_colors, dtype=\"category\")\n col_colors = pd.Series(\n self.col_colors, dtype=\"category\", index=self.df_norm.columns\n )\n\n kws['row_colors'] = row_colors\n kws['col_colors'] = col_colors\n\n exp_row_colors = list(map(mpl.colors.to_rgb, row_colors))\n exp_col_colors = list(map(mpl.colors.to_rgb, col_colors))\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, exp_row_colors)\n npt.assert_array_equal(cg.col_colors, exp_col_colors)\n\n assert len(cg.fig.axes) == 6\n\n def test_nested_colors_input(self):\n kws = self.default_kws.copy()\n\n row_colors = [self.row_colors, self.row_colors]\n col_colors = [self.col_colors, self.col_colors]\n kws['row_colors'] = row_colors\n kws['col_colors'] = col_colors\n\n cm = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cm.row_colors, row_colors)\n npt.assert_array_equal(cm.col_colors, col_colors)\n\n assert len(cm.fig.axes) == 6\n\n def test_colors_input_custom_cmap(self):\n kws = self.default_kws.copy()\n\n kws['cmap'] = mpl.cm.PRGn\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cg = mat.clustermap(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, self.row_colors)\n npt.assert_array_equal(cg.col_colors, self.col_colors)\n\n assert len(cg.fig.axes) == 6\n\n def test_z_score(self):\n df = self.df_norm.copy()\n df = (df - df.mean()) / df.std()\n kws = self.default_kws.copy()\n kws['z_score'] = 1\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_z_score_axis0(self):\n df = self.df_norm.copy()\n df = df.T\n df = (df - df.mean()) / df.std()\n df = df.T\n kws = self.default_kws.copy()\n kws['z_score'] = 0\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_standard_scale(self):\n df = self.df_norm.copy()\n df = (df - df.min()) / (df.max() - df.min())\n kws = self.default_kws.copy()\n kws['standard_scale'] = 1\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_standard_scale_axis0(self):\n df = self.df_norm.copy()\n df = df.T\n df = (df - df.min()) / (df.max() - df.min())\n df = df.T\n kws = self.default_kws.copy()\n kws['standard_scale'] = 0\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_z_score_standard_scale(self):\n kws = self.default_kws.copy()\n kws['z_score'] = True\n kws['standard_scale'] = True\n with pytest.raises(ValueError):\n mat.ClusterGrid(self.df_norm, **kws)\n\n def test_color_list_to_matrix_and_cmap(self):\n # Note this uses the attribute named col_colors but tests row colors\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n self.col_colors, self.x_norm_leaves, axis=0)\n\n for i, leaf in enumerate(self.x_norm_leaves):\n color = self.col_colors[leaf]\n assert_colors_equal(cmap(matrix[i, 0]), color)\n\n def test_nested_color_list_to_matrix_and_cmap(self):\n # Note this uses the attribute named col_colors but tests row colors\n colors = [self.col_colors, self.col_colors[::-1]]\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n colors, self.x_norm_leaves, axis=0)\n\n for i, leaf in enumerate(self.x_norm_leaves):\n for j, color_row in enumerate(colors):\n color = color_row[leaf]\n assert_colors_equal(cmap(matrix[i, j]), color)\n\n def test_color_list_to_matrix_and_cmap_axis1(self):\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n self.col_colors, self.x_norm_leaves, axis=1)\n\n for j, leaf in enumerate(self.x_norm_leaves):\n color = self.col_colors[leaf]\n assert_colors_equal(cmap(matrix[0, j]), color)\n\n def test_color_list_to_matrix_and_cmap_different_sizes(self):\n colors = [self.col_colors, self.col_colors * 2]\n with pytest.raises(ValueError):\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n colors, self.x_norm_leaves, axis=1)\n\n def test_savefig(self):\n # Not sure if this is the right way to test....\n cg = mat.ClusterGrid(self.df_norm, **self.default_kws)\n cg.plot(**self.default_plot_kws)\n cg.savefig(tempfile.NamedTemporaryFile(), format='png')\n\n def test_plot_dendrograms(self):\n cm = mat.clustermap(self.df_norm, **self.default_kws)\n\n assert len(cm.ax_row_dendrogram.collections[0].get_paths()) == len(\n cm.dendrogram_row.independent_coord\n )\n assert len(cm.ax_col_dendrogram.collections[0].get_paths()) == len(\n cm.dendrogram_col.independent_coord\n )\n data2d = self.df_norm.iloc[cm.dendrogram_row.reordered_ind,\n cm.dendrogram_col.reordered_ind]\n pdt.assert_frame_equal(cm.data2d, data2d)\n\n def test_cluster_false(self):\n kws = self.default_kws.copy()\n kws['row_cluster'] = False\n kws['col_cluster'] = False\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert len(cm.ax_row_dendrogram.lines) == 0\n assert len(cm.ax_col_dendrogram.lines) == 0\n\n assert len(cm.ax_row_dendrogram.get_xticks()) == 0\n assert len(cm.ax_row_dendrogram.get_yticks()) == 0\n assert len(cm.ax_col_dendrogram.get_xticks()) == 0\n assert len(cm.ax_col_dendrogram.get_yticks()) == 0\n\n pdt.assert_frame_equal(cm.data2d, self.df_norm)\n\n def test_row_col_colors(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert len(cm.ax_row_colors.collections) == 1\n assert len(cm.ax_col_colors.collections) == 1\n\n def test_cluster_false_row_col_colors(self):\n kws = self.default_kws.copy()\n kws['row_cluster'] = False\n kws['col_cluster'] = False\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert len(cm.ax_row_dendrogram.lines) == 0\n assert len(cm.ax_col_dendrogram.lines) == 0\n\n assert len(cm.ax_row_dendrogram.get_xticks()) == 0\n assert len(cm.ax_row_dendrogram.get_yticks()) == 0\n assert len(cm.ax_col_dendrogram.get_xticks()) == 0\n assert len(cm.ax_col_dendrogram.get_yticks()) == 0\n assert len(cm.ax_row_colors.collections) == 1\n assert len(cm.ax_col_colors.collections) == 1\n\n pdt.assert_frame_equal(cm.data2d, self.df_norm)\n\n def test_row_col_colors_df(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),\n 'row_2': list(self.row_colors)},\n index=self.df_norm.index,\n columns=['row_1', 'row_2'])\n kws['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),\n 'col_2': list(self.col_colors)},\n index=self.df_norm.columns,\n columns=['col_1', 'col_2'])\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n row_labels = [l.get_text() for l in\n cm.ax_row_colors.get_xticklabels()]\n assert cm.row_color_labels == ['row_1', 'row_2']\n assert row_labels == cm.row_color_labels\n\n col_labels = [l.get_text() for l in\n cm.ax_col_colors.get_yticklabels()]\n assert cm.col_color_labels == ['col_1', 'col_2']\n assert col_labels == cm.col_color_labels\n\n def test_row_col_colors_df_shuffled(self):\n # Tests if colors are properly matched, even if given in wrong order\n\n m, n = self.df_norm.shape\n shuffled_inds = [self.df_norm.index[i] for i in\n list(range(0, m, 2)) + list(range(1, m, 2))]\n shuffled_cols = [self.df_norm.columns[i] for i in\n list(range(0, n, 2)) + list(range(1, n, 2))]\n\n kws = self.default_kws.copy()\n\n row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.loc[shuffled_inds]\n\n col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.loc[shuffled_cols]\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert list(cm.col_colors)[0] == list(self.col_colors)\n assert list(cm.row_colors)[0] == list(self.row_colors)\n\n def test_row_col_colors_df_missing(self):\n kws = self.default_kws.copy()\n row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.drop(self.df_norm.index[0])\n\n col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert list(cm.col_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])\n assert list(cm.row_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])\n\n def test_row_col_colors_df_one_axis(self):\n # Test case with only row annotation.\n kws1 = self.default_kws.copy()\n kws1['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),\n 'row_2': list(self.row_colors)},\n index=self.df_norm.index,\n columns=['row_1', 'row_2'])\n\n cm1 = mat.clustermap(self.df_norm, **kws1)\n\n row_labels = [l.get_text() for l in\n cm1.ax_row_colors.get_xticklabels()]\n assert cm1.row_color_labels == ['row_1', 'row_2']\n assert row_labels == cm1.row_color_labels\n\n # Test case with only col annotation.\n kws2 = self.default_kws.copy()\n kws2['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),\n 'col_2': list(self.col_colors)},\n index=self.df_norm.columns,\n columns=['col_1', 'col_2'])\n\n cm2 = mat.clustermap(self.df_norm, **kws2)\n\n col_labels = [l.get_text() for l in\n cm2.ax_col_colors.get_yticklabels()]\n assert cm2.col_color_labels == ['col_1', 'col_2']\n assert col_labels == cm2.col_color_labels\n\n def test_row_col_colors_series(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = pd.Series(list(self.row_colors), name='row_annot',\n index=self.df_norm.index)\n kws['col_colors'] = pd.Series(list(self.col_colors), name='col_annot',\n index=self.df_norm.columns)\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n row_labels = [l.get_text() for l in cm.ax_row_colors.get_xticklabels()]\n assert cm.row_color_labels == ['row_annot']\n assert row_labels == cm.row_color_labels\n\n col_labels = [l.get_text() for l in cm.ax_col_colors.get_yticklabels()]\n assert cm.col_color_labels == ['col_annot']\n assert col_labels == cm.col_color_labels\n\n def test_row_col_colors_series_shuffled(self):\n # Tests if colors are properly matched, even if given in wrong order\n\n m, n = self.df_norm.shape\n shuffled_inds = [self.df_norm.index[i] for i in\n list(range(0, m, 2)) + list(range(1, m, 2))]\n shuffled_cols = [self.df_norm.columns[i] for i in\n list(range(0, n, 2)) + list(range(1, n, 2))]\n\n kws = self.default_kws.copy()\n\n row_colors = pd.Series(list(self.row_colors), name='row_annot',\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.loc[shuffled_inds]\n\n col_colors = pd.Series(list(self.col_colors), name='col_annot',\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.loc[shuffled_cols]\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert list(cm.col_colors) == list(self.col_colors)\n assert list(cm.row_colors) == list(self.row_colors)\n\n def test_row_col_colors_series_missing(self):\n kws = self.default_kws.copy()\n row_colors = pd.Series(list(self.row_colors), name='row_annot',\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.drop(self.df_norm.index[0])\n\n col_colors = pd.Series(list(self.col_colors), name='col_annot',\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert list(cm.col_colors) == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])\n assert list(cm.row_colors) == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])\n\n def test_row_col_colors_ignore_heatmap_kwargs(self):\n\n g = mat.clustermap(self.rs.uniform(0, 200, self.df_norm.shape),\n row_colors=self.row_colors,\n col_colors=self.col_colors,\n cmap=\"Spectral\",\n norm=mpl.colors.LogNorm(),\n vmax=100)\n\n assert np.array_equal(\n np.array(self.row_colors)[g.dendrogram_row.reordered_ind],\n g.ax_row_colors.collections[0].get_facecolors()[:, :3]\n )\n\n assert np.array_equal(\n np.array(self.col_colors)[g.dendrogram_col.reordered_ind],\n g.ax_col_colors.collections[0].get_facecolors()[:, :3]\n )\n\n def test_row_col_colors_raise_on_mixed_index_types(self):\n\n row_colors = pd.Series(\n list(self.row_colors), name=\"row_annot\", index=self.df_norm.index\n )\n\n col_colors = pd.Series(\n list(self.col_colors), name=\"col_annot\", index=self.df_norm.columns\n )\n\n with pytest.raises(TypeError):\n mat.clustermap(self.x_norm, row_colors=row_colors)\n\n with pytest.raises(TypeError):\n mat.clustermap(self.x_norm, col_colors=col_colors)\n\n def test_mask_reorganization(self):\n\n kws = self.default_kws.copy()\n kws[\"mask\"] = self.df_norm > 0\n\n g = mat.clustermap(self.df_norm, **kws)\n npt.assert_array_equal(g.data2d.index, g.mask.index)\n npt.assert_array_equal(g.data2d.columns, g.mask.columns)\n\n npt.assert_array_equal(g.mask.index,\n self.df_norm.index[\n g.dendrogram_row.reordered_ind])\n npt.assert_array_equal(g.mask.columns,\n self.df_norm.columns[\n g.dendrogram_col.reordered_ind])\n\n def test_ticklabel_reorganization(self):\n\n kws = self.default_kws.copy()\n xtl = np.arange(self.df_norm.shape[1])\n kws[\"xticklabels\"] = list(xtl)\n ytl = self.letters.loc[:self.df_norm.shape[0]]\n kws[\"yticklabels\"] = ytl\n\n g = mat.clustermap(self.df_norm, **kws)\n\n xtl_actual = [t.get_text() for t in g.ax_heatmap.get_xticklabels()]\n ytl_actual = [t.get_text() for t in g.ax_heatmap.get_yticklabels()]\n\n xtl_want = xtl[g.dendrogram_col.reordered_ind].astype(\" g1.ax_col_dendrogram.get_position().height)\n\n assert (g2.ax_col_colors.get_position().height\n > g1.ax_col_colors.get_position().height)\n\n assert (g2.ax_heatmap.get_position().height\n < g1.ax_heatmap.get_position().height)\n\n assert (g2.ax_row_dendrogram.get_position().width\n > g1.ax_row_dendrogram.get_position().width)\n\n assert (g2.ax_row_colors.get_position().width\n > g1.ax_row_colors.get_position().width)\n\n assert (g2.ax_heatmap.get_position().width\n < g1.ax_heatmap.get_position().width)\n\n kws1 = self.default_kws.copy()\n kws1.update(col_colors=self.col_colors)\n kws2 = kws1.copy()\n kws2.update(col_colors=[self.col_colors, self.col_colors])\n\n g1 = mat.clustermap(self.df_norm, **kws1)\n g2 = mat.clustermap(self.df_norm, **kws2)\n\n assert (g2.ax_col_colors.get_position().height\n > g1.ax_col_colors.get_position().height)\n\n kws1 = self.default_kws.copy()\n kws1.update(dendrogram_ratio=(.2, .2))\n\n kws2 = kws1.copy()\n kws2.update(dendrogram_ratio=(.2, .3))\n\n g1 = mat.clustermap(self.df_norm, **kws1)\n g2 = mat.clustermap(self.df_norm, **kws2)\n\n # Fails on pinned matplotlib?\n # assert (g2.ax_row_dendrogram.get_position().width\n # == g1.ax_row_dendrogram.get_position().width)\n assert g1.gs.get_width_ratios() == g2.gs.get_width_ratios()\n\n assert (g2.ax_col_dendrogram.get_position().height\n > g1.ax_col_dendrogram.get_position().height)\n\n def test_cbar_pos(self):\n\n kws = self.default_kws.copy()\n kws[\"cbar_pos\"] = (.2, .1, .4, .3)\n\n g = mat.clustermap(self.df_norm, **kws)\n pos = g.ax_cbar.get_position()\n assert pytest.approx(tuple(pos.p0)) == kws[\"cbar_pos\"][:2]\n assert pytest.approx(pos.width) == kws[\"cbar_pos\"][2]\n assert pytest.approx(pos.height) == kws[\"cbar_pos\"][3]\n\n kws[\"cbar_pos\"] = None\n g = mat.clustermap(self.df_norm, **kws)\n assert g.ax_cbar is None\n\n def test_square_warning(self):\n\n kws = self.default_kws.copy()\n g1 = mat.clustermap(self.df_norm, **kws)\n\n with pytest.warns(UserWarning):\n kws[\"square\"] = True\n g2 = mat.clustermap(self.df_norm, **kws)\n\n g1_shape = g1.ax_heatmap.get_position().get_points()\n g2_shape = g2.ax_heatmap.get_position().get_points()\n assert np.array_equal(g1_shape, g2_shape)\n\n def test_clustermap_annotation(self):\n\n g = mat.clustermap(self.df_norm, annot=True, fmt=\".1f\")\n for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):\n assert text.get_text() == f\"{val:.1f}\"\n\n g = mat.clustermap(self.df_norm, annot=self.df_norm, fmt=\".1f\")\n for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):\n assert text.get_text() == f\"{val:.1f}\"\n\n def test_tree_kws(self):\n\n rgb = (1, .5, .2)\n g = mat.clustermap(self.df_norm, tree_kws=dict(color=rgb))\n for ax in [g.ax_col_dendrogram, g.ax_row_dendrogram]:\n tree, = ax.collections\n assert tuple(tree.get_color().squeeze())[:3] == rgb\n\n\nif _no_scipy:\n\n def test_required_scipy_errors():\n\n x = np.random.normal(0, 1, (10, 10))\n\n with pytest.raises(RuntimeError):\n mat.clustermap(x)\n\n with pytest.raises(RuntimeError):\n mat.ClusterGrid(x)\n\n with pytest.raises(RuntimeError):\n mat.dendrogram(x)\n"},{"attributeType":"list","col":0,"comment":"null","endLoc":1045,"id":1081,"name":"_flare_lut","nodeType":"Attribute","startLoc":1045,"text":"_flare_lut"},{"col":4,"comment":"Yield each subplot dictionary with Axes object and metadata.","endLoc":265,"header":"def __iter__(self) -> Generator[dict, None, None]","id":1082,"name":"__iter__","nodeType":"Function","startLoc":263,"text":"def __iter__(self) -> Generator[dict, None, None]: # TODO TypedDict?\n \"\"\"Yield each subplot dictionary with Axes object and metadata.\"\"\"\n yield from self._subplot_list"},{"col":4,"comment":"Return the number of subplots in this figure.","endLoc":269,"header":"def __len__(self) -> int","id":1083,"name":"__len__","nodeType":"Function","startLoc":267,"text":"def __len__(self) -> int:\n \"\"\"Return the number of subplots in this figure.\"\"\"\n return len(self._subplot_list)"},{"attributeType":"null","col":12,"comment":"null","endLoc":179,"id":1084,"name":"_figure","nodeType":"Attribute","startLoc":179,"text":"self._figure"},{"attributeType":"dict","col":8,"comment":"null","endLoc":82,"id":1085,"name":"grid_dimensions","nodeType":"Attribute","startLoc":82,"text":"self.grid_dimensions"},{"attributeType":"list","col":12,"comment":"null","endLoc":168,"id":1086,"name":"_subplot_list","nodeType":"Attribute","startLoc":168,"text":"self._subplot_list"},{"attributeType":"list","col":0,"comment":"null","endLoc":1305,"id":1087,"name":"_crest_lut","nodeType":"Attribute","startLoc":1305,"text":"_crest_lut"},{"col":0,"comment":"null","endLoc":90,"header":"def assert_colors_equal(a, b, check_alpha=True)","id":1088,"name":"assert_colors_equal","nodeType":"Function","startLoc":75,"text":"def assert_colors_equal(a, b, check_alpha=True):\n\n def handle_array(x):\n\n if isinstance(x, np.ndarray):\n if x.ndim > 1:\n x = np.unique(x, axis=0).squeeze()\n if x.ndim > 1:\n raise ValueError(\"Color arrays must be 1 dimensional\")\n return x\n\n a = handle_array(a)\n b = handle_array(b)\n\n f = to_rgba if check_alpha else to_rgb\n assert f(a) == f(b)"},{"attributeType":"str","col":8,"comment":"null","endLoc":119,"id":1089,"name":"wrap_dim","nodeType":"Attribute","startLoc":119,"text":"self.wrap_dim"},{"fileName":"properties.py","filePath":"seaborn/_core","id":1090,"nodeType":"File","text":"from __future__ import annotations\nimport itertools\nimport warnings\n\nimport numpy as np\nfrom pandas import Series\nimport matplotlib as mpl\nfrom matplotlib.colors import to_rgb, to_rgba, to_rgba_array\nfrom matplotlib.path import Path\n\nfrom seaborn._core.scales import Scale, Nominal, Continuous, Temporal\nfrom seaborn._core.rules import categorical_order, variable_type\nfrom seaborn._compat import MarkerStyle\nfrom seaborn.palettes import QUAL_PALETTES, color_palette, blend_palette\nfrom seaborn.utils import get_color_cycle\n\nfrom typing import Any, Callable, Tuple, List, Union, Optional\n\ntry:\n from numpy.typing import ArrayLike\nexcept ImportError:\n # numpy<1.20.0 (Jan 2021)\n ArrayLike = Any\n\nRGBTuple = Tuple[float, float, float]\nRGBATuple = Tuple[float, float, float, float]\nColorSpec = Union[RGBTuple, RGBATuple, str]\n\nDashPattern = Tuple[float, ...]\nDashPatternWithOffset = Tuple[float, Optional[DashPattern]]\n\nMarkerPattern = Union[\n float,\n str,\n Tuple[int, int, float],\n List[Tuple[float, float]],\n Path,\n MarkerStyle,\n]\n\n\n# =================================================================================== #\n# Base classes\n# =================================================================================== #\n\n\nclass Property:\n \"\"\"Base class for visual properties that can be set directly or be data scaling.\"\"\"\n\n # When True, scales for this property will populate the legend by default\n legend = False\n\n # When True, scales for this property normalize data to [0, 1] before mapping\n normed = False\n\n def __init__(self, variable: str | None = None):\n \"\"\"Initialize the property with the name of the corresponding plot variable.\"\"\"\n if not variable:\n variable = self.__class__.__name__.lower()\n self.variable = variable\n\n def default_scale(self, data: Series) -> Scale:\n \"\"\"Given data, initialize appropriate scale class.\"\"\"\n # TODO allow variable_type to be \"boolean\" if that's a scale?\n # TODO how will this handle data with units that can be treated as numeric\n # if passed through a registered matplotlib converter?\n var_type = variable_type(data, boolean_type=\"numeric\")\n if var_type == \"numeric\":\n return Continuous()\n elif var_type == \"datetime\":\n return Temporal()\n # TODO others\n # time-based (TimeStamp, TimeDelta, Period)\n # boolean scale?\n else:\n return Nominal()\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n # TODO put these somewhere external for validation\n # TODO putting this here won't pick it up if subclasses define infer_scale\n # (e.g. color). How best to handle that? One option is to call super after\n # handling property-specific possibilities (e.g. for color check that the\n # arg is not a valid palette name) but that could get tricky.\n trans_args = [\"log\", \"symlog\", \"logit\", \"pow\", \"sqrt\"]\n if isinstance(arg, str):\n if any(arg.startswith(k) for k in trans_args):\n # TODO validate numeric type? That should happen centrally somewhere\n return Continuous(trans=arg)\n else:\n msg = f\"Unknown magic arg for {self.variable} scale: '{arg}'.\"\n raise ValueError(msg)\n else:\n arg_type = type(arg).__name__\n msg = f\"Magic arg for {self.variable} scale must be str, not {arg_type}.\"\n raise TypeError(msg)\n\n def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to property range.\"\"\"\n def identity(x):\n return x\n return identity\n\n def standardize(self, val: Any) -> Any:\n \"\"\"Coerce flexible property value to standardized representation.\"\"\"\n return val\n\n def _check_dict_entries(self, levels: list, values: dict) -> None:\n \"\"\"Input check when values are provided as a dictionary.\"\"\"\n missing = set(levels) - set(values)\n if missing:\n formatted = \", \".join(map(repr, sorted(missing, key=str)))\n err = f\"No entry in {self.variable} dictionary for {formatted}\"\n raise ValueError(err)\n\n def _check_list_length(self, levels: list, values: list) -> list:\n \"\"\"Input check when values are provided as a list.\"\"\"\n message = \"\"\n if len(levels) > len(values):\n message = \" \".join([\n f\"\\nThe {self.variable} list has fewer values ({len(values)})\",\n f\"than needed ({len(levels)}) and will cycle, which may\",\n \"produce an uninterpretable plot.\"\n ])\n values = [x for _, x in zip(levels, itertools.cycle(values))]\n\n elif len(values) > len(levels):\n message = \" \".join([\n f\"The {self.variable} list has more values ({len(values)})\",\n f\"than needed ({len(levels)}), which may not be intended.\",\n ])\n values = values[:len(levels)]\n\n # TODO look into custom PlotSpecWarning with better formatting\n if message:\n warnings.warn(message, UserWarning)\n\n return values\n\n\n# =================================================================================== #\n# Properties relating to spatial position of marks on the plotting axes\n# =================================================================================== #\n\n\nclass Coordinate(Property):\n \"\"\"The position of visual marks with respect to the axes of the plot.\"\"\"\n legend = False\n normed = False\n\n\n# =================================================================================== #\n# Properties with numeric values where scale range can be defined as an interval\n# =================================================================================== #\n\n\nclass IntervalProperty(Property):\n \"\"\"A numeric property where scale range can be defined as an interval.\"\"\"\n legend = True\n normed = True\n\n _default_range: tuple[float, float] = (0, 1)\n\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n return self._default_range\n\n def _forward(self, values: ArrayLike) -> ArrayLike:\n \"\"\"Transform applied to native values before linear mapping into interval.\"\"\"\n return values\n\n def _inverse(self, values: ArrayLike) -> ArrayLike:\n \"\"\"Transform applied to results of mapping that returns to native values.\"\"\"\n return values\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n\n # TODO infer continuous based on log/sqrt etc?\n\n if isinstance(arg, (list, dict)):\n return Nominal(arg)\n elif variable_type(data) == \"categorical\":\n return Nominal(arg)\n elif variable_type(data) == \"datetime\":\n return Temporal(arg)\n # TODO other variable types\n else:\n return Continuous(arg)\n\n def get_mapping(\n self, scale: Scale, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to property range.\"\"\"\n if isinstance(scale, Nominal):\n return self._get_categorical_mapping(scale, data)\n\n if scale.values is None:\n vmin, vmax = self._forward(self.default_range)\n elif isinstance(scale.values, tuple) and len(scale.values) == 2:\n vmin, vmax = self._forward(scale.values)\n else:\n if isinstance(scale.values, tuple):\n actual = f\"{len(scale.values)}-tuple\"\n else:\n actual = str(type(scale.values))\n scale_class = scale.__class__.__name__\n err = \" \".join([\n f\"Values for {self.variable} variables with {scale_class} scale\",\n f\"must be 2-tuple; not {actual}.\",\n ])\n raise TypeError(err)\n\n def mapping(x):\n return self._inverse(np.multiply(x, vmax - vmin) + vmin)\n\n return mapping\n\n def _get_categorical_mapping(\n self, scale: Nominal, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Identify evenly-spaced values using interval or explicit mapping.\"\"\"\n levels = categorical_order(data, scale.order)\n\n if isinstance(scale.values, dict):\n self._check_dict_entries(levels, scale.values)\n values = [scale.values[x] for x in levels]\n elif isinstance(scale.values, list):\n values = self._check_list_length(levels, scale.values)\n else:\n if scale.values is None:\n vmin, vmax = self.default_range\n elif isinstance(scale.values, tuple):\n vmin, vmax = scale.values\n else:\n scale_class = scale.__class__.__name__\n err = \" \".join([\n f\"Values for {self.variable} variables with {scale_class} scale\",\n f\"must be a dict, list or tuple; not {type(scale.values)}\",\n ])\n raise TypeError(err)\n\n vmin, vmax = self._forward([vmin, vmax])\n values = self._inverse(np.linspace(vmax, vmin, len(levels)))\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n out = np.full(len(x), np.nan)\n use = np.isfinite(x)\n out[use] = np.take(values, ixs[use])\n return out\n\n return mapping\n\n\nclass PointSize(IntervalProperty):\n \"\"\"Size (diameter) of a point mark, in points, with scaling by area.\"\"\"\n _default_range = 2, 8 # TODO use rcparams?\n\n def _forward(self, values):\n \"\"\"Square native values to implement linear scaling of point area.\"\"\"\n return np.square(values)\n\n def _inverse(self, values):\n \"\"\"Invert areal values back to point diameter.\"\"\"\n return np.sqrt(values)\n\n\nclass LineWidth(IntervalProperty):\n \"\"\"Thickness of a line mark, in points.\"\"\"\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"lines.linewidth\"]\n return base * .5, base * 2\n\n\nclass EdgeWidth(IntervalProperty):\n \"\"\"Thickness of the edges on a patch mark, in points.\"\"\"\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"patch.linewidth\"]\n return base * .5, base * 2\n\n\nclass Stroke(IntervalProperty):\n \"\"\"Thickness of lines that define point glyphs.\"\"\"\n _default_range = .25, 2.5\n\n\nclass Alpha(IntervalProperty):\n \"\"\"Opacity of the color values for an arbitrary mark.\"\"\"\n _default_range = .3, .95\n # TODO validate / enforce that output is in [0, 1]\n\n\nclass Offset(IntervalProperty):\n \"\"\"Offset for edge-aligned text, in point units.\"\"\"\n _default_range = 0, 5\n _legend = False\n\n\nclass FontSize(IntervalProperty):\n \"\"\"Font size for textual marks, in points.\"\"\"\n _legend = False\n\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"font.size\"]\n return base * .5, base * 2\n\n\n# =================================================================================== #\n# Properties defined by arbitrary objects with inherently nominal scaling\n# =================================================================================== #\n\n\nclass ObjectProperty(Property):\n \"\"\"A property defined by arbitrary an object, with inherently nominal scaling.\"\"\"\n legend = True\n normed = False\n\n # Object representing null data, should appear invisible when drawn by matplotlib\n # Note that we now drop nulls in Plot._plot_layer and thus may not need this\n null_value: Any = None\n\n def _default_values(self, n: int) -> list:\n raise NotImplementedError()\n\n def default_scale(self, data: Series) -> Nominal:\n return Nominal()\n\n def infer_scale(self, arg: Any, data: Series) -> Nominal:\n return Nominal(arg)\n\n def get_mapping(\n self, scale: Scale, data: Series,\n ) -> Callable[[ArrayLike], list]:\n \"\"\"Define mapping as lookup into list of object values.\"\"\"\n order = getattr(scale, \"order\", None)\n levels = categorical_order(data, order)\n n = len(levels)\n\n if isinstance(scale.values, dict):\n self._check_dict_entries(levels, scale.values)\n values = [scale.values[x] for x in levels]\n elif isinstance(scale.values, list):\n values = self._check_list_length(levels, scale.values)\n elif scale.values is None:\n values = self._default_values(n)\n else:\n msg = \" \".join([\n f\"Scale values for a {self.variable} variable must be provided\",\n f\"in a dict or list; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n values = [self.standardize(x) for x in values]\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n return [\n values[ix] if np.isfinite(x_i) else self.null_value\n for x_i, ix in zip(x, ixs)\n ]\n\n return mapping\n\n\nclass Marker(ObjectProperty):\n \"\"\"Shape of points in scatter-type marks or lines with data points marked.\"\"\"\n null_value = MarkerStyle(\"\")\n\n # TODO should we have named marker \"palettes\"? (e.g. see d3 options)\n\n # TODO need some sort of \"require_scale\" functionality\n # to raise when we get the wrong kind explicitly specified\n\n def standardize(self, val: MarkerPattern) -> MarkerStyle:\n return MarkerStyle(val)\n\n def _default_values(self, n: int) -> list[MarkerStyle]:\n \"\"\"Build an arbitrarily long list of unique marker styles.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n \"\"\"\n # Start with marker specs that are well distinguishable\n markers = [\n \"o\", \"X\", (4, 0, 45), \"P\", (4, 0, 0), (4, 1, 0), \"^\", (4, 1, 45), \"v\",\n ]\n\n # Now generate more from regular polygons of increasing order\n s = 5\n while len(markers) < n:\n a = 360 / (s + 1) / 2\n markers.extend([(s + 1, 1, a), (s + 1, 0, a), (s, 1, 0), (s, 0, 0)])\n s += 1\n\n markers = [MarkerStyle(m) for m in markers[:n]]\n\n return markers\n\n\nclass LineStyle(ObjectProperty):\n \"\"\"Dash pattern for line-type marks.\"\"\"\n null_value = \"\"\n\n def standardize(self, val: str | DashPattern) -> DashPatternWithOffset:\n return self._get_dash_pattern(val)\n\n def _default_values(self, n: int) -> list[DashPatternWithOffset]:\n \"\"\"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n \"\"\"\n # Start with dash specs that are well distinguishable\n dashes: list[str | DashPattern] = [\n \"-\", (4, 1.5), (1, 1), (3, 1.25, 1.5, 1.25), (5, 1, 1, 1),\n ]\n\n # Now programmatically build as many as we need\n p = 3\n while len(dashes) < n:\n\n # Take combinations of long and short dashes\n a = itertools.combinations_with_replacement([3, 1.25], p)\n b = itertools.combinations_with_replacement([4, 1], p)\n\n # Interleave the combinations, reversing one of the streams\n segment_list = itertools.chain(*zip(list(a)[1:-1][::-1], list(b)[1:-1]))\n\n # Now insert the gaps\n for segments in segment_list:\n gap = min(segments)\n spec = tuple(itertools.chain(*((seg, gap) for seg in segments)))\n dashes.append(spec)\n\n p += 1\n\n return [self._get_dash_pattern(x) for x in dashes]\n\n @staticmethod\n def _get_dash_pattern(style: str | DashPattern) -> DashPatternWithOffset:\n \"\"\"Convert linestyle arguments to dash pattern with offset.\"\"\"\n # Copied and modified from Matplotlib 3.4\n # go from short hand -> full strings\n ls_mapper = {\"-\": \"solid\", \"--\": \"dashed\", \"-.\": \"dashdot\", \":\": \"dotted\"}\n if isinstance(style, str):\n style = ls_mapper.get(style, style)\n # un-dashed styles\n if style in [\"solid\", \"none\", \"None\"]:\n offset = 0\n dashes = None\n # dashed styles\n elif style in [\"dashed\", \"dashdot\", \"dotted\"]:\n offset = 0\n dashes = tuple(mpl.rcParams[f\"lines.{style}_pattern\"])\n else:\n options = [*ls_mapper.values(), *ls_mapper.keys()]\n msg = f\"Linestyle string must be one of {options}, not {repr(style)}.\"\n raise ValueError(msg)\n\n elif isinstance(style, tuple):\n if len(style) > 1 and isinstance(style[1], tuple):\n offset, dashes = style\n elif len(style) > 1 and style[1] is None:\n offset, dashes = style\n else:\n offset = 0\n dashes = style\n else:\n val_type = type(style).__name__\n msg = f\"Linestyle must be str or tuple, not {val_type}.\"\n raise TypeError(msg)\n\n # Normalize offset to be positive and shorter than the dash cycle\n if dashes is not None:\n try:\n dsum = sum(dashes)\n except TypeError as err:\n msg = f\"Invalid dash pattern: {dashes}\"\n raise TypeError(msg) from err\n if dsum:\n offset %= dsum\n\n return offset, dashes\n\n\nclass TextAlignment(ObjectProperty):\n legend = False\n\n\nclass HorizontalAlignment(TextAlignment):\n\n def _default_values(self, n: int) -> list:\n vals = itertools.cycle([\"left\", \"right\"])\n return [next(vals) for _ in range(n)]\n\n\nclass VerticalAlignment(TextAlignment):\n\n def _default_values(self, n: int) -> list:\n vals = itertools.cycle([\"top\", \"bottom\"])\n return [next(vals) for _ in range(n)]\n\n\n# =================================================================================== #\n# Properties with RGB(A) color values\n# =================================================================================== #\n\n\nclass Color(Property):\n \"\"\"Color, as RGB(A), scalable with nominal palettes or continuous gradients.\"\"\"\n legend = True\n normed = True\n\n def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple:\n # Return color with alpha channel only if the input spec has it\n # This is so that RGBA colors can override the Alpha property\n if to_rgba(val) != to_rgba(val, 1):\n return to_rgba(val)\n else:\n return to_rgb(val)\n\n def _standardize_color_sequence(self, colors: ArrayLike) -> ArrayLike:\n \"\"\"Convert color sequence to RGB(A) array, preserving but not adding alpha.\"\"\"\n def has_alpha(x):\n return to_rgba(x) != to_rgba(x, 1)\n\n if isinstance(colors, np.ndarray):\n needs_alpha = colors.shape[1] == 4\n else:\n needs_alpha = any(has_alpha(x) for x in colors)\n\n if needs_alpha:\n return to_rgba_array(colors)\n else:\n return to_rgba_array(colors)[:, :3]\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n # TODO when inferring Continuous without data, verify type\n\n # TODO need to rethink the variable type system\n # (e.g. boolean, ordered categories as Ordinal, etc)..\n var_type = variable_type(data, boolean_type=\"categorical\")\n\n if isinstance(arg, (dict, list)):\n return Nominal(arg)\n\n if isinstance(arg, tuple):\n if var_type == \"categorical\":\n # TODO It seems reasonable to allow a gradient mapping for nominal\n # scale but it also feels \"technically\" wrong. Should this infer\n # Ordinal with categorical data and, if so, verify orderedness?\n return Nominal(arg)\n return Continuous(arg)\n\n if callable(arg):\n return Continuous(arg)\n\n # TODO Do we accept str like \"log\", \"pow\", etc. for semantics?\n\n # TODO what about\n # - Temporal? (i.e. datetime)\n # - Boolean?\n\n if not isinstance(arg, str):\n msg = \" \".join([\n f\"A single scale argument for {self.variable} variables must be\",\n f\"a string, dict, tuple, list, or callable, not {type(arg)}.\"\n ])\n raise TypeError(msg)\n\n if arg in QUAL_PALETTES:\n return Nominal(arg)\n elif var_type == \"numeric\":\n return Continuous(arg)\n # TODO implement scales for date variables and any others.\n else:\n return Nominal(arg)\n\n def _get_categorical_mapping(self, scale, data):\n \"\"\"Define mapping as lookup in list of discrete color values.\"\"\"\n levels = categorical_order(data, scale.order)\n n = len(levels)\n values = scale.values\n\n if isinstance(values, dict):\n self._check_dict_entries(levels, values)\n # TODO where to ensure that dict values have consistent representation?\n colors = [values[x] for x in levels]\n elif isinstance(values, list):\n colors = self._check_list_length(levels, scale.values)\n elif isinstance(values, tuple):\n colors = blend_palette(values, n)\n elif isinstance(values, str):\n colors = color_palette(values, n)\n elif values is None:\n if n <= len(get_color_cycle()):\n # Use current (global) default palette\n colors = color_palette(n_colors=n)\n else:\n colors = color_palette(\"husl\", n)\n else:\n scale_class = scale.__class__.__name__\n msg = \" \".join([\n f\"Scale values for {self.variable} with a {scale_class} mapping\",\n f\"must be string, list, tuple, or dict; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n # If color specified here has alpha channel, it will override alpha property\n colors = self._standardize_color_sequence(colors)\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n use = np.isfinite(x)\n out = np.full((len(ixs), colors.shape[1]), np.nan)\n out[use] = np.take(colors, ixs[use], axis=0)\n return out\n\n return mapping\n\n def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to color values.\"\"\"\n # TODO what is best way to do this conditional?\n # Should it be class-based or should classes have behavioral attributes?\n if isinstance(scale, Nominal):\n return self._get_categorical_mapping(scale, data)\n\n if scale.values is None:\n # TODO Rethink best default continuous color gradient\n mapping = color_palette(\"ch:\", as_cmap=True)\n elif isinstance(scale.values, tuple):\n # TODO blend_palette will strip alpha, but we should support\n # interpolation on all four channels\n mapping = blend_palette(scale.values, as_cmap=True)\n elif isinstance(scale.values, str):\n # TODO for matplotlib colormaps this will clip extremes, which is\n # different from what using the named colormap directly would do\n # This may or may not be desireable.\n mapping = color_palette(scale.values, as_cmap=True)\n elif callable(scale.values):\n mapping = scale.values\n else:\n scale_class = scale.__class__.__name__\n msg = \" \".join([\n f\"Scale values for {self.variable} with a {scale_class} mapping\",\n f\"must be string, tuple, or callable; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n def _mapping(x):\n # Remove alpha channel so it does not override alpha property downstream\n # TODO this will need to be more flexible to support RGBA tuples (see above)\n invalid = ~np.isfinite(x)\n out = mapping(x)[:, :3]\n out[invalid] = np.nan\n return out\n\n return _mapping\n\n\n# =================================================================================== #\n# Properties that can take only two states\n# =================================================================================== #\n\n\nclass Fill(Property):\n \"\"\"Boolean property of points/bars/patches that can be solid or outlined.\"\"\"\n legend = True\n normed = False\n\n # TODO default to Nominal scale always?\n # Actually this will just not work with Continuous (except 0/1), suggesting we need\n # an abstraction for failing gracefully on bad Property <> Scale interactions\n\n def standardize(self, val: Any) -> bool:\n return bool(val)\n\n def _default_values(self, n: int) -> list:\n \"\"\"Return a list of n values, alternating True and False.\"\"\"\n if n > 2:\n msg = \" \".join([\n f\"The variable assigned to {self.variable} has more than two levels,\",\n f\"so {self.variable} values will cycle and may be uninterpretable\",\n ])\n # TODO fire in a \"nice\" way (see above)\n warnings.warn(msg, UserWarning)\n return [x for x, _ in zip(itertools.cycle([True, False]), range(n))]\n\n def default_scale(self, data: Series) -> Nominal:\n \"\"\"Given data, initialize appropriate scale class.\"\"\"\n return Nominal()\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n # TODO infer Boolean where possible?\n return Nominal(arg)\n\n def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps each data value to True or False.\"\"\"\n # TODO categorical_order is going to return [False, True] for booleans,\n # and [0, 1] for binary, but the default values order is [True, False].\n # We should special case this to handle it properly, or change\n # categorical_order to not \"sort\" booleans. Note that we need to sync with\n # what's going to happen upstream in the scale, so we can't just do it here.\n order = getattr(scale, \"order\", None)\n levels = categorical_order(data, order)\n\n if isinstance(scale.values, list):\n values = [bool(x) for x in scale.values]\n elif isinstance(scale.values, dict):\n values = [bool(scale.values[x]) for x in levels]\n elif scale.values is None:\n values = self._default_values(len(levels))\n else:\n msg = \" \".join([\n f\"Scale values for {self.variable} must be passed in\",\n f\"a list or dict; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n return [\n values[ix] if np.isfinite(x_i) else False\n for x_i, ix in zip(x, ixs)\n ]\n\n return mapping\n\n\n# =================================================================================== #\n# Enumeration of properties for use by Plot and Mark classes\n# =================================================================================== #\n# TODO turn this into a property registry with hooks, etc.\n# TODO Users do not interact directly with properties, so how to document them?\n\n\nPROPERTY_CLASSES = {\n \"x\": Coordinate,\n \"y\": Coordinate,\n \"color\": Color,\n \"alpha\": Alpha,\n \"fill\": Fill,\n \"marker\": Marker,\n \"pointsize\": PointSize,\n \"stroke\": Stroke,\n \"linewidth\": LineWidth,\n \"linestyle\": LineStyle,\n \"fillcolor\": Color,\n \"fillalpha\": Alpha,\n \"edgewidth\": EdgeWidth,\n \"edgestyle\": LineStyle,\n \"edgecolor\": Color,\n \"edgealpha\": Alpha,\n \"text\": Property,\n \"halign\": HorizontalAlignment,\n \"valign\": VerticalAlignment,\n \"offset\": Offset,\n \"fontsize\": FontSize,\n \"xmin\": Coordinate,\n \"xmax\": Coordinate,\n \"ymin\": Coordinate,\n \"ymax\": Coordinate,\n \"group\": Property,\n # TODO pattern?\n # TODO gradient?\n}\n\nPROPERTIES = {var: cls(var) for var, cls in PROPERTY_CLASSES.items()}\n"},{"attributeType":"int | None","col":8,"comment":"null","endLoc":106,"id":1091,"name":"wrap","nodeType":"Attribute","startLoc":106,"text":"self.wrap"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":1565,"id":1092,"name":"_lut_dict","nodeType":"Attribute","startLoc":1565,"text":"_lut_dict"},{"attributeType":"list","col":0,"comment":"null","endLoc":344,"id":1093,"name":"List","nodeType":"Attribute","startLoc":344,"text":"List"},{"attributeType":"_SpecialForm","col":0,"comment":"null","endLoc":200,"id":1094,"name":"Union","nodeType":"Attribute","startLoc":200,"text":"Union"},{"className":"Coordinate","col":0,"comment":"The position of visual marks with respect to the axes of the plot.","endLoc":151,"id":1095,"nodeType":"Class","startLoc":148,"text":"class Coordinate(Property):\n \"\"\"The position of visual marks with respect to the axes of the plot.\"\"\"\n legend = False\n normed = False"},{"attributeType":"dict","col":8,"comment":"null","endLoc":39,"id":1096,"name":"subplot_spec","nodeType":"Attribute","startLoc":39,"text":"self.subplot_spec"},{"attributeType":"null","col":8,"comment":"null","endLoc":100,"id":1097,"name":"n_subplots","nodeType":"Attribute","startLoc":100,"text":"self.n_subplots"},{"attributeType":"null","col":16,"comment":"null","endLoc":4,"id":1098,"name":"np","nodeType":"Attribute","startLoc":4,"text":"np"},{"attributeType":"bool","col":4,"comment":"null","endLoc":150,"id":1099,"name":"legend","nodeType":"Attribute","startLoc":150,"text":"legend"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":1100,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":6,"id":1101,"name":"plt","nodeType":"Attribute","startLoc":6,"text":"plt"},{"attributeType":"bool","col":4,"comment":"null","endLoc":151,"id":1102,"name":"normed","nodeType":"Attribute","startLoc":151,"text":"normed"},{"col":0,"comment":"","endLoc":1,"header":"subplots.py#","id":1103,"name":"","nodeType":"Function","startLoc":1,"text":"if TYPE_CHECKING: # TODO move to seaborn._core.typing?\n from seaborn._core.plot import FacetSpec, PairSpec\n from matplotlib.figure import SubFigure"},{"className":"IntervalProperty","col":0,"comment":"A numeric property where scale range can be defined as an interval.","endLoc":256,"id":1104,"nodeType":"Class","startLoc":159,"text":"class IntervalProperty(Property):\n \"\"\"A numeric property where scale range can be defined as an interval.\"\"\"\n legend = True\n normed = True\n\n _default_range: tuple[float, float] = (0, 1)\n\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n return self._default_range\n\n def _forward(self, values: ArrayLike) -> ArrayLike:\n \"\"\"Transform applied to native values before linear mapping into interval.\"\"\"\n return values\n\n def _inverse(self, values: ArrayLike) -> ArrayLike:\n \"\"\"Transform applied to results of mapping that returns to native values.\"\"\"\n return values\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n\n # TODO infer continuous based on log/sqrt etc?\n\n if isinstance(arg, (list, dict)):\n return Nominal(arg)\n elif variable_type(data) == \"categorical\":\n return Nominal(arg)\n elif variable_type(data) == \"datetime\":\n return Temporal(arg)\n # TODO other variable types\n else:\n return Continuous(arg)\n\n def get_mapping(\n self, scale: Scale, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to property range.\"\"\"\n if isinstance(scale, Nominal):\n return self._get_categorical_mapping(scale, data)\n\n if scale.values is None:\n vmin, vmax = self._forward(self.default_range)\n elif isinstance(scale.values, tuple) and len(scale.values) == 2:\n vmin, vmax = self._forward(scale.values)\n else:\n if isinstance(scale.values, tuple):\n actual = f\"{len(scale.values)}-tuple\"\n else:\n actual = str(type(scale.values))\n scale_class = scale.__class__.__name__\n err = \" \".join([\n f\"Values for {self.variable} variables with {scale_class} scale\",\n f\"must be 2-tuple; not {actual}.\",\n ])\n raise TypeError(err)\n\n def mapping(x):\n return self._inverse(np.multiply(x, vmax - vmin) + vmin)\n\n return mapping\n\n def _get_categorical_mapping(\n self, scale: Nominal, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Identify evenly-spaced values using interval or explicit mapping.\"\"\"\n levels = categorical_order(data, scale.order)\n\n if isinstance(scale.values, dict):\n self._check_dict_entries(levels, scale.values)\n values = [scale.values[x] for x in levels]\n elif isinstance(scale.values, list):\n values = self._check_list_length(levels, scale.values)\n else:\n if scale.values is None:\n vmin, vmax = self.default_range\n elif isinstance(scale.values, tuple):\n vmin, vmax = scale.values\n else:\n scale_class = scale.__class__.__name__\n err = \" \".join([\n f\"Values for {self.variable} variables with {scale_class} scale\",\n f\"must be a dict, list or tuple; not {type(scale.values)}\",\n ])\n raise TypeError(err)\n\n vmin, vmax = self._forward([vmin, vmax])\n values = self._inverse(np.linspace(vmax, vmin, len(levels)))\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n out = np.full(len(x), np.nan)\n use = np.isfinite(x)\n out[use] = np.take(values, ixs[use])\n return out\n\n return mapping"},{"col":4,"comment":"Min and max values used by default for semantic mapping.","endLoc":169,"header":"@property\n def default_range(self) -> tuple[float, float]","id":1105,"name":"default_range","nodeType":"Function","startLoc":166,"text":"@property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n return self._default_range"},{"col":4,"comment":"Transform applied to native values before linear mapping into interval.","endLoc":173,"header":"def _forward(self, values: ArrayLike) -> ArrayLike","id":1106,"name":"_forward","nodeType":"Function","startLoc":171,"text":"def _forward(self, values: ArrayLike) -> ArrayLike:\n \"\"\"Transform applied to native values before linear mapping into interval.\"\"\"\n return values"},{"col":4,"comment":"Transform applied to results of mapping that returns to native values.","endLoc":177,"header":"def _inverse(self, values: ArrayLike) -> ArrayLike","id":1107,"name":"_inverse","nodeType":"Function","startLoc":175,"text":"def _inverse(self, values: ArrayLike) -> ArrayLike:\n \"\"\"Transform applied to results of mapping that returns to native values.\"\"\"\n return values"},{"col":4,"comment":"Given data and a scaling argument, initialize appropriate scale class.","endLoc":192,"header":"def infer_scale(self, arg: Any, data: Series) -> Scale","id":1108,"name":"infer_scale","nodeType":"Function","startLoc":179,"text":"def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n\n # TODO infer continuous based on log/sqrt etc?\n\n if isinstance(arg, (list, dict)):\n return Nominal(arg)\n elif variable_type(data) == \"categorical\":\n return Nominal(arg)\n elif variable_type(data) == \"datetime\":\n return Temporal(arg)\n # TODO other variable types\n else:\n return Continuous(arg)"},{"col":0,"comment":"Resample one or more arrays with replacement and store aggregate values.\n\n Positional arguments are a sequence of arrays to bootstrap along the first\n axis and pass to a summary function.\n\n Keyword arguments:\n n_boot : int, default=10000\n Number of iterations\n axis : int, default=None\n Will pass axis to ``func`` as a keyword argument.\n units : array, default=None\n Array of sampling unit IDs. When used the bootstrap resamples units\n and then observations within units instead of individual\n datapoints.\n func : string or callable, default=\"mean\"\n Function to call on the args that are passed in. If string, uses as\n name of function in the numpy namespace. If nans are present in the\n data, will try to use nan-aware version of named function.\n seed : Generator | SeedSequence | RandomState | int | None\n Seed for the random number generator; useful if you want\n reproducible resamples.\n\n Returns\n -------\n boot_dist: array\n array of bootstrapped statistic values\n\n ","endLoc":99,"header":"def bootstrap(*args, **kwargs)","id":1109,"name":"bootstrap","nodeType":"Function","startLoc":7,"text":"def bootstrap(*args, **kwargs):\n \"\"\"Resample one or more arrays with replacement and store aggregate values.\n\n Positional arguments are a sequence of arrays to bootstrap along the first\n axis and pass to a summary function.\n\n Keyword arguments:\n n_boot : int, default=10000\n Number of iterations\n axis : int, default=None\n Will pass axis to ``func`` as a keyword argument.\n units : array, default=None\n Array of sampling unit IDs. When used the bootstrap resamples units\n and then observations within units instead of individual\n datapoints.\n func : string or callable, default=\"mean\"\n Function to call on the args that are passed in. If string, uses as\n name of function in the numpy namespace. If nans are present in the\n data, will try to use nan-aware version of named function.\n seed : Generator | SeedSequence | RandomState | int | None\n Seed for the random number generator; useful if you want\n reproducible resamples.\n\n Returns\n -------\n boot_dist: array\n array of bootstrapped statistic values\n\n \"\"\"\n # Ensure list of arrays are same length\n if len(np.unique(list(map(len, args)))) > 1:\n raise ValueError(\"All input arrays must have the same length\")\n n = len(args[0])\n\n # Default keyword arguments\n n_boot = kwargs.get(\"n_boot\", 10000)\n func = kwargs.get(\"func\", \"mean\")\n axis = kwargs.get(\"axis\", None)\n units = kwargs.get(\"units\", None)\n random_seed = kwargs.get(\"random_seed\", None)\n if random_seed is not None:\n msg = \"`random_seed` has been renamed to `seed` and will be removed\"\n warnings.warn(msg)\n seed = kwargs.get(\"seed\", random_seed)\n if axis is None:\n func_kwargs = dict()\n else:\n func_kwargs = dict(axis=axis)\n\n # Initialize the resampler\n rng = _handle_random_seed(seed)\n\n # Coerce to arrays\n args = list(map(np.asarray, args))\n if units is not None:\n units = np.asarray(units)\n\n if isinstance(func, str):\n\n # Allow named numpy functions\n f = getattr(np, func)\n\n # Try to use nan-aware version of function if necessary\n missing_data = np.isnan(np.sum(np.column_stack(args)))\n\n if missing_data and not func.startswith(\"nan\"):\n nanf = getattr(np, f\"nan{func}\", None)\n if nanf is None:\n msg = f\"Data contain nans but no nan-aware version of `{func}` found\"\n warnings.warn(msg, UserWarning)\n else:\n f = nanf\n\n else:\n f = func\n\n # Handle numpy changes\n try:\n integers = rng.integers\n except AttributeError:\n integers = rng.randint\n\n # Do the bootstrap\n if units is not None:\n return _structured_bootstrap(args, n_boot, units, f,\n func_kwargs, integers)\n\n boot_dist = []\n for i in range(int(n_boot)):\n resampler = integers(0, n, n, dtype=np.intp) # intp is indexing dtype\n sample = [a.take(resampler, axis=0) for a in args]\n boot_dist.append(f(*sample, **func_kwargs))\n return np.array(boot_dist)"},{"attributeType":"null","col":0,"comment":"null","endLoc":26,"id":1110,"name":"networks","nodeType":"Attribute","startLoc":26,"text":"networks"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":1111,"name":"network_colors","nodeType":"Attribute","startLoc":27,"text":"network_colors"},{"attributeType":"ClusterGrid","col":0,"comment":"null","endLoc":30,"id":1112,"name":"g","nodeType":"Attribute","startLoc":30,"text":"g"},{"col":4,"comment":"Add axis labels if not present, set visibility to match ticklabels.","endLoc":1332,"header":"def _add_axis_labels(self, ax, default_x=\"\", default_y=\"\")","id":1113,"name":"_add_axis_labels","nodeType":"Function","startLoc":1321,"text":"def _add_axis_labels(self, ax, default_x=\"\", default_y=\"\"):\n \"\"\"Add axis labels if not present, set visibility to match ticklabels.\"\"\"\n # TODO ax could default to None and use attached axes if present\n # but what to do about the case of facets? Currently using FacetGrid's\n # set_axis_labels method, which doesn't add labels to the interior even\n # when the axes are not shared. Maybe that makes sense?\n if not ax.get_xlabel():\n x_visible = any(t.get_visible() for t in ax.get_xticklabels())\n ax.set_xlabel(self.variables.get(\"x\", default_x), visible=x_visible)\n if not ax.get_ylabel():\n y_visible = any(t.get_visible() for t in ax.get_yticklabels())\n ax.set_ylabel(self.variables.get(\"y\", default_y), visible=y_visible)"},{"fileName":"data.py","filePath":"seaborn/_core","id":1114,"nodeType":"File","text":"\"\"\"\nComponents for parsing variable assignments and internally representing plot data.\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Mapping, Sized\nfrom typing import cast\n\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom seaborn._core.typing import DataSource, VariableSpec, ColumnName\n\n\nclass PlotData:\n \"\"\"\n Data table with plot variable schema and mapping to original names.\n\n Contains logic for parsing variable specification arguments and updating\n the table with layer-specific data and/or mappings.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Attributes\n ----------\n frame\n Data table with column names having defined plot variables.\n names\n Dictionary mapping plot variable names to names in source data structure(s).\n ids\n Dictionary mapping plot variable names to unique data source identifiers.\n\n \"\"\"\n frame: DataFrame\n frames: dict[tuple, DataFrame]\n names: dict[str, str | None]\n ids: dict[str, str | int]\n source_data: DataSource\n source_vars: dict[str, VariableSpec]\n\n def __init__(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ):\n\n frame, names, ids = self._assign_variables(data, variables)\n\n self.frame = frame\n self.names = names\n self.ids = ids\n\n self.frames = {} # TODO this is a hack, remove\n\n self.source_data = data\n self.source_vars = variables\n\n def __contains__(self, key: str) -> bool:\n \"\"\"Boolean check on whether a variable is defined in this dataset.\"\"\"\n if self.frame is None:\n return any(key in df for df in self.frames.values())\n return key in self.frame\n\n def join(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec] | None,\n ) -> PlotData:\n \"\"\"Add, replace, or drop variables and return as a new dataset.\"\"\"\n # Inherit the original source of the upsteam data by default\n if data is None:\n data = self.source_data\n\n # TODO allow `data` to be a function (that is called on the source data?)\n\n if not variables:\n variables = self.source_vars\n\n # Passing var=None implies that we do not want that variable in this layer\n disinherit = [k for k, v in variables.items() if v is None]\n\n # Create a new dataset with just the info passed here\n new = PlotData(data, variables)\n\n # -- Update the inherited DataSource with this new information\n\n drop_cols = [k for k in self.frame if k in new.frame or k in disinherit]\n parts = [self.frame.drop(columns=drop_cols), new.frame]\n\n # Because we are combining distinct columns, this is perhaps more\n # naturally thought of as a \"merge\"/\"join\". But using concat because\n # some simple testing suggests that it is marginally faster.\n frame = pd.concat(parts, axis=1, sort=False, copy=False)\n\n names = {k: v for k, v in self.names.items() if k not in disinherit}\n names.update(new.names)\n\n ids = {k: v for k, v in self.ids.items() if k not in disinherit}\n ids.update(new.ids)\n\n new.frame = frame\n new.names = names\n new.ids = ids\n\n # Multiple chained operations should always inherit from the original object\n new.source_data = self.source_data\n new.source_vars = self.source_vars\n\n return new\n\n def _assign_variables(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataFrame, dict[str, str | None], dict[str, str | int]]:\n \"\"\"\n Assign values for plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Returns\n -------\n frame\n Table mapping seaborn variables (x, y, color, ...) to data vectors.\n names\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n ids\n Like the `names` dict, but `None` values are replaced by the `id()`\n of the data object that defined the variable.\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in `data`, or when they are\n non-indexed vector datatypes that have a different length from `data`.\n\n \"\"\"\n source_data: Mapping | DataFrame\n frame: DataFrame\n names: dict[str, str | None]\n ids: dict[str, str | int]\n\n plot_data = {}\n names = {}\n ids = {}\n\n given_data = data is not None\n if data is not None:\n source_data = data\n else:\n # Data is optional; all variables can be defined as vectors\n # But simplify downstream code by always having a usable source data object\n source_data = {}\n\n # TODO Generally interested in accepting a generic DataFrame interface\n # Track https://data-apis.org/ for development\n\n # Variables can also be extracted from the index of a DataFrame\n if isinstance(source_data, pd.DataFrame):\n index = source_data.index.to_frame().to_dict(\"series\")\n else:\n index = {}\n\n for key, val in variables.items():\n\n # Simply ignore variables with no specification\n if val is None:\n continue\n\n # Try to treat the argument as a key for the data collection.\n # But be flexible about what can be used as a key.\n # Usually it will be a string, but allow other hashables when\n # taking from the main data object. Allow only strings to reference\n # fields in the index, because otherwise there is too much ambiguity.\n\n # TODO this will be rendered unnecessary by the following pandas fix:\n # https://github.com/pandas-dev/pandas/pull/41283\n try:\n hash(val)\n val_is_hashable = True\n except TypeError:\n val_is_hashable = False\n\n val_as_data_key = (\n # See https://github.com/pandas-dev/pandas/pull/41283\n # (isinstance(val, abc.Hashable) and val in source_data)\n (val_is_hashable and val in source_data)\n or (isinstance(val, str) and val in index)\n )\n\n if val_as_data_key:\n val = cast(ColumnName, val)\n if val in source_data:\n plot_data[key] = source_data[val]\n elif val in index:\n plot_data[key] = index[val]\n names[key] = ids[key] = str(val)\n\n elif isinstance(val, str):\n\n # This looks like a column name but, lookup failed.\n\n err = f\"Could not interpret value `{val}` for `{key}`. \"\n if not given_data:\n err += \"Value is a string, but `data` was not passed.\"\n else:\n err += \"An entry with this name does not appear in `data`.\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, assume the value somehow represents data\n\n # Ignore empty data structures\n if isinstance(val, Sized) and len(val) == 0:\n continue\n\n # If vector has no index, it must match length of data table\n if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series):\n if isinstance(val, Sized) and len(data) != len(val):\n val_cls = val.__class__.__name__\n err = (\n f\"Length of {val_cls} vectors must match length of `data`\"\n f\" when both are used, but `data` has length {len(data)}\"\n f\" and the vector passed to `{key}` has length {len(val)}.\"\n )\n raise ValueError(err)\n\n plot_data[key] = val\n\n # Try to infer the original name using pandas-like metadata\n if hasattr(val, \"name\"):\n names[key] = ids[key] = str(val.name) # type: ignore # mypy/1424\n else:\n names[key] = None\n ids[key] = id(val)\n\n # Construct a tidy plot DataFrame. This will convert a number of\n # types automatically, aligning on index in case of pandas objects\n # TODO Note: this fails when variable specs *only* have scalars!\n frame = pd.DataFrame(plot_data)\n\n return frame, names, ids\n"},{"className":"Sized","col":0,"comment":"null","endLoc":410,"id":1115,"nodeType":"Class","startLoc":407,"text":"@runtime_checkable\nclass Sized(Protocol, metaclass=ABCMeta):\n @abstractmethod\n def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":410,"header":"@abstractmethod\n def __len__(self) -> int","id":1116,"name":"__len__","nodeType":"Function","startLoc":409,"text":"@abstractmethod\n def __len__(self) -> int: ..."},{"col":0,"comment":"null","endLoc":881,"header":"@overload\ndef cast(typ: type[_T], val: Any) -> _T","id":1117,"name":"cast","nodeType":"Function","startLoc":880,"text":"@overload\ndef cast(typ: type[_T], val: Any) -> _T: ..."},{"col":0,"comment":"null","endLoc":883,"header":"@overload\ndef cast(typ: str, val: Any) -> Any","id":1118,"name":"cast","nodeType":"Function","startLoc":882,"text":"@overload\ndef cast(typ: str, val: Any) -> Any: ..."},{"col":0,"comment":"null","endLoc":885,"header":"@overload\ndef cast(typ: object, val: Any) -> Any","id":1119,"name":"cast","nodeType":"Function","startLoc":884,"text":"@overload\ndef cast(typ: object, val: Any) -> Any: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":20,"id":1120,"name":"DataSource","nodeType":"Attribute","startLoc":20,"text":"DataSource"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":1121,"name":"VariableSpec","nodeType":"Attribute","startLoc":17,"text":"VariableSpec"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":1122,"name":"ColumnName","nodeType":"Attribute","startLoc":12,"text":"ColumnName"},{"className":"PlotData","col":0,"comment":"\n Data table with plot variable schema and mapping to original names.\n\n Contains logic for parsing variable specification arguments and updating\n the table with layer-specific data and/or mappings.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Attributes\n ----------\n frame\n Data table with column names having defined plot variables.\n names\n Dictionary mapping plot variable names to names in source data structure(s).\n ids\n Dictionary mapping plot variable names to unique data source identifiers.\n\n ","endLoc":260,"id":1123,"nodeType":"Class","startLoc":15,"text":"class PlotData:\n \"\"\"\n Data table with plot variable schema and mapping to original names.\n\n Contains logic for parsing variable specification arguments and updating\n the table with layer-specific data and/or mappings.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Attributes\n ----------\n frame\n Data table with column names having defined plot variables.\n names\n Dictionary mapping plot variable names to names in source data structure(s).\n ids\n Dictionary mapping plot variable names to unique data source identifiers.\n\n \"\"\"\n frame: DataFrame\n frames: dict[tuple, DataFrame]\n names: dict[str, str | None]\n ids: dict[str, str | int]\n source_data: DataSource\n source_vars: dict[str, VariableSpec]\n\n def __init__(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ):\n\n frame, names, ids = self._assign_variables(data, variables)\n\n self.frame = frame\n self.names = names\n self.ids = ids\n\n self.frames = {} # TODO this is a hack, remove\n\n self.source_data = data\n self.source_vars = variables\n\n def __contains__(self, key: str) -> bool:\n \"\"\"Boolean check on whether a variable is defined in this dataset.\"\"\"\n if self.frame is None:\n return any(key in df for df in self.frames.values())\n return key in self.frame\n\n def join(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec] | None,\n ) -> PlotData:\n \"\"\"Add, replace, or drop variables and return as a new dataset.\"\"\"\n # Inherit the original source of the upsteam data by default\n if data is None:\n data = self.source_data\n\n # TODO allow `data` to be a function (that is called on the source data?)\n\n if not variables:\n variables = self.source_vars\n\n # Passing var=None implies that we do not want that variable in this layer\n disinherit = [k for k, v in variables.items() if v is None]\n\n # Create a new dataset with just the info passed here\n new = PlotData(data, variables)\n\n # -- Update the inherited DataSource with this new information\n\n drop_cols = [k for k in self.frame if k in new.frame or k in disinherit]\n parts = [self.frame.drop(columns=drop_cols), new.frame]\n\n # Because we are combining distinct columns, this is perhaps more\n # naturally thought of as a \"merge\"/\"join\". But using concat because\n # some simple testing suggests that it is marginally faster.\n frame = pd.concat(parts, axis=1, sort=False, copy=False)\n\n names = {k: v for k, v in self.names.items() if k not in disinherit}\n names.update(new.names)\n\n ids = {k: v for k, v in self.ids.items() if k not in disinherit}\n ids.update(new.ids)\n\n new.frame = frame\n new.names = names\n new.ids = ids\n\n # Multiple chained operations should always inherit from the original object\n new.source_data = self.source_data\n new.source_vars = self.source_vars\n\n return new\n\n def _assign_variables(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataFrame, dict[str, str | None], dict[str, str | int]]:\n \"\"\"\n Assign values for plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Returns\n -------\n frame\n Table mapping seaborn variables (x, y, color, ...) to data vectors.\n names\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n ids\n Like the `names` dict, but `None` values are replaced by the `id()`\n of the data object that defined the variable.\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in `data`, or when they are\n non-indexed vector datatypes that have a different length from `data`.\n\n \"\"\"\n source_data: Mapping | DataFrame\n frame: DataFrame\n names: dict[str, str | None]\n ids: dict[str, str | int]\n\n plot_data = {}\n names = {}\n ids = {}\n\n given_data = data is not None\n if data is not None:\n source_data = data\n else:\n # Data is optional; all variables can be defined as vectors\n # But simplify downstream code by always having a usable source data object\n source_data = {}\n\n # TODO Generally interested in accepting a generic DataFrame interface\n # Track https://data-apis.org/ for development\n\n # Variables can also be extracted from the index of a DataFrame\n if isinstance(source_data, pd.DataFrame):\n index = source_data.index.to_frame().to_dict(\"series\")\n else:\n index = {}\n\n for key, val in variables.items():\n\n # Simply ignore variables with no specification\n if val is None:\n continue\n\n # Try to treat the argument as a key for the data collection.\n # But be flexible about what can be used as a key.\n # Usually it will be a string, but allow other hashables when\n # taking from the main data object. Allow only strings to reference\n # fields in the index, because otherwise there is too much ambiguity.\n\n # TODO this will be rendered unnecessary by the following pandas fix:\n # https://github.com/pandas-dev/pandas/pull/41283\n try:\n hash(val)\n val_is_hashable = True\n except TypeError:\n val_is_hashable = False\n\n val_as_data_key = (\n # See https://github.com/pandas-dev/pandas/pull/41283\n # (isinstance(val, abc.Hashable) and val in source_data)\n (val_is_hashable and val in source_data)\n or (isinstance(val, str) and val in index)\n )\n\n if val_as_data_key:\n val = cast(ColumnName, val)\n if val in source_data:\n plot_data[key] = source_data[val]\n elif val in index:\n plot_data[key] = index[val]\n names[key] = ids[key] = str(val)\n\n elif isinstance(val, str):\n\n # This looks like a column name but, lookup failed.\n\n err = f\"Could not interpret value `{val}` for `{key}`. \"\n if not given_data:\n err += \"Value is a string, but `data` was not passed.\"\n else:\n err += \"An entry with this name does not appear in `data`.\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, assume the value somehow represents data\n\n # Ignore empty data structures\n if isinstance(val, Sized) and len(val) == 0:\n continue\n\n # If vector has no index, it must match length of data table\n if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series):\n if isinstance(val, Sized) and len(data) != len(val):\n val_cls = val.__class__.__name__\n err = (\n f\"Length of {val_cls} vectors must match length of `data`\"\n f\" when both are used, but `data` has length {len(data)}\"\n f\" and the vector passed to `{key}` has length {len(val)}.\"\n )\n raise ValueError(err)\n\n plot_data[key] = val\n\n # Try to infer the original name using pandas-like metadata\n if hasattr(val, \"name\"):\n names[key] = ids[key] = str(val.name) # type: ignore # mypy/1424\n else:\n names[key] = None\n ids[key] = id(val)\n\n # Construct a tidy plot DataFrame. This will convert a number of\n # types automatically, aligning on index in case of pandas objects\n # TODO Note: this fails when variable specs *only* have scalars!\n frame = pd.DataFrame(plot_data)\n\n return frame, names, ids"},{"col":4,"comment":"null","endLoc":64,"header":"def __init__(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n )","id":1124,"name":"__init__","nodeType":"Function","startLoc":49,"text":"def __init__(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ):\n\n frame, names, ids = self._assign_variables(data, variables)\n\n self.frame = frame\n self.names = names\n self.ids = ids\n\n self.frames = {} # TODO this is a hack, remove\n\n self.source_data = data\n self.source_vars = variables"},{"col":0,"comment":"","endLoc":6,"header":"structured_heatmap.py#","id":1126,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nDiscovering structure in heatmap data\n=====================================\n\n_thumb: .3, .25\n\"\"\"\n\nsns.set_theme()\n\ndf = sns.load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n\nused_networks = [1, 5, 6, 7, 8, 12, 13, 17]\n\nused_columns = (df.columns.get_level_values(\"network\")\n .astype(int)\n .isin(used_networks))\n\ndf = df.loc[:, used_columns]\n\nnetwork_pal = sns.husl_palette(8, s=.45)\n\nnetwork_lut = dict(zip(map(str, used_networks), network_pal))\n\nnetworks = df.columns.get_level_values(\"network\")\n\nnetwork_colors = pd.Series(networks, index=df.columns).map(network_lut)\n\ng = sns.clustermap(df.corr(), center=0, cmap=\"vlag\",\n row_colors=network_colors, col_colors=network_colors,\n dendrogram_ratio=(.1, .2),\n cbar_pos=(.02, .32, .03, .2),\n linewidths=.75, figsize=(12, 13))\n\ng.ax_row_dendrogram.remove()"},{"col":0,"comment":"\n Plot a matrix dataset as a hierarchically-clustered heatmap.\n\n This function requires scipy to be available.\n\n Parameters\n ----------\n data : 2D array-like\n Rectangular data for clustering. Cannot contain NAs.\n pivot_kws : dict, optional\n If `data` is a tidy dataframe, can provide keyword arguments for\n pivot to create a rectangular dataframe.\n method : str, optional\n Linkage method to use for calculating clusters. See\n :func:`scipy.cluster.hierarchy.linkage` documentation for more\n information.\n metric : str, optional\n Distance metric to use for the data. See\n :func:`scipy.spatial.distance.pdist` documentation for more options.\n To use different metrics (or methods) for rows and columns, you may\n construct each linkage matrix yourself and provide them as\n `{row,col}_linkage`.\n z_score : int or None, optional\n Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores\n for the rows or the columns. Z scores are: z = (x - mean)/std, so\n values in each row (column) will get the mean of the row (column)\n subtracted, then divided by the standard deviation of the row (column).\n This ensures that each row (column) has mean of 0 and variance of 1.\n standard_scale : int or None, optional\n Either 0 (rows) or 1 (columns). Whether or not to standardize that\n dimension, meaning for each row or column, subtract the minimum and\n divide each by its maximum.\n figsize : tuple of (width, height), optional\n Overall size of the figure.\n cbar_kws : dict, optional\n Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to\n add a label to the colorbar.\n {row,col}_cluster : bool, optional\n If ``True``, cluster the {rows, columns}.\n {row,col}_linkage : :class:`numpy.ndarray`, optional\n Precomputed linkage matrix for the rows or columns. See\n :func:`scipy.cluster.hierarchy.linkage` for specific formats.\n {row,col}_colors : list-like or pandas DataFrame/Series, optional\n List of colors to label for either the rows or columns. Useful to evaluate\n whether samples within a group are clustered together. Can use nested lists or\n DataFrame for multiple color levels of labeling. If given as a\n :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are\n extracted from the DataFrames column names or from the name of the Series.\n DataFrame/Series colors are also matched to the data by their index, ensuring\n colors are drawn in the correct order.\n mask : bool array or DataFrame, optional\n If passed, data will not be shown in cells where `mask` is True.\n Cells with missing values are automatically masked. Only used for\n visualizing, not for calculating.\n {dendrogram,colors}_ratio : float, or pair of floats, optional\n Proportion of the figure size devoted to the two marginal elements. If\n a pair is given, they correspond to (row, col) ratios.\n cbar_pos : tuple of (left, bottom, width, height), optional\n Position of the colorbar axes in the figure. Setting to ``None`` will\n disable the colorbar.\n tree_kws : dict, optional\n Parameters for the :class:`matplotlib.collections.LineCollection`\n that is used to plot the lines of the dendrogram tree.\n kwargs : other keyword arguments\n All other keyword arguments are passed to :func:`heatmap`.\n\n Returns\n -------\n :class:`ClusterGrid`\n A :class:`ClusterGrid` instance.\n\n See Also\n --------\n heatmap : Plot rectangular data as a color-encoded matrix.\n\n Notes\n -----\n The returned object has a ``savefig`` method that should be used if you\n want to save the figure object without clipping the dendrograms.\n\n To access the reordered row indices, use:\n ``clustergrid.dendrogram_row.reordered_ind``\n\n Column indices, use:\n ``clustergrid.dendrogram_col.reordered_ind``\n\n Examples\n --------\n\n .. include:: ../docstrings/clustermap.rst\n\n ","endLoc":1262,"header":"def clustermap(\n data, *,\n pivot_kws=None, method='average', metric='euclidean',\n z_score=None, standard_scale=None, figsize=(10, 10),\n cbar_kws=None, row_cluster=True, col_cluster=True,\n row_linkage=None, col_linkage=None,\n row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=.2, colors_ratio=0.03,\n cbar_pos=(.02, .8, .05, .18), tree_kws=None,\n **kwargs\n)","id":1127,"name":"clustermap","nodeType":"Function","startLoc":1146,"text":"def clustermap(\n data, *,\n pivot_kws=None, method='average', metric='euclidean',\n z_score=None, standard_scale=None, figsize=(10, 10),\n cbar_kws=None, row_cluster=True, col_cluster=True,\n row_linkage=None, col_linkage=None,\n row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=.2, colors_ratio=0.03,\n cbar_pos=(.02, .8, .05, .18), tree_kws=None,\n **kwargs\n):\n \"\"\"\n Plot a matrix dataset as a hierarchically-clustered heatmap.\n\n This function requires scipy to be available.\n\n Parameters\n ----------\n data : 2D array-like\n Rectangular data for clustering. Cannot contain NAs.\n pivot_kws : dict, optional\n If `data` is a tidy dataframe, can provide keyword arguments for\n pivot to create a rectangular dataframe.\n method : str, optional\n Linkage method to use for calculating clusters. See\n :func:`scipy.cluster.hierarchy.linkage` documentation for more\n information.\n metric : str, optional\n Distance metric to use for the data. See\n :func:`scipy.spatial.distance.pdist` documentation for more options.\n To use different metrics (or methods) for rows and columns, you may\n construct each linkage matrix yourself and provide them as\n `{row,col}_linkage`.\n z_score : int or None, optional\n Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores\n for the rows or the columns. Z scores are: z = (x - mean)/std, so\n values in each row (column) will get the mean of the row (column)\n subtracted, then divided by the standard deviation of the row (column).\n This ensures that each row (column) has mean of 0 and variance of 1.\n standard_scale : int or None, optional\n Either 0 (rows) or 1 (columns). Whether or not to standardize that\n dimension, meaning for each row or column, subtract the minimum and\n divide each by its maximum.\n figsize : tuple of (width, height), optional\n Overall size of the figure.\n cbar_kws : dict, optional\n Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to\n add a label to the colorbar.\n {row,col}_cluster : bool, optional\n If ``True``, cluster the {rows, columns}.\n {row,col}_linkage : :class:`numpy.ndarray`, optional\n Precomputed linkage matrix for the rows or columns. See\n :func:`scipy.cluster.hierarchy.linkage` for specific formats.\n {row,col}_colors : list-like or pandas DataFrame/Series, optional\n List of colors to label for either the rows or columns. Useful to evaluate\n whether samples within a group are clustered together. Can use nested lists or\n DataFrame for multiple color levels of labeling. If given as a\n :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are\n extracted from the DataFrames column names or from the name of the Series.\n DataFrame/Series colors are also matched to the data by their index, ensuring\n colors are drawn in the correct order.\n mask : bool array or DataFrame, optional\n If passed, data will not be shown in cells where `mask` is True.\n Cells with missing values are automatically masked. Only used for\n visualizing, not for calculating.\n {dendrogram,colors}_ratio : float, or pair of floats, optional\n Proportion of the figure size devoted to the two marginal elements. If\n a pair is given, they correspond to (row, col) ratios.\n cbar_pos : tuple of (left, bottom, width, height), optional\n Position of the colorbar axes in the figure. Setting to ``None`` will\n disable the colorbar.\n tree_kws : dict, optional\n Parameters for the :class:`matplotlib.collections.LineCollection`\n that is used to plot the lines of the dendrogram tree.\n kwargs : other keyword arguments\n All other keyword arguments are passed to :func:`heatmap`.\n\n Returns\n -------\n :class:`ClusterGrid`\n A :class:`ClusterGrid` instance.\n\n See Also\n --------\n heatmap : Plot rectangular data as a color-encoded matrix.\n\n Notes\n -----\n The returned object has a ``savefig`` method that should be used if you\n want to save the figure object without clipping the dendrograms.\n\n To access the reordered row indices, use:\n ``clustergrid.dendrogram_row.reordered_ind``\n\n Column indices, use:\n ``clustergrid.dendrogram_col.reordered_ind``\n\n Examples\n --------\n\n .. include:: ../docstrings/clustermap.rst\n\n \"\"\"\n if _no_scipy:\n raise RuntimeError(\"clustermap requires scipy to be available\")\n\n plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize,\n row_colors=row_colors, col_colors=col_colors,\n z_score=z_score, standard_scale=standard_scale,\n mask=mask, dendrogram_ratio=dendrogram_ratio,\n colors_ratio=colors_ratio, cbar_pos=cbar_pos)\n\n return plotter.plot(metric=metric, method=method,\n colorbar_kws=cbar_kws,\n row_cluster=row_cluster, col_cluster=col_cluster,\n row_linkage=row_linkage, col_linkage=col_linkage,\n tree_kws=tree_kws, **kwargs)"},{"col":4,"comment":"null","endLoc":510,"header":"def numeric_mapping(self, data, sizes, norm)","id":1128,"name":"numeric_mapping","nodeType":"Function","startLoc":433,"text":"def numeric_mapping(self, data, sizes, norm):\n\n if isinstance(sizes, dict):\n # The presence of a norm object overrides a dictionary of sizes\n # in specifying a numeric mapping, so we need to process it\n # dictionary here\n levels = list(np.sort(list(sizes)))\n size_values = sizes.values()\n size_range = min(size_values), max(size_values)\n\n else:\n\n # The levels here will be the unique values in the data\n levels = list(np.sort(remove_na(data.unique())))\n\n if isinstance(sizes, tuple):\n\n # For numeric inputs, the size can be parametrized by\n # the minimum and maximum artist values to map to. The\n # norm object that gets set up next specifies how to\n # do the mapping.\n\n if len(sizes) != 2:\n err = \"A `sizes` tuple must have only 2 values\"\n raise ValueError(err)\n\n size_range = sizes\n\n elif sizes is not None:\n\n err = f\"Value for `sizes` not understood: {sizes}\"\n raise ValueError(err)\n\n else:\n\n # When not provided, we get the size range from the plotter\n # object we are attached to. See the note in the categorical\n # method about how this is suboptimal for future development.\n size_range = self.plotter._default_size_range\n\n # Now that we know the minimum and maximum sizes that will get drawn,\n # we need to map the data values that we have into that range. We will\n # use a matplotlib Normalize class, which is typically used for numeric\n # color mapping but works fine here too. It takes data values and maps\n # them into a [0, 1] interval, potentially nonlinear-ly.\n\n if norm is None:\n # Default is a linear function between the min and max data values\n norm = mpl.colors.Normalize()\n elif isinstance(norm, tuple):\n # It is also possible to give different limits in data space\n norm = mpl.colors.Normalize(*norm)\n elif not isinstance(norm, mpl.colors.Normalize):\n err = f\"Value for size `norm` parameter not understood: {norm}\"\n raise ValueError(err)\n else:\n # If provided with Normalize object, copy it so we can modify\n norm = copy(norm)\n\n # Set the mapping so all output values are in [0, 1]\n norm.clip = True\n\n # If the input range is not set, use the full range of the data\n if not norm.scaled():\n norm(levels)\n\n # Map from data values to [0, 1] range\n sizes_scaled = norm(levels)\n\n # Now map from the scaled range into the artist units\n if isinstance(sizes, dict):\n lookup_table = sizes\n else:\n lo, hi = size_range\n sizes = lo + sizes_scaled * (hi - lo)\n lookup_table = dict(zip(levels, sizes))\n\n return levels, lookup_table, norm, size_range"},{"col":4,"comment":"null","endLoc":1343,"header":"def scale_native(self, axis, *args, **kwargs)","id":1129,"name":"scale_native","nodeType":"Function","startLoc":1339,"text":"def scale_native(self, axis, *args, **kwargs):\n\n # Default, defer to matplotlib\n\n raise NotImplementedError"},{"col":4,"comment":"null","endLoc":1350,"header":"def scale_numeric(self, axis, *args, **kwargs)","id":1130,"name":"scale_numeric","nodeType":"Function","startLoc":1345,"text":"def scale_numeric(self, axis, *args, **kwargs):\n\n # Feels needed to completeness, what should it do?\n # Perhaps handle log scaling? Set the ticker/formatter/limits?\n\n raise NotImplementedError"},{"col":4,"comment":"null","endLoc":1357,"header":"def scale_datetime(self, axis, *args, **kwargs)","id":1131,"name":"scale_datetime","nodeType":"Function","startLoc":1352,"text":"def scale_datetime(self, axis, *args, **kwargs):\n\n # Use pd.to_datetime to convert strings or numbers to datetime objects\n # Note, use day-resolution for numeric->datetime to match matplotlib\n\n raise NotImplementedError"},{"col":4,"comment":"\n Enforce categorical (fixed-scale) rules for the data on given axis.\n\n Parameters\n ----------\n axis : \"x\" or \"y\"\n Axis of the plot to operate on.\n order : list\n Order that unique values should appear in.\n formatter : callable\n Function mapping values to a string representation.\n\n Returns\n -------\n self\n\n ","endLoc":1450,"header":"def scale_categorical(self, axis, order=None, formatter=None)","id":1132,"name":"scale_categorical","nodeType":"Function","startLoc":1359,"text":"def scale_categorical(self, axis, order=None, formatter=None):\n \"\"\"\n Enforce categorical (fixed-scale) rules for the data on given axis.\n\n Parameters\n ----------\n axis : \"x\" or \"y\"\n Axis of the plot to operate on.\n order : list\n Order that unique values should appear in.\n formatter : callable\n Function mapping values to a string representation.\n\n Returns\n -------\n self\n\n \"\"\"\n # This method both modifies the internal representation of the data\n # (converting it to string) and sets some attributes on self. It might be\n # a good idea to have a separate object attached to self that contains the\n # information in those attributes (i.e. whether to enforce variable order\n # across facets, the order to use) similar to the SemanticMapping objects\n # we have for semantic variables. That object could also hold the converter\n # objects that get used, if we can decouple those from an existing axis\n # (cf. https://github.com/matplotlib/matplotlib/issues/19229).\n # There are some interactions with faceting information that would need\n # to be thought through, since the converts to use depend on facets.\n # If we go that route, these methods could become \"borrowed\" methods similar\n # to what happens with the alternate semantic mapper constructors, although\n # that approach is kind of fussy and confusing.\n\n # TODO this method could also set the grid state? Since we like to have no\n # grid on the categorical axis by default. Again, a case where we'll need to\n # store information until we use it, so best to have a way to collect the\n # attributes that this method sets.\n\n # TODO if we are going to set visual properties of the axes with these methods,\n # then we could do the steps currently in CategoricalPlotter._adjust_cat_axis\n\n # TODO another, and distinct idea, is to expose a cut= param here\n\n _check_argument(\"axis\", [\"x\", \"y\"], axis)\n\n # Categorical plots can be \"univariate\" in which case they get an anonymous\n # category label on the opposite axis.\n if axis not in self.variables:\n self.variables[axis] = None\n self.var_types[axis] = \"categorical\"\n self.plot_data[axis] = \"\"\n\n # If the \"categorical\" variable has a numeric type, sort the rows so that\n # the default result from categorical_order has those values sorted after\n # they have been coerced to strings. The reason for this is so that later\n # we can get facet-wise orders that are correct.\n # XXX Should this also sort datetimes?\n # It feels more consistent, but technically will be a default change\n # If so, should also change categorical_order to behave that way\n if self.var_types[axis] == \"numeric\":\n self.plot_data = self.plot_data.sort_values(axis, kind=\"mergesort\")\n\n # Now get a reference to the categorical data vector\n cat_data = self.plot_data[axis]\n\n # Get the initial categorical order, which we do before string\n # conversion to respect the original types of the order list.\n # Track whether the order is given explicitly so that we can know\n # whether or not to use the order constructed here downstream\n self._var_ordered[axis] = order is not None or cat_data.dtype.name == \"category\"\n order = pd.Index(categorical_order(cat_data, order))\n\n # Then convert data to strings. This is because in matplotlib,\n # \"categorical\" data really mean \"string\" data, so doing this artists\n # will be drawn on the categorical axis with a fixed scale.\n # TODO implement formatter here; check that it returns strings?\n if formatter is not None:\n cat_data = cat_data.map(formatter)\n order = order.map(formatter)\n else:\n cat_data = cat_data.astype(str)\n order = order.astype(str)\n\n # Update the levels list with the type-converted order variable\n self.var_levels[axis] = order\n\n # Now ensure that seaborn will use categorical rules internally\n self.var_types[axis] = \"categorical\"\n\n # Put the string-typed categorical vector back into the plot_data structure\n self.plot_data[axis] = cat_data\n\n return self"},{"col":4,"comment":"Grid object for organizing clustered heatmap input on to axes","endLoc":772,"header":"def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None,\n figsize=None, row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=None, colors_ratio=None, cbar_pos=None)","id":1133,"name":"__init__","nodeType":"Function","startLoc":698,"text":"def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None,\n figsize=None, row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=None, colors_ratio=None, cbar_pos=None):\n \"\"\"Grid object for organizing clustered heatmap input on to axes\"\"\"\n if _no_scipy:\n raise RuntimeError(\"ClusterGrid requires scipy to be available\")\n\n if isinstance(data, pd.DataFrame):\n self.data = data\n else:\n self.data = pd.DataFrame(data)\n\n self.data2d = self.format_data(self.data, pivot_kws, z_score,\n standard_scale)\n\n self.mask = _matrix_mask(self.data2d, mask)\n\n self._figure = plt.figure(figsize=figsize)\n\n self.row_colors, self.row_color_labels = \\\n self._preprocess_colors(data, row_colors, axis=0)\n self.col_colors, self.col_color_labels = \\\n self._preprocess_colors(data, col_colors, axis=1)\n\n try:\n row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio\n except TypeError:\n row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio\n\n try:\n row_colors_ratio, col_colors_ratio = colors_ratio\n except TypeError:\n row_colors_ratio = col_colors_ratio = colors_ratio\n\n width_ratios = self.dim_ratios(self.row_colors,\n row_dendrogram_ratio,\n row_colors_ratio)\n height_ratios = self.dim_ratios(self.col_colors,\n col_dendrogram_ratio,\n col_colors_ratio)\n\n nrows = 2 if self.col_colors is None else 3\n ncols = 2 if self.row_colors is None else 3\n\n self.gs = gridspec.GridSpec(nrows, ncols,\n width_ratios=width_ratios,\n height_ratios=height_ratios)\n\n self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0])\n self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1])\n self.ax_row_dendrogram.set_axis_off()\n self.ax_col_dendrogram.set_axis_off()\n\n self.ax_row_colors = None\n self.ax_col_colors = None\n\n if self.row_colors is not None:\n self.ax_row_colors = self._figure.add_subplot(\n self.gs[-1, 1])\n if self.col_colors is not None:\n self.ax_col_colors = self._figure.add_subplot(\n self.gs[1, -1])\n\n self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1])\n if cbar_pos is None:\n self.ax_cbar = self.cax = None\n else:\n # Initialize the colorbar axes in the gridspec so that tight_layout\n # works. We will move it where it belongs later. This is a hack.\n self.ax_cbar = self._figure.add_subplot(self.gs[0, 0])\n self.cax = self.ax_cbar # Backwards compatibility\n self.cbar_pos = cbar_pos\n\n self.dendrogram_row = None\n self.dendrogram_col = None"},{"attributeType":"null","col":4,"comment":"null","endLoc":616,"id":1134,"name":"_semantic_mappings","nodeType":"Attribute","startLoc":616,"text":"_semantic_mappings"},{"attributeType":"null","col":4,"comment":"null","endLoc":624,"id":1135,"name":"semantics","nodeType":"Attribute","startLoc":624,"text":"semantics"},{"attributeType":"null","col":4,"comment":"null","endLoc":625,"id":1136,"name":"wide_structure","nodeType":"Attribute","startLoc":625,"text":"wide_structure"},{"attributeType":"null","col":4,"comment":"null","endLoc":628,"id":1137,"name":"flat_structure","nodeType":"Attribute","startLoc":628,"text":"flat_structure"},{"attributeType":"null","col":4,"comment":"null","endLoc":630,"id":1138,"name":"_default_size_range","nodeType":"Attribute","startLoc":630,"text":"_default_size_range"},{"attributeType":"function","col":12,"comment":"null","endLoc":1136,"id":1139,"name":"_comp_data","nodeType":"Attribute","startLoc":1136,"text":"self._comp_data"},{"attributeType":"null","col":8,"comment":"null","endLoc":706,"id":1140,"name":"variables","nodeType":"Attribute","startLoc":706,"text":"self.variables"},{"attributeType":"null","col":8,"comment":"null","endLoc":639,"id":1141,"name":"_var_ordered","nodeType":"Attribute","startLoc":639,"text":"self._var_ordered"},{"attributeType":"null","col":8,"comment":"null","endLoc":705,"id":1142,"name":"plot_data","nodeType":"Attribute","startLoc":705,"text":"self.plot_data"},{"attributeType":"null","col":12,"comment":"null","endLoc":1178,"id":1143,"name":"ax","nodeType":"Attribute","startLoc":1178,"text":"self.ax"},{"attributeType":"null","col":8,"comment":"null","endLoc":634,"id":1144,"name":"_var_levels","nodeType":"Attribute","startLoc":634,"text":"self._var_levels"},{"attributeType":"null","col":8,"comment":"null","endLoc":707,"id":1145,"name":"var_types","nodeType":"Attribute","startLoc":707,"text":"self.var_types"},{"attributeType":"null","col":8,"comment":"null","endLoc":1217,"id":1146,"name":"converters","nodeType":"Attribute","startLoc":1217,"text":"self.converters"},{"attributeType":"null","col":12,"comment":"null","endLoc":695,"id":1147,"name":"input_format","nodeType":"Attribute","startLoc":695,"text":"self.input_format"},{"className":"TestHeatmap","col":0,"comment":"null","endLoc":470,"id":1148,"nodeType":"Class","startLoc":36,"text":"class TestHeatmap:\n rs = np.random.RandomState(sum(map(ord, \"heatmap\")))\n\n x_norm = rs.randn(4, 8)\n letters = pd.Series([\"A\", \"B\", \"C\", \"D\"], name=\"letters\")\n df_norm = pd.DataFrame(x_norm, index=letters)\n\n x_unif = rs.rand(20, 13)\n df_unif = pd.DataFrame(x_unif)\n\n default_kws = dict(vmin=None, vmax=None, cmap=None, center=None,\n robust=False, annot=False, fmt=\".2f\", annot_kws=None,\n cbar=True, cbar_kws=None, mask=None)\n\n def test_ndarray_input(self):\n\n p = mat._HeatMapper(self.x_norm, **self.default_kws)\n npt.assert_array_equal(p.plot_data, self.x_norm)\n pdt.assert_frame_equal(p.data, pd.DataFrame(self.x_norm))\n\n npt.assert_array_equal(p.xticklabels, np.arange(8))\n npt.assert_array_equal(p.yticklabels, np.arange(4))\n\n assert p.xlabel == \"\"\n assert p.ylabel == \"\"\n\n def test_df_input(self):\n\n p = mat._HeatMapper(self.df_norm, **self.default_kws)\n npt.assert_array_equal(p.plot_data, self.x_norm)\n pdt.assert_frame_equal(p.data, self.df_norm)\n\n npt.assert_array_equal(p.xticklabels, np.arange(8))\n npt.assert_array_equal(p.yticklabels, self.letters.values)\n\n assert p.xlabel == \"\"\n assert p.ylabel == \"letters\"\n\n def test_df_multindex_input(self):\n\n df = self.df_norm.copy()\n index = pd.MultiIndex.from_tuples([(\"A\", 1), (\"B\", 2),\n (\"C\", 3), (\"D\", 4)],\n names=[\"letter\", \"number\"])\n index.name = \"letter-number\"\n df.index = index\n\n p = mat._HeatMapper(df, **self.default_kws)\n\n combined_tick_labels = [\"A-1\", \"B-2\", \"C-3\", \"D-4\"]\n npt.assert_array_equal(p.yticklabels, combined_tick_labels)\n assert p.ylabel == \"letter-number\"\n\n p = mat._HeatMapper(df.T, **self.default_kws)\n\n npt.assert_array_equal(p.xticklabels, combined_tick_labels)\n assert p.xlabel == \"letter-number\"\n\n @pytest.mark.parametrize(\"dtype\", [float, np.int64, object])\n def test_mask_input(self, dtype):\n kws = self.default_kws.copy()\n\n mask = self.x_norm > 0\n kws['mask'] = mask\n data = self.x_norm.astype(dtype)\n p = mat._HeatMapper(data, **kws)\n plot_data = np.ma.masked_where(mask, data)\n\n npt.assert_array_equal(p.plot_data, plot_data)\n\n def test_mask_limits(self):\n \"\"\"Make sure masked cells are not used to calculate extremes\"\"\"\n\n kws = self.default_kws.copy()\n\n mask = self.x_norm > 0\n kws['mask'] = mask\n p = mat._HeatMapper(self.x_norm, **kws)\n\n assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()\n assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()\n\n mask = self.x_norm < 0\n kws['mask'] = mask\n p = mat._HeatMapper(self.x_norm, **kws)\n\n assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()\n assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()\n\n def test_default_vlims(self):\n\n p = mat._HeatMapper(self.df_unif, **self.default_kws)\n assert p.vmin == self.x_unif.min()\n assert p.vmax == self.x_unif.max()\n\n def test_robust_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"robust\"] = True\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == np.percentile(self.x_unif, 2)\n assert p.vmax == np.percentile(self.x_unif, 98)\n\n def test_custom_sequential_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"vmin\"] = 0\n kws[\"vmax\"] = 1\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == 0\n assert p.vmax == 1\n\n def test_custom_diverging_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"vmin\"] = -4\n kws[\"vmax\"] = 5\n kws[\"center\"] = 0\n p = mat._HeatMapper(self.df_norm, **kws)\n\n assert p.vmin == -4\n assert p.vmax == 5\n\n def test_array_with_nans(self):\n\n x1 = self.rs.rand(10, 10)\n nulls = np.zeros(10) * np.nan\n x2 = np.c_[x1, nulls]\n\n m1 = mat._HeatMapper(x1, **self.default_kws)\n m2 = mat._HeatMapper(x2, **self.default_kws)\n\n assert m1.vmin == m2.vmin\n assert m1.vmax == m2.vmax\n\n def test_mask(self):\n\n df = pd.DataFrame(data={'a': [1, 1, 1],\n 'b': [2, np.nan, 2],\n 'c': [3, 3, np.nan]})\n\n kws = self.default_kws.copy()\n kws[\"mask\"] = np.isnan(df.values)\n\n m = mat._HeatMapper(df, **kws)\n\n npt.assert_array_equal(np.isnan(m.plot_data.data),\n m.plot_data.mask)\n\n def test_custom_cmap(self):\n\n kws = self.default_kws.copy()\n kws[\"cmap\"] = \"BuGn\"\n p = mat._HeatMapper(self.df_unif, **kws)\n assert p.cmap == mpl.cm.BuGn\n\n def test_centered_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"center\"] = .5\n\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == self.df_unif.values.min()\n assert p.vmax == self.df_unif.values.max()\n\n def test_default_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n cvals = np.linspace(0, 1, 9)\n npt.assert_array_almost_equal(fc, cmap(cvals), 2)\n\n def test_custom_vlim_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], vmin=0, cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n npt.assert_array_almost_equal(fc, cmap(vals), 2)\n\n def test_custom_center_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], center=.5, cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n npt.assert_array_almost_equal(fc, cmap(vals), 2)\n\n def test_cmap_with_properties(self):\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_bad(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(\n cmap(np.ma.masked_invalid([np.nan])),\n hm.cmap(np.ma.masked_invalid([np.nan])))\n\n kws[\"center\"] = 0.5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(\n cmap(np.ma.masked_invalid([np.nan])),\n hm.cmap(np.ma.masked_invalid([np.nan])))\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_under(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws[\"center\"] = .5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_over(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws[\"center\"] = .5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(np.inf), hm.cmap(np.inf))\n\n def test_ticklabels_off(self):\n kws = self.default_kws.copy()\n kws['xticklabels'] = False\n kws['yticklabels'] = False\n p = mat._HeatMapper(self.df_norm, **kws)\n assert p.xticklabels == []\n assert p.yticklabels == []\n\n def test_custom_ticklabels(self):\n kws = self.default_kws.copy()\n xticklabels = list('iheartheatmaps'[:self.df_norm.shape[1]])\n yticklabels = list('heatmapsarecool'[:self.df_norm.shape[0]])\n kws['xticklabels'] = xticklabels\n kws['yticklabels'] = yticklabels\n p = mat._HeatMapper(self.df_norm, **kws)\n assert p.xticklabels == xticklabels\n assert p.yticklabels == yticklabels\n\n def test_custom_ticklabel_interval(self):\n\n kws = self.default_kws.copy()\n xstep, ystep = 2, 3\n kws['xticklabels'] = xstep\n kws['yticklabels'] = ystep\n p = mat._HeatMapper(self.df_norm, **kws)\n\n nx, ny = self.df_norm.T.shape\n npt.assert_array_equal(p.xticks, np.arange(0, nx, xstep) + .5)\n npt.assert_array_equal(p.yticks, np.arange(0, ny, ystep) + .5)\n npt.assert_array_equal(p.xticklabels,\n self.df_norm.columns[0:nx:xstep])\n npt.assert_array_equal(p.yticklabels,\n self.df_norm.index[0:ny:ystep])\n\n def test_heatmap_annotation(self):\n\n ax = mat.heatmap(self.df_norm, annot=True, fmt=\".1f\",\n annot_kws={\"fontsize\": 14})\n for val, text in zip(self.x_norm.flat, ax.texts):\n assert text.get_text() == f\"{val:.1f}\"\n assert text.get_fontsize() == 14\n\n def test_heatmap_annotation_overwrite_kws(self):\n\n annot_kws = dict(color=\"0.3\", va=\"bottom\", ha=\"left\")\n ax = mat.heatmap(self.df_norm, annot=True, fmt=\".1f\",\n annot_kws=annot_kws)\n for text in ax.texts:\n assert text.get_color() == \"0.3\"\n assert text.get_ha() == \"left\"\n assert text.get_va() == \"bottom\"\n\n def test_heatmap_annotation_with_mask(self):\n\n df = pd.DataFrame(data={'a': [1, 1, 1],\n 'b': [2, np.nan, 2],\n 'c': [3, 3, np.nan]})\n mask = np.isnan(df.values)\n df_masked = np.ma.masked_where(mask, df)\n ax = mat.heatmap(df, annot=True, fmt='.1f', mask=mask)\n assert len(df_masked.compressed()) == len(ax.texts)\n for val, text in zip(df_masked.compressed(), ax.texts):\n assert f\"{val:.1f}\" == text.get_text()\n\n def test_heatmap_annotation_mesh_colors(self):\n\n ax = mat.heatmap(self.df_norm, annot=True)\n mesh = ax.collections[0]\n assert len(mesh.get_facecolors()) == self.df_norm.values.size\n\n plt.close(\"all\")\n\n def test_heatmap_annotation_other_data(self):\n annot_data = self.df_norm + 10\n\n ax = mat.heatmap(self.df_norm, annot=annot_data, fmt=\".1f\",\n annot_kws={\"fontsize\": 14})\n\n for val, text in zip(annot_data.values.flat, ax.texts):\n assert text.get_text() == f\"{val:.1f}\"\n assert text.get_fontsize() == 14\n\n def test_heatmap_annotation_different_shapes(self):\n\n annot_data = self.df_norm.iloc[:-1]\n with pytest.raises(ValueError):\n mat.heatmap(self.df_norm, annot=annot_data)\n\n def test_heatmap_annotation_with_limited_ticklabels(self):\n ax = mat.heatmap(self.df_norm, fmt=\".2f\", annot=True,\n xticklabels=False, yticklabels=False)\n for val, text in zip(self.x_norm.flat, ax.texts):\n assert text.get_text() == f\"{val:.2f}\"\n\n def test_heatmap_cbar(self):\n\n f = plt.figure()\n mat.heatmap(self.df_norm)\n assert len(f.axes) == 2\n plt.close(f)\n\n f = plt.figure()\n mat.heatmap(self.df_norm, cbar=False)\n assert len(f.axes) == 1\n plt.close(f)\n\n f, (ax1, ax2) = plt.subplots(2)\n mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2)\n assert len(f.axes) == 2\n plt.close(f)\n\n @pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_heatmap_axes(self):\n\n ax = mat.heatmap(self.df_norm)\n\n xtl = [int(l.get_text()) for l in ax.get_xticklabels()]\n assert xtl == list(self.df_norm.columns)\n ytl = [l.get_text() for l in ax.get_yticklabels()]\n assert ytl == list(self.df_norm.index)\n\n assert ax.get_xlabel() == \"\"\n assert ax.get_ylabel() == \"letters\"\n\n assert ax.get_xlim() == (0, 8)\n assert ax.get_ylim() == (4, 0)\n\n def test_heatmap_ticklabel_rotation(self):\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.heatmap(self.df_norm, xticklabels=1, yticklabels=1, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 0\n\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 90\n\n plt.close(f)\n\n df = self.df_norm.copy()\n df.columns = [str(c) * 10 for c in df.columns]\n df.index = [i * 10 for i in df.index]\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.heatmap(df, xticklabels=1, yticklabels=1, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 90\n\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 0\n\n plt.close(f)\n\n def test_heatmap_inner_lines(self):\n\n c = (0, 0, 1, 1)\n ax = mat.heatmap(self.df_norm, linewidths=2, linecolor=c)\n mesh = ax.collections[0]\n assert mesh.get_linewidths()[0] == 2\n assert tuple(mesh.get_edgecolor()[0]) == c\n\n def test_square_aspect(self):\n\n ax = mat.heatmap(self.df_norm, square=True)\n obs_aspect = ax.get_aspect()\n # mpl>3.3 returns 1 for setting \"equal\" aspect\n # so test for the two possible equal outcomes\n assert obs_aspect == \"equal\" or obs_aspect == 1\n\n def test_mask_validation(self):\n\n mask = mat._matrix_mask(self.df_norm, None)\n assert mask.shape == self.df_norm.shape\n assert mask.values.sum() == 0\n\n with pytest.raises(ValueError):\n bad_array_mask = self.rs.randn(3, 6) > 0\n mat._matrix_mask(self.df_norm, bad_array_mask)\n\n with pytest.raises(ValueError):\n bad_df_mask = pd.DataFrame(self.rs.randn(4, 8) > 0)\n mat._matrix_mask(self.df_norm, bad_df_mask)\n\n def test_missing_data_mask(self):\n\n data = pd.DataFrame(np.arange(4, dtype=float).reshape(2, 2))\n data.loc[0, 0] = np.nan\n mask = mat._matrix_mask(data, None)\n npt.assert_array_equal(mask, [[True, False], [False, False]])\n\n mask_in = np.array([[False, True], [False, False]])\n mask_out = mat._matrix_mask(data, mask_in)\n npt.assert_array_equal(mask_out, [[True, True], [False, False]])\n\n def test_cbar_ticks(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2,\n cbar_kws=dict(drawedges=True))\n assert len(ax2.collections) == 2"},{"attributeType":"null","col":12,"comment":"null","endLoc":1179,"id":1149,"name":"facets","nodeType":"Attribute","startLoc":1179,"text":"self.facets"},{"col":4,"comment":"Return True if only x or y are used.","endLoc":122,"header":"@property\n def univariate(self)","id":1150,"name":"univariate","nodeType":"Function","startLoc":115,"text":"@property\n def univariate(self):\n \"\"\"Return True if only x or y are used.\"\"\"\n # TODO this could go down to core, but putting it here now.\n # We'd want to be conceptually clear that univariate only applies\n # to x/y and not to other semantics, which can exist.\n # We haven't settled on a good conceptual name for x/y.\n return bool({\"x\", \"y\"} - set(self.variables))"},{"col":4,"comment":"null","endLoc":60,"header":"def test_ndarray_input(self)","id":1151,"name":"test_ndarray_input","nodeType":"Function","startLoc":50,"text":"def test_ndarray_input(self):\n\n p = mat._HeatMapper(self.x_norm, **self.default_kws)\n npt.assert_array_equal(p.plot_data, self.x_norm)\n pdt.assert_frame_equal(p.data, pd.DataFrame(self.x_norm))\n\n npt.assert_array_equal(p.xticklabels, np.arange(8))\n npt.assert_array_equal(p.yticklabels, np.arange(4))\n\n assert p.xlabel == \"\"\n assert p.ylabel == \"\""},{"col":4,"comment":"Return a function that maps from data domain to property range.","endLoc":220,"header":"def get_mapping(\n self, scale: Scale, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]","id":1152,"name":"get_mapping","nodeType":"Function","startLoc":194,"text":"def get_mapping(\n self, scale: Scale, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to property range.\"\"\"\n if isinstance(scale, Nominal):\n return self._get_categorical_mapping(scale, data)\n\n if scale.values is None:\n vmin, vmax = self._forward(self.default_range)\n elif isinstance(scale.values, tuple) and len(scale.values) == 2:\n vmin, vmax = self._forward(scale.values)\n else:\n if isinstance(scale.values, tuple):\n actual = f\"{len(scale.values)}-tuple\"\n else:\n actual = str(type(scale.values))\n scale_class = scale.__class__.__name__\n err = \" \".join([\n f\"Values for {self.variable} variables with {scale_class} scale\",\n f\"must be 2-tuple; not {actual}.\",\n ])\n raise TypeError(err)\n\n def mapping(x):\n return self._inverse(np.multiply(x, vmax - vmin) + vmin)\n\n return mapping"},{"col":4,"comment":"Extract variables from data or use directly.","endLoc":834,"header":"def format_data(self, data, pivot_kws, z_score=None,\n standard_scale=None)","id":1153,"name":"format_data","nodeType":"Function","startLoc":816,"text":"def format_data(self, data, pivot_kws, z_score=None,\n standard_scale=None):\n \"\"\"Extract variables from data or use directly.\"\"\"\n\n # Either the data is already in 2d matrix format, or need to do a pivot\n if pivot_kws is not None:\n data2d = data.pivot(**pivot_kws)\n else:\n data2d = data\n\n if z_score is not None and standard_scale is not None:\n raise ValueError(\n 'Cannot perform both z-scoring and standard-scaling on data')\n\n if z_score is not None:\n data2d = self.z_score(data2d, z_score)\n if standard_scale is not None:\n data2d = self.standard_scale(data2d, standard_scale)\n return data2d"},{"col":4,"comment":"null","endLoc":72,"header":"def test_df_input(self)","id":1154,"name":"test_df_input","nodeType":"Function","startLoc":62,"text":"def test_df_input(self):\n\n p = mat._HeatMapper(self.df_norm, **self.default_kws)\n npt.assert_array_equal(p.plot_data, self.x_norm)\n pdt.assert_frame_equal(p.data, self.df_norm)\n\n npt.assert_array_equal(p.xticklabels, np.arange(8))\n npt.assert_array_equal(p.yticklabels, self.letters.values)\n\n assert p.xlabel == \"\"\n assert p.ylabel == \"letters\""},{"col":4,"comment":"null","endLoc":92,"header":"def test_df_multindex_input(self)","id":1155,"name":"test_df_multindex_input","nodeType":"Function","startLoc":74,"text":"def test_df_multindex_input(self):\n\n df = self.df_norm.copy()\n index = pd.MultiIndex.from_tuples([(\"A\", 1), (\"B\", 2),\n (\"C\", 3), (\"D\", 4)],\n names=[\"letter\", \"number\"])\n index.name = \"letter-number\"\n df.index = index\n\n p = mat._HeatMapper(df, **self.default_kws)\n\n combined_tick_labels = [\"A-1\", \"B-2\", \"C-3\", \"D-4\"]\n npt.assert_array_equal(p.yticklabels, combined_tick_labels)\n assert p.ylabel == \"letter-number\"\n\n p = mat._HeatMapper(df.T, **self.default_kws)\n\n npt.assert_array_equal(p.xticklabels, combined_tick_labels)\n assert p.xlabel == \"letter-number\""},{"col":4,"comment":"Return the variable with data for univariate plots.","endLoc":130,"header":"@property\n def data_variable(self)","id":1156,"name":"data_variable","nodeType":"Function","startLoc":124,"text":"@property\n def data_variable(self):\n \"\"\"Return the variable with data for univariate plots.\"\"\"\n # TODO This could also be in core, but it should have a better name.\n if not self.univariate:\n raise AttributeError(\"This is not a univariate plot\")\n return {\"x\", \"y\"}.intersection(self.variables).pop()"},{"col":4,"comment":"Identify evenly-spaced values using interval or explicit mapping.","endLoc":256,"header":"def _get_categorical_mapping(\n self, scale: Nominal, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]","id":1157,"name":"_get_categorical_mapping","nodeType":"Function","startLoc":222,"text":"def _get_categorical_mapping(\n self, scale: Nominal, data: ArrayLike\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Identify evenly-spaced values using interval or explicit mapping.\"\"\"\n levels = categorical_order(data, scale.order)\n\n if isinstance(scale.values, dict):\n self._check_dict_entries(levels, scale.values)\n values = [scale.values[x] for x in levels]\n elif isinstance(scale.values, list):\n values = self._check_list_length(levels, scale.values)\n else:\n if scale.values is None:\n vmin, vmax = self.default_range\n elif isinstance(scale.values, tuple):\n vmin, vmax = scale.values\n else:\n scale_class = scale.__class__.__name__\n err = \" \".join([\n f\"Values for {self.variable} variables with {scale_class} scale\",\n f\"must be a dict, list or tuple; not {type(scale.values)}\",\n ])\n raise TypeError(err)\n\n vmin, vmax = self._forward([vmin, vmax])\n values = self._inverse(np.linspace(vmax, vmin, len(levels)))\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n out = np.full(len(x), np.nan)\n use = np.isfinite(x)\n out[use] = np.take(values, ixs[use])\n return out\n\n return mapping"},{"col":4,"comment":"Standarize the mean and variance of the data axis\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n normalized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n ","endLoc":864,"header":"@staticmethod\n def z_score(data2d, axis=1)","id":1158,"name":"z_score","nodeType":"Function","startLoc":836,"text":"@staticmethod\n def z_score(data2d, axis=1):\n \"\"\"Standarize the mean and variance of the data axis\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n normalized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n \"\"\"\n if axis == 1:\n z_scored = data2d\n else:\n z_scored = data2d.T\n\n z_scored = (z_scored - z_scored.mean()) / z_scored.std()\n\n if axis == 1:\n return z_scored\n else:\n return z_scored.T"},{"col":4,"comment":"\n Assign values for plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Returns\n -------\n frame\n Table mapping seaborn variables (x, y, color, ...) to data vectors.\n names\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n ids\n Like the `names` dict, but `None` values are replaced by the `id()`\n of the data object that defined the variable.\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in `data`, or when they are\n non-indexed vector datatypes that have a different length from `data`.\n\n ","endLoc":260,"header":"def _assign_variables(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataFrame, dict[str, str | None], dict[str, str | int]]","id":1159,"name":"_assign_variables","nodeType":"Function","startLoc":119,"text":"def _assign_variables(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataFrame, dict[str, str | None], dict[str, str | int]]:\n \"\"\"\n Assign values for plot variables given long-form data and/or vector inputs.\n\n Parameters\n ----------\n data\n Input data where variable names map to vector values.\n variables\n Keys are names of plot variables (x, y, ...) each value is one of:\n\n - name of a column (or index level, or dictionary entry) in `data`\n - vector in any format that can construct a :class:`pandas.DataFrame`\n\n Returns\n -------\n frame\n Table mapping seaborn variables (x, y, color, ...) to data vectors.\n names\n Keys are defined seaborn variables; values are names inferred from\n the inputs (or None when no name can be determined).\n ids\n Like the `names` dict, but `None` values are replaced by the `id()`\n of the data object that defined the variable.\n\n Raises\n ------\n ValueError\n When variables are strings that don't appear in `data`, or when they are\n non-indexed vector datatypes that have a different length from `data`.\n\n \"\"\"\n source_data: Mapping | DataFrame\n frame: DataFrame\n names: dict[str, str | None]\n ids: dict[str, str | int]\n\n plot_data = {}\n names = {}\n ids = {}\n\n given_data = data is not None\n if data is not None:\n source_data = data\n else:\n # Data is optional; all variables can be defined as vectors\n # But simplify downstream code by always having a usable source data object\n source_data = {}\n\n # TODO Generally interested in accepting a generic DataFrame interface\n # Track https://data-apis.org/ for development\n\n # Variables can also be extracted from the index of a DataFrame\n if isinstance(source_data, pd.DataFrame):\n index = source_data.index.to_frame().to_dict(\"series\")\n else:\n index = {}\n\n for key, val in variables.items():\n\n # Simply ignore variables with no specification\n if val is None:\n continue\n\n # Try to treat the argument as a key for the data collection.\n # But be flexible about what can be used as a key.\n # Usually it will be a string, but allow other hashables when\n # taking from the main data object. Allow only strings to reference\n # fields in the index, because otherwise there is too much ambiguity.\n\n # TODO this will be rendered unnecessary by the following pandas fix:\n # https://github.com/pandas-dev/pandas/pull/41283\n try:\n hash(val)\n val_is_hashable = True\n except TypeError:\n val_is_hashable = False\n\n val_as_data_key = (\n # See https://github.com/pandas-dev/pandas/pull/41283\n # (isinstance(val, abc.Hashable) and val in source_data)\n (val_is_hashable and val in source_data)\n or (isinstance(val, str) and val in index)\n )\n\n if val_as_data_key:\n val = cast(ColumnName, val)\n if val in source_data:\n plot_data[key] = source_data[val]\n elif val in index:\n plot_data[key] = index[val]\n names[key] = ids[key] = str(val)\n\n elif isinstance(val, str):\n\n # This looks like a column name but, lookup failed.\n\n err = f\"Could not interpret value `{val}` for `{key}`. \"\n if not given_data:\n err += \"Value is a string, but `data` was not passed.\"\n else:\n err += \"An entry with this name does not appear in `data`.\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, assume the value somehow represents data\n\n # Ignore empty data structures\n if isinstance(val, Sized) and len(val) == 0:\n continue\n\n # If vector has no index, it must match length of data table\n if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series):\n if isinstance(val, Sized) and len(data) != len(val):\n val_cls = val.__class__.__name__\n err = (\n f\"Length of {val_cls} vectors must match length of `data`\"\n f\" when both are used, but `data` has length {len(data)}\"\n f\" and the vector passed to `{key}` has length {len(val)}.\"\n )\n raise ValueError(err)\n\n plot_data[key] = val\n\n # Try to infer the original name using pandas-like metadata\n if hasattr(val, \"name\"):\n names[key] = ids[key] = str(val.name) # type: ignore # mypy/1424\n else:\n names[key] = None\n ids[key] = id(val)\n\n # Construct a tidy plot DataFrame. This will convert a number of\n # types automatically, aligning on index in case of pandas objects\n # TODO Note: this fails when variable specs *only* have scalars!\n frame = pd.DataFrame(plot_data)\n\n return frame, names, ids"},{"fileName":"relational.py","filePath":"seaborn","id":1160,"nodeType":"File","text":"import warnings\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom ._oldcore import (\n VectorPlotter,\n)\nfrom .utils import (\n locator_to_legend_entries,\n adjust_legend_subtitles,\n _default_color,\n _deprecate_ci,\n)\nfrom ._statistics import EstimateAggregator\nfrom .axisgrid import FacetGrid, _facet_docs\nfrom ._docstrings import DocstringComponents, _core_docs\n\n\n__all__ = [\"relplot\", \"scatterplot\", \"lineplot\"]\n\n\n_relational_narrative = DocstringComponents(dict(\n\n # --- Introductory prose\n main_api=\"\"\"\nThe relationship between `x` and `y` can be shown for different subsets\nof the data using the `hue`, `size`, and `style` parameters. These\nparameters control what visual semantics are used to identify the different\nsubsets. It is possible to show up to three dimensions independently by\nusing all three semantic types, but this style of plot can be hard to\ninterpret and is often ineffective. Using redundant semantics (i.e. both\n`hue` and `style` for the same variable) can be helpful for making\ngraphics more accessible.\n\nSee the :ref:`tutorial ` for more information.\n \"\"\",\n\n relational_semantic=\"\"\"\nThe default treatment of the `hue` (and to a lesser extent, `size`)\nsemantic, if present, depends on whether the variable is inferred to\nrepresent \"numeric\" or \"categorical\" data. In particular, numeric variables\nare represented with a sequential colormap by default, and the legend\nentries show regular \"ticks\" with values that may or may not exist in the\ndata. This behavior can be controlled through various parameters, as\ndescribed and illustrated below.\n \"\"\",\n))\n\n_relational_docs = dict(\n\n # --- Shared function parameters\n data_vars=\"\"\"\nx, y : names of variables in `data` or vector data\n Input data variables; must be numeric. Can pass data directly or\n reference columns in `data`.\n \"\"\",\n data=\"\"\"\ndata : DataFrame, array, or list of arrays\n Input data structure. If `x` and `y` are specified as names, this\n should be a \"long-form\" DataFrame containing those columns. Otherwise\n it is treated as \"wide-form\" data and grouping variables are ignored.\n See the examples for the various ways this parameter can be specified\n and the different effects of each.\n \"\"\",\n palette=\"\"\"\npalette : string, list, dict, or matplotlib colormap\n An object that determines how colors are chosen when `hue` is used.\n It can be the name of a seaborn palette or matplotlib colormap, a list\n of colors (anything matplotlib understands), a dict mapping levels\n of the `hue` variable to colors, or a matplotlib colormap object.\n \"\"\",\n hue_order=\"\"\"\nhue_order : list\n Specified order for the appearance of the `hue` variable levels,\n otherwise they are determined from the data. Not relevant when the\n `hue` variable is numeric.\n \"\"\",\n hue_norm=\"\"\"\nhue_norm : tuple or :class:`matplotlib.colors.Normalize` object\n Normalization in data units for colormap applied to the `hue`\n variable when it is numeric. Not relevant if `hue` is categorical.\n \"\"\",\n sizes=\"\"\"\nsizes : list, dict, or tuple\n An object that determines how sizes are chosen when `size` is used.\n List or dict arguments should provide a size for each unique data value,\n which forces a categorical interpretation. The argument may also be a\n min, max tuple.\n \"\"\",\n size_order=\"\"\"\nsize_order : list\n Specified order for appearance of the `size` variable levels,\n otherwise they are determined from the data. Not relevant when the\n `size` variable is numeric.\n \"\"\",\n size_norm=\"\"\"\nsize_norm : tuple or Normalize object\n Normalization in data units for scaling plot objects when the\n `size` variable is numeric.\n \"\"\",\n dashes=\"\"\"\ndashes : boolean, list, or dictionary\n Object determining how to draw the lines for different levels of the\n `style` variable. Setting to `True` will use default dash codes, or\n you can pass a list of dash codes or a dictionary mapping levels of the\n `style` variable to dash codes. Setting to `False` will use solid\n lines for all subsets. Dashes are specified as in matplotlib: a tuple\n of `(segment, gap)` lengths, or an empty string to draw a solid line.\n \"\"\",\n markers=\"\"\"\nmarkers : boolean, list, or dictionary\n Object determining how to draw the markers for different levels of the\n `style` variable. Setting to `True` will use default markers, or\n you can pass a list of markers or a dictionary mapping levels of the\n `style` variable to markers. Setting to `False` will draw\n marker-less lines. Markers are specified as in matplotlib.\n \"\"\",\n style_order=\"\"\"\nstyle_order : list\n Specified order for appearance of the `style` variable levels\n otherwise they are determined from the data. Not relevant when the\n `style` variable is numeric.\n \"\"\",\n units=\"\"\"\nunits : vector or key in `data`\n Grouping variable identifying sampling units. When used, a separate\n line will be drawn for each unit with appropriate semantics, but no\n legend entry will be added. Useful for showing distribution of\n experimental replicates when exact identities are not needed.\n \"\"\",\n estimator=\"\"\"\nestimator : name of pandas method or callable or None\n Method for aggregating across multiple observations of the `y`\n variable at the same `x` level. If `None`, all observations will\n be drawn.\n \"\"\",\n ci=\"\"\"\nci : int or \"sd\" or None\n Size of the confidence interval to draw when aggregating.\n\n .. deprecated:: 0.12.0\n Use the new `errorbar` parameter for more flexibility.\n\n \"\"\",\n n_boot=\"\"\"\nn_boot : int\n Number of bootstraps to use for computing the confidence interval.\n \"\"\",\n seed=\"\"\"\nseed : int, numpy.random.Generator, or numpy.random.RandomState\n Seed or random number generator for reproducible bootstrapping.\n \"\"\",\n legend=\"\"\"\nlegend : \"auto\", \"brief\", \"full\", or False\n How to draw the legend. If \"brief\", numeric `hue` and `size`\n variables will be represented with a sample of evenly spaced values.\n If \"full\", every group will get an entry in the legend. If \"auto\",\n choose between brief or full representation based on number of levels.\n If `False`, no legend data is added and no legend is drawn.\n \"\"\",\n ax_in=\"\"\"\nax : matplotlib Axes\n Axes object to draw the plot onto, otherwise uses the current Axes.\n \"\"\",\n ax_out=\"\"\"\nax : matplotlib Axes\n Returns the Axes object with the plot drawn onto it.\n \"\"\",\n\n)\n\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n facets=DocstringComponents(_facet_docs),\n rel=DocstringComponents(_relational_docs),\n stat=DocstringComponents.from_function_params(EstimateAggregator.__init__),\n)\n\n\nclass _RelationalPlotter(VectorPlotter):\n\n wide_structure = {\n \"x\": \"@index\", \"y\": \"@values\", \"hue\": \"@columns\", \"style\": \"@columns\",\n }\n\n # TODO where best to define default parameters?\n sort = True\n\n def add_legend_data(self, ax):\n \"\"\"Add labeled artists to represent the different plot semantics.\"\"\"\n verbosity = self.legend\n if isinstance(verbosity, str) and verbosity not in [\"auto\", \"brief\", \"full\"]:\n err = \"`legend` must be 'auto', 'brief', 'full', or a boolean.\"\n raise ValueError(err)\n elif verbosity is True:\n verbosity = \"auto\"\n\n legend_kwargs = {}\n keys = []\n\n # Assign a legend title if there is only going to be one sub-legend,\n # otherwise, subtitles will be inserted into the texts list with an\n # invisible handle (which is a hack)\n titles = {\n title for title in\n (self.variables.get(v, None) for v in [\"hue\", \"size\", \"style\"])\n if title is not None\n }\n if len(titles) == 1:\n legend_title = titles.pop()\n else:\n legend_title = \"\"\n\n title_kws = dict(\n visible=False, color=\"w\", s=0, linewidth=0, marker=\"\", dashes=\"\"\n )\n\n def update(var_name, val_name, **kws):\n\n key = var_name, val_name\n if key in legend_kwargs:\n legend_kwargs[key].update(**kws)\n else:\n keys.append(key)\n\n legend_kwargs[key] = dict(**kws)\n\n # Define the maximum number of ticks to use for \"brief\" legends\n brief_ticks = 6\n\n # -- Add a legend for hue semantics\n brief_hue = self._hue_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._hue_map.levels) > brief_ticks)\n )\n if brief_hue:\n if isinstance(self._hue_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n limits = min(self._hue_map.levels), max(self._hue_map.levels)\n hue_levels, hue_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"hue\"].infer_objects().dtype\n )\n elif self._hue_map.levels is None:\n hue_levels = hue_formatted_levels = []\n else:\n hue_levels = hue_formatted_levels = self._hue_map.levels\n\n # Add the hue semantic subtitle\n if not legend_title and self.variables.get(\"hue\", None) is not None:\n update((self.variables[\"hue\"], \"title\"),\n self.variables[\"hue\"], **title_kws)\n\n # Add the hue semantic labels\n for level, formatted_level in zip(hue_levels, hue_formatted_levels):\n if level is not None:\n color = self._hue_map(level)\n update(self.variables[\"hue\"], formatted_level, color=color)\n\n # -- Add a legend for size semantics\n brief_size = self._size_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._size_map.levels) > brief_ticks)\n )\n if brief_size:\n # Define how ticks will interpolate between the min/max data values\n if isinstance(self._size_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n # Define the min/max data values\n limits = min(self._size_map.levels), max(self._size_map.levels)\n size_levels, size_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"size\"].infer_objects().dtype\n )\n elif self._size_map.levels is None:\n size_levels = size_formatted_levels = []\n else:\n size_levels = size_formatted_levels = self._size_map.levels\n\n # Add the size semantic subtitle\n if not legend_title and self.variables.get(\"size\", None) is not None:\n update((self.variables[\"size\"], \"title\"),\n self.variables[\"size\"], **title_kws)\n\n # Add the size semantic labels\n for level, formatted_level in zip(size_levels, size_formatted_levels):\n if level is not None:\n size = self._size_map(level)\n update(\n self.variables[\"size\"],\n formatted_level,\n linewidth=size,\n s=size,\n )\n\n # -- Add a legend for style semantics\n\n # Add the style semantic title\n if not legend_title and self.variables.get(\"style\", None) is not None:\n update((self.variables[\"style\"], \"title\"),\n self.variables[\"style\"], **title_kws)\n\n # Add the style semantic labels\n if self._style_map.levels is not None:\n for level in self._style_map.levels:\n if level is not None:\n attrs = self._style_map(level)\n update(\n self.variables[\"style\"],\n level,\n marker=attrs.get(\"marker\", \"\"),\n dashes=attrs.get(\"dashes\", \"\"),\n )\n\n func = getattr(ax, self._legend_func)\n\n legend_data = {}\n legend_order = []\n\n for key in keys:\n\n _, label = key\n kws = legend_kwargs[key]\n kws.setdefault(\"color\", \".2\")\n use_kws = {}\n for attr in self._legend_attributes + [\"visible\"]:\n if attr in kws:\n use_kws[attr] = kws[attr]\n artist = func([], [], label=label, **use_kws)\n if self._legend_func == \"plot\":\n artist = artist[0]\n legend_data[key] = artist\n legend_order.append(key)\n\n self.legend_title = legend_title\n self.legend_data = legend_data\n self.legend_order = legend_order\n\n\nclass _LinePlotter(_RelationalPlotter):\n\n _legend_attributes = [\"color\", \"linewidth\", \"marker\", \"dashes\"]\n _legend_func = \"plot\"\n\n def __init__(\n self, *,\n data=None, variables={},\n estimator=None, n_boot=None, seed=None, errorbar=None,\n sort=True, orient=\"x\", err_style=None, err_kws=None, legend=None\n ):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * mpl.rcParams[\"lines.linewidth\"]\n )\n\n super().__init__(data=data, variables=variables)\n\n self.estimator = estimator\n self.errorbar = errorbar\n self.n_boot = n_boot\n self.seed = seed\n self.sort = sort\n self.orient = orient\n self.err_style = err_style\n self.err_kws = {} if err_kws is None else err_kws\n\n self.legend = legend\n\n def plot(self, ax, kws):\n \"\"\"Draw the plot onto an axes, passing matplotlib kwargs.\"\"\"\n\n # Draw a test plot, using the passed in kwargs. The goal here is to\n # honor both (a) the current state of the plot cycler and (b) the\n # specified kwargs on all the lines we will draw, overriding when\n # relevant with the data semantics. Note that we won't cycle\n # internally; in other words, if `hue` is not used, all elements will\n # have the same color, but they will have the color that you would have\n # gotten from the corresponding matplotlib function, and calling the\n # function will advance the axes property cycle.\n\n kws.setdefault(\"markeredgewidth\", kws.pop(\"mew\", .75))\n kws.setdefault(\"markeredgecolor\", kws.pop(\"mec\", \"w\"))\n\n # Set default error kwargs\n err_kws = self.err_kws.copy()\n if self.err_style == \"band\":\n err_kws.setdefault(\"alpha\", .2)\n elif self.err_style == \"bars\":\n pass\n elif self.err_style is not None:\n err = \"`err_style` must be 'band' or 'bars', not {}\"\n raise ValueError(err.format(self.err_style))\n\n # Initialize the aggregation object\n agg = EstimateAggregator(\n self.estimator, self.errorbar, n_boot=self.n_boot, seed=self.seed,\n )\n\n # TODO abstract variable to aggregate over here-ish. Better name?\n orient = self.orient\n if orient not in {\"x\", \"y\"}:\n err = f\"`orient` must be either 'x' or 'y', not {orient!r}.\"\n raise ValueError(err)\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n\n # TODO How to handle NA? We don't want NA to propagate through to the\n # estimate/CI when some values are present, but we would also like\n # matplotlib to show \"gaps\" in the line when all values are missing.\n # This is straightforward absent aggregation, but complicated with it.\n # If we want to use nas, we need to conditionalize dropna in iter_data.\n\n # Loop over the semantic subsets and add to the plot\n grouping_vars = \"hue\", \"size\", \"style\"\n for sub_vars, sub_data in self.iter_data(grouping_vars, from_comp_data=True):\n\n if self.sort:\n sort_vars = [\"units\", orient, other]\n sort_cols = [var for var in sort_vars if var in self.variables]\n sub_data = sub_data.sort_values(sort_cols)\n\n if self.estimator is not None:\n if \"units\" in self.variables:\n # TODO eventually relax this constraint\n err = \"estimator must be None when specifying units\"\n raise ValueError(err)\n grouped = sub_data.groupby(orient, sort=self.sort)\n # Could pass as_index=False instead of reset_index,\n # but that fails on a corner case with older pandas.\n sub_data = grouped.apply(agg, other).reset_index()\n\n # TODO this is pretty ad hoc ; see GH2409\n for var in \"xy\":\n if self._log_scaled(var):\n for col in sub_data.filter(regex=f\"^{var}\"):\n sub_data[col] = np.power(10, sub_data[col])\n\n # --- Draw the main line(s)\n\n if \"units\" in self.variables: # XXX why not add to grouping variables?\n lines = []\n for _, unit_data in sub_data.groupby(\"units\"):\n lines.extend(ax.plot(unit_data[\"x\"], unit_data[\"y\"], **kws))\n else:\n lines = ax.plot(sub_data[\"x\"], sub_data[\"y\"], **kws)\n\n for line in lines:\n\n if \"hue\" in sub_vars:\n line.set_color(self._hue_map(sub_vars[\"hue\"]))\n\n if \"size\" in sub_vars:\n line.set_linewidth(self._size_map(sub_vars[\"size\"]))\n\n if \"style\" in sub_vars:\n attributes = self._style_map(sub_vars[\"style\"])\n if \"dashes\" in attributes:\n line.set_dashes(attributes[\"dashes\"])\n if \"marker\" in attributes:\n line.set_marker(attributes[\"marker\"])\n\n line_color = line.get_color()\n line_alpha = line.get_alpha()\n line_capstyle = line.get_solid_capstyle()\n\n # --- Draw the confidence intervals\n\n if self.estimator is not None and self.errorbar is not None:\n\n # TODO handling of orientation will need to happen here\n\n if self.err_style == \"band\":\n\n func = {\"x\": ax.fill_between, \"y\": ax.fill_betweenx}[orient]\n func(\n sub_data[orient],\n sub_data[f\"{other}min\"], sub_data[f\"{other}max\"],\n color=line_color, **err_kws\n )\n\n elif self.err_style == \"bars\":\n\n error_param = {\n f\"{other}err\": (\n sub_data[other] - sub_data[f\"{other}min\"],\n sub_data[f\"{other}max\"] - sub_data[other],\n )\n }\n ebars = ax.errorbar(\n sub_data[\"x\"], sub_data[\"y\"], **error_param,\n linestyle=\"\", color=line_color, alpha=line_alpha,\n **err_kws\n )\n\n # Set the capstyle properly on the error bars\n for obj in ebars.get_children():\n if isinstance(obj, mpl.collections.LineCollection):\n obj.set_capstyle(line_capstyle)\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)\n\n\nclass _ScatterPlotter(_RelationalPlotter):\n\n _legend_attributes = [\"color\", \"s\", \"marker\"]\n _legend_func = \"scatter\"\n\n def __init__(self, *, data=None, variables={}, legend=None):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * np.square(mpl.rcParams[\"lines.markersize\"])\n )\n\n super().__init__(data=data, variables=variables)\n\n self.legend = legend\n\n def plot(self, ax, kws):\n\n # --- Determine the visual attributes of the plot\n\n data = self.plot_data.dropna()\n if data.empty:\n return\n\n # Define the vectors of x and y positions\n empty = np.full(len(data), np.nan)\n x = data.get(\"x\", empty)\n y = data.get(\"y\", empty)\n\n if \"style\" in self.variables:\n # Use a representative marker so scatter sets the edgecolor\n # properly for line art markers. We currently enforce either\n # all or none line art so this works.\n example_level = self._style_map.levels[0]\n example_marker = self._style_map(example_level, \"marker\")\n kws.setdefault(\"marker\", example_marker)\n\n # Conditionally set the marker edgecolor based on whether the marker is \"filled\"\n # See https://github.com/matplotlib/matplotlib/issues/17849 for context\n m = kws.get(\"marker\", mpl.rcParams.get(\"marker\", \"o\"))\n if not isinstance(m, mpl.markers.MarkerStyle):\n # TODO in more recent matplotlib (which?) can pass a MarkerStyle here\n m = mpl.markers.MarkerStyle(m)\n if m.is_filled():\n kws.setdefault(\"edgecolor\", \"w\")\n\n # Draw the scatter plot\n points = ax.scatter(x=x, y=y, **kws)\n\n # Apply the mapping from semantic variables to artist attributes\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(data[\"hue\"]))\n\n if \"size\" in self.variables:\n points.set_sizes(self._size_map(data[\"size\"]))\n\n if \"style\" in self.variables:\n p = [self._style_map(val, \"path\") for val in data[\"style\"]]\n points.set_paths(p)\n\n # Apply dependent default attributes\n\n if \"linewidth\" not in kws:\n sizes = points.get_sizes()\n points.set_linewidths(.08 * np.sqrt(np.percentile(sizes, 10)))\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)\n\n\ndef lineplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None, units=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n dashes=True, markers=None, style_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, seed=None,\n orient=\"x\", sort=True, err_style=\"band\", err_kws=None,\n legend=\"auto\", ci=\"deprecated\", ax=None, **kwargs\n):\n\n # Handle deprecation of ci parameter\n errorbar = _deprecate_ci(errorbar, ci)\n\n variables = _LinePlotter.get_semantics(locals())\n p = _LinePlotter(\n data=data, variables=variables,\n estimator=estimator, n_boot=n_boot, seed=seed, errorbar=errorbar,\n sort=sort, orient=orient, err_style=err_style, err_kws=err_kws,\n legend=legend,\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, dashes=dashes, order=style_order)\n\n if ax is None:\n ax = plt.gca()\n\n if style is None and not {\"ls\", \"linestyle\"} & set(kwargs): # XXX\n kwargs[\"dashes\"] = \"\" if dashes is None or isinstance(dashes, bool) else dashes\n\n if not p.has_xy_data:\n return ax\n\n p._attach(ax)\n\n # Other functions have color as an explicit param,\n # and we should probably do that here too\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n p.plot(ax, kwargs)\n return ax\n\n\nlineplot.__doc__ = \"\"\"\\\nDraw a line plot with possibility of several semantic groupings.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nBy default, the plot aggregates over multiple `y` values at each value of\n`x` and shows an estimate of the central tendency and a confidence\ninterval for that estimate.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nhue : vector or key in `data`\n Grouping variable that will produce lines with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in `data`\n Grouping variable that will produce lines with different widths.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in `data`\n Grouping variable that will produce lines with different dashes\n and/or markers. Can have a numeric dtype but will always be treated\n as categorical.\n{params.rel.units}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.dashes}\n{params.rel.markers}\n{params.rel.style_order}\n{params.rel.estimator}\n{params.stat.errorbar}\n{params.rel.n_boot}\n{params.rel.seed}\norient : \"x\" or \"y\"\n Dimension along which the data are sorted / aggregated. Equivalently,\n the \"independent variable\" of the resulting function.\nsort : boolean\n If True, the data will be sorted by the x and y variables, otherwise\n lines will connect points in the order they appear in the dataset.\nerr_style : \"band\" or \"bars\"\n Whether to draw the confidence intervals with translucent error bands\n or discrete error bars.\nerr_kws : dict of keyword arguments\n Additional parameters to control the aesthetics of the error bars. The\n kwargs are passed either to :meth:`matplotlib.axes.Axes.fill_between`\n or :meth:`matplotlib.axes.Axes.errorbar`, depending on `err_style`.\n{params.rel.legend}\n{params.rel.ci}\n{params.core.ax}\nkwargs : key, value mappings\n Other keyword arguments are passed down to\n :meth:`matplotlib.axes.Axes.plot`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.scatterplot}\n{seealso.pointplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/lineplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef scatterplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=True, style_order=None, legend=\"auto\", ax=None,\n **kwargs\n):\n\n variables = _ScatterPlotter.get_semantics(locals())\n p = _ScatterPlotter(data=data, variables=variables, legend=legend)\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, order=style_order)\n\n if ax is None:\n ax = plt.gca()\n\n if not p.has_xy_data:\n return ax\n\n p._attach(ax)\n\n # Other functions have color as an explicit param,\n # and we should probably do that here too\n color = kwargs.pop(\"color\", None)\n kwargs[\"color\"] = _default_color(ax.scatter, hue, color, kwargs)\n\n p.plot(ax, kwargs)\n\n return ax\n\n\nscatterplot.__doc__ = \"\"\"\\\nDraw a scatter plot with possibility of several semantic groupings.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nhue : vector or key in `data`\n Grouping variable that will produce points with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in `data`\n Grouping variable that will produce points with different sizes.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in `data`\n Grouping variable that will produce points with different markers.\n Can have a numeric dtype but will always be treated as categorical.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.markers}\n{params.rel.style_order}\n{params.rel.legend}\n{params.core.ax}\nkwargs : key, value mappings\n Other keyword arguments are passed down to\n :meth:`matplotlib.axes.Axes.scatter`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.lineplot}\n{seealso.stripplot}\n{seealso.swarmplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/scatterplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef relplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None, units=None,\n row=None, col=None, col_wrap=None, row_order=None, col_order=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=None, dashes=None, style_order=None,\n legend=\"auto\", kind=\"scatter\", height=5, aspect=1, facet_kws=None,\n **kwargs\n):\n\n if kind == \"scatter\":\n\n plotter = _ScatterPlotter\n func = scatterplot\n markers = True if markers is None else markers\n\n elif kind == \"line\":\n\n plotter = _LinePlotter\n func = lineplot\n dashes = True if dashes is None else dashes\n\n else:\n err = f\"Plot kind {kind} not recognized\"\n raise ValueError(err)\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\n \"relplot is a figure-level function and does not accept \"\n \"the `ax` parameter. You may wish to try {}\".format(kind + \"plot\")\n )\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n # Use the full dataset to map the semantics\n p = plotter(\n data=data,\n variables=plotter.get_semantics(locals()),\n legend=legend,\n )\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, dashes=dashes, order=style_order)\n\n # Extract the semantic mappings\n if \"hue\" in p.variables:\n palette = p._hue_map.lookup_table\n hue_order = p._hue_map.levels\n hue_norm = p._hue_map.norm\n else:\n palette = hue_order = hue_norm = None\n\n if \"size\" in p.variables:\n sizes = p._size_map.lookup_table\n size_order = p._size_map.levels\n size_norm = p._size_map.norm\n\n if \"style\" in p.variables:\n style_order = p._style_map.levels\n if markers:\n markers = {k: p._style_map(k, \"marker\") for k in style_order}\n else:\n markers = None\n if dashes:\n dashes = {k: p._style_map(k, \"dashes\") for k in style_order}\n else:\n dashes = None\n else:\n markers = dashes = style_order = None\n\n # Now extract the data that would be used to draw a single plot\n variables = p.variables\n plot_data = p.plot_data\n plot_semantics = p.semantics\n\n # Define the common plotting parameters\n plot_kws = dict(\n palette=palette, hue_order=hue_order, hue_norm=hue_norm,\n sizes=sizes, size_order=size_order, size_norm=size_norm,\n markers=markers, dashes=dashes, style_order=style_order,\n legend=False,\n )\n plot_kws.update(kwargs)\n if kind == \"scatter\":\n plot_kws.pop(\"dashes\")\n\n # Add the grid semantics onto the plotter\n grid_semantics = \"row\", \"col\"\n p.semantics = plot_semantics + grid_semantics\n p.assign_variables(\n data=data,\n variables=dict(\n x=x, y=y,\n hue=hue, size=size, style=style, units=units,\n row=row, col=col,\n ),\n )\n\n # Define the named variables for plotting on each facet\n # Rename the variables with a leading underscore to avoid\n # collisions with faceting variable names\n plot_variables = {v: f\"_{v}\" for v in variables}\n plot_kws.update(plot_variables)\n\n # Pass the row/col variables to FacetGrid with their original\n # names so that the axes titles render correctly\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n grid_kws = {v: p.variables.get(v) for v in grid_semantics}\n\n # Rename the columns of the plot_data structure appropriately\n new_cols = plot_variables.copy()\n new_cols.update(grid_kws)\n full_data = p.plot_data.rename(columns=new_cols)\n\n # Set up the FacetGrid object\n facet_kws = {} if facet_kws is None else facet_kws.copy()\n g = FacetGrid(\n data=full_data.dropna(axis=1, how=\"all\"),\n **grid_kws,\n col_wrap=col_wrap, row_order=row_order, col_order=col_order,\n height=height, aspect=aspect, dropna=False,\n **facet_kws\n )\n\n # Draw the plot\n g.map_dataframe(func, **plot_kws)\n\n # Label the axes, using the original variables\n g.set(xlabel=variables.get(\"x\"), ylabel=variables.get(\"y\"))\n\n # Show the legend\n if legend:\n # Replace the original plot data so the legend uses\n # numeric data with the correct type\n p.plot_data = plot_data\n p.add_legend_data(g.axes.flat[0])\n if p.legend_data:\n g.add_legend(legend_data=p.legend_data,\n label_order=p.legend_order,\n title=p.legend_title,\n adjust_subtitles=True)\n\n # Rename the columns of the FacetGrid's `data` attribute\n # to match the original column names\n orig_cols = {\n f\"_{k}\": f\"_{k}_\" if v is None else v for k, v in variables.items()\n }\n grid_data = g.data.rename(columns=orig_cols)\n if data is not None and (x is not None or y is not None):\n if not isinstance(data, pd.DataFrame):\n data = pd.DataFrame(data)\n g.data = pd.merge(\n data,\n grid_data[grid_data.columns.difference(data.columns)],\n left_index=True,\n right_index=True,\n )\n else:\n g.data = grid_data\n\n return g\n\n\nrelplot.__doc__ = \"\"\"\\\nFigure-level interface for drawing relational plots onto a FacetGrid.\n\nThis function provides access to several different axes-level functions\nthat show the relationship between two variables with semantic mappings\nof subsets. The `kind` parameter selects the underlying axes-level\nfunction to use:\n\n- :func:`scatterplot` (with `kind=\"scatter\"`; the default)\n- :func:`lineplot` (with `kind=\"line\"`)\n\nExtra keyword arguments are passed to the underlying function, so you\nshould refer to the documentation for each to see kind-specific options.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nAfter plotting, the :class:`FacetGrid` with the plot is returned and can\nbe used directly to tweak supporting plot details or add other layers.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nhue : vector or key in `data`\n Grouping variable that will produce elements with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in `data`\n Grouping variable that will produce elements with different sizes.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in `data`\n Grouping variable that will produce elements with different styles.\n Can have a numeric dtype but will always be treated as categorical.\n{params.rel.units}\n{params.facets.rowcol}\n{params.facets.col_wrap}\nrow_order, col_order : lists of strings\n Order to organize the rows and/or columns of the grid in, otherwise the\n orders are inferred from the data objects.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.style_order}\n{params.rel.dashes}\n{params.rel.markers}\n{params.rel.legend}\nkind : string\n Kind of plot to draw, corresponding to a seaborn relational plot.\n Options are `\"scatter\"` or `\"line\"`.\n{params.facets.height}\n{params.facets.aspect}\nfacet_kws : dict\n Dictionary of other keyword arguments to pass to :class:`FacetGrid`.\nkwargs : key, value pairings\n Other keyword arguments are passed through to the underlying plotting\n function.\n\nReturns\n-------\n{returns.facetgrid}\n\nExamples\n--------\n\n.. include:: ../docstrings/relplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n"},{"col":0,"comment":"Return levels and formatted levels for brief numeric legends.","endLoc":706,"header":"def locator_to_legend_entries(locator, limits, dtype)","id":1161,"name":"locator_to_legend_entries","nodeType":"Function","startLoc":683,"text":"def locator_to_legend_entries(locator, limits, dtype):\n \"\"\"Return levels and formatted levels for brief numeric legends.\"\"\"\n raw_levels = locator.tick_values(*limits).astype(dtype)\n\n # The locator can return ticks outside the limits, clip them here\n raw_levels = [l for l in raw_levels if l >= limits[0] and l <= limits[1]]\n\n class dummy_axis:\n def get_view_interval(self):\n return limits\n\n if isinstance(locator, mpl.ticker.LogLocator):\n formatter = mpl.ticker.LogFormatter()\n else:\n formatter = mpl.ticker.ScalarFormatter()\n formatter.axis = dummy_axis()\n\n # TODO: The following two lines should be replaced\n # once pinned matplotlib>=3.1.0 with:\n # formatted_levels = formatter.format_ticks(raw_levels)\n formatter.set_locs(raw_levels)\n formatted_levels = [formatter(x) for x in raw_levels]\n\n return raw_levels, formatted_levels"},{"col":4,"comment":"Divide the data by the difference between the max and min\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n standardized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n\n ","endLoc":898,"header":"@staticmethod\n def standard_scale(data2d, axis=1)","id":1162,"name":"standard_scale","nodeType":"Function","startLoc":866,"text":"@staticmethod\n def standard_scale(data2d, axis=1):\n \"\"\"Divide the data by the difference between the max and min\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n standardized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n\n \"\"\"\n # Normalize these values to range from 0 to 1\n if axis == 1:\n standardized = data2d\n else:\n standardized = data2d.T\n\n subtract = standardized.min()\n standardized = (standardized - subtract) / (\n standardized.max() - standardized.min())\n\n if axis == 1:\n return standardized\n else:\n return standardized.T"},{"col":4,"comment":"Return True at least one of x or y is defined.","endLoc":136,"header":"@property\n def has_xy_data(self)","id":1164,"name":"has_xy_data","nodeType":"Function","startLoc":132,"text":"@property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n # TODO see above points about where this should go\n return bool({\"x\", \"y\"} & set(self.variables))"},{"className":"EstimateAggregator","col":0,"comment":"null","endLoc":516,"id":1165,"nodeType":"Class","startLoc":454,"text":"class EstimateAggregator:\n\n def __init__(self, estimator, errorbar=None, **boot_kws):\n \"\"\"\n Data aggregator that produces an estimate and error bar interval.\n\n Parameters\n ----------\n estimator : callable or string\n Function (or method name) that maps a vector to a scalar.\n errorbar : string, (string, number) tuple, or callable\n Name of errorbar method (either \"ci\", \"pi\", \"se\", or \"sd\"), or a tuple\n with a method name and a level parameter, or a function that maps from a\n vector to a (min, max) interval.\n boot_kws\n Additional keywords are passed to bootstrap when error_method is \"ci\".\n\n \"\"\"\n self.estimator = estimator\n\n method, level = _validate_errorbar_arg(errorbar)\n self.error_method = method\n self.error_level = level\n\n self.boot_kws = boot_kws\n\n def __call__(self, data, var):\n \"\"\"Aggregate over `var` column of `data` with estimate and error interval.\"\"\"\n vals = data[var]\n if callable(self.estimator):\n # You would think we could pass to vals.agg, and yet:\n # https://github.com/mwaskom/seaborn/issues/2943\n estimate = self.estimator(vals)\n else:\n estimate = vals.agg(self.estimator)\n\n # Options that produce no error bars\n if self.error_method is None:\n err_min = err_max = np.nan\n elif len(data) <= 1:\n err_min = err_max = np.nan\n\n # Generic errorbars from user-supplied function\n elif callable(self.error_method):\n err_min, err_max = self.error_method(vals)\n\n # Parametric options\n elif self.error_method == \"sd\":\n half_interval = vals.std() * self.error_level\n err_min, err_max = estimate - half_interval, estimate + half_interval\n elif self.error_method == \"se\":\n half_interval = vals.sem() * self.error_level\n err_min, err_max = estimate - half_interval, estimate + half_interval\n\n # Nonparametric options\n elif self.error_method == \"pi\":\n err_min, err_max = _percentile_interval(vals, self.error_level)\n elif self.error_method == \"ci\":\n units = data.get(\"units\", None)\n boots = bootstrap(vals, units=units, func=self.estimator, **self.boot_kws)\n err_min, err_max = _percentile_interval(boots, self.error_level)\n\n return pd.Series({var: estimate, f\"{var}min\": err_min, f\"{var}max\": err_max})"},{"col":4,"comment":"Aggregate over `var` column of `data` with estimate and error interval.","endLoc":516,"header":"def __call__(self, data, var)","id":1166,"name":"__call__","nodeType":"Function","startLoc":480,"text":"def __call__(self, data, var):\n \"\"\"Aggregate over `var` column of `data` with estimate and error interval.\"\"\"\n vals = data[var]\n if callable(self.estimator):\n # You would think we could pass to vals.agg, and yet:\n # https://github.com/mwaskom/seaborn/issues/2943\n estimate = self.estimator(vals)\n else:\n estimate = vals.agg(self.estimator)\n\n # Options that produce no error bars\n if self.error_method is None:\n err_min = err_max = np.nan\n elif len(data) <= 1:\n err_min = err_max = np.nan\n\n # Generic errorbars from user-supplied function\n elif callable(self.error_method):\n err_min, err_max = self.error_method(vals)\n\n # Parametric options\n elif self.error_method == \"sd\":\n half_interval = vals.std() * self.error_level\n err_min, err_max = estimate - half_interval, estimate + half_interval\n elif self.error_method == \"se\":\n half_interval = vals.sem() * self.error_level\n err_min, err_max = estimate - half_interval, estimate + half_interval\n\n # Nonparametric options\n elif self.error_method == \"pi\":\n err_min, err_max = _percentile_interval(vals, self.error_level)\n elif self.error_method == \"ci\":\n units = data.get(\"units\", None)\n boots = bootstrap(vals, units=units, func=self.estimator, **self.boot_kws)\n err_min, err_max = _percentile_interval(boots, self.error_level)\n\n return pd.Series({var: estimate, f\"{var}min\": err_min, f\"{var}max\": err_max})"},{"col":0,"comment":"Given a seed in one of many formats, return a random number generator.\n\n Generalizes across the numpy 1.17 changes, preferring newer functionality.\n\n ","endLoc":142,"header":"def _handle_random_seed(seed=None)","id":1167,"name":"_handle_random_seed","nodeType":"Function","startLoc":121,"text":"def _handle_random_seed(seed=None):\n \"\"\"Given a seed in one of many formats, return a random number generator.\n\n Generalizes across the numpy 1.17 changes, preferring newer functionality.\n\n \"\"\"\n if isinstance(seed, np.random.RandomState):\n rng = seed\n else:\n try:\n # General interface for seeding on numpy >= 1.17\n rng = np.random.default_rng(seed)\n except AttributeError:\n # We are on numpy < 1.17, handle options ourselves\n if isinstance(seed, (numbers.Integral, np.integer)):\n rng = np.random.RandomState(seed)\n elif seed is None:\n rng = np.random.RandomState()\n else:\n err = \"{} cannot be used to seed the random number generator\"\n raise ValueError(err.format(seed))\n return rng"},{"col":4,"comment":"Preprocess {row/col}_colors to extract labels and convert colors.","endLoc":814,"header":"def _preprocess_colors(self, data, colors, axis)","id":1168,"name":"_preprocess_colors","nodeType":"Function","startLoc":774,"text":"def _preprocess_colors(self, data, colors, axis):\n \"\"\"Preprocess {row/col}_colors to extract labels and convert colors.\"\"\"\n labels = None\n\n if colors is not None:\n if isinstance(colors, (pd.DataFrame, pd.Series)):\n\n # If data is unindexed, raise\n if (not hasattr(data, \"index\") and axis == 0) or (\n not hasattr(data, \"columns\") and axis == 1\n ):\n axis_name = \"col\" if axis else \"row\"\n msg = (f\"{axis_name}_colors indices can't be matched with data \"\n f\"indices. Provide {axis_name}_colors as a non-indexed \"\n \"datatype, e.g. by using `.to_numpy()``\")\n raise TypeError(msg)\n\n # Ensure colors match data indices\n if axis == 0:\n colors = colors.reindex(data.index)\n else:\n colors = colors.reindex(data.columns)\n\n # Replace na's with white color\n # TODO We should set these to transparent instead\n colors = colors.astype(object).fillna('white')\n\n # Extract color values and labels from frame/series\n if isinstance(colors, pd.DataFrame):\n labels = list(colors.columns)\n colors = colors.T.values\n else:\n if colors.name is None:\n labels = [\"\"]\n else:\n labels = [colors.name]\n colors = colors.values\n\n colors = _convert_colors(colors)\n\n return colors, labels"},{"col":4,"comment":"Add artists that reflect semantic mappings and put then in a legend.","endLoc":171,"header":"def _add_legend(\n self,\n ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,\n )","id":1169,"name":"_add_legend","nodeType":"Function","startLoc":138,"text":"def _add_legend(\n self,\n ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,\n ):\n \"\"\"Add artists that reflect semantic mappings and put then in a legend.\"\"\"\n # TODO note that this doesn't handle numeric mappings like the relational plots\n handles = []\n labels = []\n for level in self._hue_map.levels:\n color = self._hue_map(level)\n\n kws = self._artist_kws(\n artist_kws, fill, element, multiple, color, alpha\n )\n\n # color gets added to the kws to workaround an issue with barplot's color\n # cycle integration but it causes problems in this context where we are\n # setting artist properties directly, so pop it off here\n if \"facecolor\" in kws:\n kws.pop(\"color\", None)\n\n handles.append(artist(**kws))\n labels.append(level)\n\n if isinstance(ax_obj, mpl.axes.Axes):\n ax_obj.legend(handles, labels, title=self.variables[\"hue\"], **legend_kws)\n else: # i.e. a FacetGrid. TODO make this better\n legend_data = dict(zip(labels, handles))\n ax_obj.add_legend(\n legend_data,\n title=self.variables[\"hue\"],\n label_order=self.var_levels[\"hue\"],\n **legend_kws\n )"},{"col":0,"comment":"Return a percentile interval from data of a given width.","endLoc":523,"header":"def _percentile_interval(data, width)","id":1170,"name":"_percentile_interval","nodeType":"Function","startLoc":519,"text":"def _percentile_interval(data, width):\n \"\"\"Return a percentile interval from data of a given width.\"\"\"\n edge = (100 - width) / 2\n percentiles = edge, 100 - edge\n return np.nanpercentile(data, percentiles)"},{"attributeType":"null","col":8,"comment":"null","endLoc":475,"id":1171,"name":"error_method","nodeType":"Attribute","startLoc":475,"text":"self.error_method"},{"attributeType":"null","col":8,"comment":"null","endLoc":476,"id":1172,"name":"error_level","nodeType":"Attribute","startLoc":476,"text":"self.error_level"},{"attributeType":"str","col":8,"comment":"null","endLoc":472,"id":1173,"name":"estimator","nodeType":"Attribute","startLoc":472,"text":"self.estimator"},{"attributeType":"dict","col":8,"comment":"null","endLoc":478,"id":1174,"name":"boot_kws","nodeType":"Attribute","startLoc":478,"text":"self.boot_kws"},{"className":"DocstringComponents","col":0,"comment":"null","endLoc":59,"id":1175,"nodeType":"Class","startLoc":6,"text":"class DocstringComponents:\n\n regexp = re.compile(r\"\\n((\\n|.)+)\\n\\s*\", re.MULTILINE)\n\n def __init__(self, comp_dict, strip_whitespace=True):\n \"\"\"Read entries from a dict, optionally stripping outer whitespace.\"\"\"\n if strip_whitespace:\n entries = {}\n for key, val in comp_dict.items():\n m = re.match(self.regexp, val)\n if m is None:\n entries[key] = val\n else:\n entries[key] = m.group(1)\n else:\n entries = comp_dict.copy()\n\n self.entries = entries\n\n def __getattr__(self, attr):\n \"\"\"Provide dot access to entries for clean raw docstrings.\"\"\"\n if attr in self.entries:\n return self.entries[attr]\n else:\n try:\n return self.__getattribute__(attr)\n except AttributeError as err:\n # If Python is run with -OO, it will strip docstrings and our lookup\n # from self.entries will fail. We check for __debug__, which is actually\n # set to False by -O (it is True for normal execution).\n # But we only want to see an error when building the docs;\n # not something users should see, so this slight inconsistency is fine.\n if __debug__:\n raise err\n else:\n pass\n\n @classmethod\n def from_nested_components(cls, **kwargs):\n \"\"\"Add multiple sub-sets of components.\"\"\"\n return cls(kwargs, strip_whitespace=False)\n\n @classmethod\n def from_function_params(cls, func):\n \"\"\"Use the numpydoc parser to extract components from existing func.\"\"\"\n params = NumpyDocString(pydoc.getdoc(func))[\"Parameters\"]\n comp_dict = {}\n for p in params:\n name = p.name\n type = p.type\n desc = \"\\n \".join(p.desc)\n comp_dict[name] = f\"{name} : {type}\\n {desc}\"\n\n return cls(comp_dict)"},{"col":4,"comment":"Handle differences between artists in filled/unfilled plots.","endLoc":194,"header":"def _artist_kws(self, kws, fill, element, multiple, color, alpha)","id":1176,"name":"_artist_kws","nodeType":"Function","startLoc":173,"text":"def _artist_kws(self, kws, fill, element, multiple, color, alpha):\n \"\"\"Handle differences between artists in filled/unfilled plots.\"\"\"\n kws = kws.copy()\n if fill:\n kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)\n kws.setdefault(\"facecolor\", to_rgba(color, alpha))\n\n if element == \"bars\":\n # Make bar() interface with property cycle correctly\n # https://github.com/matplotlib/matplotlib/issues/19385\n kws[\"color\"] = \"none\"\n\n if multiple in [\"stack\", \"fill\"] or element == \"bars\":\n kws.setdefault(\"edgecolor\", mpl.rcParams[\"patch.edgecolor\"])\n else:\n kws.setdefault(\"edgecolor\", to_rgba(color, 1))\n elif element == \"bars\":\n kws[\"facecolor\"] = \"none\"\n kws[\"edgecolor\"] = to_rgba(color, alpha)\n else:\n kws[\"color\"] = to_rgba(color, alpha)\n return kws"},{"col":4,"comment":"Read entries from a dict, optionally stripping outer whitespace.","endLoc":23,"header":"def __init__(self, comp_dict, strip_whitespace=True)","id":1177,"name":"__init__","nodeType":"Function","startLoc":10,"text":"def __init__(self, comp_dict, strip_whitespace=True):\n \"\"\"Read entries from a dict, optionally stripping outer whitespace.\"\"\"\n if strip_whitespace:\n entries = {}\n for key, val in comp_dict.items():\n m = re.match(self.regexp, val)\n if m is None:\n entries[key] = val\n else:\n entries[key] = m.group(1)\n else:\n entries = comp_dict.copy()\n\n self.entries = entries"},{"attributeType":"str","col":4,"comment":"null","endLoc":1575,"id":1178,"name":"_name","nodeType":"Attribute","startLoc":1575,"text":"_name"},{"col":0,"comment":"Convert either a list of colors or nested lists of colors to RGB.","endLoc":57,"header":"def _convert_colors(colors)","id":1179,"name":"_convert_colors","nodeType":"Function","startLoc":47,"text":"def _convert_colors(colors):\n \"\"\"Convert either a list of colors or nested lists of colors to RGB.\"\"\"\n to_rgb = mpl.colors.to_rgb\n\n try:\n to_rgb(colors[0])\n # If this works, there is only one level of colors\n return list(map(to_rgb, colors))\n except ValueError:\n # If we get here, we have nested lists\n return [list(map(to_rgb, l)) for l in colors]"},{"col":4,"comment":"Provide dot access to entries for clean raw docstrings.","endLoc":41,"header":"def __getattr__(self, attr)","id":1180,"name":"__getattr__","nodeType":"Function","startLoc":25,"text":"def __getattr__(self, attr):\n \"\"\"Provide dot access to entries for clean raw docstrings.\"\"\"\n if attr in self.entries:\n return self.entries[attr]\n else:\n try:\n return self.__getattribute__(attr)\n except AttributeError as err:\n # If Python is run with -OO, it will strip docstrings and our lookup\n # from self.entries will fail. We check for __debug__, which is actually\n # set to False by -O (it is True for normal execution).\n # But we only want to see an error when building the docs;\n # not something users should see, so this slight inconsistency is fine.\n if __debug__:\n raise err\n else:\n pass"},{"col":4,"comment":"null","endLoc":112,"header":"def __getattribute__(self, __name: str) -> Any","id":1181,"name":"__getattribute__","nodeType":"Function","startLoc":112,"text":"def __getattribute__(self, __name: str) -> Any: ..."},{"col":4,"comment":"Add multiple sub-sets of components.","endLoc":46,"header":"@classmethod\n def from_nested_components(cls, **kwargs)","id":1182,"name":"from_nested_components","nodeType":"Function","startLoc":43,"text":"@classmethod\n def from_nested_components(cls, **kwargs):\n \"\"\"Add multiple sub-sets of components.\"\"\"\n return cls(kwargs, strip_whitespace=False)"},{"col":4,"comment":"Use the numpydoc parser to extract components from existing func.","endLoc":59,"header":"@classmethod\n def from_function_params(cls, func)","id":1183,"name":"from_function_params","nodeType":"Function","startLoc":48,"text":"@classmethod\n def from_function_params(cls, func):\n \"\"\"Use the numpydoc parser to extract components from existing func.\"\"\"\n params = NumpyDocString(pydoc.getdoc(func))[\"Parameters\"]\n comp_dict = {}\n for p in params:\n name = p.name\n type = p.type\n desc = \"\\n \".join(p.desc)\n comp_dict[name] = f\"{name} : {type}\\n {desc}\"\n\n return cls(comp_dict)"},{"col":0,"comment":"Resample units instead of datapoints.","endLoc":118,"header":"def _structured_bootstrap(args, n_boot, units, func, func_kwargs, integers)","id":1185,"name":"_structured_bootstrap","nodeType":"Function","startLoc":102,"text":"def _structured_bootstrap(args, n_boot, units, func, func_kwargs, integers):\n \"\"\"Resample units instead of datapoints.\"\"\"\n unique_units = np.unique(units)\n n_units = len(unique_units)\n\n args = [[a[units == unit] for unit in unique_units] for a in args]\n\n boot_dist = []\n for i in range(int(n_boot)):\n resampler = integers(0, n_units, n_units, dtype=np.intp)\n sample = [[a[i] for i in resampler] for a in args]\n lengths = map(len, sample[0])\n resampler = [integers(0, n, n, dtype=np.intp) for n in lengths]\n sample = [[c.take(r, axis=0) for c, r in zip(a, resampler)] for a in sample]\n sample = list(map(np.concatenate, sample))\n boot_dist.append(func(*sample, **func_kwargs))\n return np.array(boot_dist)"},{"attributeType":"null","col":8,"comment":"null","endLoc":492,"id":1186,"name":"rotate","nodeType":"Attribute","startLoc":492,"text":"self.rotate"},{"attributeType":"str","col":25,"comment":"null","endLoc":524,"id":1187,"name":"ylabel","nodeType":"Attribute","startLoc":524,"text":"self.ylabel"},{"attributeType":"null","col":8,"comment":"null","endLoc":485,"id":1188,"name":"data","nodeType":"Attribute","startLoc":485,"text":"self.data"},{"attributeType":"null","col":8,"comment":"null","endLoc":487,"id":1189,"name":"shape","nodeType":"Attribute","startLoc":487,"text":"self.shape"},{"attributeType":"null","col":8,"comment":"null","endLoc":489,"id":1190,"name":"method","nodeType":"Attribute","startLoc":489,"text":"self.method"},{"attributeType":"list","col":12,"comment":"null","endLoc":523,"id":1191,"name":"yticklabels","nodeType":"Attribute","startLoc":523,"text":"self.yticklabels"},{"attributeType":"list","col":12,"comment":"null","endLoc":522,"id":1192,"name":"xticks","nodeType":"Attribute","startLoc":522,"text":"self.xticks"},{"attributeType":"null","col":8,"comment":"null","endLoc":491,"id":1193,"name":"label","nodeType":"Attribute","startLoc":491,"text":"self.label"},{"attributeType":"null","col":12,"comment":"null","endLoc":497,"id":1194,"name":"linkage","nodeType":"Attribute","startLoc":497,"text":"self.linkage"},{"attributeType":"null","col":8,"comment":"null","endLoc":490,"id":1195,"name":"axis","nodeType":"Attribute","startLoc":490,"text":"self.axis"},{"attributeType":"list","col":25,"comment":"null","endLoc":522,"id":1196,"name":"yticks","nodeType":"Attribute","startLoc":522,"text":"self.yticks"},{"attributeType":"null","col":8,"comment":"null","endLoc":484,"id":1197,"name":"array","nodeType":"Attribute","startLoc":484,"text":"self.array"},{"attributeType":"null","col":8,"comment":"null","endLoc":488,"id":1198,"name":"metric","nodeType":"Attribute","startLoc":488,"text":"self.metric"},{"attributeType":"null","col":8,"comment":"null","endLoc":527,"id":1199,"name":"independent_coord","nodeType":"Attribute","startLoc":527,"text":"self.independent_coord"},{"attributeType":"list","col":30,"comment":"null","endLoc":523,"id":1200,"name":"xticklabels","nodeType":"Attribute","startLoc":523,"text":"self.xticklabels"},{"attributeType":"str","col":12,"comment":"null","endLoc":524,"id":1201,"name":"xlabel","nodeType":"Attribute","startLoc":524,"text":"self.xlabel"},{"attributeType":"dict","col":8,"comment":"null","endLoc":498,"id":1202,"name":"dendrogram","nodeType":"Attribute","startLoc":498,"text":"self.dendrogram"},{"attributeType":"null","col":8,"comment":"null","endLoc":526,"id":1203,"name":"dependent_coord","nodeType":"Attribute","startLoc":526,"text":"self.dependent_coord"},{"className":"ClusterGrid","col":0,"comment":"null","endLoc":1143,"id":1204,"nodeType":"Class","startLoc":696,"text":"class ClusterGrid(Grid):\n\n def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None,\n figsize=None, row_colors=None, col_colors=None, mask=None,\n dendrogram_ratio=None, colors_ratio=None, cbar_pos=None):\n \"\"\"Grid object for organizing clustered heatmap input on to axes\"\"\"\n if _no_scipy:\n raise RuntimeError(\"ClusterGrid requires scipy to be available\")\n\n if isinstance(data, pd.DataFrame):\n self.data = data\n else:\n self.data = pd.DataFrame(data)\n\n self.data2d = self.format_data(self.data, pivot_kws, z_score,\n standard_scale)\n\n self.mask = _matrix_mask(self.data2d, mask)\n\n self._figure = plt.figure(figsize=figsize)\n\n self.row_colors, self.row_color_labels = \\\n self._preprocess_colors(data, row_colors, axis=0)\n self.col_colors, self.col_color_labels = \\\n self._preprocess_colors(data, col_colors, axis=1)\n\n try:\n row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio\n except TypeError:\n row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio\n\n try:\n row_colors_ratio, col_colors_ratio = colors_ratio\n except TypeError:\n row_colors_ratio = col_colors_ratio = colors_ratio\n\n width_ratios = self.dim_ratios(self.row_colors,\n row_dendrogram_ratio,\n row_colors_ratio)\n height_ratios = self.dim_ratios(self.col_colors,\n col_dendrogram_ratio,\n col_colors_ratio)\n\n nrows = 2 if self.col_colors is None else 3\n ncols = 2 if self.row_colors is None else 3\n\n self.gs = gridspec.GridSpec(nrows, ncols,\n width_ratios=width_ratios,\n height_ratios=height_ratios)\n\n self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0])\n self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1])\n self.ax_row_dendrogram.set_axis_off()\n self.ax_col_dendrogram.set_axis_off()\n\n self.ax_row_colors = None\n self.ax_col_colors = None\n\n if self.row_colors is not None:\n self.ax_row_colors = self._figure.add_subplot(\n self.gs[-1, 1])\n if self.col_colors is not None:\n self.ax_col_colors = self._figure.add_subplot(\n self.gs[1, -1])\n\n self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1])\n if cbar_pos is None:\n self.ax_cbar = self.cax = None\n else:\n # Initialize the colorbar axes in the gridspec so that tight_layout\n # works. We will move it where it belongs later. This is a hack.\n self.ax_cbar = self._figure.add_subplot(self.gs[0, 0])\n self.cax = self.ax_cbar # Backwards compatibility\n self.cbar_pos = cbar_pos\n\n self.dendrogram_row = None\n self.dendrogram_col = None\n\n def _preprocess_colors(self, data, colors, axis):\n \"\"\"Preprocess {row/col}_colors to extract labels and convert colors.\"\"\"\n labels = None\n\n if colors is not None:\n if isinstance(colors, (pd.DataFrame, pd.Series)):\n\n # If data is unindexed, raise\n if (not hasattr(data, \"index\") and axis == 0) or (\n not hasattr(data, \"columns\") and axis == 1\n ):\n axis_name = \"col\" if axis else \"row\"\n msg = (f\"{axis_name}_colors indices can't be matched with data \"\n f\"indices. Provide {axis_name}_colors as a non-indexed \"\n \"datatype, e.g. by using `.to_numpy()``\")\n raise TypeError(msg)\n\n # Ensure colors match data indices\n if axis == 0:\n colors = colors.reindex(data.index)\n else:\n colors = colors.reindex(data.columns)\n\n # Replace na's with white color\n # TODO We should set these to transparent instead\n colors = colors.astype(object).fillna('white')\n\n # Extract color values and labels from frame/series\n if isinstance(colors, pd.DataFrame):\n labels = list(colors.columns)\n colors = colors.T.values\n else:\n if colors.name is None:\n labels = [\"\"]\n else:\n labels = [colors.name]\n colors = colors.values\n\n colors = _convert_colors(colors)\n\n return colors, labels\n\n def format_data(self, data, pivot_kws, z_score=None,\n standard_scale=None):\n \"\"\"Extract variables from data or use directly.\"\"\"\n\n # Either the data is already in 2d matrix format, or need to do a pivot\n if pivot_kws is not None:\n data2d = data.pivot(**pivot_kws)\n else:\n data2d = data\n\n if z_score is not None and standard_scale is not None:\n raise ValueError(\n 'Cannot perform both z-scoring and standard-scaling on data')\n\n if z_score is not None:\n data2d = self.z_score(data2d, z_score)\n if standard_scale is not None:\n data2d = self.standard_scale(data2d, standard_scale)\n return data2d\n\n @staticmethod\n def z_score(data2d, axis=1):\n \"\"\"Standarize the mean and variance of the data axis\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n normalized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n \"\"\"\n if axis == 1:\n z_scored = data2d\n else:\n z_scored = data2d.T\n\n z_scored = (z_scored - z_scored.mean()) / z_scored.std()\n\n if axis == 1:\n return z_scored\n else:\n return z_scored.T\n\n @staticmethod\n def standard_scale(data2d, axis=1):\n \"\"\"Divide the data by the difference between the max and min\n\n Parameters\n ----------\n data2d : pandas.DataFrame\n Data to normalize\n axis : int\n Which axis to normalize across. If 0, normalize across rows, if 1,\n normalize across columns.\n\n Returns\n -------\n standardized : pandas.DataFrame\n Noramlized data with a mean of 0 and variance of 1 across the\n specified axis.\n\n \"\"\"\n # Normalize these values to range from 0 to 1\n if axis == 1:\n standardized = data2d\n else:\n standardized = data2d.T\n\n subtract = standardized.min()\n standardized = (standardized - subtract) / (\n standardized.max() - standardized.min())\n\n if axis == 1:\n return standardized\n else:\n return standardized.T\n\n def dim_ratios(self, colors, dendrogram_ratio, colors_ratio):\n \"\"\"Get the proportions of the figure taken up by each axes.\"\"\"\n ratios = [dendrogram_ratio]\n\n if colors is not None:\n # Colors are encoded as rgb, so there is an extra dimension\n if np.ndim(colors) > 2:\n n_colors = len(colors)\n else:\n n_colors = 1\n\n ratios += [n_colors * colors_ratio]\n\n # Add the ratio for the heatmap itself\n ratios.append(1 - sum(ratios))\n\n return ratios\n\n @staticmethod\n def color_list_to_matrix_and_cmap(colors, ind, axis=0):\n \"\"\"Turns a list of colors into a numpy matrix and matplotlib colormap\n\n These arguments can now be plotted using heatmap(matrix, cmap)\n and the provided colors will be plotted.\n\n Parameters\n ----------\n colors : list of matplotlib colors\n Colors to label the rows or columns of a dataframe.\n ind : list of ints\n Ordering of the rows or columns, to reorder the original colors\n by the clustered dendrogram order\n axis : int\n Which axis this is labeling\n\n Returns\n -------\n matrix : numpy.array\n A numpy array of integer values, where each indexes into the cmap\n cmap : matplotlib.colors.ListedColormap\n\n \"\"\"\n try:\n mpl.colors.to_rgb(colors[0])\n except ValueError:\n # We have a 2D color structure\n m, n = len(colors), len(colors[0])\n if not all(len(c) == n for c in colors[1:]):\n raise ValueError(\"Multiple side color vectors must have same size\")\n else:\n # We have one vector of colors\n m, n = 1, len(colors)\n colors = [colors]\n\n # Map from unique colors to colormap index value\n unique_colors = {}\n matrix = np.zeros((m, n), int)\n for i, inner in enumerate(colors):\n for j, color in enumerate(inner):\n idx = unique_colors.setdefault(color, len(unique_colors))\n matrix[i, j] = idx\n\n # Reorder for clustering and transpose for axis\n matrix = matrix[:, ind]\n if axis == 0:\n matrix = matrix.T\n\n cmap = mpl.colors.ListedColormap(list(unique_colors))\n return matrix, cmap\n\n def plot_dendrograms(self, row_cluster, col_cluster, metric, method,\n row_linkage, col_linkage, tree_kws):\n # Plot the row dendrogram\n if row_cluster:\n self.dendrogram_row = dendrogram(\n self.data2d, metric=metric, method=method, label=False, axis=0,\n ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage,\n tree_kws=tree_kws\n )\n else:\n self.ax_row_dendrogram.set_xticks([])\n self.ax_row_dendrogram.set_yticks([])\n # PLot the column dendrogram\n if col_cluster:\n self.dendrogram_col = dendrogram(\n self.data2d, metric=metric, method=method, label=False,\n axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage,\n tree_kws=tree_kws\n )\n else:\n self.ax_col_dendrogram.set_xticks([])\n self.ax_col_dendrogram.set_yticks([])\n despine(ax=self.ax_row_dendrogram, bottom=True, left=True)\n despine(ax=self.ax_col_dendrogram, bottom=True, left=True)\n\n def plot_colors(self, xind, yind, **kws):\n \"\"\"Plots color labels between the dendrogram and the heatmap\n\n Parameters\n ----------\n heatmap_kws : dict\n Keyword arguments heatmap\n\n \"\"\"\n # Remove any custom colormap and centering\n # TODO this code has consistently caused problems when we\n # have missed kwargs that need to be excluded that it might\n # be better to rewrite *in*clusively.\n kws = kws.copy()\n kws.pop('cmap', None)\n kws.pop('norm', None)\n kws.pop('center', None)\n kws.pop('annot', None)\n kws.pop('vmin', None)\n kws.pop('vmax', None)\n kws.pop('robust', None)\n kws.pop('xticklabels', None)\n kws.pop('yticklabels', None)\n\n # Plot the row colors\n if self.row_colors is not None:\n matrix, cmap = self.color_list_to_matrix_and_cmap(\n self.row_colors, yind, axis=0)\n\n # Get row_color labels\n if self.row_color_labels is not None:\n row_color_labels = self.row_color_labels\n else:\n row_color_labels = False\n\n heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors,\n xticklabels=row_color_labels, yticklabels=False, **kws)\n\n # Adjust rotation of labels\n if row_color_labels is not False:\n plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90)\n else:\n despine(self.ax_row_colors, left=True, bottom=True)\n\n # Plot the column colors\n if self.col_colors is not None:\n matrix, cmap = self.color_list_to_matrix_and_cmap(\n self.col_colors, xind, axis=1)\n\n # Get col_color labels\n if self.col_color_labels is not None:\n col_color_labels = self.col_color_labels\n else:\n col_color_labels = False\n\n heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors,\n xticklabels=False, yticklabels=col_color_labels, **kws)\n\n # Adjust rotation of labels, place on right side\n if col_color_labels is not False:\n self.ax_col_colors.yaxis.tick_right()\n plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0)\n else:\n despine(self.ax_col_colors, left=True, bottom=True)\n\n def plot_matrix(self, colorbar_kws, xind, yind, **kws):\n self.data2d = self.data2d.iloc[yind, xind]\n self.mask = self.mask.iloc[yind, xind]\n\n # Try to reorganize specified tick labels, if provided\n xtl = kws.pop(\"xticklabels\", \"auto\")\n try:\n xtl = np.asarray(xtl)[xind]\n except (TypeError, IndexError):\n pass\n ytl = kws.pop(\"yticklabels\", \"auto\")\n try:\n ytl = np.asarray(ytl)[yind]\n except (TypeError, IndexError):\n pass\n\n # Reorganize the annotations to match the heatmap\n annot = kws.pop(\"annot\", None)\n if annot is None or annot is False:\n pass\n else:\n if isinstance(annot, bool):\n annot_data = self.data2d\n else:\n annot_data = np.asarray(annot)\n if annot_data.shape != self.data2d.shape:\n err = \"`data` and `annot` must have same shape.\"\n raise ValueError(err)\n annot_data = annot_data[yind][:, xind]\n annot = annot_data\n\n # Setting ax_cbar=None in clustermap call implies no colorbar\n kws.setdefault(\"cbar\", self.ax_cbar is not None)\n heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar,\n cbar_kws=colorbar_kws, mask=self.mask,\n xticklabels=xtl, yticklabels=ytl, annot=annot, **kws)\n\n ytl = self.ax_heatmap.get_yticklabels()\n ytl_rot = None if not ytl else ytl[0].get_rotation()\n self.ax_heatmap.yaxis.set_ticks_position('right')\n self.ax_heatmap.yaxis.set_label_position('right')\n if ytl_rot is not None:\n ytl = self.ax_heatmap.get_yticklabels()\n plt.setp(ytl, rotation=ytl_rot)\n\n tight_params = dict(h_pad=.02, w_pad=.02)\n if self.ax_cbar is None:\n self._figure.tight_layout(**tight_params)\n else:\n # Turn the colorbar axes off for tight layout so that its\n # ticks don't interfere with the rest of the plot layout.\n # Then move it.\n self.ax_cbar.set_axis_off()\n self._figure.tight_layout(**tight_params)\n self.ax_cbar.set_axis_on()\n self.ax_cbar.set_position(self.cbar_pos)\n\n def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster,\n row_linkage, col_linkage, tree_kws, **kws):\n\n # heatmap square=True sets the aspect ratio on the axes, but that is\n # not compatible with the multi-axes layout of clustergrid\n if kws.get(\"square\", False):\n msg = \"``square=True`` ignored in clustermap\"\n warnings.warn(msg)\n kws.pop(\"square\")\n\n colorbar_kws = {} if colorbar_kws is None else colorbar_kws\n\n self.plot_dendrograms(row_cluster, col_cluster, metric, method,\n row_linkage=row_linkage, col_linkage=col_linkage,\n tree_kws=tree_kws)\n try:\n xind = self.dendrogram_col.reordered_ind\n except AttributeError:\n xind = np.arange(self.data2d.shape[1])\n try:\n yind = self.dendrogram_row.reordered_ind\n except AttributeError:\n yind = np.arange(self.data2d.shape[0])\n\n self.plot_colors(xind, yind, **kws)\n self.plot_matrix(colorbar_kws, xind, yind, **kws)\n return self"},{"col":4,"comment":"Get the proportions of the figure taken up by each axes.","endLoc":916,"header":"def dim_ratios(self, colors, dendrogram_ratio, colors_ratio)","id":1205,"name":"dim_ratios","nodeType":"Function","startLoc":900,"text":"def dim_ratios(self, colors, dendrogram_ratio, colors_ratio):\n \"\"\"Get the proportions of the figure taken up by each axes.\"\"\"\n ratios = [dendrogram_ratio]\n\n if colors is not None:\n # Colors are encoded as rgb, so there is an extra dimension\n if np.ndim(colors) > 2:\n n_colors = len(colors)\n else:\n n_colors = 1\n\n ratios += [n_colors * colors_ratio]\n\n # Add the ratio for the heatmap itself\n ratios.append(1 - sum(ratios))\n\n return ratios"},{"attributeType":"bool","col":4,"comment":"null","endLoc":161,"id":1206,"name":"legend","nodeType":"Attribute","startLoc":161,"text":"legend"},{"attributeType":"bool","col":4,"comment":"null","endLoc":162,"id":1207,"name":"normed","nodeType":"Attribute","startLoc":162,"text":"normed"},{"attributeType":"(float, float)","col":4,"comment":"null","endLoc":164,"id":1208,"name":"_default_range","nodeType":"Attribute","startLoc":164,"text":"_default_range"},{"className":"PointSize","col":0,"comment":"Size (diameter) of a point mark, in points, with scaling by area.","endLoc":269,"id":1209,"nodeType":"Class","startLoc":259,"text":"class PointSize(IntervalProperty):\n \"\"\"Size (diameter) of a point mark, in points, with scaling by area.\"\"\"\n _default_range = 2, 8 # TODO use rcparams?\n\n def _forward(self, values):\n \"\"\"Square native values to implement linear scaling of point area.\"\"\"\n return np.square(values)\n\n def _inverse(self, values):\n \"\"\"Invert areal values back to point diameter.\"\"\"\n return np.sqrt(values)"},{"col":4,"comment":"Square native values to implement linear scaling of point area.","endLoc":265,"header":"def _forward(self, values)","id":1210,"name":"_forward","nodeType":"Function","startLoc":263,"text":"def _forward(self, values):\n \"\"\"Square native values to implement linear scaling of point area.\"\"\"\n return np.square(values)"},{"col":4,"comment":"Invert areal values back to point diameter.","endLoc":269,"header":"def _inverse(self, values)","id":1211,"name":"_inverse","nodeType":"Function","startLoc":267,"text":"def _inverse(self, values):\n \"\"\"Invert areal values back to point diameter.\"\"\"\n return np.sqrt(values)"},{"attributeType":"(int, int)","col":4,"comment":"null","endLoc":261,"id":1212,"name":"_default_range","nodeType":"Attribute","startLoc":261,"text":"_default_range"},{"className":"LineWidth","col":0,"comment":"Thickness of a line mark, in points.","endLoc":278,"id":1213,"nodeType":"Class","startLoc":272,"text":"class LineWidth(IntervalProperty):\n \"\"\"Thickness of a line mark, in points.\"\"\"\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"lines.linewidth\"]\n return base * .5, base * 2"},{"col":4,"comment":"Min and max values used by default for semantic mapping.","endLoc":278,"header":"@property\n def default_range(self) -> tuple[float, float]","id":1214,"name":"default_range","nodeType":"Function","startLoc":274,"text":"@property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"lines.linewidth\"]\n return base * .5, base * 2"},{"className":"EdgeWidth","col":0,"comment":"Thickness of the edges on a patch mark, in points.","endLoc":287,"id":1215,"nodeType":"Class","startLoc":281,"text":"class EdgeWidth(IntervalProperty):\n \"\"\"Thickness of the edges on a patch mark, in points.\"\"\"\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"patch.linewidth\"]\n return base * .5, base * 2"},{"col":4,"comment":"Min and max values used by default for semantic mapping.","endLoc":287,"header":"@property\n def default_range(self) -> tuple[float, float]","id":1216,"name":"default_range","nodeType":"Function","startLoc":283,"text":"@property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"patch.linewidth\"]\n return base * .5, base * 2"},{"className":"Stroke","col":0,"comment":"Thickness of lines that define point glyphs.","endLoc":292,"id":1217,"nodeType":"Class","startLoc":290,"text":"class Stroke(IntervalProperty):\n \"\"\"Thickness of lines that define point glyphs.\"\"\"\n _default_range = .25, 2.5"},{"attributeType":"(float, float)","col":4,"comment":"null","endLoc":292,"id":1218,"name":"_default_range","nodeType":"Attribute","startLoc":292,"text":"_default_range"},{"className":"Alpha","col":0,"comment":"Opacity of the color values for an arbitrary mark.","endLoc":298,"id":1219,"nodeType":"Class","startLoc":295,"text":"class Alpha(IntervalProperty):\n \"\"\"Opacity of the color values for an arbitrary mark.\"\"\"\n _default_range = .3, .95\n # TODO validate / enforce that output is in [0, 1]"},{"attributeType":"(float, float)","col":4,"comment":"null","endLoc":297,"id":1220,"name":"_default_range","nodeType":"Attribute","startLoc":297,"text":"_default_range"},{"className":"Offset","col":0,"comment":"Offset for edge-aligned text, in point units.","endLoc":304,"id":1221,"nodeType":"Class","startLoc":301,"text":"class Offset(IntervalProperty):\n \"\"\"Offset for edge-aligned text, in point units.\"\"\"\n _default_range = 0, 5\n _legend = False"},{"attributeType":"(int, int)","col":4,"comment":"null","endLoc":303,"id":1222,"name":"_default_range","nodeType":"Attribute","startLoc":303,"text":"_default_range"},{"attributeType":"bool","col":4,"comment":"null","endLoc":304,"id":1223,"name":"_legend","nodeType":"Attribute","startLoc":304,"text":"_legend"},{"className":"FontSize","col":0,"comment":"Font size for textual marks, in points.","endLoc":315,"id":1224,"nodeType":"Class","startLoc":307,"text":"class FontSize(IntervalProperty):\n \"\"\"Font size for textual marks, in points.\"\"\"\n _legend = False\n\n @property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"font.size\"]\n return base * .5, base * 2"},{"col":4,"comment":"Min and max values used by default for semantic mapping.","endLoc":315,"header":"@property\n def default_range(self) -> tuple[float, float]","id":1225,"name":"default_range","nodeType":"Function","startLoc":311,"text":"@property\n def default_range(self) -> tuple[float, float]:\n \"\"\"Min and max values used by default for semantic mapping.\"\"\"\n base = mpl.rcParams[\"font.size\"]\n return base * .5, base * 2"},{"attributeType":"bool","col":4,"comment":"null","endLoc":309,"id":1226,"name":"_legend","nodeType":"Attribute","startLoc":309,"text":"_legend"},{"className":"ObjectProperty","col":0,"comment":"A property defined by arbitrary an object, with inherently nominal scaling.","endLoc":372,"id":1227,"nodeType":"Class","startLoc":323,"text":"class ObjectProperty(Property):\n \"\"\"A property defined by arbitrary an object, with inherently nominal scaling.\"\"\"\n legend = True\n normed = False\n\n # Object representing null data, should appear invisible when drawn by matplotlib\n # Note that we now drop nulls in Plot._plot_layer and thus may not need this\n null_value: Any = None\n\n def _default_values(self, n: int) -> list:\n raise NotImplementedError()\n\n def default_scale(self, data: Series) -> Nominal:\n return Nominal()\n\n def infer_scale(self, arg: Any, data: Series) -> Nominal:\n return Nominal(arg)\n\n def get_mapping(\n self, scale: Scale, data: Series,\n ) -> Callable[[ArrayLike], list]:\n \"\"\"Define mapping as lookup into list of object values.\"\"\"\n order = getattr(scale, \"order\", None)\n levels = categorical_order(data, order)\n n = len(levels)\n\n if isinstance(scale.values, dict):\n self._check_dict_entries(levels, scale.values)\n values = [scale.values[x] for x in levels]\n elif isinstance(scale.values, list):\n values = self._check_list_length(levels, scale.values)\n elif scale.values is None:\n values = self._default_values(n)\n else:\n msg = \" \".join([\n f\"Scale values for a {self.variable} variable must be provided\",\n f\"in a dict or list; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n values = [self.standardize(x) for x in values]\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n return [\n values[ix] if np.isfinite(x_i) else self.null_value\n for x_i, ix in zip(x, ixs)\n ]\n\n return mapping"},{"col":4,"comment":"null","endLoc":333,"header":"def _default_values(self, n: int) -> list","id":1228,"name":"_default_values","nodeType":"Function","startLoc":332,"text":"def _default_values(self, n: int) -> list:\n raise NotImplementedError()"},{"col":4,"comment":"Turns a list of colors into a numpy matrix and matplotlib colormap\n\n These arguments can now be plotted using heatmap(matrix, cmap)\n and the provided colors will be plotted.\n\n Parameters\n ----------\n colors : list of matplotlib colors\n Colors to label the rows or columns of a dataframe.\n ind : list of ints\n Ordering of the rows or columns, to reorder the original colors\n by the clustered dendrogram order\n axis : int\n Which axis this is labeling\n\n Returns\n -------\n matrix : numpy.array\n A numpy array of integer values, where each indexes into the cmap\n cmap : matplotlib.colors.ListedColormap\n\n ","endLoc":968,"header":"@staticmethod\n def color_list_to_matrix_and_cmap(colors, ind, axis=0)","id":1229,"name":"color_list_to_matrix_and_cmap","nodeType":"Function","startLoc":918,"text":"@staticmethod\n def color_list_to_matrix_and_cmap(colors, ind, axis=0):\n \"\"\"Turns a list of colors into a numpy matrix and matplotlib colormap\n\n These arguments can now be plotted using heatmap(matrix, cmap)\n and the provided colors will be plotted.\n\n Parameters\n ----------\n colors : list of matplotlib colors\n Colors to label the rows or columns of a dataframe.\n ind : list of ints\n Ordering of the rows or columns, to reorder the original colors\n by the clustered dendrogram order\n axis : int\n Which axis this is labeling\n\n Returns\n -------\n matrix : numpy.array\n A numpy array of integer values, where each indexes into the cmap\n cmap : matplotlib.colors.ListedColormap\n\n \"\"\"\n try:\n mpl.colors.to_rgb(colors[0])\n except ValueError:\n # We have a 2D color structure\n m, n = len(colors), len(colors[0])\n if not all(len(c) == n for c in colors[1:]):\n raise ValueError(\"Multiple side color vectors must have same size\")\n else:\n # We have one vector of colors\n m, n = 1, len(colors)\n colors = [colors]\n\n # Map from unique colors to colormap index value\n unique_colors = {}\n matrix = np.zeros((m, n), int)\n for i, inner in enumerate(colors):\n for j, color in enumerate(inner):\n idx = unique_colors.setdefault(color, len(unique_colors))\n matrix[i, j] = idx\n\n # Reorder for clustering and transpose for axis\n matrix = matrix[:, ind]\n if axis == 0:\n matrix = matrix.T\n\n cmap = mpl.colors.ListedColormap(list(unique_colors))\n return matrix, cmap"},{"col":4,"comment":"null","endLoc":336,"header":"def default_scale(self, data: Series) -> Nominal","id":1230,"name":"default_scale","nodeType":"Function","startLoc":335,"text":"def default_scale(self, data: Series) -> Nominal:\n return Nominal()"},{"col":4,"comment":"null","endLoc":431,"header":"def categorical_mapping(self, data, sizes, order)","id":1231,"name":"categorical_mapping","nodeType":"Function","startLoc":375,"text":"def categorical_mapping(self, data, sizes, order):\n\n levels = categorical_order(data, order)\n\n if isinstance(sizes, dict):\n\n # Dict inputs map existing data values to the size attribute\n missing = set(levels) - set(sizes)\n if any(missing):\n err = f\"Missing sizes for the following levels: {missing}\"\n raise ValueError(err)\n lookup_table = sizes.copy()\n\n elif isinstance(sizes, list):\n\n # List inputs give size values in the same order as the levels\n sizes = self._check_list_length(levels, sizes, \"sizes\")\n lookup_table = dict(zip(levels, sizes))\n\n else:\n\n if isinstance(sizes, tuple):\n\n # Tuple input sets the min, max size values\n if len(sizes) != 2:\n err = \"A `sizes` tuple must have only 2 values\"\n raise ValueError(err)\n\n elif sizes is not None:\n\n err = f\"Value for `sizes` not understood: {sizes}\"\n raise ValueError(err)\n\n else:\n\n # Otherwise, we need to get the min, max size values from\n # the plotter object we are attached to.\n\n # TODO this is going to cause us trouble later, because we\n # want to restructure things so that the plotter is generic\n # across the visual representation of the data. But at this\n # point, we don't know the visual representation. Likely we\n # want to change the logic of this Mapping so that it gives\n # points on a normalized range that then gets un-normalized\n # when we know what we're drawing. But given the way the\n # package works now, this way is cleanest.\n sizes = self.plotter._default_size_range\n\n # For categorical sizes, use regularly-spaced linear steps\n # between the minimum and maximum sizes. Then reverse the\n # ramp so that the largest value is used for the first entry\n # in size_order, etc. This is because \"ordered\" categories\n # are often though to go in decreasing priority.\n sizes = np.linspace(*sizes, len(levels))[::-1]\n lookup_table = dict(zip(levels, sizes))\n\n return levels, lookup_table"},{"col":4,"comment":"null","endLoc":339,"header":"def infer_scale(self, arg: Any, data: Series) -> Nominal","id":1232,"name":"infer_scale","nodeType":"Function","startLoc":338,"text":"def infer_scale(self, arg: Any, data: Series) -> Nominal:\n return Nominal(arg)"},{"attributeType":"list","col":11,"comment":"null","endLoc":1575,"id":1233,"name":"_lut","nodeType":"Attribute","startLoc":1575,"text":"_lut"},{"col":4,"comment":"Define mapping as lookup into list of object values.","endLoc":372,"header":"def get_mapping(\n self, scale: Scale, data: Series,\n ) -> Callable[[ArrayLike], list]","id":1234,"name":"get_mapping","nodeType":"Function","startLoc":341,"text":"def get_mapping(\n self, scale: Scale, data: Series,\n ) -> Callable[[ArrayLike], list]:\n \"\"\"Define mapping as lookup into list of object values.\"\"\"\n order = getattr(scale, \"order\", None)\n levels = categorical_order(data, order)\n n = len(levels)\n\n if isinstance(scale.values, dict):\n self._check_dict_entries(levels, scale.values)\n values = [scale.values[x] for x in levels]\n elif isinstance(scale.values, list):\n values = self._check_list_length(levels, scale.values)\n elif scale.values is None:\n values = self._default_values(n)\n else:\n msg = \" \".join([\n f\"Scale values for a {self.variable} variable must be provided\",\n f\"in a dict or list; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n values = [self.standardize(x) for x in values]\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n return [\n values[ix] if np.isfinite(x_i) else self.null_value\n for x_i, ix in zip(x, ixs)\n ]\n\n return mapping"},{"col":4,"comment":"null","endLoc":175,"header":"def __init__(self, docstring, config={})","id":1235,"name":"__init__","nodeType":"Function","startLoc":164,"text":"def __init__(self, docstring, config={}):\n orig_docstring = docstring\n docstring = textwrap.dedent(docstring).split('\\n')\n\n self._doc = Reader(docstring)\n self._parsed_data = copy.deepcopy(self.sections)\n\n try:\n self._parse()\n except ParseError as e:\n e.docstring = orig_docstring\n raise"},{"attributeType":"null","col":4,"comment":"null","endLoc":1577,"id":1236,"name":"_cmap","nodeType":"Attribute","startLoc":1577,"text":"_cmap"},{"col":4,"comment":"Return data levels corresponding to quantile cuts of mass.","endLoc":204,"header":"def _quantile_to_level(self, data, quantile)","id":1237,"name":"_quantile_to_level","nodeType":"Function","startLoc":196,"text":"def _quantile_to_level(self, data, quantile):\n \"\"\"Return data levels corresponding to quantile cuts of mass.\"\"\"\n isoprop = np.asarray(quantile)\n values = np.ravel(data)\n sorted_values = np.sort(values)[::-1]\n normalized_values = np.cumsum(sorted_values) / values.sum()\n idx = np.searchsorted(normalized_values, 1 - isoprop)\n levels = np.take(sorted_values, idx, mode=\"clip\")\n return levels"},{"attributeType":"null","col":4,"comment":"null","endLoc":1580,"id":1238,"name":"_cmap_r","nodeType":"Attribute","startLoc":1580,"text":"_cmap_r"},{"col":0,"comment":"","endLoc":1,"header":"cm.py#","id":1239,"name":"","nodeType":"Function","startLoc":1,"text":"_rocket_lut = [\n [ 0.01060815, 0.01808215, 0.10018654],\n [ 0.01428972, 0.02048237, 0.10374486],\n [ 0.01831941, 0.0229766 , 0.10738511],\n [ 0.02275049, 0.02554464, 0.11108639],\n [ 0.02759119, 0.02818316, 0.11483751],\n [ 0.03285175, 0.03088792, 0.11863035],\n [ 0.03853466, 0.03365771, 0.12245873],\n [ 0.04447016, 0.03648425, 0.12631831],\n [ 0.05032105, 0.03936808, 0.13020508],\n [ 0.05611171, 0.04224835, 0.13411624],\n [ 0.0618531 , 0.04504866, 0.13804929],\n [ 0.06755457, 0.04778179, 0.14200206],\n [ 0.0732236 , 0.05045047, 0.14597263],\n [ 0.0788708 , 0.05305461, 0.14995981],\n [ 0.08450105, 0.05559631, 0.15396203],\n [ 0.09011319, 0.05808059, 0.15797687],\n [ 0.09572396, 0.06050127, 0.16200507],\n [ 0.10132312, 0.06286782, 0.16604287],\n [ 0.10692823, 0.06517224, 0.17009175],\n [ 0.1125315 , 0.06742194, 0.17414848],\n [ 0.11813947, 0.06961499, 0.17821272],\n [ 0.12375803, 0.07174938, 0.18228425],\n [ 0.12938228, 0.07383015, 0.18636053],\n [ 0.13501631, 0.07585609, 0.19044109],\n [ 0.14066867, 0.0778224 , 0.19452676],\n [ 0.14633406, 0.07973393, 0.1986151 ],\n [ 0.15201338, 0.08159108, 0.20270523],\n [ 0.15770877, 0.08339312, 0.20679668],\n [ 0.16342174, 0.0851396 , 0.21088893],\n [ 0.16915387, 0.08682996, 0.21498104],\n [ 0.17489524, 0.08848235, 0.2190294 ],\n [ 0.18065495, 0.09009031, 0.22303512],\n [ 0.18643324, 0.09165431, 0.22699705],\n [ 0.19223028, 0.09317479, 0.23091409],\n [ 0.19804623, 0.09465217, 0.23478512],\n [ 0.20388117, 0.09608689, 0.23860907],\n [ 0.20973515, 0.09747934, 0.24238489],\n [ 0.21560818, 0.09882993, 0.24611154],\n [ 0.22150014, 0.10013944, 0.2497868 ],\n [ 0.22741085, 0.10140876, 0.25340813],\n [ 0.23334047, 0.10263737, 0.25697736],\n [ 0.23928891, 0.10382562, 0.2604936 ],\n [ 0.24525608, 0.10497384, 0.26395596],\n [ 0.25124182, 0.10608236, 0.26736359],\n [ 0.25724602, 0.10715148, 0.27071569],\n [ 0.26326851, 0.1081815 , 0.27401148],\n [ 0.26930915, 0.1091727 , 0.2772502 ],\n [ 0.27536766, 0.11012568, 0.28043021],\n [ 0.28144375, 0.11104133, 0.2835489 ],\n [ 0.2875374 , 0.11191896, 0.28660853],\n [ 0.29364846, 0.11275876, 0.2896085 ],\n [ 0.29977678, 0.11356089, 0.29254823],\n [ 0.30592213, 0.11432553, 0.29542718],\n [ 0.31208435, 0.11505284, 0.29824485],\n [ 0.31826327, 0.1157429 , 0.30100076],\n [ 0.32445869, 0.11639585, 0.30369448],\n [ 0.33067031, 0.11701189, 0.30632563],\n [ 0.33689808, 0.11759095, 0.3088938 ],\n [ 0.34314168, 0.11813362, 0.31139721],\n [ 0.34940101, 0.11863987, 0.3138355 ],\n [ 0.355676 , 0.11910909, 0.31620996],\n [ 0.36196644, 0.1195413 , 0.31852037],\n [ 0.36827206, 0.11993653, 0.32076656],\n [ 0.37459292, 0.12029443, 0.32294825],\n [ 0.38092887, 0.12061482, 0.32506528],\n [ 0.38727975, 0.12089756, 0.3271175 ],\n [ 0.39364518, 0.12114272, 0.32910494],\n [ 0.40002537, 0.12134964, 0.33102734],\n [ 0.40642019, 0.12151801, 0.33288464],\n [ 0.41282936, 0.12164769, 0.33467689],\n [ 0.41925278, 0.12173833, 0.33640407],\n [ 0.42569057, 0.12178916, 0.33806605],\n [ 0.43214263, 0.12179973, 0.33966284],\n [ 0.43860848, 0.12177004, 0.34119475],\n [ 0.44508855, 0.12169883, 0.34266151],\n [ 0.45158266, 0.12158557, 0.34406324],\n [ 0.45809049, 0.12142996, 0.34540024],\n [ 0.46461238, 0.12123063, 0.34667231],\n [ 0.47114798, 0.12098721, 0.34787978],\n [ 0.47769736, 0.12069864, 0.34902273],\n [ 0.48426077, 0.12036349, 0.35010104],\n [ 0.49083761, 0.11998161, 0.35111537],\n [ 0.49742847, 0.11955087, 0.35206533],\n [ 0.50403286, 0.11907081, 0.35295152],\n [ 0.51065109, 0.11853959, 0.35377385],\n [ 0.51728314, 0.1179558 , 0.35453252],\n [ 0.52392883, 0.11731817, 0.35522789],\n [ 0.53058853, 0.11662445, 0.35585982],\n [ 0.53726173, 0.11587369, 0.35642903],\n [ 0.54394898, 0.11506307, 0.35693521],\n [ 0.5506426 , 0.11420757, 0.35737863],\n [ 0.55734473, 0.11330456, 0.35775059],\n [ 0.56405586, 0.11235265, 0.35804813],\n [ 0.57077365, 0.11135597, 0.35827146],\n [ 0.5774991 , 0.11031233, 0.35841679],\n [ 0.58422945, 0.10922707, 0.35848469],\n [ 0.59096382, 0.10810205, 0.35847347],\n [ 0.59770215, 0.10693774, 0.35838029],\n [ 0.60444226, 0.10573912, 0.35820487],\n [ 0.61118304, 0.10450943, 0.35794557],\n [ 0.61792306, 0.10325288, 0.35760108],\n [ 0.62466162, 0.10197244, 0.35716891],\n [ 0.63139686, 0.10067417, 0.35664819],\n [ 0.63812122, 0.09938212, 0.35603757],\n [ 0.64483795, 0.0980891 , 0.35533555],\n [ 0.65154562, 0.09680192, 0.35454107],\n [ 0.65824241, 0.09552918, 0.3536529 ],\n [ 0.66492652, 0.09428017, 0.3526697 ],\n [ 0.67159578, 0.09306598, 0.35159077],\n [ 0.67824099, 0.09192342, 0.3504148 ],\n [ 0.684863 , 0.09085633, 0.34914061],\n [ 0.69146268, 0.0898675 , 0.34776864],\n [ 0.69803757, 0.08897226, 0.3462986 ],\n [ 0.70457834, 0.0882129 , 0.34473046],\n [ 0.71108138, 0.08761223, 0.3430635 ],\n [ 0.7175507 , 0.08716212, 0.34129974],\n [ 0.72398193, 0.08688725, 0.33943958],\n [ 0.73035829, 0.0868623 , 0.33748452],\n [ 0.73669146, 0.08704683, 0.33543669],\n [ 0.74297501, 0.08747196, 0.33329799],\n [ 0.74919318, 0.08820542, 0.33107204],\n [ 0.75535825, 0.08919792, 0.32876184],\n [ 0.76145589, 0.09050716, 0.32637117],\n [ 0.76748424, 0.09213602, 0.32390525],\n [ 0.77344838, 0.09405684, 0.32136808],\n [ 0.77932641, 0.09634794, 0.31876642],\n [ 0.78513609, 0.09892473, 0.31610488],\n [ 0.79085854, 0.10184672, 0.313391 ],\n [ 0.7965014 , 0.10506637, 0.31063031],\n [ 0.80205987, 0.10858333, 0.30783 ],\n [ 0.80752799, 0.11239964, 0.30499738],\n [ 0.81291606, 0.11645784, 0.30213802],\n [ 0.81820481, 0.12080606, 0.29926105],\n [ 0.82341472, 0.12535343, 0.2963705 ],\n [ 0.82852822, 0.13014118, 0.29347474],\n [ 0.83355779, 0.13511035, 0.29057852],\n [ 0.83850183, 0.14025098, 0.2876878 ],\n [ 0.84335441, 0.14556683, 0.28480819],\n [ 0.84813096, 0.15099892, 0.281943 ],\n [ 0.85281737, 0.15657772, 0.27909826],\n [ 0.85742602, 0.1622583 , 0.27627462],\n [ 0.86196552, 0.16801239, 0.27346473],\n [ 0.86641628, 0.17387796, 0.27070818],\n [ 0.87079129, 0.17982114, 0.26797378],\n [ 0.87507281, 0.18587368, 0.26529697],\n [ 0.87925878, 0.19203259, 0.26268136],\n [ 0.8833417 , 0.19830556, 0.26014181],\n [ 0.88731387, 0.20469941, 0.25769539],\n [ 0.89116859, 0.21121788, 0.2553592 ],\n [ 0.89490337, 0.21785614, 0.25314362],\n [ 0.8985026 , 0.22463251, 0.25108745],\n [ 0.90197527, 0.23152063, 0.24918223],\n [ 0.90530097, 0.23854541, 0.24748098],\n [ 0.90848638, 0.24568473, 0.24598324],\n [ 0.911533 , 0.25292623, 0.24470258],\n [ 0.9144225 , 0.26028902, 0.24369359],\n [ 0.91717106, 0.26773821, 0.24294137],\n [ 0.91978131, 0.27526191, 0.24245973],\n [ 0.92223947, 0.28287251, 0.24229568],\n [ 0.92456587, 0.29053388, 0.24242622],\n [ 0.92676657, 0.29823282, 0.24285536],\n [ 0.92882964, 0.30598085, 0.24362274],\n [ 0.93078135, 0.31373977, 0.24468803],\n [ 0.93262051, 0.3215093 , 0.24606461],\n [ 0.93435067, 0.32928362, 0.24775328],\n [ 0.93599076, 0.33703942, 0.24972157],\n [ 0.93752831, 0.34479177, 0.25199928],\n [ 0.93899289, 0.35250734, 0.25452808],\n [ 0.94036561, 0.36020899, 0.25734661],\n [ 0.94167588, 0.36786594, 0.2603949 ],\n [ 0.94291042, 0.37549479, 0.26369821],\n [ 0.94408513, 0.3830811 , 0.26722004],\n [ 0.94520419, 0.39062329, 0.27094924],\n [ 0.94625977, 0.39813168, 0.27489742],\n [ 0.94727016, 0.4055909 , 0.27902322],\n [ 0.94823505, 0.41300424, 0.28332283],\n [ 0.94914549, 0.42038251, 0.28780969],\n [ 0.95001704, 0.42771398, 0.29244728],\n [ 0.95085121, 0.43500005, 0.29722817],\n [ 0.95165009, 0.44224144, 0.30214494],\n [ 0.9524044 , 0.44944853, 0.3072105 ],\n [ 0.95312556, 0.45661389, 0.31239776],\n [ 0.95381595, 0.46373781, 0.31769923],\n [ 0.95447591, 0.47082238, 0.32310953],\n [ 0.95510255, 0.47787236, 0.32862553],\n [ 0.95569679, 0.48489115, 0.33421404],\n [ 0.95626788, 0.49187351, 0.33985601],\n [ 0.95681685, 0.49882008, 0.34555431],\n [ 0.9573439 , 0.50573243, 0.35130912],\n [ 0.95784842, 0.51261283, 0.35711942],\n [ 0.95833051, 0.51946267, 0.36298589],\n [ 0.95879054, 0.52628305, 0.36890904],\n [ 0.95922872, 0.53307513, 0.3748895 ],\n [ 0.95964538, 0.53983991, 0.38092784],\n [ 0.96004345, 0.54657593, 0.3870292 ],\n [ 0.96042097, 0.55328624, 0.39319057],\n [ 0.96077819, 0.55997184, 0.39941173],\n [ 0.9611152 , 0.5666337 , 0.40569343],\n [ 0.96143273, 0.57327231, 0.41203603],\n [ 0.96173392, 0.57988594, 0.41844491],\n [ 0.96201757, 0.58647675, 0.42491751],\n [ 0.96228344, 0.59304598, 0.43145271],\n [ 0.96253168, 0.5995944 , 0.43805131],\n [ 0.96276513, 0.60612062, 0.44471698],\n [ 0.96298491, 0.6126247 , 0.45145074],\n [ 0.96318967, 0.61910879, 0.45824902],\n [ 0.96337949, 0.6255736 , 0.46511271],\n [ 0.96355923, 0.63201624, 0.47204746],\n [ 0.96372785, 0.63843852, 0.47905028],\n [ 0.96388426, 0.64484214, 0.4861196 ],\n [ 0.96403203, 0.65122535, 0.4932578 ],\n [ 0.96417332, 0.65758729, 0.50046894],\n [ 0.9643063 , 0.66393045, 0.5077467 ],\n [ 0.96443322, 0.67025402, 0.51509334],\n [ 0.96455845, 0.67655564, 0.52251447],\n [ 0.96467922, 0.68283846, 0.53000231],\n [ 0.96479861, 0.68910113, 0.53756026],\n [ 0.96492035, 0.69534192, 0.5451917 ],\n [ 0.96504223, 0.7015636 , 0.5528892 ],\n [ 0.96516917, 0.70776351, 0.5606593 ],\n [ 0.96530224, 0.71394212, 0.56849894],\n [ 0.96544032, 0.72010124, 0.57640375],\n [ 0.96559206, 0.72623592, 0.58438387],\n [ 0.96575293, 0.73235058, 0.59242739],\n [ 0.96592829, 0.73844258, 0.60053991],\n [ 0.96612013, 0.74451182, 0.60871954],\n [ 0.96632832, 0.75055966, 0.61696136],\n [ 0.96656022, 0.75658231, 0.62527295],\n [ 0.96681185, 0.76258381, 0.63364277],\n [ 0.96709183, 0.76855969, 0.64207921],\n [ 0.96739773, 0.77451297, 0.65057302],\n [ 0.96773482, 0.78044149, 0.65912731],\n [ 0.96810471, 0.78634563, 0.66773889],\n [ 0.96850919, 0.79222565, 0.6764046 ],\n [ 0.96893132, 0.79809112, 0.68512266],\n [ 0.96935926, 0.80395415, 0.69383201],\n [ 0.9698028 , 0.80981139, 0.70252255],\n [ 0.97025511, 0.81566605, 0.71120296],\n [ 0.97071849, 0.82151775, 0.71987163],\n [ 0.97120159, 0.82736371, 0.72851999],\n [ 0.97169389, 0.83320847, 0.73716071],\n [ 0.97220061, 0.83905052, 0.74578903],\n [ 0.97272597, 0.84488881, 0.75440141],\n [ 0.97327085, 0.85072354, 0.76299805],\n [ 0.97383206, 0.85655639, 0.77158353],\n [ 0.97441222, 0.86238689, 0.78015619],\n [ 0.97501782, 0.86821321, 0.78871034],\n [ 0.97564391, 0.87403763, 0.79725261],\n [ 0.97628674, 0.87986189, 0.8057883 ],\n [ 0.97696114, 0.88568129, 0.81430324],\n [ 0.97765722, 0.89149971, 0.82280948],\n [ 0.97837585, 0.89731727, 0.83130786],\n [ 0.97912374, 0.90313207, 0.83979337],\n [ 0.979891 , 0.90894778, 0.84827858],\n [ 0.98067764, 0.91476465, 0.85676611],\n [ 0.98137749, 0.92061729, 0.86536915]\n]\n\n_mako_lut = [\n [ 0.04503935, 0.01482344, 0.02092227],\n [ 0.04933018, 0.01709292, 0.02535719],\n [ 0.05356262, 0.01950702, 0.03018802],\n [ 0.05774337, 0.02205989, 0.03545515],\n [ 0.06188095, 0.02474764, 0.04115287],\n [ 0.06598247, 0.0275665 , 0.04691409],\n [ 0.07005374, 0.03051278, 0.05264306],\n [ 0.07409947, 0.03358324, 0.05834631],\n [ 0.07812339, 0.03677446, 0.06403249],\n [ 0.08212852, 0.0400833 , 0.06970862],\n [ 0.08611731, 0.04339148, 0.07538208],\n [ 0.09009161, 0.04664706, 0.08105568],\n [ 0.09405308, 0.04985685, 0.08673591],\n [ 0.09800301, 0.05302279, 0.09242646],\n [ 0.10194255, 0.05614641, 0.09813162],\n [ 0.10587261, 0.05922941, 0.103854 ],\n [ 0.1097942 , 0.06227277, 0.10959847],\n [ 0.11370826, 0.06527747, 0.11536893],\n [ 0.11761516, 0.06824548, 0.12116393],\n [ 0.12151575, 0.07117741, 0.12698763],\n [ 0.12541095, 0.07407363, 0.1328442 ],\n [ 0.12930083, 0.07693611, 0.13873064],\n [ 0.13317849, 0.07976988, 0.14465095],\n [ 0.13701138, 0.08259683, 0.15060265],\n [ 0.14079223, 0.08542126, 0.15659379],\n [ 0.14452486, 0.08824175, 0.16262484],\n [ 0.14820351, 0.09106304, 0.16869476],\n [ 0.15183185, 0.09388372, 0.17480366],\n [ 0.15540398, 0.09670855, 0.18094993],\n [ 0.15892417, 0.09953561, 0.18713384],\n [ 0.16238588, 0.10236998, 0.19335329],\n [ 0.16579435, 0.10520905, 0.19960847],\n [ 0.16914226, 0.10805832, 0.20589698],\n [ 0.17243586, 0.11091443, 0.21221911],\n [ 0.17566717, 0.11378321, 0.21857219],\n [ 0.17884322, 0.11666074, 0.2249565 ],\n [ 0.18195582, 0.11955283, 0.23136943],\n [ 0.18501213, 0.12245547, 0.23781116],\n [ 0.18800459, 0.12537395, 0.24427914],\n [ 0.19093944, 0.1283047 , 0.25077369],\n [ 0.19381092, 0.13125179, 0.25729255],\n [ 0.19662307, 0.13421303, 0.26383543],\n [ 0.19937337, 0.13719028, 0.27040111],\n [ 0.20206187, 0.14018372, 0.27698891],\n [ 0.20469116, 0.14319196, 0.28359861],\n [ 0.20725547, 0.14621882, 0.29022775],\n [ 0.20976258, 0.14925954, 0.29687795],\n [ 0.21220409, 0.15231929, 0.30354703],\n [ 0.21458611, 0.15539445, 0.31023563],\n [ 0.21690827, 0.15848519, 0.31694355],\n [ 0.21916481, 0.16159489, 0.32366939],\n [ 0.2213631 , 0.16471913, 0.33041431],\n [ 0.22349947, 0.1678599 , 0.33717781],\n [ 0.2255714 , 0.1710185 , 0.34395925],\n [ 0.22758415, 0.17419169, 0.35075983],\n [ 0.22953569, 0.17738041, 0.35757941],\n [ 0.23142077, 0.18058733, 0.3644173 ],\n [ 0.2332454 , 0.18380872, 0.37127514],\n [ 0.2350092 , 0.18704459, 0.3781528 ],\n [ 0.23670785, 0.190297 , 0.38504973],\n [ 0.23834119, 0.19356547, 0.39196711],\n [ 0.23991189, 0.19684817, 0.39890581],\n [ 0.24141903, 0.20014508, 0.4058667 ],\n [ 0.24286214, 0.20345642, 0.4128484 ],\n [ 0.24423453, 0.20678459, 0.41985299],\n [ 0.24554109, 0.21012669, 0.42688124],\n [ 0.2467815 , 0.21348266, 0.43393244],\n [ 0.24795393, 0.21685249, 0.4410088 ],\n [ 0.24905614, 0.22023618, 0.448113 ],\n [ 0.25007383, 0.22365053, 0.45519562],\n [ 0.25098926, 0.22710664, 0.46223892],\n [ 0.25179696, 0.23060342, 0.46925447],\n [ 0.25249346, 0.23414353, 0.47623196],\n [ 0.25307401, 0.23772973, 0.48316271],\n [ 0.25353152, 0.24136961, 0.49001976],\n [ 0.25386167, 0.24506548, 0.49679407],\n [ 0.25406082, 0.2488164 , 0.50348932],\n [ 0.25412435, 0.25262843, 0.51007843],\n [ 0.25404842, 0.25650743, 0.51653282],\n [ 0.25383134, 0.26044852, 0.52286845],\n [ 0.2534705 , 0.26446165, 0.52903422],\n [ 0.25296722, 0.2685428 , 0.53503572],\n [ 0.2523226 , 0.27269346, 0.54085315],\n [ 0.25153974, 0.27691629, 0.54645752],\n [ 0.25062402, 0.28120467, 0.55185939],\n [ 0.24958205, 0.28556371, 0.55701246],\n [ 0.24842386, 0.28998148, 0.56194601],\n [ 0.24715928, 0.29446327, 0.56660884],\n [ 0.24580099, 0.29899398, 0.57104399],\n [ 0.24436202, 0.30357852, 0.57519929],\n [ 0.24285591, 0.30819938, 0.57913247],\n [ 0.24129828, 0.31286235, 0.58278615],\n [ 0.23970131, 0.3175495 , 0.5862272 ],\n [ 0.23807973, 0.32226344, 0.58941872],\n [ 0.23644557, 0.32699241, 0.59240198],\n [ 0.2348113 , 0.33173196, 0.59518282],\n [ 0.23318874, 0.33648036, 0.59775543],\n [ 0.2315855 , 0.34122763, 0.60016456],\n [ 0.23001121, 0.34597357, 0.60240251],\n [ 0.2284748 , 0.35071512, 0.6044784 ],\n [ 0.22698081, 0.35544612, 0.60642528],\n [ 0.22553305, 0.36016515, 0.60825252],\n [ 0.22413977, 0.36487341, 0.60994938],\n [ 0.22280246, 0.36956728, 0.61154118],\n [ 0.22152555, 0.37424409, 0.61304472],\n [ 0.22030752, 0.37890437, 0.61446646],\n [ 0.2191538 , 0.38354668, 0.61581561],\n [ 0.21806257, 0.38817169, 0.61709794],\n [ 0.21703799, 0.39277882, 0.61831922],\n [ 0.21607792, 0.39736958, 0.61948028],\n [ 0.21518463, 0.40194196, 0.62059763],\n [ 0.21435467, 0.40649717, 0.62167507],\n [ 0.21358663, 0.41103579, 0.62271724],\n [ 0.21288172, 0.41555771, 0.62373011],\n [ 0.21223835, 0.42006355, 0.62471794],\n [ 0.21165312, 0.42455441, 0.62568371],\n [ 0.21112526, 0.42903064, 0.6266318 ],\n [ 0.21065161, 0.43349321, 0.62756504],\n [ 0.21023306, 0.43794288, 0.62848279],\n [ 0.20985996, 0.44238227, 0.62938329],\n [ 0.20951045, 0.44680966, 0.63030696],\n [ 0.20916709, 0.45122981, 0.63124483],\n [ 0.20882976, 0.45564335, 0.63219599],\n [ 0.20849798, 0.46005094, 0.63315928],\n [ 0.20817199, 0.46445309, 0.63413391],\n [ 0.20785149, 0.46885041, 0.63511876],\n [ 0.20753716, 0.47324327, 0.63611321],\n [ 0.20722876, 0.47763224, 0.63711608],\n [ 0.20692679, 0.48201774, 0.63812656],\n [ 0.20663156, 0.48640018, 0.63914367],\n [ 0.20634336, 0.49078002, 0.64016638],\n [ 0.20606303, 0.49515755, 0.6411939 ],\n [ 0.20578999, 0.49953341, 0.64222457],\n [ 0.20552612, 0.50390766, 0.64325811],\n [ 0.20527189, 0.50828072, 0.64429331],\n [ 0.20502868, 0.51265277, 0.64532947],\n [ 0.20479718, 0.51702417, 0.64636539],\n [ 0.20457804, 0.52139527, 0.64739979],\n [ 0.20437304, 0.52576622, 0.64843198],\n [ 0.20418396, 0.53013715, 0.64946117],\n [ 0.20401238, 0.53450825, 0.65048638],\n [ 0.20385896, 0.53887991, 0.65150606],\n [ 0.20372653, 0.54325208, 0.65251978],\n [ 0.20361709, 0.5476249 , 0.6535266 ],\n [ 0.20353258, 0.55199854, 0.65452542],\n [ 0.20347472, 0.55637318, 0.655515 ],\n [ 0.20344718, 0.56074869, 0.65649508],\n [ 0.20345161, 0.56512531, 0.65746419],\n [ 0.20349089, 0.56950304, 0.65842151],\n [ 0.20356842, 0.57388184, 0.65936642],\n [ 0.20368663, 0.57826181, 0.66029768],\n [ 0.20384884, 0.58264293, 0.6612145 ],\n [ 0.20405904, 0.58702506, 0.66211645],\n [ 0.20431921, 0.59140842, 0.66300179],\n [ 0.20463464, 0.59579264, 0.66387079],\n [ 0.20500731, 0.60017798, 0.66472159],\n [ 0.20544449, 0.60456387, 0.66555409],\n [ 0.20596097, 0.60894927, 0.66636568],\n [ 0.20654832, 0.61333521, 0.66715744],\n [ 0.20721003, 0.61772167, 0.66792838],\n [ 0.20795035, 0.62210845, 0.66867802],\n [ 0.20877302, 0.62649546, 0.66940555],\n [ 0.20968223, 0.63088252, 0.6701105 ],\n [ 0.21068163, 0.63526951, 0.67079211],\n [ 0.21177544, 0.63965621, 0.67145005],\n [ 0.21298582, 0.64404072, 0.67208182],\n [ 0.21430361, 0.64842404, 0.67268861],\n [ 0.21572716, 0.65280655, 0.67326978],\n [ 0.21726052, 0.65718791, 0.6738255 ],\n [ 0.21890636, 0.66156803, 0.67435491],\n [ 0.220668 , 0.66594665, 0.67485792],\n [ 0.22255447, 0.67032297, 0.67533374],\n [ 0.22458372, 0.67469531, 0.67578061],\n [ 0.22673713, 0.67906542, 0.67620044],\n [ 0.22901625, 0.6834332 , 0.67659251],\n [ 0.23142316, 0.68779836, 0.67695703],\n [ 0.23395924, 0.69216072, 0.67729378],\n [ 0.23663857, 0.69651881, 0.67760151],\n [ 0.23946645, 0.70087194, 0.67788018],\n [ 0.24242624, 0.70522162, 0.67813088],\n [ 0.24549008, 0.70957083, 0.67835215],\n [ 0.24863372, 0.71392166, 0.67854868],\n [ 0.25187832, 0.71827158, 0.67872193],\n [ 0.25524083, 0.72261873, 0.67887024],\n [ 0.25870947, 0.72696469, 0.67898912],\n [ 0.26229238, 0.73130855, 0.67907645],\n [ 0.26604085, 0.73564353, 0.67914062],\n [ 0.26993099, 0.73997282, 0.67917264],\n [ 0.27397488, 0.74429484, 0.67917096],\n [ 0.27822463, 0.74860229, 0.67914468],\n [ 0.28264201, 0.75290034, 0.67907959],\n [ 0.2873016 , 0.75717817, 0.67899164],\n [ 0.29215894, 0.76144162, 0.67886578],\n [ 0.29729823, 0.76567816, 0.67871894],\n [ 0.30268199, 0.76989232, 0.67853896],\n [ 0.30835665, 0.77407636, 0.67833512],\n [ 0.31435139, 0.77822478, 0.67811118],\n [ 0.3206671 , 0.78233575, 0.67786729],\n [ 0.32733158, 0.78640315, 0.67761027],\n [ 0.33437168, 0.79042043, 0.67734882],\n [ 0.34182112, 0.79437948, 0.67709394],\n [ 0.34968889, 0.79827511, 0.67685638],\n [ 0.35799244, 0.80210037, 0.67664969],\n [ 0.36675371, 0.80584651, 0.67649539],\n [ 0.3759816 , 0.80950627, 0.67641393],\n [ 0.38566792, 0.81307432, 0.67642947],\n [ 0.39579804, 0.81654592, 0.67656899],\n [ 0.40634556, 0.81991799, 0.67686215],\n [ 0.41730243, 0.82318339, 0.67735255],\n [ 0.4285828 , 0.82635051, 0.6780564 ],\n [ 0.44012728, 0.82942353, 0.67900049],\n [ 0.45189421, 0.83240398, 0.68021733],\n [ 0.46378379, 0.83530763, 0.6817062 ],\n [ 0.47573199, 0.83814472, 0.68347352],\n [ 0.48769865, 0.84092197, 0.68552698],\n [ 0.49962354, 0.84365379, 0.68783929],\n [ 0.5114027 , 0.8463718 , 0.69029789],\n [ 0.52301693, 0.84908401, 0.69288545],\n [ 0.53447549, 0.85179048, 0.69561066],\n [ 0.54578602, 0.8544913 , 0.69848331],\n [ 0.55695565, 0.85718723, 0.70150427],\n [ 0.56798832, 0.85987893, 0.70468261],\n [ 0.57888639, 0.86256715, 0.70802931],\n [ 0.5896541 , 0.8652532 , 0.71154204],\n [ 0.60028928, 0.86793835, 0.71523675],\n [ 0.61079441, 0.87062438, 0.71910895],\n [ 0.62116633, 0.87331311, 0.72317003],\n [ 0.63140509, 0.87600675, 0.72741689],\n [ 0.64150735, 0.87870746, 0.73185717],\n [ 0.65147219, 0.8814179 , 0.73648495],\n [ 0.66129632, 0.8841403 , 0.74130658],\n [ 0.67097934, 0.88687758, 0.74631123],\n [ 0.68051833, 0.88963189, 0.75150483],\n [ 0.68991419, 0.89240612, 0.75687187],\n [ 0.69916533, 0.89520211, 0.76241714],\n [ 0.70827373, 0.89802257, 0.76812286],\n [ 0.71723995, 0.90086891, 0.77399039],\n [ 0.72606665, 0.90374337, 0.7800041 ],\n [ 0.73475675, 0.90664718, 0.78615802],\n [ 0.74331358, 0.90958151, 0.79244474],\n [ 0.75174143, 0.91254787, 0.79884925],\n [ 0.76004473, 0.91554656, 0.80536823],\n [ 0.76827704, 0.91856549, 0.81196513],\n [ 0.77647029, 0.921603 , 0.81855729],\n [ 0.78462009, 0.92466151, 0.82514119],\n [ 0.79273542, 0.92773848, 0.83172131],\n [ 0.8008109 , 0.93083672, 0.83829355],\n [ 0.80885107, 0.93395528, 0.84485982],\n [ 0.81685878, 0.9370938 , 0.85142101],\n [ 0.82483206, 0.94025378, 0.8579751 ],\n [ 0.83277661, 0.94343371, 0.86452477],\n [ 0.84069127, 0.94663473, 0.87106853],\n [ 0.84857662, 0.9498573 , 0.8776059 ],\n [ 0.8564431 , 0.95309792, 0.88414253],\n [ 0.86429066, 0.95635719, 0.89067759],\n [ 0.87218969, 0.95960708, 0.89725384]\n]\n\n_vlag_lut = [\n [ 0.13850039, 0.41331206, 0.74052025],\n [ 0.15077609, 0.41762684, 0.73970427],\n [ 0.16235219, 0.4219191 , 0.7389667 ],\n [ 0.1733322 , 0.42619024, 0.73832537],\n [ 0.18382538, 0.43044226, 0.73776764],\n [ 0.19394034, 0.4346772 , 0.73725867],\n [ 0.20367115, 0.43889576, 0.73685314],\n [ 0.21313625, 0.44310003, 0.73648045],\n [ 0.22231173, 0.44729079, 0.73619681],\n [ 0.23125148, 0.45146945, 0.73597803],\n [ 0.23998101, 0.45563715, 0.7358223 ],\n [ 0.24853358, 0.45979489, 0.73571524],\n [ 0.25691416, 0.4639437 , 0.73566943],\n [ 0.26513894, 0.46808455, 0.73568319],\n [ 0.27322194, 0.47221835, 0.73575497],\n [ 0.28117543, 0.47634598, 0.73588332],\n [ 0.28901021, 0.48046826, 0.73606686],\n [ 0.2967358 , 0.48458597, 0.73630433],\n [ 0.30436071, 0.48869986, 0.73659451],\n [ 0.3118955 , 0.49281055, 0.73693255],\n [ 0.31935389, 0.49691847, 0.73730851],\n [ 0.32672701, 0.5010247 , 0.73774013],\n [ 0.33402607, 0.50512971, 0.73821941],\n [ 0.34125337, 0.50923419, 0.73874905],\n [ 0.34840921, 0.51333892, 0.73933402],\n [ 0.35551826, 0.51744353, 0.73994642],\n [ 0.3625676 , 0.52154929, 0.74060763],\n [ 0.36956356, 0.52565656, 0.74131327],\n [ 0.37649902, 0.52976642, 0.74207698],\n [ 0.38340273, 0.53387791, 0.74286286],\n [ 0.39025859, 0.53799253, 0.7436962 ],\n [ 0.39706821, 0.54211081, 0.744578 ],\n [ 0.40384046, 0.54623277, 0.74549872],\n [ 0.41058241, 0.55035849, 0.74645094],\n [ 0.41728385, 0.55448919, 0.74745174],\n [ 0.42395178, 0.55862494, 0.74849357],\n [ 0.4305964 , 0.56276546, 0.74956387],\n [ 0.4372044 , 0.56691228, 0.75068412],\n [ 0.4437909 , 0.57106468, 0.75183427],\n [ 0.45035117, 0.5752235 , 0.75302312],\n [ 0.45687824, 0.57938983, 0.75426297],\n [ 0.46339713, 0.58356191, 0.75551816],\n [ 0.46988778, 0.58774195, 0.75682037],\n [ 0.47635605, 0.59192986, 0.75816245],\n [ 0.48281101, 0.5961252 , 0.75953212],\n [ 0.4892374 , 0.60032986, 0.76095418],\n [ 0.49566225, 0.60454154, 0.76238852],\n [ 0.50206137, 0.60876307, 0.76387371],\n [ 0.50845128, 0.61299312, 0.76538551],\n [ 0.5148258 , 0.61723272, 0.76693475],\n [ 0.52118385, 0.62148236, 0.76852436],\n [ 0.52753571, 0.62574126, 0.77013939],\n [ 0.53386831, 0.63001125, 0.77180152],\n [ 0.54020159, 0.63429038, 0.7734803 ],\n [ 0.54651272, 0.63858165, 0.77521306],\n [ 0.55282975, 0.64288207, 0.77695608],\n [ 0.55912585, 0.64719519, 0.77875327],\n [ 0.56542599, 0.65151828, 0.78056551],\n [ 0.57170924, 0.65585426, 0.78242747],\n [ 0.57799572, 0.6602009 , 0.78430751],\n [ 0.58426817, 0.66456073, 0.78623458],\n [ 0.590544 , 0.66893178, 0.78818117],\n [ 0.59680758, 0.67331643, 0.79017369],\n [ 0.60307553, 0.67771273, 0.79218572],\n [ 0.60934065, 0.68212194, 0.79422987],\n [ 0.61559495, 0.68654548, 0.7963202 ],\n [ 0.62185554, 0.69098125, 0.79842918],\n [ 0.62810662, 0.69543176, 0.80058381],\n [ 0.63436425, 0.69989499, 0.80275812],\n [ 0.64061445, 0.70437326, 0.80497621],\n [ 0.6468706 , 0.70886488, 0.80721641],\n [ 0.65312213, 0.7133717 , 0.80949719],\n [ 0.65937818, 0.71789261, 0.81180392],\n [ 0.66563334, 0.72242871, 0.81414642],\n [ 0.67189155, 0.72697967, 0.81651872],\n [ 0.67815314, 0.73154569, 0.81892097],\n [ 0.68441395, 0.73612771, 0.82136094],\n [ 0.69068321, 0.74072452, 0.82382353],\n [ 0.69694776, 0.7453385 , 0.82633199],\n [ 0.70322431, 0.74996721, 0.8288583 ],\n [ 0.70949595, 0.75461368, 0.83143221],\n [ 0.7157774 , 0.75927574, 0.83402904],\n [ 0.72206299, 0.76395461, 0.83665922],\n [ 0.72835227, 0.76865061, 0.8393242 ],\n [ 0.73465238, 0.7733628 , 0.84201224],\n [ 0.74094862, 0.77809393, 0.84474951],\n [ 0.74725683, 0.78284158, 0.84750915],\n [ 0.75357103, 0.78760701, 0.85030217],\n [ 0.75988961, 0.79239077, 0.85313207],\n [ 0.76621987, 0.79719185, 0.85598668],\n [ 0.77255045, 0.8020125 , 0.85888658],\n [ 0.77889241, 0.80685102, 0.86181298],\n [ 0.78524572, 0.81170768, 0.86476656],\n [ 0.79159841, 0.81658489, 0.86776906],\n [ 0.79796459, 0.82148036, 0.8707962 ],\n [ 0.80434168, 0.82639479, 0.87385315],\n [ 0.8107221 , 0.83132983, 0.87695392],\n [ 0.81711301, 0.8362844 , 0.88008641],\n [ 0.82351479, 0.84125863, 0.88325045],\n [ 0.82992772, 0.84625263, 0.88644594],\n [ 0.83634359, 0.85126806, 0.8896878 ],\n [ 0.84277295, 0.85630293, 0.89295721],\n [ 0.84921192, 0.86135782, 0.89626076],\n [ 0.85566206, 0.866432 , 0.89959467],\n [ 0.86211514, 0.87152627, 0.90297183],\n [ 0.86857483, 0.87663856, 0.90638248],\n [ 0.87504231, 0.88176648, 0.90981938],\n [ 0.88151194, 0.88690782, 0.91328493],\n [ 0.88797938, 0.89205857, 0.91677544],\n [ 0.89443865, 0.89721298, 0.9202854 ],\n [ 0.90088204, 0.90236294, 0.92380601],\n [ 0.90729768, 0.90749778, 0.92732797],\n [ 0.91367037, 0.91260329, 0.93083814],\n [ 0.91998105, 0.91766106, 0.93431861],\n [ 0.92620596, 0.92264789, 0.93774647],\n [ 0.93231683, 0.9275351 , 0.94109192],\n [ 0.93827772, 0.9322888 , 0.94432312],\n [ 0.94404755, 0.93686925, 0.94740137],\n [ 0.94958284, 0.94123072, 0.95027696],\n [ 0.95482682, 0.9453245 , 0.95291103],\n [ 0.9597248 , 0.94909728, 0.95525103],\n [ 0.96422552, 0.95249273, 0.95723271],\n [ 0.96826161, 0.95545812, 0.95882188],\n [ 0.97178458, 0.95793984, 0.95995705],\n [ 0.97474105, 0.95989142, 0.96059997],\n [ 0.97708604, 0.96127366, 0.96071853],\n [ 0.97877855, 0.96205832, 0.96030095],\n [ 0.97978484, 0.96222949, 0.95935496],\n [ 0.9805997 , 0.96155216, 0.95813083],\n [ 0.98152619, 0.95993719, 0.95639322],\n [ 0.9819726 , 0.95766608, 0.95399269],\n [ 0.98191855, 0.9547873 , 0.95098107],\n [ 0.98138514, 0.95134771, 0.94740644],\n [ 0.98040845, 0.94739906, 0.94332125],\n [ 0.97902107, 0.94300131, 0.93878672],\n [ 0.97729348, 0.93820409, 0.93385135],\n [ 0.9752533 , 0.933073 , 0.92858252],\n [ 0.97297834, 0.92765261, 0.92302309],\n [ 0.97049104, 0.92200317, 0.91723505],\n [ 0.96784372, 0.91616744, 0.91126063],\n [ 0.96507281, 0.91018664, 0.90514124],\n [ 0.96222034, 0.90409203, 0.89890756],\n [ 0.9593079 , 0.89791478, 0.89259122],\n [ 0.95635626, 0.89167908, 0.88621654],\n [ 0.95338303, 0.88540373, 0.87980238],\n [ 0.95040174, 0.87910333, 0.87336339],\n [ 0.94742246, 0.87278899, 0.86691076],\n [ 0.94445249, 0.86646893, 0.86045277],\n [ 0.94150476, 0.86014606, 0.85399191],\n [ 0.93857394, 0.85382798, 0.84753642],\n [ 0.93566206, 0.84751766, 0.84108935],\n [ 0.93277194, 0.8412164 , 0.83465197],\n [ 0.92990106, 0.83492672, 0.82822708],\n [ 0.92704736, 0.82865028, 0.82181656],\n [ 0.92422703, 0.82238092, 0.81541333],\n [ 0.92142581, 0.81612448, 0.80902415],\n [ 0.91864501, 0.80988032, 0.80264838],\n [ 0.91587578, 0.80365187, 0.79629001],\n [ 0.9131367 , 0.79743115, 0.78994 ],\n [ 0.91041602, 0.79122265, 0.78360361],\n [ 0.90771071, 0.78502727, 0.77728196],\n [ 0.90501581, 0.77884674, 0.7709771 ],\n [ 0.90235365, 0.77267117, 0.76467793],\n [ 0.8997019 , 0.76650962, 0.75839484],\n [ 0.89705346, 0.76036481, 0.752131 ],\n [ 0.89444021, 0.75422253, 0.74587047],\n [ 0.89183355, 0.74809474, 0.73962689],\n [ 0.88923216, 0.74198168, 0.73340061],\n [ 0.88665892, 0.73587283, 0.72717995],\n [ 0.88408839, 0.72977904, 0.72097718],\n [ 0.88153537, 0.72369332, 0.71478461],\n [ 0.87899389, 0.7176179 , 0.70860487],\n [ 0.87645157, 0.71155805, 0.7024439 ],\n [ 0.8739399 , 0.70549893, 0.6962854 ],\n [ 0.87142626, 0.6994551 , 0.69014561],\n [ 0.8689268 , 0.69341868, 0.68401597],\n [ 0.86643562, 0.687392 , 0.67789917],\n [ 0.86394434, 0.68137863, 0.67179927],\n [ 0.86147586, 0.67536728, 0.665704 ],\n [ 0.85899928, 0.66937226, 0.6596292 ],\n [ 0.85654668, 0.66337773, 0.6535577 ],\n [ 0.85408818, 0.65739772, 0.64750494],\n [ 0.85164413, 0.65142189, 0.64145983],\n [ 0.84920091, 0.6454565 , 0.63542932],\n [ 0.84676427, 0.63949827, 0.62941 ],\n [ 0.84433231, 0.63354773, 0.62340261],\n [ 0.84190106, 0.62760645, 0.61740899],\n [ 0.83947935, 0.62166951, 0.61142404],\n [ 0.8370538 , 0.61574332, 0.60545478],\n [ 0.83463975, 0.60981951, 0.59949247],\n [ 0.83221877, 0.60390724, 0.593547 ],\n [ 0.82980985, 0.59799607, 0.58760751],\n [ 0.82740268, 0.59209095, 0.58167944],\n [ 0.82498638, 0.5861973 , 0.57576866],\n [ 0.82258181, 0.5803034 , 0.56986307],\n [ 0.82016611, 0.57442123, 0.56397539],\n [ 0.81776305, 0.56853725, 0.55809173],\n [ 0.81534551, 0.56266602, 0.55222741],\n [ 0.81294293, 0.55679056, 0.5463651 ],\n [ 0.81052113, 0.55092973, 0.54052443],\n [ 0.80811509, 0.54506305, 0.53468464],\n [ 0.80568952, 0.53921036, 0.52886622],\n [ 0.80327506, 0.53335335, 0.52305077],\n [ 0.80084727, 0.52750583, 0.51725256],\n [ 0.79842217, 0.5216578 , 0.51146173],\n [ 0.79599382, 0.51581223, 0.50568155],\n [ 0.79355781, 0.50997127, 0.49991444],\n [ 0.79112596, 0.50412707, 0.49415289],\n [ 0.78867442, 0.49829386, 0.48841129],\n [ 0.7862306 , 0.49245398, 0.48267247],\n [ 0.7837687 , 0.48662309, 0.47695216],\n [ 0.78130809, 0.4807883 , 0.47123805],\n [ 0.77884467, 0.47495151, 0.46553236],\n [ 0.77636283, 0.46912235, 0.45984473],\n [ 0.77388383, 0.46328617, 0.45416141],\n [ 0.77138912, 0.45745466, 0.44849398],\n [ 0.76888874, 0.45162042, 0.44283573],\n [ 0.76638802, 0.44577901, 0.43718292],\n [ 0.76386116, 0.43994762, 0.43155211],\n [ 0.76133542, 0.43410655, 0.42592523],\n [ 0.75880631, 0.42825801, 0.42030488],\n [ 0.75624913, 0.42241905, 0.41470727],\n [ 0.7536919 , 0.41656866, 0.40911347],\n [ 0.75112748, 0.41071104, 0.40352792],\n [ 0.74854331, 0.40485474, 0.3979589 ],\n [ 0.74594723, 0.39899309, 0.39240088],\n [ 0.74334332, 0.39312199, 0.38685075],\n [ 0.74073277, 0.38723941, 0.3813074 ],\n [ 0.73809409, 0.38136133, 0.37578553],\n [ 0.73544692, 0.37547129, 0.37027123],\n [ 0.73278943, 0.36956954, 0.36476549],\n [ 0.73011829, 0.36365761, 0.35927038],\n [ 0.72743485, 0.35773314, 0.35378465],\n [ 0.72472722, 0.35180504, 0.34831662],\n [ 0.72200473, 0.34586421, 0.34285937],\n [ 0.71927052, 0.33990649, 0.33741033],\n [ 0.71652049, 0.33393396, 0.33197219],\n [ 0.71375362, 0.32794602, 0.32654545],\n [ 0.71096951, 0.32194148, 0.32113016],\n [ 0.70816772, 0.31591904, 0.31572637],\n [ 0.70534784, 0.30987734, 0.31033414],\n [ 0.70250944, 0.30381489, 0.30495353],\n [ 0.69965211, 0.2977301 , 0.2995846 ],\n [ 0.6967754 , 0.29162126, 0.29422741],\n [ 0.69388446, 0.28548074, 0.28887769],\n [ 0.69097561, 0.2793096 , 0.28353795],\n [ 0.68803513, 0.27311993, 0.27821876],\n [ 0.6850794 , 0.26689144, 0.27290694],\n [ 0.682108 , 0.26062114, 0.26760246],\n [ 0.67911013, 0.2543177 , 0.26231367],\n [ 0.67609393, 0.24796818, 0.25703372],\n [ 0.67305921, 0.24156846, 0.25176238],\n [ 0.67000176, 0.23511902, 0.24650278],\n [ 0.66693423, 0.22859879, 0.24124404],\n [ 0.6638441 , 0.22201742, 0.2359961 ],\n [ 0.66080672, 0.21526712, 0.23069468]\n]\n\n_icefire_lut = [\n [ 0.73936227, 0.90443867, 0.85757238],\n [ 0.72888063, 0.89639109, 0.85488394],\n [ 0.71834255, 0.88842162, 0.8521605 ],\n [ 0.70773866, 0.88052939, 0.849422 ],\n [ 0.69706215, 0.87271313, 0.84668315],\n [ 0.68629021, 0.86497329, 0.84398721],\n [ 0.67543654, 0.85730617, 0.84130969],\n [ 0.66448539, 0.84971123, 0.83868005],\n [ 0.65342679, 0.84218728, 0.83611512],\n [ 0.64231804, 0.83471867, 0.83358584],\n [ 0.63117745, 0.827294 , 0.83113431],\n [ 0.62000484, 0.81991069, 0.82876741],\n [ 0.60879435, 0.81256797, 0.82648905],\n [ 0.59754118, 0.80526458, 0.82430414],\n [ 0.58624247, 0.79799884, 0.82221573],\n [ 0.57489525, 0.7907688 , 0.82022901],\n [ 0.56349779, 0.78357215, 0.81834861],\n [ 0.55204294, 0.77640827, 0.81657563],\n [ 0.54052516, 0.76927562, 0.81491462],\n [ 0.52894085, 0.76217215, 0.81336913],\n [ 0.51728854, 0.75509528, 0.81194156],\n [ 0.50555676, 0.74804469, 0.81063503],\n [ 0.49373871, 0.7410187 , 0.80945242],\n [ 0.48183174, 0.73401449, 0.80839675],\n [ 0.46982587, 0.72703075, 0.80747097],\n [ 0.45770893, 0.72006648, 0.80667756],\n [ 0.44547249, 0.71311941, 0.80601991],\n [ 0.43318643, 0.70617126, 0.80549278],\n [ 0.42110294, 0.69916972, 0.80506683],\n [ 0.40925101, 0.69211059, 0.80473246],\n [ 0.3976693 , 0.68498786, 0.80448272],\n [ 0.38632002, 0.67781125, 0.80431024],\n [ 0.37523981, 0.67057537, 0.80420832],\n [ 0.36442578, 0.66328229, 0.80417474],\n [ 0.35385939, 0.65593699, 0.80420591],\n [ 0.34358916, 0.64853177, 0.8043 ],\n [ 0.33355526, 0.64107876, 0.80445484],\n [ 0.32383062, 0.63356578, 0.80467091],\n [ 0.31434372, 0.62600624, 0.8049475 ],\n [ 0.30516161, 0.618389 , 0.80528692],\n [ 0.29623491, 0.61072284, 0.80569021],\n [ 0.28759072, 0.60300319, 0.80616055],\n [ 0.27923924, 0.59522877, 0.80669803],\n [ 0.27114651, 0.5874047 , 0.80730545],\n [ 0.26337153, 0.57952055, 0.80799113],\n [ 0.25588696, 0.57157984, 0.80875922],\n [ 0.248686 , 0.56358255, 0.80961366],\n [ 0.24180668, 0.55552289, 0.81055123],\n [ 0.23526251, 0.54739477, 0.8115939 ],\n [ 0.22921445, 0.53918506, 0.81267292],\n [ 0.22397687, 0.53086094, 0.8137141 ],\n [ 0.21977058, 0.52241482, 0.81457651],\n [ 0.21658989, 0.51384321, 0.81528511],\n [ 0.21452772, 0.50514155, 0.81577278],\n [ 0.21372783, 0.49630865, 0.81589566],\n [ 0.21409503, 0.48734861, 0.81566163],\n [ 0.2157176 , 0.47827123, 0.81487615],\n [ 0.21842857, 0.46909168, 0.81351614],\n [ 0.22211705, 0.45983212, 0.81146983],\n [ 0.22665681, 0.45052233, 0.80860217],\n [ 0.23176013, 0.44119137, 0.80494325],\n [ 0.23727775, 0.43187704, 0.80038017],\n [ 0.24298285, 0.42261123, 0.79493267],\n [ 0.24865068, 0.41341842, 0.78869164],\n [ 0.25423116, 0.40433127, 0.78155831],\n [ 0.25950239, 0.39535521, 0.77376848],\n [ 0.2644736 , 0.38651212, 0.76524809],\n [ 0.26901584, 0.37779582, 0.75621942],\n [ 0.27318141, 0.36922056, 0.746605 ],\n [ 0.27690355, 0.3607736 , 0.73659374],\n [ 0.28023585, 0.35244234, 0.72622103],\n [ 0.28306009, 0.34438449, 0.71500731],\n [ 0.28535896, 0.33660243, 0.70303975],\n [ 0.28708711, 0.32912157, 0.69034504],\n [ 0.28816354, 0.32200604, 0.67684067],\n [ 0.28862749, 0.31519824, 0.66278813],\n [ 0.28847904, 0.30869064, 0.6482815 ],\n [ 0.28770912, 0.30250126, 0.63331265],\n [ 0.28640325, 0.29655509, 0.61811374],\n [ 0.28458943, 0.29082155, 0.60280913],\n [ 0.28233561, 0.28527482, 0.58742866],\n [ 0.27967038, 0.2798938 , 0.57204225],\n [ 0.27665361, 0.27465357, 0.55667809],\n [ 0.27332564, 0.2695165 , 0.54145387],\n [ 0.26973851, 0.26447054, 0.52634916],\n [ 0.2659204 , 0.25949691, 0.511417 ],\n [ 0.26190145, 0.25458123, 0.49668768],\n [ 0.2577151 , 0.24971691, 0.48214874],\n [ 0.25337618, 0.24490494, 0.46778758],\n [ 0.24890842, 0.24013332, 0.45363816],\n [ 0.24433654, 0.23539226, 0.4397245 ],\n [ 0.23967922, 0.23067729, 0.4260591 ],\n [ 0.23495608, 0.22598894, 0.41262952],\n [ 0.23018113, 0.22132414, 0.39945577],\n [ 0.22534609, 0.21670847, 0.38645794],\n [ 0.22048761, 0.21211723, 0.37372555],\n [ 0.2156198 , 0.20755389, 0.36125301],\n [ 0.21074637, 0.20302717, 0.34903192],\n [ 0.20586893, 0.19855368, 0.33701661],\n [ 0.20101757, 0.19411573, 0.32529173],\n [ 0.19619947, 0.18972425, 0.31383846],\n [ 0.19140726, 0.18540157, 0.30260777],\n [ 0.1866769 , 0.1811332 , 0.29166583],\n [ 0.18201285, 0.17694992, 0.28088776],\n [ 0.17745228, 0.17282141, 0.27044211],\n [ 0.17300684, 0.16876921, 0.26024893],\n [ 0.16868273, 0.16479861, 0.25034479],\n [ 0.16448691, 0.16091728, 0.24075373],\n [ 0.16043195, 0.15714351, 0.23141745],\n [ 0.15652427, 0.15348248, 0.22238175],\n [ 0.15277065, 0.14994111, 0.21368395],\n [ 0.14918274, 0.14653431, 0.20529486],\n [ 0.14577095, 0.14327403, 0.19720829],\n [ 0.14254381, 0.14016944, 0.18944326],\n [ 0.13951035, 0.13723063, 0.18201072],\n [ 0.13667798, 0.13446606, 0.17493774],\n [ 0.13405762, 0.13188822, 0.16820842],\n [ 0.13165767, 0.12950667, 0.16183275],\n [ 0.12948748, 0.12733187, 0.15580631],\n [ 0.12755435, 0.1253723 , 0.15014098],\n [ 0.12586516, 0.12363617, 0.1448459 ],\n [ 0.12442647, 0.12213143, 0.13992571],\n [ 0.12324241, 0.12086419, 0.13539995],\n [ 0.12232067, 0.11984278, 0.13124644],\n [ 0.12166209, 0.11907077, 0.12749671],\n [ 0.12126982, 0.11855309, 0.12415079],\n [ 0.12114244, 0.11829179, 0.1212385 ],\n [ 0.12127766, 0.11828837, 0.11878534],\n [ 0.12284806, 0.1179729 , 0.11772022],\n [ 0.12619498, 0.11721796, 0.11770203],\n [ 0.129968 , 0.11663788, 0.11792377],\n [ 0.13410011, 0.11625146, 0.11839138],\n [ 0.13855459, 0.11606618, 0.11910584],\n [ 0.14333775, 0.11607038, 0.1200606 ],\n [ 0.148417 , 0.11626929, 0.12125453],\n [ 0.15377389, 0.11666192, 0.12268364],\n [ 0.15941427, 0.11723486, 0.12433911],\n [ 0.16533376, 0.11797856, 0.12621303],\n [ 0.17152547, 0.11888403, 0.12829735],\n [ 0.17797765, 0.11994436, 0.13058435],\n [ 0.18468769, 0.12114722, 0.13306426],\n [ 0.19165663, 0.12247737, 0.13572616],\n [ 0.19884415, 0.12394381, 0.1385669 ],\n [ 0.20627181, 0.12551883, 0.14157124],\n [ 0.21394877, 0.12718055, 0.14472604],\n [ 0.22184572, 0.12893119, 0.14802579],\n [ 0.22994394, 0.13076731, 0.15146314],\n [ 0.23823937, 0.13267611, 0.15502793],\n [ 0.24676041, 0.13462172, 0.15870321],\n [ 0.25546457, 0.13661751, 0.16248722],\n [ 0.26433628, 0.13865956, 0.16637301],\n [ 0.27341345, 0.14070412, 0.17034221],\n [ 0.28264773, 0.14277192, 0.1743957 ],\n [ 0.29202272, 0.14486161, 0.17852793],\n [ 0.30159648, 0.14691224, 0.1827169 ],\n [ 0.31129002, 0.14897583, 0.18695213],\n [ 0.32111555, 0.15103351, 0.19119629],\n [ 0.33107961, 0.1530674 , 0.19543758],\n [ 0.34119892, 0.15504762, 0.1996803 ],\n [ 0.35142388, 0.15701131, 0.20389086],\n [ 0.36178937, 0.1589124 , 0.20807639],\n [ 0.37229381, 0.16073993, 0.21223189],\n [ 0.38288348, 0.16254006, 0.2163249 ],\n [ 0.39359592, 0.16426336, 0.22036577],\n [ 0.40444332, 0.16588767, 0.22434027],\n [ 0.41537995, 0.16745325, 0.2282297 ],\n [ 0.42640867, 0.16894939, 0.23202755],\n [ 0.43754706, 0.17034847, 0.23572899],\n [ 0.44878564, 0.1716535 , 0.23932344],\n [ 0.4601126 , 0.17287365, 0.24278607],\n [ 0.47151732, 0.17401641, 0.24610337],\n [ 0.48300689, 0.17506676, 0.2492737 ],\n [ 0.49458302, 0.17601892, 0.25227688],\n [ 0.50623876, 0.17687777, 0.255096 ],\n [ 0.5179623 , 0.17765528, 0.2577162 ],\n [ 0.52975234, 0.17835232, 0.2601134 ],\n [ 0.54159776, 0.17898292, 0.26226847],\n [ 0.55348804, 0.17956232, 0.26416003],\n [ 0.56541729, 0.18010175, 0.26575971],\n [ 0.57736669, 0.180631 , 0.26704888],\n [ 0.58932081, 0.18117827, 0.26800409],\n [ 0.60127582, 0.18175888, 0.26858488],\n [ 0.61319563, 0.1824336 , 0.2687872 ],\n [ 0.62506376, 0.18324015, 0.26858301],\n [ 0.63681202, 0.18430173, 0.26795276],\n [ 0.64842603, 0.18565472, 0.26689463],\n [ 0.65988195, 0.18734638, 0.26543435],\n [ 0.67111966, 0.18948885, 0.26357955],\n [ 0.68209194, 0.19216636, 0.26137175],\n [ 0.69281185, 0.19535326, 0.25887063],\n [ 0.70335022, 0.19891271, 0.25617971],\n [ 0.71375229, 0.20276438, 0.25331365],\n [ 0.72401436, 0.20691287, 0.25027366],\n [ 0.73407638, 0.21145051, 0.24710661],\n [ 0.74396983, 0.21631913, 0.24380715],\n [ 0.75361506, 0.22163653, 0.24043996],\n [ 0.7630579 , 0.22731637, 0.23700095],\n [ 0.77222228, 0.23346231, 0.23356628],\n [ 0.78115441, 0.23998404, 0.23013825],\n [ 0.78979746, 0.24694858, 0.22678822],\n [ 0.79819286, 0.25427223, 0.22352658],\n [ 0.80630444, 0.26198807, 0.22040877],\n [ 0.81417437, 0.27001406, 0.21744645],\n [ 0.82177364, 0.27837336, 0.21468316],\n [ 0.82915955, 0.28696963, 0.21210766],\n [ 0.83628628, 0.2958499 , 0.20977813],\n [ 0.84322168, 0.30491136, 0.20766435],\n [ 0.84995458, 0.31415945, 0.2057863 ],\n [ 0.85648867, 0.32358058, 0.20415327],\n [ 0.86286243, 0.33312058, 0.20274969],\n [ 0.86908321, 0.34276705, 0.20157271],\n [ 0.87512876, 0.3525416 , 0.20064949],\n [ 0.88100349, 0.36243385, 0.19999078],\n [ 0.8866469 , 0.37249496, 0.1997976 ],\n [ 0.89203964, 0.38273475, 0.20013431],\n [ 0.89713496, 0.39318156, 0.20121514],\n [ 0.90195099, 0.40380687, 0.20301555],\n [ 0.90648379, 0.41460191, 0.20558847],\n [ 0.9106967 , 0.42557857, 0.20918529],\n [ 0.91463791, 0.43668557, 0.21367954],\n [ 0.91830723, 0.44790913, 0.21916352],\n [ 0.92171507, 0.45922856, 0.22568002],\n [ 0.92491786, 0.4705936 , 0.23308207],\n [ 0.92790792, 0.48200153, 0.24145932],\n [ 0.93073701, 0.49341219, 0.25065486],\n [ 0.93343918, 0.5048017 , 0.26056148],\n [ 0.93602064, 0.51616486, 0.27118485],\n [ 0.93850535, 0.52748892, 0.28242464],\n [ 0.94092933, 0.53875462, 0.29416042],\n [ 0.94330011, 0.5499628 , 0.30634189],\n [ 0.94563159, 0.56110987, 0.31891624],\n [ 0.94792955, 0.57219822, 0.33184256],\n [ 0.95020929, 0.5832232 , 0.34508419],\n [ 0.95247324, 0.59419035, 0.35859866],\n [ 0.95471709, 0.60510869, 0.37236035],\n [ 0.95698411, 0.61595766, 0.38629631],\n [ 0.95923863, 0.62676473, 0.40043317],\n [ 0.9615041 , 0.6375203 , 0.41474106],\n [ 0.96371553, 0.64826619, 0.42928335],\n [ 0.96591497, 0.65899621, 0.44380444],\n [ 0.96809871, 0.66971662, 0.45830232],\n [ 0.9702495 , 0.6804394 , 0.47280492],\n [ 0.9723881 , 0.69115622, 0.48729272],\n [ 0.97450723, 0.70187358, 0.50178034],\n [ 0.9766108 , 0.712592 , 0.51626837],\n [ 0.97871716, 0.72330511, 0.53074053],\n [ 0.98082222, 0.73401769, 0.54520694],\n [ 0.9829001 , 0.74474445, 0.5597019 ],\n [ 0.98497466, 0.75547635, 0.57420239],\n [ 0.98705581, 0.76621129, 0.58870185],\n [ 0.98913325, 0.77695637, 0.60321626],\n [ 0.99119918, 0.78771716, 0.61775821],\n [ 0.9932672 , 0.79848979, 0.63231691],\n [ 0.99535958, 0.80926704, 0.64687278],\n [ 0.99740544, 0.82008078, 0.66150571],\n [ 0.9992197 , 0.83100723, 0.6764127 ]\n]\n\n_flare_lut = [\n [0.92907237, 0.68878959, 0.50411509],\n [0.92891402, 0.68494686, 0.50173994],\n [0.92864754, 0.68116207, 0.4993754],\n [0.92836112, 0.67738527, 0.49701572],\n [0.9280599, 0.67361354, 0.49466044],\n [0.92775569, 0.66983999, 0.49230866],\n [0.9274375, 0.66607098, 0.48996097],\n [0.927111, 0.66230315, 0.48761688],\n [0.92677996, 0.6585342, 0.485276],\n [0.92644317, 0.65476476, 0.48293832],\n [0.92609759, 0.65099658, 0.48060392],\n [0.925747, 0.64722729, 0.47827244],\n [0.92539502, 0.64345456, 0.47594352],\n [0.92503106, 0.6396848, 0.47361782],\n [0.92466877, 0.6359095, 0.47129427],\n [0.92429828, 0.63213463, 0.46897349],\n [0.92392172, 0.62835879, 0.46665526],\n [0.92354597, 0.62457749, 0.46433898],\n [0.9231622, 0.6207962, 0.46202524],\n [0.92277222, 0.61701365, 0.45971384],\n [0.92237978, 0.61322733, 0.45740444],\n [0.92198615, 0.60943622, 0.45509686],\n [0.92158735, 0.60564276, 0.45279137],\n [0.92118373, 0.60184659, 0.45048789],\n [0.92077582, 0.59804722, 0.44818634],\n [0.92036413, 0.59424414, 0.44588663],\n [0.91994924, 0.5904368, 0.44358868],\n [0.91952943, 0.58662619, 0.4412926],\n [0.91910675, 0.58281075, 0.43899817],\n [0.91868096, 0.57899046, 0.4367054],\n [0.91825103, 0.57516584, 0.43441436],\n [0.91781857, 0.57133556, 0.43212486],\n [0.9173814, 0.56750099, 0.4298371],\n [0.91694139, 0.56366058, 0.42755089],\n [0.91649756, 0.55981483, 0.42526631],\n [0.91604942, 0.55596387, 0.42298339],\n [0.9155979, 0.55210684, 0.42070204],\n [0.9151409, 0.54824485, 0.4184247],\n [0.91466138, 0.54438817, 0.41617858],\n [0.91416896, 0.54052962, 0.41396347],\n [0.91366559, 0.53666778, 0.41177769],\n [0.91315173, 0.53280208, 0.40962196],\n [0.91262605, 0.52893336, 0.40749715],\n [0.91208866, 0.52506133, 0.40540404],\n [0.91153952, 0.52118582, 0.40334346],\n [0.91097732, 0.51730767, 0.4013163],\n [0.910403, 0.51342591, 0.39932342],\n [0.90981494, 0.50954168, 0.39736571],\n [0.90921368, 0.5056543, 0.39544411],\n [0.90859797, 0.50176463, 0.39355952],\n [0.90796841, 0.49787195, 0.39171297],\n [0.90732341, 0.4939774, 0.38990532],\n [0.90666382, 0.49008006, 0.38813773],\n [0.90598815, 0.486181, 0.38641107],\n [0.90529624, 0.48228017, 0.38472641],\n [0.90458808, 0.47837738, 0.38308489],\n [0.90386248, 0.47447348, 0.38148746],\n [0.90311921, 0.4705685, 0.37993524],\n [0.90235809, 0.46666239, 0.37842943],\n [0.90157824, 0.46275577, 0.37697105],\n [0.90077904, 0.45884905, 0.37556121],\n [0.89995995, 0.45494253, 0.37420106],\n [0.89912041, 0.4510366, 0.37289175],\n [0.8982602, 0.44713126, 0.37163458],\n [0.89737819, 0.44322747, 0.37043052],\n [0.89647387, 0.43932557, 0.36928078],\n [0.89554477, 0.43542759, 0.36818855],\n [0.89458871, 0.4315354, 0.36715654],\n [0.89360794, 0.42764714, 0.36618273],\n [0.89260152, 0.42376366, 0.36526813],\n [0.8915687, 0.41988565, 0.36441384],\n [0.89050882, 0.41601371, 0.36362102],\n [0.8894159, 0.41215334, 0.36289639],\n [0.888292, 0.40830288, 0.36223756],\n [0.88713784, 0.40446193, 0.36164328],\n [0.88595253, 0.40063149, 0.36111438],\n [0.88473115, 0.39681635, 0.3606566],\n [0.88347246, 0.39301805, 0.36027074],\n [0.88217931, 0.38923439, 0.35995244],\n [0.880851, 0.38546632, 0.35970244],\n [0.87947728, 0.38172422, 0.35953127],\n [0.87806542, 0.37800172, 0.35942941],\n [0.87661509, 0.37429964, 0.35939659],\n [0.87511668, 0.37062819, 0.35944178],\n [0.87357554, 0.36698279, 0.35955811],\n [0.87199254, 0.3633634, 0.35974223],\n [0.87035691, 0.35978174, 0.36000516],\n [0.86867647, 0.35623087, 0.36033559],\n [0.86694949, 0.35271349, 0.36073358],\n [0.86516775, 0.34923921, 0.36120624],\n [0.86333996, 0.34580008, 0.36174113],\n [0.86145909, 0.3424046, 0.36234402],\n [0.85952586, 0.33905327, 0.36301129],\n [0.85754536, 0.33574168, 0.36373567],\n [0.855514, 0.33247568, 0.36451271],\n [0.85344392, 0.32924217, 0.36533344],\n [0.8513284, 0.32604977, 0.36620106],\n [0.84916723, 0.32289973, 0.36711424],\n [0.84696243, 0.31979068, 0.36806976],\n [0.84470627, 0.31673295, 0.36907066],\n [0.84240761, 0.31371695, 0.37010969],\n [0.84005337, 0.31075974, 0.37119284],\n [0.83765537, 0.30784814, 0.3723105],\n [0.83520234, 0.30499724, 0.37346726],\n [0.83270291, 0.30219766, 0.37465552],\n [0.83014895, 0.29946081, 0.37587769],\n [0.82754694, 0.29677989, 0.37712733],\n [0.82489111, 0.29416352, 0.37840532],\n [0.82218644, 0.29160665, 0.37970606],\n [0.81942908, 0.28911553, 0.38102921],\n [0.81662276, 0.28668665, 0.38236999],\n [0.81376555, 0.28432371, 0.383727],\n [0.81085964, 0.28202508, 0.38509649],\n [0.8079055, 0.27979128, 0.38647583],\n [0.80490309, 0.27762348, 0.3878626],\n [0.80185613, 0.2755178, 0.38925253],\n [0.79876118, 0.27347974, 0.39064559],\n [0.79562644, 0.27149928, 0.39203532],\n [0.79244362, 0.2695883, 0.39342447],\n [0.78922456, 0.26773176, 0.3948046],\n [0.78596161, 0.26594053, 0.39617873],\n [0.7826624, 0.26420493, 0.39754146],\n [0.77932717, 0.26252522, 0.39889102],\n [0.77595363, 0.2609049, 0.4002279],\n [0.77254999, 0.25933319, 0.40154704],\n [0.76911107, 0.25781758, 0.40284959],\n [0.76564158, 0.25635173, 0.40413341],\n [0.76214598, 0.25492998, 0.40539471],\n [0.75861834, 0.25356035, 0.40663694],\n [0.75506533, 0.25223402, 0.40785559],\n [0.75148963, 0.2509473, 0.40904966],\n [0.74788835, 0.24970413, 0.41022028],\n [0.74426345, 0.24850191, 0.41136599],\n [0.74061927, 0.24733457, 0.41248516],\n [0.73695678, 0.24620072, 0.41357737],\n [0.73327278, 0.24510469, 0.41464364],\n [0.72957096, 0.24404127, 0.4156828],\n [0.72585394, 0.24300672, 0.41669383],\n [0.7221226, 0.24199971, 0.41767651],\n [0.71837612, 0.24102046, 0.41863486],\n [0.71463236, 0.24004289, 0.41956983],\n [0.7108932, 0.23906316, 0.42048681],\n [0.70715842, 0.23808142, 0.42138647],\n [0.70342811, 0.2370976, 0.42226844],\n [0.69970218, 0.23611179, 0.42313282],\n [0.69598055, 0.2351247, 0.42397678],\n [0.69226314, 0.23413578, 0.42480327],\n [0.68854988, 0.23314511, 0.42561234],\n [0.68484064, 0.23215279, 0.42640419],\n [0.68113541, 0.23115942, 0.42717615],\n [0.67743412, 0.23016472, 0.42792989],\n [0.67373662, 0.22916861, 0.42866642],\n [0.67004287, 0.22817117, 0.42938576],\n [0.66635279, 0.22717328, 0.43008427],\n [0.66266621, 0.22617435, 0.43076552],\n [0.65898313, 0.22517434, 0.43142956],\n [0.65530349, 0.22417381, 0.43207427],\n [0.65162696, 0.22317307, 0.4327001],\n [0.64795375, 0.22217149, 0.43330852],\n [0.64428351, 0.22116972, 0.43389854],\n [0.64061624, 0.22016818, 0.43446845],\n [0.63695183, 0.21916625, 0.43502123],\n [0.63329016, 0.21816454, 0.43555493],\n [0.62963102, 0.2171635, 0.43606881],\n [0.62597451, 0.21616235, 0.43656529],\n [0.62232019, 0.21516239, 0.43704153],\n [0.61866821, 0.21416307, 0.43749868],\n [0.61501835, 0.21316435, 0.43793808],\n [0.61137029, 0.21216761, 0.4383556],\n [0.60772426, 0.2111715, 0.43875552],\n [0.60407977, 0.21017746, 0.43913439],\n [0.60043678, 0.20918503, 0.43949412],\n [0.59679524, 0.20819447, 0.43983393],\n [0.59315487, 0.20720639, 0.44015254],\n [0.58951566, 0.20622027, 0.44045213],\n [0.58587715, 0.20523751, 0.44072926],\n [0.5822395, 0.20425693, 0.44098758],\n [0.57860222, 0.20328034, 0.44122241],\n [0.57496549, 0.20230637, 0.44143805],\n [0.57132875, 0.20133689, 0.4416298],\n [0.56769215, 0.20037071, 0.44180142],\n [0.5640552, 0.19940936, 0.44194923],\n [0.56041794, 0.19845221, 0.44207535],\n [0.55678004, 0.1975, 0.44217824],\n [0.55314129, 0.19655316, 0.44225723],\n [0.54950166, 0.19561118, 0.44231412],\n [0.54585987, 0.19467771, 0.44234111],\n [0.54221157, 0.19375869, 0.44233698],\n [0.5385549, 0.19285696, 0.44229959],\n [0.5348913, 0.19197036, 0.44222958],\n [0.53122177, 0.1910974, 0.44212735],\n [0.52754464, 0.19024042, 0.44199159],\n [0.52386353, 0.18939409, 0.44182449],\n [0.52017476, 0.18856368, 0.44162345],\n [0.51648277, 0.18774266, 0.44139128],\n [0.51278481, 0.18693492, 0.44112605],\n [0.50908361, 0.18613639, 0.4408295],\n [0.50537784, 0.18534893, 0.44050064],\n [0.50166912, 0.18457008, 0.44014054],\n [0.49795686, 0.18380056, 0.43974881],\n [0.49424218, 0.18303865, 0.43932623],\n [0.49052472, 0.18228477, 0.43887255],\n [0.48680565, 0.1815371, 0.43838867],\n [0.48308419, 0.18079663, 0.43787408],\n [0.47936222, 0.18006056, 0.43733022],\n [0.47563799, 0.17933127, 0.43675585],\n [0.47191466, 0.17860416, 0.43615337],\n [0.46818879, 0.17788392, 0.43552047],\n [0.46446454, 0.17716458, 0.43486036],\n [0.46073893, 0.17645017, 0.43417097],\n [0.45701462, 0.17573691, 0.43345429],\n [0.45329097, 0.17502549, 0.43271025],\n [0.44956744, 0.17431649, 0.4319386],\n [0.44584668, 0.17360625, 0.43114133],\n [0.44212538, 0.17289906, 0.43031642],\n [0.43840678, 0.17219041, 0.42946642],\n [0.43469046, 0.17148074, 0.42859124],\n [0.4309749, 0.17077192, 0.42769008],\n [0.42726297, 0.17006003, 0.42676519],\n [0.42355299, 0.16934709, 0.42581586],\n [0.41984535, 0.16863258, 0.42484219],\n [0.41614149, 0.16791429, 0.42384614],\n [0.41244029, 0.16719372, 0.42282661],\n [0.40874177, 0.16647061, 0.42178429],\n [0.40504765, 0.16574261, 0.42072062],\n [0.401357, 0.16501079, 0.41963528],\n [0.397669, 0.16427607, 0.418528],\n [0.39398585, 0.16353554, 0.41740053],\n [0.39030735, 0.16278924, 0.41625344],\n [0.3866314, 0.16203977, 0.41508517],\n [0.38295904, 0.16128519, 0.41389849],\n [0.37928736, 0.16052483, 0.41270599],\n [0.37562649, 0.15974704, 0.41151182],\n [0.37197803, 0.15895049, 0.41031532],\n [0.36833779, 0.15813871, 0.40911916],\n [0.36470944, 0.15730861, 0.40792149],\n [0.36109117, 0.15646169, 0.40672362],\n [0.35748213, 0.15559861, 0.40552633],\n [0.353885, 0.15471714, 0.40432831],\n [0.35029682, 0.15381967, 0.4031316],\n [0.34671861, 0.1529053, 0.40193587],\n [0.34315191, 0.15197275, 0.40074049],\n [0.33959331, 0.15102466, 0.3995478],\n [0.33604378, 0.15006017, 0.39835754],\n [0.33250529, 0.14907766, 0.39716879],\n [0.32897621, 0.14807831, 0.39598285],\n [0.3254559, 0.14706248, 0.39480044],\n [0.32194567, 0.14602909, 0.39362106],\n [0.31844477, 0.14497857, 0.39244549],\n [0.31494974, 0.14391333, 0.39127626],\n [0.31146605, 0.14282918, 0.39011024],\n [0.30798857, 0.1417297, 0.38895105],\n [0.30451661, 0.14061515, 0.38779953],\n [0.30105136, 0.13948445, 0.38665531],\n [0.2975886, 0.1383403, 0.38552159],\n [0.29408557, 0.13721193, 0.38442775]\n]\n\n_crest_lut = [\n [0.6468274, 0.80289262, 0.56592265],\n [0.64233318, 0.80081141, 0.56639461],\n [0.63791969, 0.7987162, 0.56674976],\n [0.6335316, 0.79661833, 0.56706128],\n [0.62915226, 0.7945212, 0.56735066],\n [0.62477862, 0.79242543, 0.56762143],\n [0.62042003, 0.79032918, 0.56786129],\n [0.61606327, 0.78823508, 0.56808666],\n [0.61171322, 0.78614216, 0.56829092],\n [0.60736933, 0.78405055, 0.56847436],\n [0.60302658, 0.78196121, 0.56864272],\n [0.59868708, 0.77987374, 0.56879289],\n [0.59435366, 0.77778758, 0.56892099],\n [0.59001953, 0.77570403, 0.56903477],\n [0.58568753, 0.77362254, 0.56913028],\n [0.58135593, 0.77154342, 0.56920908],\n [0.57702623, 0.76946638, 0.56926895],\n [0.57269165, 0.76739266, 0.5693172],\n [0.56835934, 0.76532092, 0.56934507],\n [0.56402533, 0.76325185, 0.56935664],\n [0.55968429, 0.76118643, 0.56935732],\n [0.55534159, 0.75912361, 0.56934052],\n [0.55099572, 0.75706366, 0.56930743],\n [0.54664626, 0.75500662, 0.56925799],\n [0.54228969, 0.75295306, 0.56919546],\n [0.53792417, 0.75090328, 0.56912118],\n [0.53355172, 0.74885687, 0.5690324],\n [0.52917169, 0.74681387, 0.56892926],\n [0.52478243, 0.74477453, 0.56881287],\n [0.52038338, 0.74273888, 0.56868323],\n [0.5159739, 0.74070697, 0.56854039],\n [0.51155269, 0.73867895, 0.56838507],\n [0.50711872, 0.73665492, 0.56821764],\n [0.50267118, 0.73463494, 0.56803826],\n [0.49822926, 0.73261388, 0.56785146],\n [0.49381422, 0.73058524, 0.56767484],\n [0.48942421, 0.72854938, 0.56751036],\n [0.48505993, 0.72650623, 0.56735752],\n [0.48072207, 0.72445575, 0.56721583],\n [0.4764113, 0.72239788, 0.56708475],\n [0.47212827, 0.72033258, 0.56696376],\n [0.46787361, 0.71825983, 0.56685231],\n [0.46364792, 0.71617961, 0.56674986],\n [0.45945271, 0.71409167, 0.56665625],\n [0.45528878, 0.71199595, 0.56657103],\n [0.45115557, 0.70989276, 0.5664931],\n [0.44705356, 0.70778212, 0.56642189],\n [0.44298321, 0.70566406, 0.56635683],\n [0.43894492, 0.70353863, 0.56629734],\n [0.43493911, 0.70140588, 0.56624286],\n [0.43096612, 0.69926587, 0.5661928],\n [0.42702625, 0.69711868, 0.56614659],\n [0.42311977, 0.69496438, 0.56610368],\n [0.41924689, 0.69280308, 0.56606355],\n [0.41540778, 0.69063486, 0.56602564],\n [0.41160259, 0.68845984, 0.56598944],\n [0.40783143, 0.68627814, 0.56595436],\n [0.40409434, 0.68408988, 0.56591994],\n [0.40039134, 0.68189518, 0.56588564],\n [0.39672238, 0.6796942, 0.56585103],\n [0.39308781, 0.67748696, 0.56581581],\n [0.38949137, 0.67527276, 0.56578084],\n [0.38592889, 0.67305266, 0.56574422],\n [0.38240013, 0.67082685, 0.56570561],\n [0.37890483, 0.66859548, 0.56566462],\n [0.37544276, 0.66635871, 0.56562081],\n [0.37201365, 0.66411673, 0.56557372],\n [0.36861709, 0.6618697, 0.5655231],\n [0.36525264, 0.65961782, 0.56546873],\n [0.36191986, 0.65736125, 0.56541032],\n [0.35861935, 0.65509998, 0.56534768],\n [0.35535621, 0.65283302, 0.56528211],\n [0.35212361, 0.65056188, 0.56521171],\n [0.34892097, 0.64828676, 0.56513633],\n [0.34574785, 0.64600783, 0.56505539],\n [0.34260357, 0.64372528, 0.5649689],\n [0.33948744, 0.64143931, 0.56487679],\n [0.33639887, 0.6391501, 0.56477869],\n [0.33334501, 0.63685626, 0.56467661],\n [0.33031952, 0.63455911, 0.564569],\n [0.3273199, 0.63225924, 0.56445488],\n [0.32434526, 0.62995682, 0.56433457],\n [0.32139487, 0.62765201, 0.56420795],\n [0.31846807, 0.62534504, 0.56407446],\n [0.3155731, 0.62303426, 0.56393695],\n [0.31270304, 0.62072111, 0.56379321],\n [0.30985436, 0.61840624, 0.56364307],\n [0.30702635, 0.61608984, 0.56348606],\n [0.30421803, 0.61377205, 0.56332267],\n [0.30143611, 0.61145167, 0.56315419],\n [0.29867863, 0.60912907, 0.56298054],\n [0.29593872, 0.60680554, 0.56280022],\n [0.29321538, 0.60448121, 0.56261376],\n [0.2905079, 0.60215628, 0.56242036],\n [0.28782827, 0.5998285, 0.56222366],\n [0.28516521, 0.59749996, 0.56202093],\n [0.28251558, 0.59517119, 0.56181204],\n [0.27987847, 0.59284232, 0.56159709],\n [0.27726216, 0.59051189, 0.56137785],\n [0.27466434, 0.58818027, 0.56115433],\n [0.2720767, 0.58584893, 0.56092486],\n [0.26949829, 0.58351797, 0.56068983],\n [0.26693801, 0.58118582, 0.56045121],\n [0.26439366, 0.57885288, 0.56020858],\n [0.26185616, 0.57652063, 0.55996077],\n [0.25932459, 0.57418919, 0.55970795],\n [0.25681303, 0.57185614, 0.55945297],\n [0.25431024, 0.56952337, 0.55919385],\n [0.25180492, 0.56719255, 0.5589305],\n [0.24929311, 0.56486397, 0.5586654],\n [0.24678356, 0.56253666, 0.55839491],\n [0.24426587, 0.56021153, 0.55812473],\n [0.24174022, 0.55788852, 0.55785448],\n [0.23921167, 0.55556705, 0.55758211],\n [0.23668315, 0.55324675, 0.55730676],\n [0.23414742, 0.55092825, 0.55703167],\n [0.23160473, 0.54861143, 0.5567573],\n [0.22905996, 0.54629572, 0.55648168],\n [0.22651648, 0.54398082, 0.5562029],\n [0.22396709, 0.54166721, 0.55592542],\n [0.22141221, 0.53935481, 0.55564885],\n [0.21885269, 0.53704347, 0.55537294],\n [0.21629986, 0.53473208, 0.55509319],\n [0.21374297, 0.53242154, 0.5548144],\n [0.21118255, 0.53011166, 0.55453708],\n [0.2086192, 0.52780237, 0.55426067],\n [0.20605624, 0.52549322, 0.55398479],\n [0.20350004, 0.5231837, 0.55370601],\n [0.20094292, 0.52087429, 0.55342884],\n [0.19838567, 0.51856489, 0.55315283],\n [0.19582911, 0.51625531, 0.55287818],\n [0.19327413, 0.51394542, 0.55260469],\n [0.19072933, 0.51163448, 0.5523289],\n [0.18819045, 0.50932268, 0.55205372],\n [0.18565609, 0.50701014, 0.55177937],\n [0.18312739, 0.50469666, 0.55150597],\n [0.18060561, 0.50238204, 0.55123374],\n [0.178092, 0.50006616, 0.55096224],\n [0.17558808, 0.49774882, 0.55069118],\n [0.17310341, 0.49542924, 0.5504176],\n [0.17063111, 0.49310789, 0.55014445],\n [0.1681728, 0.49078458, 0.54987159],\n [0.1657302, 0.48845913, 0.54959882],\n [0.16330517, 0.48613135, 0.54932605],\n [0.16089963, 0.48380104, 0.54905306],\n [0.15851561, 0.48146803, 0.54877953],\n [0.15615526, 0.47913212, 0.54850526],\n [0.15382083, 0.47679313, 0.54822991],\n [0.15151471, 0.47445087, 0.54795318],\n [0.14924112, 0.47210502, 0.54767411],\n [0.1470032, 0.46975537, 0.54739226],\n [0.14480101, 0.46740187, 0.54710832],\n [0.14263736, 0.46504434, 0.54682188],\n [0.14051521, 0.46268258, 0.54653253],\n [0.13843761, 0.46031639, 0.54623985],\n [0.13640774, 0.45794558, 0.5459434],\n [0.13442887, 0.45556994, 0.54564272],\n [0.1325044, 0.45318928, 0.54533736],\n [0.13063777, 0.4508034, 0.54502674],\n [0.12883252, 0.44841211, 0.5447104],\n [0.12709242, 0.44601517, 0.54438795],\n [0.1254209, 0.44361244, 0.54405855],\n [0.12382162, 0.44120373, 0.54372156],\n [0.12229818, 0.43878887, 0.54337634],\n [0.12085453, 0.4363676, 0.54302253],\n [0.11949938, 0.43393955, 0.54265715],\n [0.11823166, 0.43150478, 0.54228104],\n [0.11705496, 0.42906306, 0.54189388],\n [0.115972, 0.42661431, 0.54149449],\n [0.11498598, 0.42415835, 0.54108222],\n [0.11409965, 0.42169502, 0.54065622],\n [0.11331533, 0.41922424, 0.5402155],\n [0.11263542, 0.41674582, 0.53975931],\n [0.1120615, 0.4142597, 0.53928656],\n [0.11159738, 0.41176567, 0.53879549],\n [0.11125248, 0.40926325, 0.53828203],\n [0.11101698, 0.40675289, 0.53774864],\n [0.11089152, 0.40423445, 0.53719455],\n [0.11085121, 0.4017095, 0.53662425],\n [0.11087217, 0.39917938, 0.53604354],\n [0.11095515, 0.39664394, 0.53545166],\n [0.11110676, 0.39410282, 0.53484509],\n [0.11131735, 0.39155635, 0.53422678],\n [0.11158595, 0.38900446, 0.53359634],\n [0.11191139, 0.38644711, 0.5329534],\n [0.11229224, 0.38388426, 0.53229748],\n [0.11273683, 0.38131546, 0.53162393],\n [0.11323438, 0.37874109, 0.53093619],\n [0.11378271, 0.37616112, 0.53023413],\n [0.11437992, 0.37357557, 0.52951727],\n [0.11502681, 0.37098429, 0.52878396],\n [0.11572661, 0.36838709, 0.52803124],\n [0.11646936, 0.36578429, 0.52726234],\n [0.11725299, 0.3631759, 0.52647685],\n [0.1180755, 0.36056193, 0.52567436],\n [0.1189438, 0.35794203, 0.5248497],\n [0.11984752, 0.35531657, 0.52400649],\n [0.1207833, 0.35268564, 0.52314492],\n [0.12174895, 0.35004927, 0.52226461],\n [0.12274959, 0.34740723, 0.52136104],\n [0.12377809, 0.34475975, 0.52043639],\n [0.12482961, 0.34210702, 0.51949179],\n [0.125902, 0.33944908, 0.51852688],\n [0.12699998, 0.33678574, 0.51753708],\n [0.12811691, 0.33411727, 0.51652464],\n [0.12924811, 0.33144384, 0.51549084],\n [0.13039157, 0.32876552, 0.51443538],\n [0.13155228, 0.32608217, 0.51335321],\n [0.13272282, 0.32339407, 0.51224759],\n [0.13389954, 0.32070138, 0.51111946],\n [0.13508064, 0.31800419, 0.50996862],\n [0.13627149, 0.31530238, 0.50878942],\n [0.13746376, 0.31259627, 0.50758645],\n [0.13865499, 0.30988598, 0.50636017],\n [0.13984364, 0.30717161, 0.50511042],\n [0.14103515, 0.30445309, 0.50383119],\n [0.14222093, 0.30173071, 0.50252813],\n [0.14339946, 0.2990046, 0.50120127],\n [0.14456941, 0.29627483, 0.49985054],\n [0.14573579, 0.29354139, 0.49847009],\n [0.14689091, 0.29080452, 0.49706566],\n [0.1480336, 0.28806432, 0.49563732],\n [0.1491628, 0.28532086, 0.49418508],\n [0.15028228, 0.28257418, 0.49270402],\n [0.15138673, 0.27982444, 0.49119848],\n [0.15247457, 0.27707172, 0.48966925],\n [0.15354487, 0.2743161, 0.48811641],\n [0.15459955, 0.27155765, 0.4865371],\n [0.15563716, 0.26879642, 0.4849321],\n [0.1566572, 0.26603191, 0.48330429],\n [0.15765823, 0.26326032, 0.48167456],\n [0.15862147, 0.26048295, 0.48005785],\n [0.15954301, 0.25770084, 0.47845341],\n [0.16043267, 0.25491144, 0.4768626],\n [0.16129262, 0.25211406, 0.4752857],\n [0.1621119, 0.24931169, 0.47372076],\n [0.16290577, 0.24649998, 0.47217025],\n [0.16366819, 0.24368054, 0.47063302],\n [0.1644021, 0.24085237, 0.46910949],\n [0.16510882, 0.2380149, 0.46759982],\n [0.16579015, 0.23516739, 0.46610429],\n [0.1664433, 0.2323105, 0.46462219],\n [0.16707586, 0.22944155, 0.46315508],\n [0.16768475, 0.22656122, 0.46170223],\n [0.16826815, 0.22366984, 0.46026308],\n [0.16883174, 0.22076514, 0.45883891],\n [0.16937589, 0.21784655, 0.45742976],\n [0.16990129, 0.21491339, 0.45603578],\n [0.1704074, 0.21196535, 0.45465677],\n [0.17089473, 0.20900176, 0.4532928],\n [0.17136819, 0.20602012, 0.45194524],\n [0.17182683, 0.20302012, 0.45061386],\n [0.17227059, 0.20000106, 0.44929865],\n [0.17270583, 0.19695949, 0.44800165],\n [0.17313804, 0.19389201, 0.44672488],\n [0.17363177, 0.19076859, 0.44549087]\n]\n\n_lut_dict = dict(\n rocket=_rocket_lut,\n mako=_mako_lut,\n icefire=_icefire_lut,\n vlag=_vlag_lut,\n flare=_flare_lut,\n crest=_crest_lut,\n\n)\n\nfor _name, _lut in _lut_dict.items():\n\n _cmap = colors.ListedColormap(_lut, _name)\n locals()[_name] = _cmap\n\n _cmap_r = colors.ListedColormap(_lut[::-1], _name + \"_r\")\n locals()[_name + \"_r\"] = _cmap_r\n\n register_colormap(_name, _cmap)\n register_colormap(_name + \"_r\", _cmap_r)\n\ndel colors, register_colormap"},{"col":4,"comment":"null","endLoc":373,"header":"def _lookup_single(self, key)","id":1240,"name":"_lookup_single","nodeType":"Function","startLoc":364,"text":"def _lookup_single(self, key):\n\n try:\n value = self.lookup_table[key]\n except KeyError:\n normed = self.norm(key)\n if np.ma.is_masked(normed):\n normed = np.nan\n value = self.size_range[0] + normed * np.ptp(self.size_range)\n return value"},{"col":4,"comment":"Return a sequential colormap given a color seed.","endLoc":218,"header":"def _cmap_from_color(self, color)","id":1241,"name":"_cmap_from_color","nodeType":"Function","startLoc":206,"text":"def _cmap_from_color(self, color):\n \"\"\"Return a sequential colormap given a color seed.\"\"\"\n # Like so much else here, this is broadly useful, but keeping it\n # in this class to signify that I haven't thought overly hard about it...\n r, g, b, _ = to_rgba(color)\n h, s, _ = husl.rgb_to_husl(r, g, b)\n xx = np.linspace(-1, 1, int(1.15 * 256))[:256]\n ramp = np.zeros((256, 3))\n ramp[:, 0] = h\n ramp[:, 1] = s * np.cos(xx)\n ramp[:, 2] = np.linspace(35, 80, 256)\n colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1)\n return mpl.colors.ListedColormap(colors[::-1])"},{"id":1242,"name":"objects.Perc.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2d44a326-029b-47ff-b560-5f4b6a4bb73f\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"diamonds = load_dataset(\\\"diamonds\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"65e975a2-2559-4bf1-8851-8bbbf52bf22d\",\n \"metadata\": {},\n \"source\": [\n \"The default behavior computes the quartiles and min/max of the input data:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"36f927f5-3b64-4871-a355-adadc4da769b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = (\\n\",\n \" so.Plot(diamonds, \\\"cut\\\", \\\"price\\\")\\n\",\n \" .scale(y=\\\"log\\\")\\n\",\n \")\\n\",\n \"p.add(so.Dot(), so.Perc())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"feba1b99-0f71-4b18-8e7e-bd5470cc2d0c\",\n \"metadata\": {},\n \"source\": [\n \"Passing an integer will compute that many evenly-spaced percentiles:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f030dd39-1223-475a-93e1-1759a8971a6c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Dot(), so.Perc(20))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"85bd754b-122e-4475-8727-2d584a90a38e\",\n \"metadata\": {},\n \"source\": [\n \"Passing a list will compute exactly those percentiles:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2fde7549-45b5-411a-afba-eb0da754d9e9\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Dot(), so.Perc([10, 25, 50, 75, 90]))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"7be16a13-dfc8-4595-a904-42f9be10f4f6\",\n \"metadata\": {},\n \"source\": [\n \"Combine with a range mark to show a percentile interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"05c561c6-0449-4a61-96d1-390611a1b694\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(diamonds, \\\"price\\\", \\\"cut\\\")\\n\",\n \" .add(so.Dots(pointsize=1, alpha=.2), so.Jitter(.3))\\n\",\n \" .add(so.Range(color=\\\"k\\\"), so.Perc([25, 75]), so.Shift(y=.2))\\n\",\n \" .scale(x=\\\"log\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d464157c-3187-49c1-9cd8-71f284ce4c50\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":1243,"name":"color_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Calling with no arguments returns all colors from the current default\\n\",\n \"color cycle:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Other variants on the seaborn categorical color palette can be referenced by name:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"pastel\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return a specified number of evenly spaced hues in the \\\"HUSL\\\" system:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"husl\\\", 9)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return all unique colors in a categorical Color Brewer palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"Set2\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return a diverging Color Brewer palette as a continuous colormap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"Spectral\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return one of the perceptually-uniform palettes included in seaborn as a discrete palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"flare\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return one of the perceptually-uniform palettes included in seaborn as a continuous colormap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"flare\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return a customized cubehelix color palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"ch:s=.25,rot=-.25\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return a light sequential gradient:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"light:#5A9\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return a reversed dark sequential gradient:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"dark:#5A9_r\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Return a blend gradient between two endpoints:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"blend:#7AB,#EDA\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Use as a context manager to change the default qualitative color palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"x, y = list(range(10)), [0] * 10\\n\",\n \"hue = list(map(str, x))\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"with sns.color_palette(\\\"Set3\\\"):\\n\",\n \" sns.relplot(x=x, y=y, hue=hue, s=500, legend=False, height=1.3, aspect=4)\\n\",\n \"\\n\",\n \"sns.relplot(x=x, y=y, hue=hue, s=500, legend=False, height=1.3, aspect=4)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"See the underlying color values as hex codes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"show-output\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"print(sns.color_palette(\\\"pastel6\\\").as_hex())\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"col":4,"comment":"null","endLoc":104,"header":"@pytest.mark.parametrize(\"dtype\", [float, np.int64, object])\n def test_mask_input(self, dtype)","id":1244,"name":"test_mask_input","nodeType":"Function","startLoc":94,"text":"@pytest.mark.parametrize(\"dtype\", [float, np.int64, object])\n def test_mask_input(self, dtype):\n kws = self.default_kws.copy()\n\n mask = self.x_norm > 0\n kws['mask'] = mask\n data = self.x_norm.astype(dtype)\n p = mat._HeatMapper(data, **kws)\n plot_data = np.ma.masked_where(mask, data)\n\n npt.assert_array_equal(p.plot_data, plot_data)"},{"attributeType":"None","col":4,"comment":"null","endLoc":295,"id":1245,"name":"norm","nodeType":"Attribute","startLoc":295,"text":"norm"},{"attributeType":"str","col":12,"comment":"null","endLoc":346,"id":1246,"name":"map_type","nodeType":"Attribute","startLoc":346,"text":"self.map_type"},{"fileName":"area.py","filePath":"seaborn/_marks","id":1247,"nodeType":"File","text":"from __future__ import annotations\nfrom collections import defaultdict\nfrom dataclasses import dataclass\n\nimport numpy as np\nimport matplotlib as mpl\n\nfrom seaborn._marks.base import (\n Mark,\n Mappable,\n MappableBool,\n MappableFloat,\n MappableColor,\n MappableStyle,\n resolve_properties,\n resolve_color,\n document_properties,\n)\n\n\nclass AreaBase:\n\n def _plot(self, split_gen, scales, orient):\n\n patches = defaultdict(list)\n\n for keys, data, ax in split_gen():\n\n kws = {}\n data = self._standardize_coordinate_parameters(data, orient)\n resolved = resolve_properties(self, keys, scales)\n verts = self._get_verts(data, orient)\n ax.update_datalim(verts)\n\n # TODO should really move this logic into resolve_color\n fc = resolve_color(self, keys, \"\", scales)\n if not resolved[\"fill\"]:\n fc = mpl.colors.to_rgba(fc, 0)\n\n kws[\"facecolor\"] = fc\n kws[\"edgecolor\"] = resolve_color(self, keys, \"edge\", scales)\n kws[\"linewidth\"] = resolved[\"edgewidth\"]\n kws[\"linestyle\"] = resolved[\"edgestyle\"]\n\n patches[ax].append(mpl.patches.Polygon(verts, **kws))\n\n for ax, ax_patches in patches.items():\n\n for patch in ax_patches:\n self._postprocess_artist(patch, ax, orient)\n ax.add_patch(patch)\n\n def _standardize_coordinate_parameters(self, data, orient):\n return data\n\n def _postprocess_artist(self, artist, ax, orient):\n pass\n\n def _get_verts(self, data, orient):\n\n dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n data = data.sort_values(orient, kind=\"mergesort\")\n verts = np.concatenate([\n data[[orient, f\"{dv}min\"]].to_numpy(),\n data[[orient, f\"{dv}max\"]].to_numpy()[::-1],\n ])\n if orient == \"y\":\n verts = verts[:, ::-1]\n return verts\n\n def _legend_artist(self, variables, value, scales):\n\n keys = {v: value for v in variables}\n resolved = resolve_properties(self, keys, scales)\n\n fc = resolve_color(self, keys, \"\", scales)\n if not resolved[\"fill\"]:\n fc = mpl.colors.to_rgba(fc, 0)\n\n return mpl.patches.Patch(\n facecolor=fc,\n edgecolor=resolve_color(self, keys, \"edge\", scales),\n linewidth=resolved[\"edgewidth\"],\n linestyle=resolved[\"edgestyle\"],\n **self.artist_kws,\n )\n\n\n@document_properties\n@dataclass\nclass Area(AreaBase, Mark):\n \"\"\"\n A fill mark drawn from a baseline to data values.\n\n See also\n --------\n Band : A fill mark representing an interval between values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Area.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", )\n alpha: MappableFloat = Mappable(.2, )\n fill: MappableBool = Mappable(True, )\n edgecolor: MappableColor = Mappable(depend=\"color\")\n edgealpha: MappableFloat = Mappable(1, )\n edgewidth: MappableFloat = Mappable(rc=\"patch.linewidth\", )\n edgestyle: MappableStyle = Mappable(\"-\", )\n\n # TODO should this be settable / mappable?\n baseline: MappableFloat = Mappable(0, grouping=False)\n\n def _standardize_coordinate_parameters(self, data, orient):\n dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return data.rename(columns={\"baseline\": f\"{dv}min\", dv: f\"{dv}max\"})\n\n def _postprocess_artist(self, artist, ax, orient):\n\n # TODO copying a lot of code from Bar, let's abstract this\n # See comments there, I am not going to repeat them too\n\n artist.set_linewidth(artist.get_linewidth() * 2)\n\n linestyle = artist.get_linestyle()\n if linestyle[1]:\n linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1]))\n artist.set_linestyle(linestyle)\n\n artist.set_clip_path(artist.get_path(), artist.get_transform() + ax.transData)\n if self.artist_kws.get(\"clip_on\", True):\n artist.set_clip_box(ax.bbox)\n\n val_idx = [\"y\", \"x\"].index(orient)\n artist.sticky_edges[val_idx][:] = (0, np.inf)\n\n\n@document_properties\n@dataclass\nclass Band(AreaBase, Mark):\n \"\"\"\n A fill mark representing an interval between values.\n\n See also\n --------\n Area : A fill mark drawn from a baseline to data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Band.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", )\n alpha: MappableFloat = Mappable(.2, )\n fill: MappableBool = Mappable(True, )\n edgecolor: MappableColor = Mappable(depend=\"color\", )\n edgealpha: MappableFloat = Mappable(1, )\n edgewidth: MappableFloat = Mappable(0, )\n edgestyle: MappableFloat = Mappable(\"-\", )\n\n def _standardize_coordinate_parameters(self, data, orient):\n # dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n # TODO assert that all(ymax >= ymin)?\n # TODO what if only one exist?\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n if not set(data.columns) & {f\"{other}min\", f\"{other}max\"}:\n agg = {f\"{other}min\": (other, \"min\"), f\"{other}max\": (other, \"max\")}\n data = data.groupby(orient).agg(**agg).reset_index()\n return data\n"},{"attributeType":"null","col":12,"comment":"null","endLoc":349,"id":1248,"name":"sizes","nodeType":"Attribute","startLoc":349,"text":"self.sizes"},{"className":"AreaBase","col":0,"comment":"null","endLoc":86,"id":1249,"nodeType":"Class","startLoc":21,"text":"class AreaBase:\n\n def _plot(self, split_gen, scales, orient):\n\n patches = defaultdict(list)\n\n for keys, data, ax in split_gen():\n\n kws = {}\n data = self._standardize_coordinate_parameters(data, orient)\n resolved = resolve_properties(self, keys, scales)\n verts = self._get_verts(data, orient)\n ax.update_datalim(verts)\n\n # TODO should really move this logic into resolve_color\n fc = resolve_color(self, keys, \"\", scales)\n if not resolved[\"fill\"]:\n fc = mpl.colors.to_rgba(fc, 0)\n\n kws[\"facecolor\"] = fc\n kws[\"edgecolor\"] = resolve_color(self, keys, \"edge\", scales)\n kws[\"linewidth\"] = resolved[\"edgewidth\"]\n kws[\"linestyle\"] = resolved[\"edgestyle\"]\n\n patches[ax].append(mpl.patches.Polygon(verts, **kws))\n\n for ax, ax_patches in patches.items():\n\n for patch in ax_patches:\n self._postprocess_artist(patch, ax, orient)\n ax.add_patch(patch)\n\n def _standardize_coordinate_parameters(self, data, orient):\n return data\n\n def _postprocess_artist(self, artist, ax, orient):\n pass\n\n def _get_verts(self, data, orient):\n\n dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n data = data.sort_values(orient, kind=\"mergesort\")\n verts = np.concatenate([\n data[[orient, f\"{dv}min\"]].to_numpy(),\n data[[orient, f\"{dv}max\"]].to_numpy()[::-1],\n ])\n if orient == \"y\":\n verts = verts[:, ::-1]\n return verts\n\n def _legend_artist(self, variables, value, scales):\n\n keys = {v: value for v in variables}\n resolved = resolve_properties(self, keys, scales)\n\n fc = resolve_color(self, keys, \"\", scales)\n if not resolved[\"fill\"]:\n fc = mpl.colors.to_rgba(fc, 0)\n\n return mpl.patches.Patch(\n facecolor=fc,\n edgecolor=resolve_color(self, keys, \"edge\", scales),\n linewidth=resolved[\"edgewidth\"],\n linestyle=resolved[\"edgestyle\"],\n **self.artist_kws,\n )"},{"col":4,"comment":"null","endLoc":51,"header":"def _plot(self, split_gen, scales, orient)","id":1250,"name":"_plot","nodeType":"Function","startLoc":23,"text":"def _plot(self, split_gen, scales, orient):\n\n patches = defaultdict(list)\n\n for keys, data, ax in split_gen():\n\n kws = {}\n data = self._standardize_coordinate_parameters(data, orient)\n resolved = resolve_properties(self, keys, scales)\n verts = self._get_verts(data, orient)\n ax.update_datalim(verts)\n\n # TODO should really move this logic into resolve_color\n fc = resolve_color(self, keys, \"\", scales)\n if not resolved[\"fill\"]:\n fc = mpl.colors.to_rgba(fc, 0)\n\n kws[\"facecolor\"] = fc\n kws[\"edgecolor\"] = resolve_color(self, keys, \"edge\", scales)\n kws[\"linewidth\"] = resolved[\"edgewidth\"]\n kws[\"linestyle\"] = resolved[\"edgestyle\"]\n\n patches[ax].append(mpl.patches.Polygon(verts, **kws))\n\n for ax, ax_patches in patches.items():\n\n for patch in ax_patches:\n self._postprocess_artist(patch, ax, orient)\n ax.add_patch(patch)"},{"col":4,"comment":"\n Parameters\n ----------\n data : str\n String with lines separated by '\n'.\n\n ","endLoc":66,"header":"def __init__(self, data)","id":1251,"name":"__init__","nodeType":"Function","startLoc":53,"text":"def __init__(self, data):\n \"\"\"\n Parameters\n ----------\n data : str\n String with lines separated by '\\n'.\n\n \"\"\"\n if isinstance(data, list):\n self._str = data\n else:\n self._str = data.split('\\n') # store string as list of lines\n\n self.reset()"},{"attributeType":"dict | dict","col":12,"comment":"null","endLoc":351,"id":1252,"name":"lookup_table","nodeType":"Attribute","startLoc":351,"text":"self.lookup_table"},{"col":4,"comment":"null","endLoc":72,"header":"def reset(self)","id":1253,"name":"reset","nodeType":"Function","startLoc":71,"text":"def reset(self):\n self._l = 0 # current line nr"},{"attributeType":"None | (SupportsDunderLT | SupportsDunderGT, SupportsDunderLT | SupportsDunderGT) | tuple","col":12,"comment":"null","endLoc":350,"id":1255,"name":"size_range","nodeType":"Attribute","startLoc":350,"text":"self.size_range"},{"attributeType":"list | list","col":12,"comment":"null","endLoc":347,"id":1256,"name":"levels","nodeType":"Attribute","startLoc":347,"text":"self.levels"},{"fileName":"dot.py","filePath":"seaborn/_marks","id":1257,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass\n\nimport numpy as np\nimport matplotlib as mpl\n\nfrom seaborn._marks.base import (\n Mark,\n Mappable,\n MappableBool,\n MappableFloat,\n MappableString,\n MappableColor,\n MappableStyle,\n resolve_properties,\n resolve_color,\n document_properties,\n)\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Any\n from matplotlib.artist import Artist\n from seaborn._core.scales import Scale\n\n\nclass DotBase(Mark):\n\n def _resolve_paths(self, data):\n\n paths = []\n path_cache = {}\n marker = data[\"marker\"]\n\n def get_transformed_path(m):\n return m.get_path().transformed(m.get_transform())\n\n if isinstance(marker, mpl.markers.MarkerStyle):\n return get_transformed_path(marker)\n\n for m in marker:\n if m not in path_cache:\n path_cache[m] = get_transformed_path(m)\n paths.append(path_cache[m])\n return paths\n\n def _resolve_properties(self, data, scales):\n\n resolved = resolve_properties(self, data, scales)\n resolved[\"path\"] = self._resolve_paths(resolved)\n resolved[\"size\"] = resolved[\"pointsize\"] ** 2\n\n if isinstance(data, dict): # Properties for single dot\n filled_marker = resolved[\"marker\"].is_filled()\n else:\n filled_marker = [m.is_filled() for m in resolved[\"marker\"]]\n\n resolved[\"fill\"] = resolved[\"fill\"] * filled_marker\n\n return resolved\n\n def _plot(self, split_gen, scales, orient):\n\n # TODO Not backcompat with allowed (but nonfunctional) univariate plots\n # (That should be solved upstream by defaulting to \"\" for unset x/y?)\n # (Be mindful of xmin/xmax, etc!)\n\n for _, data, ax in split_gen():\n\n offsets = np.column_stack([data[\"x\"], data[\"y\"]])\n data = self._resolve_properties(data, scales)\n\n points = mpl.collections.PathCollection(\n offsets=offsets,\n paths=data[\"path\"],\n sizes=data[\"size\"],\n facecolors=data[\"facecolor\"],\n edgecolors=data[\"edgecolor\"],\n linewidths=data[\"linewidth\"],\n linestyles=data[\"edgestyle\"],\n transOffset=ax.transData,\n transform=mpl.transforms.IdentityTransform(),\n **self.artist_kws,\n )\n ax.add_collection(points)\n\n def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n\n key = {v: value for v in variables}\n res = self._resolve_properties(key, scales)\n\n return mpl.collections.PathCollection(\n paths=[res[\"path\"]],\n sizes=[res[\"size\"]],\n facecolors=[res[\"facecolor\"]],\n edgecolors=[res[\"edgecolor\"]],\n linewidths=[res[\"linewidth\"]],\n linestyles=[res[\"edgestyle\"]],\n transform=mpl.transforms.IdentityTransform(),\n **self.artist_kws,\n )\n\n\n@document_properties\n@dataclass\nclass Dot(DotBase):\n \"\"\"\n A mark suitable for dot plots or less-dense scatterplots.\n\n See also\n --------\n Dots : A dot mark defined by strokes to better handle overplotting.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Dot.rst\n\n \"\"\"\n marker: MappableString = Mappable(\"o\", grouping=False)\n pointsize: MappableFloat = Mappable(6, grouping=False) # TODO rcParam?\n stroke: MappableFloat = Mappable(.75, grouping=False) # TODO rcParam?\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(1, grouping=False)\n fill: MappableBool = Mappable(True, grouping=False)\n edgecolor: MappableColor = Mappable(depend=\"color\", grouping=False)\n edgealpha: MappableFloat = Mappable(depend=\"alpha\", grouping=False)\n edgewidth: MappableFloat = Mappable(.5, grouping=False) # TODO rcParam?\n edgestyle: MappableStyle = Mappable(\"-\", grouping=False)\n\n def _resolve_properties(self, data, scales):\n\n resolved = super()._resolve_properties(data, scales)\n filled = resolved[\"fill\"]\n\n main_stroke = resolved[\"stroke\"]\n edge_stroke = resolved[\"edgewidth\"]\n resolved[\"linewidth\"] = np.where(filled, edge_stroke, main_stroke)\n\n main_color = resolve_color(self, data, \"\", scales)\n edge_color = resolve_color(self, data, \"edge\", scales)\n\n if not np.isscalar(filled):\n # Expand dims to use in np.where with rgba arrays\n filled = filled[:, None]\n resolved[\"edgecolor\"] = np.where(filled, edge_color, main_color)\n\n filled = np.squeeze(filled)\n if isinstance(main_color, tuple):\n # TODO handle this in resolve_color\n main_color = tuple([*main_color[:3], main_color[3] * filled])\n else:\n main_color = np.c_[main_color[:, :3], main_color[:, 3] * filled]\n resolved[\"facecolor\"] = main_color\n\n return resolved\n\n\n@document_properties\n@dataclass\nclass Dots(DotBase):\n \"\"\"\n A dot mark defined by strokes to better handle overplotting.\n\n See also\n --------\n Dot : A mark suitable for dot plots or less-dense scatterplots.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Dots.rst\n\n \"\"\"\n # TODO retype marker as MappableMarker\n marker: MappableString = Mappable(rc=\"scatter.marker\", grouping=False)\n pointsize: MappableFloat = Mappable(4, grouping=False) # TODO rcParam?\n stroke: MappableFloat = Mappable(.75, grouping=False) # TODO rcParam?\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(1, grouping=False) # TODO auto alpha?\n fill: MappableBool = Mappable(True, grouping=False)\n fillcolor: MappableColor = Mappable(depend=\"color\", grouping=False)\n fillalpha: MappableFloat = Mappable(.2, grouping=False)\n\n def _resolve_properties(self, data, scales):\n\n resolved = super()._resolve_properties(data, scales)\n resolved[\"linewidth\"] = resolved.pop(\"stroke\")\n resolved[\"facecolor\"] = resolve_color(self, data, \"fill\", scales)\n resolved[\"edgecolor\"] = resolve_color(self, data, \"\", scales)\n resolved.setdefault(\"edgestyle\", (0, None))\n\n fc = resolved[\"facecolor\"]\n if isinstance(fc, tuple):\n resolved[\"facecolor\"] = fc[0], fc[1], fc[2], fc[3] * resolved[\"fill\"]\n else:\n fc[:, 3] = fc[:, 3] * resolved[\"fill\"] # TODO Is inplace mod a problem?\n resolved[\"facecolor\"] = fc\n\n return resolved\n"},{"col":4,"comment":"null","endLoc":428,"header":"def _parse(self)","id":1258,"name":"_parse","nodeType":"Function","startLoc":393,"text":"def _parse(self):\n self._doc.reset()\n self._parse_summary()\n\n sections = list(self._read_sections())\n section_names = {section for section, content in sections}\n\n has_returns = 'Returns' in section_names\n has_yields = 'Yields' in section_names\n # We could do more tests, but we are not. Arbitrarily.\n if has_returns and has_yields:\n msg = 'Docstring contains both a Returns and Yields section.'\n raise ValueError(msg)\n if not has_yields and 'Receives' in section_names:\n msg = 'Docstring contains a Receives section but not Yields.'\n raise ValueError(msg)\n\n for (section, content) in sections:\n if not section.startswith('..'):\n section = (s.capitalize() for s in section.split(' '))\n section = ' '.join(section)\n if self.get(section):\n self._error_location(f\"The section {section} appears twice\")\n\n if section in ('Parameters', 'Other Parameters', 'Attributes',\n 'Methods'):\n self[section] = self._parse_param_list(content)\n elif section in ('Returns', 'Yields', 'Raises', 'Warns', 'Receives'):\n self[section] = self._parse_param_list(\n content, single_element_is_type=True)\n elif section.startswith('.. index::'):\n self['index'] = self._parse_index(section, content)\n elif section == 'See Also':\n self['See Also'] = self._parse_see_also(content)\n else:\n self[section] = content"},{"attributeType":"{clip, scaled} | None","col":12,"comment":"null","endLoc":348,"id":1259,"name":"norm","nodeType":"Attribute","startLoc":348,"text":"self.norm"},{"className":"StyleMapping","col":0,"comment":"Mapping that sets artist style according to data values.","endLoc":607,"id":1260,"nodeType":"Class","startLoc":513,"text":"@share_init_params_with_map\nclass StyleMapping(SemanticMapping):\n \"\"\"Mapping that sets artist style according to data values.\"\"\"\n\n # Style mapping is always treated as categorical\n map_type = \"categorical\"\n\n def __init__(\n self, plotter, markers=None, dashes=None, order=None,\n ):\n \"\"\"Map the levels of the `style` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"style\", pd.Series(dtype=float))\n\n if data.notna().any():\n\n # Cast to list to handle numpy/pandas datetime quirks\n if variable_type(data) == \"datetime\":\n data = list(data)\n\n # Find ordered unique values\n levels = categorical_order(data, order)\n\n markers = self._map_attributes(\n markers, levels, unique_markers(len(levels)), \"markers\",\n )\n dashes = self._map_attributes(\n dashes, levels, unique_dashes(len(levels)), \"dashes\",\n )\n\n # Build the paths matplotlib will use to draw the markers\n paths = {}\n filled_markers = []\n for k, m in markers.items():\n if not isinstance(m, mpl.markers.MarkerStyle):\n m = mpl.markers.MarkerStyle(m)\n paths[k] = m.get_path().transformed(m.get_transform())\n filled_markers.append(m.is_filled())\n\n # Mixture of filled and unfilled markers will show line art markers\n # in the edge color, which defaults to white. This can be handled,\n # but there would be additional complexity with specifying the\n # weight of the line art markers without overwhelming the filled\n # ones with the edges. So for now, we will disallow mixtures.\n if any(filled_markers) and not all(filled_markers):\n err = \"Filled and line art markers cannot be mixed\"\n raise ValueError(err)\n\n lookup_table = {}\n for key in levels:\n lookup_table[key] = {}\n if markers:\n lookup_table[key][\"marker\"] = markers[key]\n lookup_table[key][\"path\"] = paths[key]\n if dashes:\n lookup_table[key][\"dashes\"] = dashes[key]\n\n self.levels = levels\n self.lookup_table = lookup_table\n\n def _lookup_single(self, key, attr=None):\n \"\"\"Get attribute(s) for a given data point.\"\"\"\n if attr is None:\n value = self.lookup_table[key]\n else:\n value = self.lookup_table[key][attr]\n return value\n\n def _map_attributes(self, arg, levels, defaults, attr):\n \"\"\"Handle the specification for a given style attribute.\"\"\"\n if arg is True:\n lookup_table = dict(zip(levels, defaults))\n elif isinstance(arg, dict):\n missing = set(levels) - set(arg)\n if missing:\n err = f\"These `{attr}` levels are missing values: {missing}\"\n raise ValueError(err)\n lookup_table = arg\n elif isinstance(arg, Sequence):\n arg = self._check_list_length(levels, arg, attr)\n lookup_table = dict(zip(levels, arg))\n elif arg:\n err = f\"This `{attr}` argument was not understood: {arg}\"\n raise ValueError(err)\n else:\n lookup_table = {}\n\n return lookup_table"},{"col":4,"comment":"Map the levels of the `style` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n ","endLoc":578,"header":"def __init__(\n self, plotter, markers=None, dashes=None, order=None,\n )","id":1261,"name":"__init__","nodeType":"Function","startLoc":520,"text":"def __init__(\n self, plotter, markers=None, dashes=None, order=None,\n ):\n \"\"\"Map the levels of the `style` variable to distinct values.\n\n Parameters\n ----------\n # TODO add generic parameters\n\n \"\"\"\n super().__init__(plotter)\n\n data = plotter.plot_data.get(\"style\", pd.Series(dtype=float))\n\n if data.notna().any():\n\n # Cast to list to handle numpy/pandas datetime quirks\n if variable_type(data) == \"datetime\":\n data = list(data)\n\n # Find ordered unique values\n levels = categorical_order(data, order)\n\n markers = self._map_attributes(\n markers, levels, unique_markers(len(levels)), \"markers\",\n )\n dashes = self._map_attributes(\n dashes, levels, unique_dashes(len(levels)), \"dashes\",\n )\n\n # Build the paths matplotlib will use to draw the markers\n paths = {}\n filled_markers = []\n for k, m in markers.items():\n if not isinstance(m, mpl.markers.MarkerStyle):\n m = mpl.markers.MarkerStyle(m)\n paths[k] = m.get_path().transformed(m.get_transform())\n filled_markers.append(m.is_filled())\n\n # Mixture of filled and unfilled markers will show line art markers\n # in the edge color, which defaults to white. This can be handled,\n # but there would be additional complexity with specifying the\n # weight of the line art markers without overwhelming the filled\n # ones with the edges. So for now, we will disallow mixtures.\n if any(filled_markers) and not all(filled_markers):\n err = \"Filled and line art markers cannot be mixed\"\n raise ValueError(err)\n\n lookup_table = {}\n for key in levels:\n lookup_table[key] = {}\n if markers:\n lookup_table[key][\"marker\"] = markers[key]\n lookup_table[key][\"path\"] = paths[key]\n if dashes:\n lookup_table[key][\"dashes\"] = dashes[key]\n\n self.levels = levels\n self.lookup_table = lookup_table"},{"className":"DotBase","col":0,"comment":"null","endLoc":103,"id":1262,"nodeType":"Class","startLoc":27,"text":"class DotBase(Mark):\n\n def _resolve_paths(self, data):\n\n paths = []\n path_cache = {}\n marker = data[\"marker\"]\n\n def get_transformed_path(m):\n return m.get_path().transformed(m.get_transform())\n\n if isinstance(marker, mpl.markers.MarkerStyle):\n return get_transformed_path(marker)\n\n for m in marker:\n if m not in path_cache:\n path_cache[m] = get_transformed_path(m)\n paths.append(path_cache[m])\n return paths\n\n def _resolve_properties(self, data, scales):\n\n resolved = resolve_properties(self, data, scales)\n resolved[\"path\"] = self._resolve_paths(resolved)\n resolved[\"size\"] = resolved[\"pointsize\"] ** 2\n\n if isinstance(data, dict): # Properties for single dot\n filled_marker = resolved[\"marker\"].is_filled()\n else:\n filled_marker = [m.is_filled() for m in resolved[\"marker\"]]\n\n resolved[\"fill\"] = resolved[\"fill\"] * filled_marker\n\n return resolved\n\n def _plot(self, split_gen, scales, orient):\n\n # TODO Not backcompat with allowed (but nonfunctional) univariate plots\n # (That should be solved upstream by defaulting to \"\" for unset x/y?)\n # (Be mindful of xmin/xmax, etc!)\n\n for _, data, ax in split_gen():\n\n offsets = np.column_stack([data[\"x\"], data[\"y\"]])\n data = self._resolve_properties(data, scales)\n\n points = mpl.collections.PathCollection(\n offsets=offsets,\n paths=data[\"path\"],\n sizes=data[\"size\"],\n facecolors=data[\"facecolor\"],\n edgecolors=data[\"edgecolor\"],\n linewidths=data[\"linewidth\"],\n linestyles=data[\"edgestyle\"],\n transOffset=ax.transData,\n transform=mpl.transforms.IdentityTransform(),\n **self.artist_kws,\n )\n ax.add_collection(points)\n\n def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n\n key = {v: value for v in variables}\n res = self._resolve_properties(key, scales)\n\n return mpl.collections.PathCollection(\n paths=[res[\"path\"]],\n sizes=[res[\"size\"]],\n facecolors=[res[\"facecolor\"]],\n edgecolors=[res[\"edgecolor\"]],\n linewidths=[res[\"linewidth\"]],\n linestyles=[res[\"edgestyle\"]],\n transform=mpl.transforms.IdentityTransform(),\n **self.artist_kws,\n )"},{"col":4,"comment":"null","endLoc":45,"header":"def _resolve_paths(self, data)","id":1263,"name":"_resolve_paths","nodeType":"Function","startLoc":29,"text":"def _resolve_paths(self, data):\n\n paths = []\n path_cache = {}\n marker = data[\"marker\"]\n\n def get_transformed_path(m):\n return m.get_path().transformed(m.get_transform())\n\n if isinstance(marker, mpl.markers.MarkerStyle):\n return get_transformed_path(marker)\n\n for m in marker:\n if m not in path_cache:\n path_cache[m] = get_transformed_path(m)\n paths.append(path_cache[m])\n return paths"},{"col":4,"comment":"Grab signature (if given) and summary","endLoc":391,"header":"def _parse_summary(self)","id":1264,"name":"_parse_summary","nodeType":"Function","startLoc":371,"text":"def _parse_summary(self):\n \"\"\"Grab signature (if given) and summary\"\"\"\n if self._is_at_section():\n return\n\n # If several signatures present, take the last one\n while True:\n summary = self._doc.read_to_next_empty_line()\n summary_str = \" \".join([s.strip() for s in summary]).strip()\n compiled = re.compile(r'^([\\w., ]+=)?\\s*[\\w\\.]+\\(.*\\)$')\n if compiled.match(summary_str):\n self['Signature'] = summary_str\n if not self._is_at_section():\n continue\n break\n\n if summary is not None:\n self['Summary'] = summary\n\n if not self._is_at_section():\n self['Extended Summary'] = self._read_to_next_section()"},{"col":4,"comment":"null","endLoc":204,"header":"def _is_at_section(self)","id":1265,"name":"_is_at_section","nodeType":"Function","startLoc":192,"text":"def _is_at_section(self):\n self._doc.seek_next_non_empty_line()\n\n if self._doc.eof():\n return False\n\n l1 = self._doc.peek().strip() # e.g. Parameters\n\n if l1.startswith('.. index::'):\n return True\n\n l2 = self._doc.peek(1).strip() # ---------- or ==========\n return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))"},{"col":4,"comment":"Find default values for discrete hist estimation based on variable type.","endLoc":228,"header":"def _default_discrete(self)","id":1266,"name":"_default_discrete","nodeType":"Function","startLoc":220,"text":"def _default_discrete(self):\n \"\"\"Find default values for discrete hist estimation based on variable type.\"\"\"\n if self.univariate:\n discrete = self.var_types[self.data_variable] == \"categorical\"\n else:\n discrete_x = self.var_types[\"x\"] == \"categorical\"\n discrete_y = self.var_types[\"y\"] == \"categorical\"\n discrete = discrete_x, discrete_y\n return discrete"},{"col":4,"comment":"Modify the density data structure to handle multiple densities.","endLoc":295,"header":"def _resolve_multiple(self, curves, multiple)","id":1267,"name":"_resolve_multiple","nodeType":"Function","startLoc":230,"text":"def _resolve_multiple(self, curves, multiple):\n \"\"\"Modify the density data structure to handle multiple densities.\"\"\"\n\n # Default baselines have all densities starting at 0\n baselines = {k: np.zeros_like(v) for k, v in curves.items()}\n\n # TODO we should have some central clearinghouse for checking if any\n # \"grouping\" (terminnology?) semantics have been assigned\n if \"hue\" not in self.variables:\n return curves, baselines\n\n if multiple in (\"stack\", \"fill\"):\n\n # Setting stack or fill means that the curves share a\n # support grid / set of bin edges, so we can make a dataframe\n # Reverse the column order to plot from top to bottom\n curves = pd.DataFrame(curves).iloc[:, ::-1]\n\n # Find column groups that are nested within col/row variables\n column_groups = {}\n for i, keyd in enumerate(map(dict, curves.columns)):\n facet_key = keyd.get(\"col\", None), keyd.get(\"row\", None)\n column_groups.setdefault(facet_key, [])\n column_groups[facet_key].append(i)\n\n baselines = curves.copy()\n for col_idxs in column_groups.values():\n cols = curves.columns[col_idxs]\n\n norm_constant = curves[cols].sum(axis=\"columns\")\n\n # Take the cumulative sum to stack\n curves[cols] = curves[cols].cumsum(axis=\"columns\")\n\n # Normalize by row sum to fill\n if multiple == \"fill\":\n curves[cols] = curves[cols].div(norm_constant, axis=\"index\")\n\n # Define where each segment starts\n baselines[cols] = curves[cols].shift(1, axis=1).fillna(0)\n\n if multiple == \"dodge\":\n\n # Account for the unique semantic (non-faceting) levels\n # This will require rethiniking if we add other semantics!\n hue_levels = self.var_levels[\"hue\"]\n n = len(hue_levels)\n for key in curves:\n level = dict(key)[\"hue\"]\n hist = curves[key].reset_index(name=\"heights\")\n level_idx = hue_levels.index(level)\n if self._log_scaled(self.data_variable):\n log_min = np.log10(hist[\"edges\"])\n log_max = np.log10(hist[\"edges\"] + hist[\"widths\"])\n log_width = (log_max - log_min) / n\n new_min = np.power(10, log_min + level_idx * log_width)\n new_max = np.power(10, log_min + (level_idx + 1) * log_width)\n hist[\"widths\"] = new_max - new_min\n hist[\"edges\"] = new_min\n else:\n hist[\"widths\"] /= n\n hist[\"edges\"] += level_idx * hist[\"widths\"]\n\n curves[key] = hist.set_index([\"edges\", \"widths\"])[\"heights\"]\n\n return curves, baselines"},{"col":0,"comment":"Build an arbitrarily long list of unique marker styles for points.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n ","endLoc":1732,"header":"def unique_markers(n)","id":1269,"name":"unique_markers","nodeType":"Function","startLoc":1689,"text":"def unique_markers(n):\n \"\"\"Build an arbitrarily long list of unique marker styles for points.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n \"\"\"\n # Start with marker specs that are well distinguishable\n markers = [\n \"o\",\n \"X\",\n (4, 0, 45),\n \"P\",\n (4, 0, 0),\n (4, 1, 0),\n \"^\",\n (4, 1, 45),\n \"v\",\n ]\n\n # Now generate more from regular polygons of increasing order\n s = 5\n while len(markers) < n:\n a = 360 / (s + 1) / 2\n markers.extend([\n (s + 1, 1, a),\n (s + 1, 0, a),\n (s, 1, 0),\n (s, 0, 0),\n ])\n s += 1\n\n # Convert to MarkerStyle object, using only exactly what we need\n # markers = [mpl.markers.MarkerStyle(m) for m in markers[:n]]\n\n return markers[:n]"},{"col":0,"comment":"Return a percentile range from an array of values.","endLoc":498,"header":"def ci(a, which=95, axis=None)","id":1270,"name":"ci","nodeType":"Function","startLoc":495,"text":"def ci(a, which=95, axis=None):\n \"\"\"Return a percentile range from an array of values.\"\"\"\n p = 50 - which / 2, 50 + which / 2\n return np.nanpercentile(a, p, axis)"},{"col":4,"comment":"Fit the regression model.","endLoc":227,"header":"def fit_regression(self, ax=None, x_range=None, grid=None)","id":1271,"name":"fit_regression","nodeType":"Function","startLoc":188,"text":"def fit_regression(self, ax=None, x_range=None, grid=None):\n \"\"\"Fit the regression model.\"\"\"\n # Create the grid for the regression\n if grid is None:\n if self.truncate:\n x_min, x_max = self.x_range\n else:\n if ax is None:\n x_min, x_max = x_range\n else:\n x_min, x_max = ax.get_xlim()\n grid = np.linspace(x_min, x_max, 100)\n ci = self.ci\n\n # Fit the regression\n if self.order > 1:\n yhat, yhat_boots = self.fit_poly(grid, self.order)\n elif self.logistic:\n from statsmodels.genmod.generalized_linear_model import GLM\n from statsmodels.genmod.families import Binomial\n yhat, yhat_boots = self.fit_statsmodels(grid, GLM,\n family=Binomial())\n elif self.lowess:\n ci = None\n grid, yhat = self.fit_lowess()\n elif self.robust:\n from statsmodels.robust.robust_linear_model import RLM\n yhat, yhat_boots = self.fit_statsmodels(grid, RLM)\n elif self.logx:\n yhat, yhat_boots = self.fit_logx(grid)\n else:\n yhat, yhat_boots = self.fit_fast(grid)\n\n # Compute the confidence interval at each grid point\n if ci is None:\n err_bands = None\n else:\n err_bands = utils.ci(yhat_boots, ci, axis=0)\n\n return grid, yhat, err_bands"},{"col":4,"comment":"null","endLoc":993,"header":"def plot_dendrograms(self, row_cluster, col_cluster, metric, method,\n row_linkage, col_linkage, tree_kws)","id":1272,"name":"plot_dendrograms","nodeType":"Function","startLoc":970,"text":"def plot_dendrograms(self, row_cluster, col_cluster, metric, method,\n row_linkage, col_linkage, tree_kws):\n # Plot the row dendrogram\n if row_cluster:\n self.dendrogram_row = dendrogram(\n self.data2d, metric=metric, method=method, label=False, axis=0,\n ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage,\n tree_kws=tree_kws\n )\n else:\n self.ax_row_dendrogram.set_xticks([])\n self.ax_row_dendrogram.set_yticks([])\n # PLot the column dendrogram\n if col_cluster:\n self.dendrogram_col = dendrogram(\n self.data2d, metric=metric, method=method, label=False,\n axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage,\n tree_kws=tree_kws\n )\n else:\n self.ax_col_dendrogram.set_xticks([])\n self.ax_col_dendrogram.set_yticks([])\n despine(ax=self.ax_row_dendrogram, bottom=True, left=True)\n despine(ax=self.ax_col_dendrogram, bottom=True, left=True)"},{"col":0,"comment":"Draw a tree diagram of relationships within a matrix\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n linkage : numpy.array, optional\n Linkage matrix\n axis : int, optional\n Which axis to use to calculate linkage. 0 is rows, 1 is columns.\n label : bool, optional\n If True, label the dendrogram at leaves with column or row names\n metric : str, optional\n Distance metric. Anything valid for scipy.spatial.distance.pdist\n method : str, optional\n Linkage method to use. Anything valid for\n scipy.cluster.hierarchy.linkage\n rotate : bool, optional\n When plotting the matrix, whether to rotate it 90 degrees\n counter-clockwise, so the leaves face right\n tree_kws : dict, optional\n Keyword arguments for the ``matplotlib.collections.LineCollection``\n that is used for plotting the lines of the dendrogram tree.\n ax : matplotlib axis, optional\n Axis to plot on, otherwise uses current axis\n\n Returns\n -------\n dendrogramplotter : _DendrogramPlotter\n A Dendrogram plotter object.\n\n Notes\n -----\n Access the reordered dendrogram indices with\n dendrogramplotter.reordered_ind\n\n ","endLoc":693,"header":"def dendrogram(\n data, *,\n linkage=None, axis=1, label=True, metric='euclidean',\n method='average', rotate=False, tree_kws=None, ax=None\n)","id":1273,"name":"dendrogram","nodeType":"Function","startLoc":642,"text":"def dendrogram(\n data, *,\n linkage=None, axis=1, label=True, metric='euclidean',\n method='average', rotate=False, tree_kws=None, ax=None\n):\n \"\"\"Draw a tree diagram of relationships within a matrix\n\n Parameters\n ----------\n data : pandas.DataFrame\n Rectangular data\n linkage : numpy.array, optional\n Linkage matrix\n axis : int, optional\n Which axis to use to calculate linkage. 0 is rows, 1 is columns.\n label : bool, optional\n If True, label the dendrogram at leaves with column or row names\n metric : str, optional\n Distance metric. Anything valid for scipy.spatial.distance.pdist\n method : str, optional\n Linkage method to use. Anything valid for\n scipy.cluster.hierarchy.linkage\n rotate : bool, optional\n When plotting the matrix, whether to rotate it 90 degrees\n counter-clockwise, so the leaves face right\n tree_kws : dict, optional\n Keyword arguments for the ``matplotlib.collections.LineCollection``\n that is used for plotting the lines of the dendrogram tree.\n ax : matplotlib axis, optional\n Axis to plot on, otherwise uses current axis\n\n Returns\n -------\n dendrogramplotter : _DendrogramPlotter\n A Dendrogram plotter object.\n\n Notes\n -----\n Access the reordered dendrogram indices with\n dendrogramplotter.reordered_ind\n\n \"\"\"\n if _no_scipy:\n raise RuntimeError(\"dendrogram requires scipy to be installed\")\n\n plotter = _DendrogramPlotter(data, linkage=linkage, axis=axis,\n metric=metric, method=method,\n label=label, rotate=rotate)\n if ax is None:\n ax = plt.gca()\n\n return plotter.plot(ax=ax, tree_kws=tree_kws)"},{"col":4,"comment":"null","endLoc":228,"header":"def _read_to_next_section(self)","id":1278,"name":"_read_to_next_section","nodeType":"Function","startLoc":219,"text":"def _read_to_next_section(self):\n section = self._doc.read_to_next_empty_line()\n\n while not self._is_at_section() and not self._doc.eof():\n if not self._doc.peek(-1).strip(): # previous line was empty\n section += ['']\n\n section += self._doc.read_to_next_empty_line()\n\n return section"},{"col":4,"comment":"null","endLoc":240,"header":"def _read_sections(self)","id":1279,"name":"_read_sections","nodeType":"Function","startLoc":230,"text":"def _read_sections(self):\n while not self._doc.eof():\n data = self._read_to_next_section()\n name = data[0].strip()\n\n if name.startswith('..'): # index section\n yield name, data[1:]\n elif len(data) < 2:\n yield StopIteration\n else:\n yield name, self._strip(data[2:])"},{"col":4,"comment":"Regression using numpy polyfit for higher-order trends.","endLoc":263,"header":"def fit_poly(self, grid, order)","id":1280,"name":"fit_poly","nodeType":"Function","startLoc":248,"text":"def fit_poly(self, grid, order):\n \"\"\"Regression using numpy polyfit for higher-order trends.\"\"\"\n def reg_func(_x, _y):\n return np.polyval(np.polyfit(_x, _y, order), grid)\n\n x, y = self.x, self.y\n yhat = reg_func(x, y)\n if self.ci is None:\n return yhat, None\n\n yhat_boots = algo.bootstrap(x, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed)\n return yhat, yhat_boots"},{"col":4,"comment":"null","endLoc":60,"header":"def _resolve_properties(self, data, scales)","id":1282,"name":"_resolve_properties","nodeType":"Function","startLoc":47,"text":"def _resolve_properties(self, data, scales):\n\n resolved = resolve_properties(self, data, scales)\n resolved[\"path\"] = self._resolve_paths(resolved)\n resolved[\"size\"] = resolved[\"pointsize\"] ** 2\n\n if isinstance(data, dict): # Properties for single dot\n filled_marker = resolved[\"marker\"].is_filled()\n else:\n filled_marker = [m.is_filled() for m in resolved[\"marker\"]]\n\n resolved[\"fill\"] = resolved[\"fill\"] * filled_marker\n\n return resolved"},{"col":4,"comment":"null","endLoc":217,"header":"def _strip(self, doc)","id":1283,"name":"_strip","nodeType":"Function","startLoc":206,"text":"def _strip(self, doc):\n i = 0\n j = 0\n for i, line in enumerate(doc):\n if line.strip():\n break\n\n for j, line in enumerate(doc[::-1]):\n if line.strip():\n break\n\n return doc[i:len(doc)-j]"},{"col":4,"comment":"null","endLoc":85,"header":"def _plot(self, split_gen, scales, orient)","id":1284,"name":"_plot","nodeType":"Function","startLoc":62,"text":"def _plot(self, split_gen, scales, orient):\n\n # TODO Not backcompat with allowed (but nonfunctional) univariate plots\n # (That should be solved upstream by defaulting to \"\" for unset x/y?)\n # (Be mindful of xmin/xmax, etc!)\n\n for _, data, ax in split_gen():\n\n offsets = np.column_stack([data[\"x\"], data[\"y\"]])\n data = self._resolve_properties(data, scales)\n\n points = mpl.collections.PathCollection(\n offsets=offsets,\n paths=data[\"path\"],\n sizes=data[\"size\"],\n facecolors=data[\"facecolor\"],\n edgecolors=data[\"edgecolor\"],\n linewidths=data[\"linewidth\"],\n linestyles=data[\"edgestyle\"],\n transOffset=ax.transData,\n transform=mpl.transforms.IdentityTransform(),\n **self.artist_kws,\n )\n ax.add_collection(points)"},{"col":4,"comment":"More general regression function using statsmodels objects.","endLoc":288,"header":"def fit_statsmodels(self, grid, model, **kwargs)","id":1285,"name":"fit_statsmodels","nodeType":"Function","startLoc":265,"text":"def fit_statsmodels(self, grid, model, **kwargs):\n \"\"\"More general regression function using statsmodels objects.\"\"\"\n import statsmodels.genmod.generalized_linear_model as glm\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), grid]\n\n def reg_func(_x, _y):\n try:\n yhat = model(_y, _x, **kwargs).fit().predict(grid)\n except glm.PerfectSeparationError:\n yhat = np.empty(len(grid))\n yhat.fill(np.nan)\n return yhat\n\n yhat = reg_func(X, y)\n if self.ci is None:\n return yhat, None\n\n yhat_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed)\n return yhat, yhat_boots"},{"col":4,"comment":"null","endLoc":103,"header":"def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist","id":1287,"name":"_legend_artist","nodeType":"Function","startLoc":87,"text":"def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n\n key = {v: value for v in variables}\n res = self._resolve_properties(key, scales)\n\n return mpl.collections.PathCollection(\n paths=[res[\"path\"]],\n sizes=[res[\"size\"]],\n facecolors=[res[\"facecolor\"]],\n edgecolors=[res[\"edgecolor\"]],\n linewidths=[res[\"linewidth\"]],\n linestyles=[res[\"edgestyle\"]],\n transform=mpl.transforms.IdentityTransform(),\n **self.artist_kws,\n )"},{"className":"Dot","col":0,"comment":"\n A mark suitable for dot plots or less-dense scatterplots.\n\n See also\n --------\n Dots : A dot mark defined by strokes to better handle overplotting.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Dot.rst\n\n ","endLoc":157,"id":1288,"nodeType":"Class","startLoc":106,"text":"@document_properties\n@dataclass\nclass Dot(DotBase):\n \"\"\"\n A mark suitable for dot plots or less-dense scatterplots.\n\n See also\n --------\n Dots : A dot mark defined by strokes to better handle overplotting.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Dot.rst\n\n \"\"\"\n marker: MappableString = Mappable(\"o\", grouping=False)\n pointsize: MappableFloat = Mappable(6, grouping=False) # TODO rcParam?\n stroke: MappableFloat = Mappable(.75, grouping=False) # TODO rcParam?\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(1, grouping=False)\n fill: MappableBool = Mappable(True, grouping=False)\n edgecolor: MappableColor = Mappable(depend=\"color\", grouping=False)\n edgealpha: MappableFloat = Mappable(depend=\"alpha\", grouping=False)\n edgewidth: MappableFloat = Mappable(.5, grouping=False) # TODO rcParam?\n edgestyle: MappableStyle = Mappable(\"-\", grouping=False)\n\n def _resolve_properties(self, data, scales):\n\n resolved = super()._resolve_properties(data, scales)\n filled = resolved[\"fill\"]\n\n main_stroke = resolved[\"stroke\"]\n edge_stroke = resolved[\"edgewidth\"]\n resolved[\"linewidth\"] = np.where(filled, edge_stroke, main_stroke)\n\n main_color = resolve_color(self, data, \"\", scales)\n edge_color = resolve_color(self, data, \"edge\", scales)\n\n if not np.isscalar(filled):\n # Expand dims to use in np.where with rgba arrays\n filled = filled[:, None]\n resolved[\"edgecolor\"] = np.where(filled, edge_color, main_color)\n\n filled = np.squeeze(filled)\n if isinstance(main_color, tuple):\n # TODO handle this in resolve_color\n main_color = tuple([*main_color[:3], main_color[3] * filled])\n else:\n main_color = np.c_[main_color[:, :3], main_color[:, 3] * filled]\n resolved[\"facecolor\"] = main_color\n\n return resolved"},{"col":4,"comment":"null","endLoc":157,"header":"def _resolve_properties(self, data, scales)","id":1289,"name":"_resolve_properties","nodeType":"Function","startLoc":132,"text":"def _resolve_properties(self, data, scales):\n\n resolved = super()._resolve_properties(data, scales)\n filled = resolved[\"fill\"]\n\n main_stroke = resolved[\"stroke\"]\n edge_stroke = resolved[\"edgewidth\"]\n resolved[\"linewidth\"] = np.where(filled, edge_stroke, main_stroke)\n\n main_color = resolve_color(self, data, \"\", scales)\n edge_color = resolve_color(self, data, \"edge\", scales)\n\n if not np.isscalar(filled):\n # Expand dims to use in np.where with rgba arrays\n filled = filled[:, None]\n resolved[\"edgecolor\"] = np.where(filled, edge_color, main_color)\n\n filled = np.squeeze(filled)\n if isinstance(main_color, tuple):\n # TODO handle this in resolve_color\n main_color = tuple([*main_color[:3], main_color[3] * filled])\n else:\n main_color = np.c_[main_color[:, :3], main_color[:, 3] * filled]\n resolved[\"facecolor\"] = main_color\n\n return resolved"},{"col":4,"comment":"Plots color labels between the dendrogram and the heatmap\n\n Parameters\n ----------\n heatmap_kws : dict\n Keyword arguments heatmap\n\n ","endLoc":1058,"header":"def plot_colors(self, xind, yind, **kws)","id":1290,"name":"plot_colors","nodeType":"Function","startLoc":995,"text":"def plot_colors(self, xind, yind, **kws):\n \"\"\"Plots color labels between the dendrogram and the heatmap\n\n Parameters\n ----------\n heatmap_kws : dict\n Keyword arguments heatmap\n\n \"\"\"\n # Remove any custom colormap and centering\n # TODO this code has consistently caused problems when we\n # have missed kwargs that need to be excluded that it might\n # be better to rewrite *in*clusively.\n kws = kws.copy()\n kws.pop('cmap', None)\n kws.pop('norm', None)\n kws.pop('center', None)\n kws.pop('annot', None)\n kws.pop('vmin', None)\n kws.pop('vmax', None)\n kws.pop('robust', None)\n kws.pop('xticklabels', None)\n kws.pop('yticklabels', None)\n\n # Plot the row colors\n if self.row_colors is not None:\n matrix, cmap = self.color_list_to_matrix_and_cmap(\n self.row_colors, yind, axis=0)\n\n # Get row_color labels\n if self.row_color_labels is not None:\n row_color_labels = self.row_color_labels\n else:\n row_color_labels = False\n\n heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors,\n xticklabels=row_color_labels, yticklabels=False, **kws)\n\n # Adjust rotation of labels\n if row_color_labels is not False:\n plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90)\n else:\n despine(self.ax_row_colors, left=True, bottom=True)\n\n # Plot the column colors\n if self.col_colors is not None:\n matrix, cmap = self.color_list_to_matrix_and_cmap(\n self.col_colors, xind, axis=1)\n\n # Get col_color labels\n if self.col_color_labels is not None:\n col_color_labels = self.col_color_labels\n else:\n col_color_labels = False\n\n heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors,\n xticklabels=False, yticklabels=col_color_labels, **kws)\n\n # Adjust rotation of labels, place on right side\n if col_color_labels is not False:\n self.ax_col_colors.yaxis.tick_right()\n plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0)\n else:\n despine(self.ax_col_colors, left=True, bottom=True)"},{"col":4,"comment":"Fit a locally-weighted regression, which returns its own grid.","endLoc":294,"header":"def fit_lowess(self)","id":1291,"name":"fit_lowess","nodeType":"Function","startLoc":290,"text":"def fit_lowess(self):\n \"\"\"Fit a locally-weighted regression, which returns its own grid.\"\"\"\n from statsmodels.nonparametric.smoothers_lowess import lowess\n grid, yhat = lowess(self.y, self.x).T\n return grid, yhat"},{"attributeType":"bool","col":4,"comment":"null","endLoc":325,"id":1292,"name":"legend","nodeType":"Attribute","startLoc":325,"text":"legend"},{"attributeType":"bool","col":4,"comment":"null","endLoc":326,"id":1293,"name":"normed","nodeType":"Attribute","startLoc":326,"text":"normed"},{"attributeType":"null","col":4,"comment":"null","endLoc":330,"id":1294,"name":"null_value","nodeType":"Attribute","startLoc":330,"text":"null_value"},{"className":"Marker","col":0,"comment":"Shape of points in scatter-type marks or lines with data points marked.","endLoc":416,"id":1295,"nodeType":"Class","startLoc":375,"text":"class Marker(ObjectProperty):\n \"\"\"Shape of points in scatter-type marks or lines with data points marked.\"\"\"\n null_value = MarkerStyle(\"\")\n\n # TODO should we have named marker \"palettes\"? (e.g. see d3 options)\n\n # TODO need some sort of \"require_scale\" functionality\n # to raise when we get the wrong kind explicitly specified\n\n def standardize(self, val: MarkerPattern) -> MarkerStyle:\n return MarkerStyle(val)\n\n def _default_values(self, n: int) -> list[MarkerStyle]:\n \"\"\"Build an arbitrarily long list of unique marker styles.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n \"\"\"\n # Start with marker specs that are well distinguishable\n markers = [\n \"o\", \"X\", (4, 0, 45), \"P\", (4, 0, 0), (4, 1, 0), \"^\", (4, 1, 45), \"v\",\n ]\n\n # Now generate more from regular polygons of increasing order\n s = 5\n while len(markers) < n:\n a = 360 / (s + 1) / 2\n markers.extend([(s + 1, 1, a), (s + 1, 0, a), (s, 1, 0), (s, 0, 0)])\n s += 1\n\n markers = [MarkerStyle(m) for m in markers[:n]]\n\n return markers"},{"col":4,"comment":"null","endLoc":385,"header":"def standardize(self, val: MarkerPattern) -> MarkerStyle","id":1296,"name":"standardize","nodeType":"Function","startLoc":384,"text":"def standardize(self, val: MarkerPattern) -> MarkerStyle:\n return MarkerStyle(val)"},{"col":4,"comment":"Build an arbitrarily long list of unique marker styles.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n ","endLoc":416,"header":"def _default_values(self, n: int) -> list[MarkerStyle]","id":1297,"name":"_default_values","nodeType":"Function","startLoc":387,"text":"def _default_values(self, n: int) -> list[MarkerStyle]:\n \"\"\"Build an arbitrarily long list of unique marker styles.\n\n Parameters\n ----------\n n : int\n Number of unique marker specs to generate.\n\n Returns\n -------\n markers : list of string or tuples\n Values for defining :class:`matplotlib.markers.MarkerStyle` objects.\n All markers will be filled.\n\n \"\"\"\n # Start with marker specs that are well distinguishable\n markers = [\n \"o\", \"X\", (4, 0, 45), \"P\", (4, 0, 0), (4, 1, 0), \"^\", (4, 1, 45), \"v\",\n ]\n\n # Now generate more from regular polygons of increasing order\n s = 5\n while len(markers) < n:\n a = 360 / (s + 1) / 2\n markers.extend([(s + 1, 1, a), (s + 1, 0, a), (s, 1, 0), (s, 0, 0)])\n s += 1\n\n markers = [MarkerStyle(m) for m in markers[:n]]\n\n return markers"},{"col":4,"comment":"Fit the model in log-space.","endLoc":315,"header":"def fit_logx(self, grid)","id":1298,"name":"fit_logx","nodeType":"Function","startLoc":296,"text":"def fit_logx(self, grid):\n \"\"\"Fit the model in log-space.\"\"\"\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), np.log(grid)]\n\n def reg_func(_x, _y):\n _x = np.c_[_x[:, 0], np.log(_x[:, 1])]\n return np.linalg.pinv(_x).dot(_y)\n\n yhat = grid.dot(reg_func(X, y))\n if self.ci is None:\n return yhat, None\n\n beta_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed).T\n yhat_boots = grid.dot(beta_boots).T\n return yhat, yhat_boots"},{"col":4,"comment":"null","endLoc":441,"header":"def _error_location(self, msg, error=True)","id":1301,"name":"_error_location","nodeType":"Function","startLoc":430,"text":"def _error_location(self, msg, error=True):\n if hasattr(self, '_obj'):\n # we know where the docs came from:\n try:\n filename = inspect.getsourcefile(self._obj)\n except TypeError:\n filename = None\n msg = msg + f\" in the docstring of {self._obj} in {filename}.\"\n if error:\n raise ValueError(msg)\n else:\n warn(msg)"},{"col":4,"comment":"Low-level regression and prediction using linear algebra.","endLoc":246,"header":"def fit_fast(self, grid)","id":1302,"name":"fit_fast","nodeType":"Function","startLoc":229,"text":"def fit_fast(self, grid):\n \"\"\"Low-level regression and prediction using linear algebra.\"\"\"\n def reg_func(_x, _y):\n return np.linalg.pinv(_x).dot(_y)\n\n X, y = np.c_[np.ones(len(self.x)), self.x], self.y\n grid = np.c_[np.ones(len(grid)), grid]\n yhat = grid.dot(reg_func(X, y))\n if self.ci is None:\n return yhat, None\n\n beta_boots = algo.bootstrap(X, y,\n func=reg_func,\n n_boot=self.n_boot,\n units=self.units,\n seed=self.seed).T\n yhat_boots = grid.dot(beta_boots).T\n return yhat, yhat_boots"},{"col":4,"comment":"Draw the full plot.","endLoc":374,"header":"def plot(self, ax, scatter_kws, line_kws)","id":1305,"name":"plot","nodeType":"Function","startLoc":340,"text":"def plot(self, ax, scatter_kws, line_kws):\n \"\"\"Draw the full plot.\"\"\"\n # Insert the plot label into the correct set of keyword arguments\n if self.scatter:\n scatter_kws[\"label\"] = self.label\n else:\n line_kws[\"label\"] = self.label\n\n # Use the current color cycle state as a default\n if self.color is None:\n lines, = ax.plot([], [])\n color = lines.get_color()\n lines.remove()\n else:\n color = self.color\n\n # Ensure that color is hex to avoid matplotlib weirdness\n color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color))\n\n # Let color in keyword arguments override overall plot color\n scatter_kws.setdefault(\"color\", color)\n line_kws.setdefault(\"color\", color)\n\n # Draw the constituent plots\n if self.scatter:\n self.scatterplot(ax, scatter_kws)\n\n if self.fit_reg:\n self.lineplot(ax, line_kws)\n\n # Label the axes\n if hasattr(self.x, \"name\"):\n ax.set_xlabel(self.x.name)\n if hasattr(self.y, \"name\"):\n ax.set_ylabel(self.y.name)"},{"col":4,"comment":"Boolean check on whether a variable is defined in this dataset.","endLoc":70,"header":"def __contains__(self, key: str) -> bool","id":1306,"name":"__contains__","nodeType":"Function","startLoc":66,"text":"def __contains__(self, key: str) -> bool:\n \"\"\"Boolean check on whether a variable is defined in this dataset.\"\"\"\n if self.frame is None:\n return any(key in df for df in self.frames.values())\n return key in self.frame"},{"col":4,"comment":"null","endLoc":373,"header":"def _compute_univariate_density(\n self,\n data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular=True,\n )","id":1307,"name":"_compute_univariate_density","nodeType":"Function","startLoc":301,"text":"def _compute_univariate_density(\n self,\n data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular=True,\n ):\n\n # Initialize the estimator object\n estimator = KDE(**estimate_kws)\n\n if set(self.variables) - {\"x\", \"y\"}:\n if common_grid:\n all_observations = self.comp_data.dropna()\n estimator.define_support(all_observations[data_variable])\n else:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n if common_norm and \"weights\" in all_data:\n whole_weight = all_data[\"weights\"].sum()\n else:\n whole_weight = len(all_data)\n\n densities = {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set and remove nulls\n observations = sub_data[data_variable]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n part_weight = weights.sum()\n else:\n weights = None\n part_weight = len(sub_data)\n\n # Estimate the density of observations at this level\n variance = np.nan_to_num(observations.var())\n singular = len(observations) < 2 or math.isclose(variance, 0)\n try:\n if not singular:\n # Convoluted approach needed because numerical failures\n # can manifest in a few different ways.\n density, support = estimator(observations, weights=weights)\n except np.linalg.LinAlgError:\n singular = True\n\n if singular:\n msg = (\n \"Dataset has 0 variance; skipping density estimate. \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning, stacklevel=4)\n continue\n\n if log_scale:\n support = np.power(10, support)\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= part_weight / whole_weight\n\n # Store the density for this level\n key = tuple(sub_vars.items())\n densities[key] = pd.Series(density, index=support)\n\n return densities"},{"col":0,"comment":"Plot rectangular data as a color-encoded matrix.\n\n This is an Axes-level function and will draw the heatmap into the\n currently-active Axes if none is provided to the ``ax`` argument. Part of\n this Axes space will be taken and used to plot a colormap, unless ``cbar``\n is False or a separate Axes is provided to ``cbar_ax``.\n\n Parameters\n ----------\n data : rectangular dataset\n 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame\n is provided, the index/column information will be used to label the\n columns and rows.\n vmin, vmax : floats, optional\n Values to anchor the colormap, otherwise they are inferred from the\n data and other keyword arguments.\n cmap : matplotlib colormap name or object, or list of colors, optional\n The mapping from data values to color space. If not provided, the\n default will depend on whether ``center`` is set.\n center : float, optional\n The value at which to center the colormap when plotting divergent data.\n Using this parameter will change the default ``cmap`` if none is\n specified.\n robust : bool, optional\n If True and ``vmin`` or ``vmax`` are absent, the colormap range is\n computed with robust quantiles instead of the extreme values.\n annot : bool or rectangular dataset, optional\n If True, write the data value in each cell. If an array-like with the\n same shape as ``data``, then use this to annotate the heatmap instead\n of the data. Note that DataFrames will match on position, not index.\n fmt : str, optional\n String formatting code to use when adding annotations.\n annot_kws : dict of key, value mappings, optional\n Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot``\n is True.\n linewidths : float, optional\n Width of the lines that will divide each cell.\n linecolor : color, optional\n Color of the lines that will divide each cell.\n cbar : bool, optional\n Whether to draw a colorbar.\n cbar_kws : dict of key, value mappings, optional\n Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`.\n cbar_ax : matplotlib Axes, optional\n Axes in which to draw the colorbar, otherwise take space from the\n main Axes.\n square : bool, optional\n If True, set the Axes aspect to \"equal\" so each cell will be\n square-shaped.\n xticklabels, yticklabels : \"auto\", bool, list-like, or int, optional\n If True, plot the column names of the dataframe. If False, don't plot\n the column names. If list-like, plot these alternate labels as the\n xticklabels. If an integer, use the column names but plot only every\n n label. If \"auto\", try to densely plot non-overlapping labels.\n mask : bool array or DataFrame, optional\n If passed, data will not be shown in cells where ``mask`` is True.\n Cells with missing values are automatically masked.\n ax : matplotlib Axes, optional\n Axes in which to draw the plot, otherwise use the currently-active\n Axes.\n kwargs : other keyword arguments\n All other keyword arguments are passed to\n :meth:`matplotlib.axes.Axes.pcolormesh`.\n\n Returns\n -------\n ax : matplotlib Axes\n Axes object with the heatmap.\n\n See Also\n --------\n clustermap : Plot a matrix using hierarchical clustering to arrange the\n rows and columns.\n\n Examples\n --------\n\n .. include:: ../docstrings/heatmap.rst\n\n ","endLoc":460,"header":"def heatmap(\n data, *,\n vmin=None, vmax=None, cmap=None, center=None, robust=False,\n annot=None, fmt=\".2g\", annot_kws=None,\n linewidths=0, linecolor=\"white\",\n cbar=True, cbar_kws=None, cbar_ax=None,\n square=False, xticklabels=\"auto\", yticklabels=\"auto\",\n mask=None, ax=None,\n **kwargs\n)","id":1308,"name":"heatmap","nodeType":"Function","startLoc":355,"text":"def heatmap(\n data, *,\n vmin=None, vmax=None, cmap=None, center=None, robust=False,\n annot=None, fmt=\".2g\", annot_kws=None,\n linewidths=0, linecolor=\"white\",\n cbar=True, cbar_kws=None, cbar_ax=None,\n square=False, xticklabels=\"auto\", yticklabels=\"auto\",\n mask=None, ax=None,\n **kwargs\n):\n \"\"\"Plot rectangular data as a color-encoded matrix.\n\n This is an Axes-level function and will draw the heatmap into the\n currently-active Axes if none is provided to the ``ax`` argument. Part of\n this Axes space will be taken and used to plot a colormap, unless ``cbar``\n is False or a separate Axes is provided to ``cbar_ax``.\n\n Parameters\n ----------\n data : rectangular dataset\n 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame\n is provided, the index/column information will be used to label the\n columns and rows.\n vmin, vmax : floats, optional\n Values to anchor the colormap, otherwise they are inferred from the\n data and other keyword arguments.\n cmap : matplotlib colormap name or object, or list of colors, optional\n The mapping from data values to color space. If not provided, the\n default will depend on whether ``center`` is set.\n center : float, optional\n The value at which to center the colormap when plotting divergent data.\n Using this parameter will change the default ``cmap`` if none is\n specified.\n robust : bool, optional\n If True and ``vmin`` or ``vmax`` are absent, the colormap range is\n computed with robust quantiles instead of the extreme values.\n annot : bool or rectangular dataset, optional\n If True, write the data value in each cell. If an array-like with the\n same shape as ``data``, then use this to annotate the heatmap instead\n of the data. Note that DataFrames will match on position, not index.\n fmt : str, optional\n String formatting code to use when adding annotations.\n annot_kws : dict of key, value mappings, optional\n Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot``\n is True.\n linewidths : float, optional\n Width of the lines that will divide each cell.\n linecolor : color, optional\n Color of the lines that will divide each cell.\n cbar : bool, optional\n Whether to draw a colorbar.\n cbar_kws : dict of key, value mappings, optional\n Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`.\n cbar_ax : matplotlib Axes, optional\n Axes in which to draw the colorbar, otherwise take space from the\n main Axes.\n square : bool, optional\n If True, set the Axes aspect to \"equal\" so each cell will be\n square-shaped.\n xticklabels, yticklabels : \"auto\", bool, list-like, or int, optional\n If True, plot the column names of the dataframe. If False, don't plot\n the column names. If list-like, plot these alternate labels as the\n xticklabels. If an integer, use the column names but plot only every\n n label. If \"auto\", try to densely plot non-overlapping labels.\n mask : bool array or DataFrame, optional\n If passed, data will not be shown in cells where ``mask`` is True.\n Cells with missing values are automatically masked.\n ax : matplotlib Axes, optional\n Axes in which to draw the plot, otherwise use the currently-active\n Axes.\n kwargs : other keyword arguments\n All other keyword arguments are passed to\n :meth:`matplotlib.axes.Axes.pcolormesh`.\n\n Returns\n -------\n ax : matplotlib Axes\n Axes object with the heatmap.\n\n See Also\n --------\n clustermap : Plot a matrix using hierarchical clustering to arrange the\n rows and columns.\n\n Examples\n --------\n\n .. include:: ../docstrings/heatmap.rst\n\n \"\"\"\n # Initialize the plotter object\n plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt,\n annot_kws, cbar, cbar_kws, xticklabels,\n yticklabels, mask)\n\n # Add the pcolormesh kwargs here\n kwargs[\"linewidths\"] = linewidths\n kwargs[\"edgecolor\"] = linecolor\n\n # Draw the plot and return the Axes\n if ax is None:\n ax = plt.gca()\n if square:\n ax.set_aspect(\"equal\")\n plotter.plot(ax, cbar_ax, kwargs)\n return ax"},{"col":4,"comment":"Make sure masked cells are not used to calculate extremes","endLoc":123,"header":"def test_mask_limits(self)","id":1309,"name":"test_mask_limits","nodeType":"Function","startLoc":106,"text":"def test_mask_limits(self):\n \"\"\"Make sure masked cells are not used to calculate extremes\"\"\"\n\n kws = self.default_kws.copy()\n\n mask = self.x_norm > 0\n kws['mask'] = mask\n p = mat._HeatMapper(self.x_norm, **kws)\n\n assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()\n assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()\n\n mask = self.x_norm < 0\n kws['mask'] = mask\n p = mat._HeatMapper(self.x_norm, **kws)\n\n assert p.vmin == np.ma.array(self.x_norm, mask=mask).min()\n assert p.vmax == np.ma.array(self.x_norm, mask=mask).max()"},{"col":4,"comment":"null","endLoc":261,"header":"def _parse_param_list(self, content, single_element_is_type=False)","id":1310,"name":"_parse_param_list","nodeType":"Function","startLoc":242,"text":"def _parse_param_list(self, content, single_element_is_type=False):\n r = Reader(content)\n params = []\n while not r.eof():\n header = r.read().strip()\n if ' : ' in header:\n arg_name, arg_type = header.split(' : ')[:2]\n else:\n if single_element_is_type:\n arg_name, arg_type = '', header\n else:\n arg_name, arg_type = header, ''\n\n desc = r.read_to_next_unindented_line()\n desc = dedent_lines(desc)\n desc = strip_blank_lines(desc)\n\n params.append(Parameter(arg_name, arg_type, desc))\n\n return params"},{"col":0,"comment":"Deindent a list of lines maximally","endLoc":574,"header":"def dedent_lines(lines)","id":1311,"name":"dedent_lines","nodeType":"Function","startLoc":572,"text":"def dedent_lines(lines):\n \"\"\"Deindent a list of lines maximally\"\"\"\n return textwrap.dedent(\"\\n\".join(lines)).split(\"\\n\")"},{"col":0,"comment":"Remove leading and trailing blank lines from a list of lines","endLoc":46,"header":"def strip_blank_lines(l)","id":1312,"name":"strip_blank_lines","nodeType":"Function","startLoc":40,"text":"def strip_blank_lines(l):\n \"Remove leading and trailing blank lines from a list of lines\"\n while l and not l[0].strip():\n del l[0]\n while l and not l[-1].strip():\n del l[-1]\n return l"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":121,"id":1313,"name":"marker","nodeType":"Attribute","startLoc":121,"text":"marker"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":122,"id":1314,"name":"pointsize","nodeType":"Attribute","startLoc":122,"text":"pointsize"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":123,"id":1315,"name":"stroke","nodeType":"Attribute","startLoc":123,"text":"stroke"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":124,"id":1316,"name":"color","nodeType":"Attribute","startLoc":124,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":125,"id":1317,"name":"alpha","nodeType":"Attribute","startLoc":125,"text":"alpha"},{"attributeType":"bool | Mappable","col":4,"comment":"null","endLoc":126,"id":1318,"name":"fill","nodeType":"Attribute","startLoc":126,"text":"fill"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":127,"id":1319,"name":"edgecolor","nodeType":"Attribute","startLoc":127,"text":"edgecolor"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":128,"id":1320,"name":"edgealpha","nodeType":"Attribute","startLoc":128,"text":"edgealpha"},{"col":4,"comment":"\n .. index: default\n :refguide: something, else, and more\n\n ","endLoc":369,"header":"def _parse_index(self, section, content)","id":1321,"name":"_parse_index","nodeType":"Function","startLoc":352,"text":"def _parse_index(self, section, content):\n \"\"\"\n .. index: default\n :refguide: something, else, and more\n\n \"\"\"\n def strip_each_in(lst):\n return [s.strip() for s in lst]\n\n out = {}\n section = section.split('::')\n if len(section) > 1:\n out['default'] = strip_each_in(section[1].split(','))[0]\n for line in content:\n line = line.split(':')\n if len(line) > 2:\n out[line[1]] = strip_each_in(line[2].split(','))\n return out"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":129,"id":1322,"name":"edgewidth","nodeType":"Attribute","startLoc":129,"text":"edgewidth"},{"attributeType":"str | (float, ...) | (float, (float, ...) | None) | Mappable","col":4,"comment":"null","endLoc":130,"id":1323,"name":"edgestyle","nodeType":"Attribute","startLoc":130,"text":"edgestyle"},{"className":"Dots","col":0,"comment":"\n A dot mark defined by strokes to better handle overplotting.\n\n See also\n --------\n Dot : A mark suitable for dot plots or less-dense scatterplots.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Dots.rst\n\n ","endLoc":200,"id":1324,"nodeType":"Class","startLoc":160,"text":"@document_properties\n@dataclass\nclass Dots(DotBase):\n \"\"\"\n A dot mark defined by strokes to better handle overplotting.\n\n See also\n --------\n Dot : A mark suitable for dot plots or less-dense scatterplots.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Dots.rst\n\n \"\"\"\n # TODO retype marker as MappableMarker\n marker: MappableString = Mappable(rc=\"scatter.marker\", grouping=False)\n pointsize: MappableFloat = Mappable(4, grouping=False) # TODO rcParam?\n stroke: MappableFloat = Mappable(.75, grouping=False) # TODO rcParam?\n color: MappableColor = Mappable(\"C0\", grouping=False)\n alpha: MappableFloat = Mappable(1, grouping=False) # TODO auto alpha?\n fill: MappableBool = Mappable(True, grouping=False)\n fillcolor: MappableColor = Mappable(depend=\"color\", grouping=False)\n fillalpha: MappableFloat = Mappable(.2, grouping=False)\n\n def _resolve_properties(self, data, scales):\n\n resolved = super()._resolve_properties(data, scales)\n resolved[\"linewidth\"] = resolved.pop(\"stroke\")\n resolved[\"facecolor\"] = resolve_color(self, data, \"fill\", scales)\n resolved[\"edgecolor\"] = resolve_color(self, data, \"\", scales)\n resolved.setdefault(\"edgestyle\", (0, None))\n\n fc = resolved[\"facecolor\"]\n if isinstance(fc, tuple):\n resolved[\"facecolor\"] = fc[0], fc[1], fc[2], fc[3] * resolved[\"fill\"]\n else:\n fc[:, 3] = fc[:, 3] * resolved[\"fill\"] # TODO Is inplace mod a problem?\n resolved[\"facecolor\"] = fc\n\n return resolved"},{"col":4,"comment":"null","endLoc":200,"header":"def _resolve_properties(self, data, scales)","id":1325,"name":"_resolve_properties","nodeType":"Function","startLoc":185,"text":"def _resolve_properties(self, data, scales):\n\n resolved = super()._resolve_properties(data, scales)\n resolved[\"linewidth\"] = resolved.pop(\"stroke\")\n resolved[\"facecolor\"] = resolve_color(self, data, \"fill\", scales)\n resolved[\"edgecolor\"] = resolve_color(self, data, \"\", scales)\n resolved.setdefault(\"edgestyle\", (0, None))\n\n fc = resolved[\"facecolor\"]\n if isinstance(fc, tuple):\n resolved[\"facecolor\"] = fc[0], fc[1], fc[2], fc[3] * resolved[\"fill\"]\n else:\n fc[:, 3] = fc[:, 3] * resolved[\"fill\"] # TODO Is inplace mod a problem?\n resolved[\"facecolor\"] = fc\n\n return resolved"},{"col":4,"comment":"null","endLoc":129,"header":"def test_default_vlims(self)","id":1326,"name":"test_default_vlims","nodeType":"Function","startLoc":125,"text":"def test_default_vlims(self):\n\n p = mat._HeatMapper(self.df_unif, **self.default_kws)\n assert p.vmin == self.x_unif.min()\n assert p.vmax == self.x_unif.max()"},{"col":4,"comment":"\n func_name : Descriptive text\n continued text\n another_func_name : Descriptive text\n func_name1, func_name2, :meth:`func_name`, func_name3\n\n ","endLoc":350,"header":"def _parse_see_also(self, content)","id":1328,"name":"_parse_see_also","nodeType":"Function","startLoc":299,"text":"def _parse_see_also(self, content):\n \"\"\"\n func_name : Descriptive text\n continued text\n another_func_name : Descriptive text\n func_name1, func_name2, :meth:`func_name`, func_name3\n\n \"\"\"\n\n items = []\n\n def parse_item_name(text):\n \"\"\"Match ':role:`name`' or 'name'.\"\"\"\n m = self._func_rgx.match(text)\n if not m:\n raise ParseError(f\"{text} is not a item name\")\n role = m.group('role')\n name = m.group('name') if role else m.group('name2')\n return name, role, m.end()\n\n rest = []\n for line in content:\n if not line.strip():\n continue\n\n line_match = self._line_rgx.match(line)\n description = None\n if line_match:\n description = line_match.group('desc')\n if line_match.group('trailing') and description:\n self._error_location(\n 'Unexpected comma or period after function list at index %d of '\n 'line \"%s\"' % (line_match.end('trailing'), line),\n error=False)\n if not description and line.startswith(' '):\n rest.append(line.strip())\n elif line_match:\n funcs = []\n text = line_match.group('allfuncs')\n while True:\n if not text.strip():\n break\n name, role, match_end = parse_item_name(text)\n funcs.append((name, role))\n text = text[match_end:].strip()\n if text and text[0] == ',':\n text = text[1:].strip()\n rest = list(filter(None, [description]))\n items.append((funcs, rest))\n else:\n raise ParseError(f\"{line} is not a item name\")\n return items"},{"col":4,"comment":"null","endLoc":138,"header":"def test_robust_vlims(self)","id":1329,"name":"test_robust_vlims","nodeType":"Function","startLoc":131,"text":"def test_robust_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"robust\"] = True\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == np.percentile(self.x_unif, 2)\n assert p.vmax == np.percentile(self.x_unif, 98)"},{"col":4,"comment":"Add, replace, or drop variables and return as a new dataset.","endLoc":117,"header":"def join(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec] | None,\n ) -> PlotData","id":1330,"name":"join","nodeType":"Function","startLoc":72,"text":"def join(\n self,\n data: DataSource,\n variables: dict[str, VariableSpec] | None,\n ) -> PlotData:\n \"\"\"Add, replace, or drop variables and return as a new dataset.\"\"\"\n # Inherit the original source of the upsteam data by default\n if data is None:\n data = self.source_data\n\n # TODO allow `data` to be a function (that is called on the source data?)\n\n if not variables:\n variables = self.source_vars\n\n # Passing var=None implies that we do not want that variable in this layer\n disinherit = [k for k, v in variables.items() if v is None]\n\n # Create a new dataset with just the info passed here\n new = PlotData(data, variables)\n\n # -- Update the inherited DataSource with this new information\n\n drop_cols = [k for k in self.frame if k in new.frame or k in disinherit]\n parts = [self.frame.drop(columns=drop_cols), new.frame]\n\n # Because we are combining distinct columns, this is perhaps more\n # naturally thought of as a \"merge\"/\"join\". But using concat because\n # some simple testing suggests that it is marginally faster.\n frame = pd.concat(parts, axis=1, sort=False, copy=False)\n\n names = {k: v for k, v in self.names.items() if k not in disinherit}\n names.update(new.names)\n\n ids = {k: v for k, v in self.ids.items() if k not in disinherit}\n ids.update(new.ids)\n\n new.frame = frame\n new.names = names\n new.ids = ids\n\n # Multiple chained operations should always inherit from the original object\n new.source_data = self.source_data\n new.source_vars = self.source_vars\n\n return new"},{"col":4,"comment":"null","endLoc":148,"header":"def test_custom_sequential_vlims(self)","id":1332,"name":"test_custom_sequential_vlims","nodeType":"Function","startLoc":140,"text":"def test_custom_sequential_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"vmin\"] = 0\n kws[\"vmax\"] = 1\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == 0\n assert p.vmax == 1"},{"attributeType":"null","col":4,"comment":"null","endLoc":377,"id":1333,"name":"null_value","nodeType":"Attribute","startLoc":377,"text":"null_value"},{"col":4,"comment":"null","endLoc":159,"header":"def test_custom_diverging_vlims(self)","id":1334,"name":"test_custom_diverging_vlims","nodeType":"Function","startLoc":150,"text":"def test_custom_diverging_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"vmin\"] = -4\n kws[\"vmax\"] = 5\n kws[\"center\"] = 0\n p = mat._HeatMapper(self.df_norm, **kws)\n\n assert p.vmin == -4\n assert p.vmax == 5"},{"col":4,"comment":"null","endLoc":171,"header":"def test_array_with_nans(self)","id":1335,"name":"test_array_with_nans","nodeType":"Function","startLoc":161,"text":"def test_array_with_nans(self):\n\n x1 = self.rs.rand(10, 10)\n nulls = np.zeros(10) * np.nan\n x2 = np.c_[x1, nulls]\n\n m1 = mat._HeatMapper(x1, **self.default_kws)\n m2 = mat._HeatMapper(x2, **self.default_kws)\n\n assert m1.vmin == m2.vmin\n assert m1.vmax == m2.vmax"},{"col":4,"comment":"null","endLoc":742,"header":"def plot_univariate_histogram(\n self,\n multiple,\n element,\n fill,\n common_norm,\n common_bins,\n shrink,\n kde,\n kde_kws,\n color,\n legend,\n line_kws,\n estimate_kws,\n **plot_kws,\n )","id":1336,"name":"plot_univariate_histogram","nodeType":"Function","startLoc":379,"text":"def plot_univariate_histogram(\n self,\n multiple,\n element,\n fill,\n common_norm,\n common_bins,\n shrink,\n kde,\n kde_kws,\n color,\n legend,\n line_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # -- Default keyword dicts\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n estimate_kws = {} if estimate_kws is None else estimate_kws.copy()\n\n # -- Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\", \"dodge\"], multiple)\n _check_argument(\"element\", [\"bars\", \"step\", \"poly\"], element)\n\n auto_bins_with_weights = (\n \"weights\" in self.variables\n and estimate_kws[\"bins\"] == \"auto\"\n and estimate_kws[\"binwidth\"] is None\n and not estimate_kws[\"discrete\"]\n )\n if auto_bins_with_weights:\n msg = (\n \"`bins` cannot be 'auto' when using weights. \"\n \"Setting `bins=10`, but you will likely want to adjust.\"\n )\n warnings.warn(msg, UserWarning)\n estimate_kws[\"bins\"] = 10\n\n # Simplify downstream code if we are not normalizing\n if estimate_kws[\"stat\"] == \"count\":\n common_norm = False\n\n orient = self.data_variable\n\n # Now initialize the Histogram estimator\n estimator = Hist(**estimate_kws)\n histograms = {}\n\n # Do pre-compute housekeeping related to multiple groups\n all_data = self.comp_data.dropna()\n all_weights = all_data.get(\"weights\", None)\n\n multiple_histograms = set(self.variables) - {\"x\", \"y\"}\n if multiple_histograms:\n if common_bins:\n bin_kws = estimator._define_bin_params(all_data, orient, None)\n else:\n common_norm = False\n\n if common_norm and all_weights is not None:\n whole_weight = all_weights.sum()\n else:\n whole_weight = len(all_data)\n\n # Estimate the smoothed kernel densities, for use later\n if kde:\n # TODO alternatively, clip at min/max bins?\n kde_kws.setdefault(\"cut\", 0)\n kde_kws[\"cumulative\"] = estimate_kws[\"cumulative\"]\n log_scale = self._log_scaled(self.data_variable)\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_bins,\n kde_kws,\n log_scale,\n warn_singular=False,\n )\n\n # First pass through the data to compute the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Prepare the relevant data\n key = tuple(sub_vars.items())\n orient = self.data_variable\n\n if \"weights\" in self.variables:\n sub_data[\"weight\"] = sub_data.pop(\"weights\")\n part_weight = sub_data[\"weight\"].sum()\n else:\n part_weight = len(sub_data)\n\n # Do the histogram computation\n if not (multiple_histograms and common_bins):\n bin_kws = estimator._define_bin_params(sub_data, orient, None)\n res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws))\n heights = res[estimator.stat].to_numpy()\n widths = res[\"space\"].to_numpy()\n edges = res[orient].to_numpy() - widths / 2\n\n # Convert edges back to original units for plotting\n if self._log_scaled(self.data_variable):\n widths = np.power(10, edges + widths) - np.power(10, edges)\n edges = np.power(10, edges)\n\n # Rescale the smoothed curve to match the histogram\n if kde and key in densities:\n density = densities[key]\n if estimator.cumulative:\n hist_norm = heights.max()\n else:\n hist_norm = (heights * widths).sum()\n densities[key] *= hist_norm\n\n # Pack the histogram data and metadata together\n edges = edges + (1 - shrink) / 2 * widths\n widths *= shrink\n index = pd.MultiIndex.from_arrays([\n pd.Index(edges, name=\"edges\"),\n pd.Index(widths, name=\"widths\"),\n ])\n hist = pd.Series(heights, index=index, name=\"heights\")\n\n # Apply scaling to normalize across groups\n if common_norm:\n hist *= part_weight / whole_weight\n\n # Store the finalized histogram data for future plotting\n histograms[key] = hist\n\n # Modify the histogram and density data to resolve multiple groups\n histograms, baselines = self._resolve_multiple(histograms, multiple)\n if kde:\n densities, _ = self._resolve_multiple(\n densities, None if multiple == \"dodge\" else multiple\n )\n\n # Set autoscaling-related meta\n sticky_stat = (0, 1) if multiple == \"fill\" else (0, np.inf)\n if multiple == \"fill\":\n # Filled plots should not have any margins\n bin_vals = histograms.index.to_frame()\n edges = bin_vals[\"edges\"]\n widths = bin_vals[\"widths\"]\n sticky_data = (\n edges.min(),\n edges.max() + widths.loc[edges.idxmax()]\n )\n else:\n sticky_data = []\n\n # --- Handle default visual attributes\n\n # Note: default linewidth is determined after plotting\n\n # Default alpha should depend on other parameters\n if fill:\n # Note: will need to account for other grouping semantics if added\n if \"hue\" in self.variables and multiple == \"layer\":\n default_alpha = .5 if element == \"bars\" else .25\n elif kde:\n default_alpha = .5\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n hist_artists = []\n\n # Go back through the dataset and draw the plots\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n key = tuple(sub_vars.items())\n hist = histograms[key].rename(\"heights\").reset_index()\n bottom = np.asarray(baselines[key])\n\n ax = self._get_axes(sub_vars)\n\n # Define the matplotlib attributes that depend on semantic mapping\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, element, multiple, sub_color, alpha\n )\n\n if element == \"bars\":\n\n # Use matplotlib bar plotting\n\n plot_func = ax.bar if self.data_variable == \"x\" else ax.barh\n artists = plot_func(\n hist[\"edges\"],\n hist[\"heights\"] - bottom,\n hist[\"widths\"],\n bottom,\n align=\"edge\",\n **artist_kws,\n )\n\n for bar in artists:\n if self.data_variable == \"x\":\n bar.sticky_edges.x[:] = sticky_data\n bar.sticky_edges.y[:] = sticky_stat\n else:\n bar.sticky_edges.x[:] = sticky_stat\n bar.sticky_edges.y[:] = sticky_data\n\n hist_artists.extend(artists)\n\n else:\n\n # Use either fill_between or plot to draw hull of histogram\n if element == \"step\":\n\n final = hist.iloc[-1]\n x = np.append(hist[\"edges\"], final[\"edges\"] + final[\"widths\"])\n y = np.append(hist[\"heights\"], final[\"heights\"])\n b = np.append(bottom, bottom[-1])\n\n if self.data_variable == \"x\":\n step = \"post\"\n drawstyle = \"steps-post\"\n else:\n step = \"post\" # fillbetweenx handles mapping internally\n drawstyle = \"steps-pre\"\n\n elif element == \"poly\":\n\n x = hist[\"edges\"] + hist[\"widths\"] / 2\n y = hist[\"heights\"]\n b = bottom\n\n step = None\n drawstyle = None\n\n if self.data_variable == \"x\":\n if fill:\n artist = ax.fill_between(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_data\n artist.sticky_edges.y[:] = sticky_stat\n else:\n if fill:\n artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_stat\n artist.sticky_edges.y[:] = sticky_data\n\n hist_artists.append(artist)\n\n if kde:\n\n # Add in the density curves\n\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n\n if \"x\" in self.variables:\n line_args = support, density\n sticky_x, sticky_y = None, (0, np.inf)\n else:\n line_args = density, support\n sticky_x, sticky_y = (0, np.inf), None\n\n line_kws[\"color\"] = to_rgba(sub_color, 1)\n line, = ax.plot(\n *line_args, **line_kws,\n )\n\n if sticky_x is not None:\n line.sticky_edges.x[:] = sticky_x\n if sticky_y is not None:\n line.sticky_edges.y[:] = sticky_y\n\n if element == \"bars\" and \"linewidth\" not in plot_kws:\n\n # Now we handle linewidth, which depends on the scaling of the plot\n\n # We will base everything on the minimum bin width\n hist_metadata = pd.concat([\n # Use .items for generality over dict or df\n h.index.to_frame() for _, h in histograms.items()\n ]).reset_index(drop=True)\n thin_bar_idx = hist_metadata[\"widths\"].idxmin()\n binwidth = hist_metadata.loc[thin_bar_idx, \"widths\"]\n left_edge = hist_metadata.loc[thin_bar_idx, \"edges\"]\n\n # Set initial value\n default_linewidth = math.inf\n\n # Loop through subsets based only on facet variables\n for sub_vars, _ in self.iter_data():\n\n ax = self._get_axes(sub_vars)\n\n # Needed in some cases to get valid transforms.\n # Innocuous in other cases?\n ax.autoscale_view()\n\n # Convert binwidth from data coordinates to pixels\n pts_x, pts_y = 72 / ax.figure.dpi * abs(\n ax.transData.transform([left_edge + binwidth] * 2)\n - ax.transData.transform([left_edge] * 2)\n )\n if self.data_variable == \"x\":\n binwidth_points = pts_x\n else:\n binwidth_points = pts_y\n\n # The relative size of the lines depends on the appearance\n # This is a provisional value and may need more tweaking\n default_linewidth = min(.1 * binwidth_points, default_linewidth)\n\n # Set the attributes\n for bar in hist_artists:\n\n # Don't let the lines get too thick\n max_linewidth = bar.get_linewidth()\n if not fill:\n max_linewidth *= 1.5\n\n linewidth = min(default_linewidth, max_linewidth)\n\n # If not filling, don't let lines disappear\n if not fill:\n min_linewidth = .5\n linewidth = max(linewidth, min_linewidth)\n\n bar.set_linewidth(linewidth)\n\n # --- Finalize the plot ----\n\n # Axis labels\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = estimator.stat.capitalize()\n if self.data_variable == \"y\":\n default_x = estimator.stat.capitalize()\n self._add_axis_labels(ax, default_x, default_y)\n\n # Legend for semantic variables\n if \"hue\" in self.variables and legend:\n\n if fill or element == \"bars\":\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, element, multiple, alpha, plot_kws, {},\n )"},{"className":"LineStyle","col":0,"comment":"Dash pattern for line-type marks.","endLoc":513,"id":1337,"nodeType":"Class","startLoc":419,"text":"class LineStyle(ObjectProperty):\n \"\"\"Dash pattern for line-type marks.\"\"\"\n null_value = \"\"\n\n def standardize(self, val: str | DashPattern) -> DashPatternWithOffset:\n return self._get_dash_pattern(val)\n\n def _default_values(self, n: int) -> list[DashPatternWithOffset]:\n \"\"\"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n \"\"\"\n # Start with dash specs that are well distinguishable\n dashes: list[str | DashPattern] = [\n \"-\", (4, 1.5), (1, 1), (3, 1.25, 1.5, 1.25), (5, 1, 1, 1),\n ]\n\n # Now programmatically build as many as we need\n p = 3\n while len(dashes) < n:\n\n # Take combinations of long and short dashes\n a = itertools.combinations_with_replacement([3, 1.25], p)\n b = itertools.combinations_with_replacement([4, 1], p)\n\n # Interleave the combinations, reversing one of the streams\n segment_list = itertools.chain(*zip(list(a)[1:-1][::-1], list(b)[1:-1]))\n\n # Now insert the gaps\n for segments in segment_list:\n gap = min(segments)\n spec = tuple(itertools.chain(*((seg, gap) for seg in segments)))\n dashes.append(spec)\n\n p += 1\n\n return [self._get_dash_pattern(x) for x in dashes]\n\n @staticmethod\n def _get_dash_pattern(style: str | DashPattern) -> DashPatternWithOffset:\n \"\"\"Convert linestyle arguments to dash pattern with offset.\"\"\"\n # Copied and modified from Matplotlib 3.4\n # go from short hand -> full strings\n ls_mapper = {\"-\": \"solid\", \"--\": \"dashed\", \"-.\": \"dashdot\", \":\": \"dotted\"}\n if isinstance(style, str):\n style = ls_mapper.get(style, style)\n # un-dashed styles\n if style in [\"solid\", \"none\", \"None\"]:\n offset = 0\n dashes = None\n # dashed styles\n elif style in [\"dashed\", \"dashdot\", \"dotted\"]:\n offset = 0\n dashes = tuple(mpl.rcParams[f\"lines.{style}_pattern\"])\n else:\n options = [*ls_mapper.values(), *ls_mapper.keys()]\n msg = f\"Linestyle string must be one of {options}, not {repr(style)}.\"\n raise ValueError(msg)\n\n elif isinstance(style, tuple):\n if len(style) > 1 and isinstance(style[1], tuple):\n offset, dashes = style\n elif len(style) > 1 and style[1] is None:\n offset, dashes = style\n else:\n offset = 0\n dashes = style\n else:\n val_type = type(style).__name__\n msg = f\"Linestyle must be str or tuple, not {val_type}.\"\n raise TypeError(msg)\n\n # Normalize offset to be positive and shorter than the dash cycle\n if dashes is not None:\n try:\n dsum = sum(dashes)\n except TypeError as err:\n msg = f\"Invalid dash pattern: {dashes}\"\n raise TypeError(msg) from err\n if dsum:\n offset %= dsum\n\n return offset, dashes"},{"col":4,"comment":"null","endLoc":424,"header":"def standardize(self, val: str | DashPattern) -> DashPatternWithOffset","id":1338,"name":"standardize","nodeType":"Function","startLoc":423,"text":"def standardize(self, val: str | DashPattern) -> DashPatternWithOffset:\n return self._get_dash_pattern(val)"},{"col":4,"comment":"null","endLoc":185,"header":"def test_mask(self)","id":1339,"name":"test_mask","nodeType":"Function","startLoc":173,"text":"def test_mask(self):\n\n df = pd.DataFrame(data={'a': [1, 1, 1],\n 'b': [2, np.nan, 2],\n 'c': [3, 3, np.nan]})\n\n kws = self.default_kws.copy()\n kws[\"mask\"] = np.isnan(df.values)\n\n m = mat._HeatMapper(df, **kws)\n\n npt.assert_array_equal(np.isnan(m.plot_data.data),\n m.plot_data.mask)"},{"col":4,"comment":"null","endLoc":192,"header":"def test_custom_cmap(self)","id":1340,"name":"test_custom_cmap","nodeType":"Function","startLoc":187,"text":"def test_custom_cmap(self):\n\n kws = self.default_kws.copy()\n kws[\"cmap\"] = \"BuGn\"\n p = mat._HeatMapper(self.df_unif, **kws)\n assert p.cmap == mpl.cm.BuGn"},{"col":4,"comment":"null","endLoc":202,"header":"def test_centered_vlims(self)","id":1341,"name":"test_centered_vlims","nodeType":"Function","startLoc":194,"text":"def test_centered_vlims(self):\n\n kws = self.default_kws.copy()\n kws[\"center\"] = .5\n\n p = mat._HeatMapper(self.df_unif, **kws)\n\n assert p.vmin == self.df_unif.values.min()\n assert p.vmax == self.df_unif.values.max()"},{"col":4,"comment":"null","endLoc":54,"header":"def _standardize_coordinate_parameters(self, data, orient)","id":1343,"name":"_standardize_coordinate_parameters","nodeType":"Function","startLoc":53,"text":"def _standardize_coordinate_parameters(self, data, orient):\n return data"},{"col":4,"comment":"Convert linestyle arguments to dash pattern with offset.","endLoc":513,"header":"@staticmethod\n def _get_dash_pattern(style: str | DashPattern) -> DashPatternWithOffset","id":1344,"name":"_get_dash_pattern","nodeType":"Function","startLoc":469,"text":"@staticmethod\n def _get_dash_pattern(style: str | DashPattern) -> DashPatternWithOffset:\n \"\"\"Convert linestyle arguments to dash pattern with offset.\"\"\"\n # Copied and modified from Matplotlib 3.4\n # go from short hand -> full strings\n ls_mapper = {\"-\": \"solid\", \"--\": \"dashed\", \"-.\": \"dashdot\", \":\": \"dotted\"}\n if isinstance(style, str):\n style = ls_mapper.get(style, style)\n # un-dashed styles\n if style in [\"solid\", \"none\", \"None\"]:\n offset = 0\n dashes = None\n # dashed styles\n elif style in [\"dashed\", \"dashdot\", \"dotted\"]:\n offset = 0\n dashes = tuple(mpl.rcParams[f\"lines.{style}_pattern\"])\n else:\n options = [*ls_mapper.values(), *ls_mapper.keys()]\n msg = f\"Linestyle string must be one of {options}, not {repr(style)}.\"\n raise ValueError(msg)\n\n elif isinstance(style, tuple):\n if len(style) > 1 and isinstance(style[1], tuple):\n offset, dashes = style\n elif len(style) > 1 and style[1] is None:\n offset, dashes = style\n else:\n offset = 0\n dashes = style\n else:\n val_type = type(style).__name__\n msg = f\"Linestyle must be str or tuple, not {val_type}.\"\n raise TypeError(msg)\n\n # Normalize offset to be positive and shorter than the dash cycle\n if dashes is not None:\n try:\n dsum = sum(dashes)\n except TypeError as err:\n msg = f\"Invalid dash pattern: {dashes}\"\n raise TypeError(msg) from err\n if dsum:\n offset %= dsum\n\n return offset, dashes"},{"col":4,"comment":"null","endLoc":211,"header":"def test_default_colors(self)","id":1345,"name":"test_default_colors","nodeType":"Function","startLoc":204,"text":"def test_default_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n cvals = np.linspace(0, 1, 9)\n npt.assert_array_almost_equal(fc, cmap(cvals), 2)"},{"col":4,"comment":"null","endLoc":69,"header":"def _get_verts(self, data, orient)","id":1346,"name":"_get_verts","nodeType":"Function","startLoc":59,"text":"def _get_verts(self, data, orient):\n\n dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n data = data.sort_values(orient, kind=\"mergesort\")\n verts = np.concatenate([\n data[[orient, f\"{dv}min\"]].to_numpy(),\n data[[orient, f\"{dv}max\"]].to_numpy()[::-1],\n ])\n if orient == \"y\":\n verts = verts[:, ::-1]\n return verts"},{"col":4,"comment":"null","endLoc":1115,"header":"def plot_matrix(self, colorbar_kws, xind, yind, **kws)","id":1347,"name":"plot_matrix","nodeType":"Function","startLoc":1060,"text":"def plot_matrix(self, colorbar_kws, xind, yind, **kws):\n self.data2d = self.data2d.iloc[yind, xind]\n self.mask = self.mask.iloc[yind, xind]\n\n # Try to reorganize specified tick labels, if provided\n xtl = kws.pop(\"xticklabels\", \"auto\")\n try:\n xtl = np.asarray(xtl)[xind]\n except (TypeError, IndexError):\n pass\n ytl = kws.pop(\"yticklabels\", \"auto\")\n try:\n ytl = np.asarray(ytl)[yind]\n except (TypeError, IndexError):\n pass\n\n # Reorganize the annotations to match the heatmap\n annot = kws.pop(\"annot\", None)\n if annot is None or annot is False:\n pass\n else:\n if isinstance(annot, bool):\n annot_data = self.data2d\n else:\n annot_data = np.asarray(annot)\n if annot_data.shape != self.data2d.shape:\n err = \"`data` and `annot` must have same shape.\"\n raise ValueError(err)\n annot_data = annot_data[yind][:, xind]\n annot = annot_data\n\n # Setting ax_cbar=None in clustermap call implies no colorbar\n kws.setdefault(\"cbar\", self.ax_cbar is not None)\n heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar,\n cbar_kws=colorbar_kws, mask=self.mask,\n xticklabels=xtl, yticklabels=ytl, annot=annot, **kws)\n\n ytl = self.ax_heatmap.get_yticklabels()\n ytl_rot = None if not ytl else ytl[0].get_rotation()\n self.ax_heatmap.yaxis.set_ticks_position('right')\n self.ax_heatmap.yaxis.set_label_position('right')\n if ytl_rot is not None:\n ytl = self.ax_heatmap.get_yticklabels()\n plt.setp(ytl, rotation=ytl_rot)\n\n tight_params = dict(h_pad=.02, w_pad=.02)\n if self.ax_cbar is None:\n self._figure.tight_layout(**tight_params)\n else:\n # Turn the colorbar axes off for tight layout so that its\n # ticks don't interfere with the rest of the plot layout.\n # Then move it.\n self.ax_cbar.set_axis_off()\n self._figure.tight_layout(**tight_params)\n self.ax_cbar.set_axis_on()\n self.ax_cbar.set_position(self.cbar_pos)"},{"col":4,"comment":"null","endLoc":219,"header":"def test_custom_vlim_colors(self)","id":1348,"name":"test_custom_vlim_colors","nodeType":"Function","startLoc":213,"text":"def test_custom_vlim_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], vmin=0, cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n npt.assert_array_almost_equal(fc, cmap(vals), 2)"},{"col":4,"comment":"null","endLoc":227,"header":"def test_custom_center_colors(self)","id":1349,"name":"test_custom_center_colors","nodeType":"Function","startLoc":221,"text":"def test_custom_center_colors(self):\n\n vals = np.linspace(.2, 1, 9)\n cmap = mpl.cm.binary\n ax = mat.heatmap([vals], center=.5, cmap=cmap)\n fc = ax.collections[0].get_facecolors()\n npt.assert_array_almost_equal(fc, cmap(vals), 2)"},{"col":4,"comment":"null","endLoc":266,"header":"def test_cmap_with_properties(self)","id":1350,"name":"test_cmap_with_properties","nodeType":"Function","startLoc":229,"text":"def test_cmap_with_properties(self):\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_bad(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(\n cmap(np.ma.masked_invalid([np.nan])),\n hm.cmap(np.ma.masked_invalid([np.nan])))\n\n kws[\"center\"] = 0.5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(\n cmap(np.ma.masked_invalid([np.nan])),\n hm.cmap(np.ma.masked_invalid([np.nan])))\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_under(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws[\"center\"] = .5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws = self.default_kws.copy()\n cmap = copy.copy(get_colormap(\"BrBG\"))\n cmap.set_over(\"red\")\n kws[\"cmap\"] = cmap\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(-np.inf), hm.cmap(-np.inf))\n\n kws[\"center\"] = .5\n hm = mat._HeatMapper(self.df_unif, **kws)\n npt.assert_array_equal(cmap(np.inf), hm.cmap(np.inf))"},{"col":4,"comment":"Draw the data.","endLoc":408,"header":"def scatterplot(self, ax, kws)","id":1351,"name":"scatterplot","nodeType":"Function","startLoc":376,"text":"def scatterplot(self, ax, kws):\n \"\"\"Draw the data.\"\"\"\n # Treat the line-based markers specially, explicitly setting larger\n # linewidth than is provided by the seaborn style defaults.\n # This would ideally be handled better in matplotlib (i.e., distinguish\n # between edgewidth for solid glyphs and linewidth for line glyphs\n # but this should do for now.\n line_markers = [\"1\", \"2\", \"3\", \"4\", \"+\", \"x\", \"|\", \"_\"]\n if self.x_estimator is None:\n if \"marker\" in kws and kws[\"marker\"] in line_markers:\n lw = mpl.rcParams[\"lines.linewidth\"]\n else:\n lw = mpl.rcParams[\"lines.markeredgewidth\"]\n kws.setdefault(\"linewidths\", lw)\n\n if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4:\n kws.setdefault(\"alpha\", .8)\n\n x, y = self.scatter_data\n ax.scatter(x, y, **kws)\n else:\n # TODO abstraction\n ci_kws = {\"color\": kws[\"color\"]}\n if \"alpha\" in kws:\n ci_kws[\"alpha\"] = kws[\"alpha\"]\n ci_kws[\"linewidth\"] = mpl.rcParams[\"lines.linewidth\"] * 1.75\n kws.setdefault(\"s\", 50)\n\n xs, ys, cis = self.estimate_data\n if [ci for ci in cis if ci is not None]:\n for x, ci in zip(xs, cis):\n ax.plot([x, x], ci, **ci_kws)\n ax.scatter(xs, ys, **kws)"},{"attributeType":"str | Mappable","col":4,"comment":"null","endLoc":176,"id":1352,"name":"marker","nodeType":"Attribute","startLoc":176,"text":"marker"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":177,"id":1353,"name":"pointsize","nodeType":"Attribute","startLoc":177,"text":"pointsize"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":178,"id":1354,"name":"stroke","nodeType":"Attribute","startLoc":178,"text":"stroke"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":179,"id":1355,"name":"color","nodeType":"Attribute","startLoc":179,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":180,"id":1356,"name":"alpha","nodeType":"Attribute","startLoc":180,"text":"alpha"},{"attributeType":"bool | Mappable","col":4,"comment":"null","endLoc":181,"id":1357,"name":"fill","nodeType":"Attribute","startLoc":181,"text":"fill"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":182,"id":1358,"name":"fillcolor","nodeType":"Attribute","startLoc":182,"text":"fillcolor"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":183,"id":1359,"name":"fillalpha","nodeType":"Attribute","startLoc":183,"text":"fillalpha"},{"attributeType":"null","col":16,"comment":"null","endLoc":4,"id":1360,"name":"np","nodeType":"Attribute","startLoc":4,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":1361,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"col":0,"comment":"","endLoc":1,"header":"dot.py#","id":1362,"name":"","nodeType":"Function","startLoc":1,"text":"if TYPE_CHECKING:\n from typing import Any\n from matplotlib.artist import Artist\n from seaborn._core.scales import Scale"},{"id":1363,"name":"error_bars.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _errorbar_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import pandas as pd\\n\",\n \"import seaborn as sns\\n\",\n \"import matplotlib as mpl\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"sns.set_theme(style=\\\"darkgrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"np.random.seed(sum(map(ord, \\\"errorbars\\\")))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Statistical estimation and error bars\\n\",\n \"=====================================\\n\",\n \"\\n\",\n \"Data visualization sometimes involves a step of aggregation or estimation, where multiple data points are reduced to a summary statistic such as the mean or median. When showing a summary statistic, it is usually appropriate to add *error bars*, which provide a visual cue about how well the summary represents the underlying data points.\\n\",\n \"\\n\",\n \"Several seaborn functions will automatically calculate both summary statistics and the error bars when given a full dataset. This chapter explains how you can control what the error bars show and why you might choose each of the options that seaborn affords.\\n\",\n \"\\n\",\n \"The error bars around an estimate of central tendency can show one of two general things: either the range of uncertainty about the estimate or the spread of the underlying data around it. These measures are related: given the same sample size, estimates will be more uncertain when data has a broader spread. But uncertainty will decrease as sample sizes grow, whereas spread will not.\\n\",\n \"\\n\",\n \"In seaborn, there are two approaches for constructing each kind of error bar. One approach is parametric, using a formula that relies on assumptions about the shape of the distribution. The other approach is nonparametric, using only the data that you provide.\\n\",\n \"\\n\",\n \"Your choice is made with the `errorbar` parameter, which exists for each function that does estimation as part of plotting. This parameter accepts the name of the method to use and, optionally, a parameter that controls the size of the interval. The choices can be defined in a 2D taxonomy that depends on what is shown and how it is constructed:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import io\\n\",\n \"from IPython.display import SVG\\n\",\n \"f = mpl.figure.Figure(figsize=(8, 5))\\n\",\n \"axs = f.subplots(2, 2, sharex=True, sharey=True,)\\n\",\n \"\\n\",\n \"plt.setp(axs, xlim=(-1, 1), ylim=(-1, 1), xticks=[], yticks=[])\\n\",\n \"for ax, color in zip(axs.flat, [\\\"C0\\\", \\\"C2\\\", \\\"C3\\\", \\\"C1\\\"]):\\n\",\n \" ax.set_facecolor(mpl.colors.to_rgba(color, .25))\\n\",\n \"\\n\",\n \"kws = dict(x=0, y=.2, ha=\\\"center\\\", va=\\\"center\\\", size=18)\\n\",\n \"axs[0, 0].text(s=\\\"Standard deviation\\\", **kws)\\n\",\n \"axs[0, 1].text(s=\\\"Standard error\\\", **kws)\\n\",\n \"axs[1, 0].text(s=\\\"Percentile interval\\\", **kws)\\n\",\n \"axs[1, 1].text(s=\\\"Confidence interval\\\", **kws)\\n\",\n \"\\n\",\n \"kws = dict(x=0, y=-.2, ha=\\\"center\\\", va=\\\"center\\\", size=18, font=\\\"Courier New\\\")\\n\",\n \"axs[0, 0].text(s='errorbar=(\\\"sd\\\", scale)', **kws)\\n\",\n \"axs[0, 1].text(s='errorbar=(\\\"se\\\", scale)', **kws)\\n\",\n \"axs[1, 0].text(s='errorbar=(\\\"pi\\\", width)', **kws)\\n\",\n \"axs[1, 1].text(s='errorbar=(\\\"ci\\\", width)', **kws)\\n\",\n \"\\n\",\n \"kws = dict(size=18)\\n\",\n \"axs[0, 0].set_title(\\\"Spread\\\", **kws)\\n\",\n \"axs[0, 1].set_title(\\\"Uncertainty\\\", **kws)\\n\",\n \"axs[0, 0].set_ylabel(\\\"Parametric\\\", **kws)\\n\",\n \"axs[1, 0].set_ylabel(\\\"Nonparametric\\\", **kws)\\n\",\n \"\\n\",\n \"f.tight_layout()\\n\",\n \"f.subplots_adjust(hspace=.05, wspace=.05 * (4 / 6))\\n\",\n \"f.savefig(svg:=io.StringIO(), format=\\\"svg\\\")\\n\",\n \"SVG(svg.getvalue())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You will note that the size parameter is defined differently for the parametric and nonparametric approaches. For parametric error bars, it is a scalar factor that is multiplied by the statistic defining the error (standard error or standard deviation). For nonparametric error bars, it is a percentile width. This is explained further for each specific approach below.\\n\",\n \"\\n\",\n \"\\n\",\n \".. note::\\n\",\n \" The `errorbar` API described here was introduced in seaborn v0.12. In prior versions, the only options were to show a bootstrap confidence interval or a standard deviation, with the choice controlled by the `ci` parameter (i.e., `ci=` or `ci=\\\"sd\\\"`).\\n\",\n \"\\n\",\n \"To compare the different parameterizations, we'll use the following helper function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"def plot_errorbars(arg, **kws):\\n\",\n \" np.random.seed(sum(map(ord, \\\"error_bars\\\")))\\n\",\n \" x = np.random.normal(0, 1, 100)\\n\",\n \" f, axs = plt.subplots(2, figsize=(7, 2), sharex=True, layout=\\\"tight\\\")\\n\",\n \" sns.pointplot(x=x, errorbar=arg, **kws, capsize=.3, ax=axs[0])\\n\",\n \" sns.stripplot(x=x, jitter=.3, ax=axs[1])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Measures of data spread\\n\",\n \"-----------------------\\n\",\n \"\\n\",\n \"Error bars that represent data spread present a compact display of the distribution, using three numbers where :func:`boxplot` would use 5 or more and :func:`violinplot` would use a complicated algorithm.\\n\",\n \"\\n\",\n \"Standard deviation error bars\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Standard deviation error bars are the simplest to explain, because the standard deviation is a familiar statistic. It is the average distance from each data point to the sample mean. By default, `errorbar=\\\"sd\\\"` will draw error bars at +/- 1 sd around the estimate, but the range can be increased by passing a scaling size parameter. Note that, assuming normally-distributed data, ~68% of the data will lie within one standard deviation, ~95% will lie within two, and ~99.7% will lie within three:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars(\\\"sd\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Percentile interval error bars\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Percentile intervals also represent the range where some amount of the data fall, but they do so by \\n\",\n \"computing those percentiles directly from your sample. By default, `errorbar=\\\"pi\\\"` will show a 95% interval, ranging from the 2.5 to the 97.5 percentiles. You can choose a different range by passing a size parameter, e.g., to show the inter-quartile range:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars((\\\"pi\\\", 50))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The standard deviation error bars will always be symmetrical around the estimate. This can be a problem when the data are skewed, especially if there are natural bounds (e.g., if the data represent a quantity that can only be positive). In some cases, standard deviation error bars may extend to \\\"impossible\\\" values. The nonparametric approach does not have this problem, because it can account for asymmetrical spread and will never extend beyond the range of the data.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Measures of estimate uncertainty\\n\",\n \"--------------------------------\\n\",\n \"\\n\",\n \"If your data are a random sample from a larger population, then the mean (or other estimate) will be an imperfect measure of the true population average. Error bars that show estimate uncertainty try to represent the range of likely values for the true parameter.\\n\",\n \"\\n\",\n \"Standard error bars\\n\",\n \"~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The standard error statistic is related to the standard deviation: in fact it is just the standard deviation divided by the square root of the sample size. The default, with `errorbar=\\\"se\\\"`, draws an interval +/-1 standard error from the mean:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars(\\\"se\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Confidence interval error bars\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The nonparametric approach to representing uncertainty uses *bootstrapping*: a procedure where the dataset is randomly resampled with replacement a number of times, and the estimate is recalculated from each resample. This procedure creates a distribution of statistics approximating the distribution of values that you could have gotten for your estimate if you had a different sample.\\n\",\n \"\\n\",\n \"The confidence interval is constructed by taking a percentile interval of the *bootstrap distribution*. By default `errorbar=\\\"ci\\\"` draws a 95% confidence interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars(\\\"ci\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The seaborn terminology is somewhat specific, because a confidence interval in statistics can be parametric or nonparametric. To draw a parametric confidence interval, you scale the standard error, using a formula similar to the one mentioned above. For example, an approximate 95% confidence interval can be constructed by taking the mean +/- two standard errors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars((\\\"se\\\", 2))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The nonparametric bootstrap has advantages similar to those of the percentile interval: it will naturally adapt to skewed and bounded data in a way that a standard error interval cannot. It is also more general. While the standard error formula is specific to the mean, error bars can be computed using the bootstrap for any estimator:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars(\\\"ci\\\", estimator=\\\"median\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Bootstrapping involves randomness, and the error bars will appear slightly different each time you run the code that creates them. A few parameters control this. One sets the number of iterations (`n_boot`): with more iterations, the resulting intervals will be more stable. The other sets the `seed` for the random number generator, which will ensure identical results:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars(\\\"ci\\\", n_boot=5000, seed=10)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Because of its iterative process, bootstrap intervals can be expensive to compute, especially for large datasets. But because uncertainty decreases with sample size, it may be more informative in that case to use an error bar that represents data spread.\\n\",\n \"\\n\",\n \"Custom error bars\\n\",\n \"~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"If these recipes are not sufficient, it is also possible to pass a generic function to the `errorbar` parameter. This function should take a vector and produce a pair of values representing the minimum and maximum points of the interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plot_errorbars(lambda x: (x.min(), x.max()))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"(In practice, you could show the full range of the data with `errorbar=(\\\"pi\\\", 100)` rather than the custom function shown above).\\n\",\n \"\\n\",\n \"Note that seaborn functions cannot currently draw error bars from values that have been calculated externally, although matplotlib functions can be used to add such error bars to seaborn plots.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Error bars on regression fits\\n\",\n \"-----------------------------\\n\",\n \"\\n\",\n \"The preceding discussion has focused on error bars shown around parameter estimates for aggregate data. Error bars also arise in seaborn when estimating regression models to visualize relationships. Here, the error bars will be represented by a \\\"band\\\" around the regression line:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"x = np.random.normal(0, 1, 50)\\n\",\n \"y = x * 2 + np.random.normal(0, 2, size=x.size)\\n\",\n \"sns.regplot(x=x, y=y)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Currently, the error bars on a regression estimate are less flexible, only showing a confidence interval with a size set through `ci=`. This may change in the future.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Are error bars enough?\\n\",\n \"----------------------\\n\",\n \"\\n\",\n \"You should always ask yourself whether it's best to use a plot that displays only a summary statistic and error bar. In many cases, it isn't.\\n\",\n \"\\n\",\n \"If you are interested in questions about summaries (such as whether the mean value differs between groups or increases over time), aggregation reduces the complexity of the plot and makes those inferences easier. But in doing so, it obscures valuable information about the underlying data points, such as the shape of the distributions and the presence of outliers.\\n\",\n \"\\n\",\n \"When analyzing your own data, don't be satisfied with summary statistics. Always look at the underlying distributions too. Sometimes, it can be helpful to combine both perspectives into the same figure. Many seaborn functions can help with this task, especially those discussed in the :doc:`categorical tutorial `.\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"fileName":"paired_pointplots.py","filePath":"examples","id":1364,"nodeType":"File","text":"\"\"\"\nPaired categorical plots\n========================\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the example Titanic dataset\ntitanic = sns.load_dataset(\"titanic\")\n\n# Set up a grid to plot survival probability against several variables\ng = sns.PairGrid(titanic, y_vars=\"survived\",\n x_vars=[\"class\", \"sex\", \"who\", \"alone\"],\n height=5, aspect=.5)\n\n# Draw a seaborn pointplot onto each Axes\ng.map(sns.pointplot, scale=1.3, errwidth=4, color=\"xkcd:plum\")\ng.set(ylim=(0, 1))\nsns.despine(fig=g.fig, left=True)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":6,"id":1365,"name":"sns","nodeType":"Attribute","startLoc":6,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":1366,"name":"titanic","nodeType":"Attribute","startLoc":10,"text":"titanic"},{"col":4,"comment":"null","endLoc":1143,"header":"def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster,\n row_linkage, col_linkage, tree_kws, **kws)","id":1367,"name":"plot","nodeType":"Function","startLoc":1117,"text":"def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster,\n row_linkage, col_linkage, tree_kws, **kws):\n\n # heatmap square=True sets the aspect ratio on the axes, but that is\n # not compatible with the multi-axes layout of clustergrid\n if kws.get(\"square\", False):\n msg = \"``square=True`` ignored in clustermap\"\n warnings.warn(msg)\n kws.pop(\"square\")\n\n colorbar_kws = {} if colorbar_kws is None else colorbar_kws\n\n self.plot_dendrograms(row_cluster, col_cluster, metric, method,\n row_linkage=row_linkage, col_linkage=col_linkage,\n tree_kws=tree_kws)\n try:\n xind = self.dendrogram_col.reordered_ind\n except AttributeError:\n xind = np.arange(self.data2d.shape[1])\n try:\n yind = self.dendrogram_row.reordered_ind\n except AttributeError:\n yind = np.arange(self.data2d.shape[0])\n\n self.plot_colors(xind, yind, **kws)\n self.plot_matrix(colorbar_kws, xind, yind, **kws)\n return self"},{"attributeType":"PairGrid","col":0,"comment":"null","endLoc":13,"id":1368,"name":"g","nodeType":"Attribute","startLoc":13,"text":"g"},{"col":0,"comment":"","endLoc":5,"header":"paired_pointplots.py#","id":1369,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPaired categorical plots\n========================\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ntitanic = sns.load_dataset(\"titanic\")\n\ng = sns.PairGrid(titanic, y_vars=\"survived\",\n x_vars=[\"class\", \"sex\", \"who\", \"alone\"],\n height=5, aspect=.5)\n\ng.map(sns.pointplot, scale=1.3, errwidth=4, color=\"xkcd:plum\")\n\ng.set(ylim=(0, 1))\n\nsns.despine(fig=g.fig, left=True)"},{"col":4,"comment":"Plot with the same function in every subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n ","endLoc":1375,"header":"def map(self, func, **kwargs)","id":1370,"name":"map","nodeType":"Function","startLoc":1360,"text":"def map(self, func, **kwargs):\n \"\"\"Plot with the same function in every subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n row_indices, col_indices = np.indices(self.axes.shape)\n indices = zip(row_indices.flat, col_indices.flat)\n self._map_bivariate(func, indices, **kwargs)\n\n return self"},{"col":4,"comment":"Handle the specification for a given style attribute.","endLoc":607,"header":"def _map_attributes(self, arg, levels, defaults, attr)","id":1371,"name":"_map_attributes","nodeType":"Function","startLoc":588,"text":"def _map_attributes(self, arg, levels, defaults, attr):\n \"\"\"Handle the specification for a given style attribute.\"\"\"\n if arg is True:\n lookup_table = dict(zip(levels, defaults))\n elif isinstance(arg, dict):\n missing = set(levels) - set(arg)\n if missing:\n err = f\"These `{attr}` levels are missing values: {missing}\"\n raise ValueError(err)\n lookup_table = arg\n elif isinstance(arg, Sequence):\n arg = self._check_list_length(levels, arg, attr)\n lookup_table = dict(zip(levels, arg))\n elif arg:\n err = f\"This `{attr}` argument was not understood: {arg}\"\n raise ValueError(err)\n else:\n lookup_table = {}\n\n return lookup_table"},{"col":0,"comment":"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n ","endLoc":1686,"header":"def unique_dashes(n)","id":1372,"name":"unique_dashes","nodeType":"Function","startLoc":1638,"text":"def unique_dashes(n):\n \"\"\"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n \"\"\"\n # Start with dash specs that are well distinguishable\n dashes = [\n \"\",\n (4, 1.5),\n (1, 1),\n (3, 1.25, 1.5, 1.25),\n (5, 1, 1, 1),\n ]\n\n # Now programmatically build as many as we need\n p = 3\n while len(dashes) < n:\n\n # Take combinations of long and short dashes\n a = itertools.combinations_with_replacement([3, 1.25], p)\n b = itertools.combinations_with_replacement([4, 1], p)\n\n # Interleave the combinations, reversing one of the streams\n segment_list = itertools.chain(*zip(\n list(a)[1:-1][::-1],\n list(b)[1:-1]\n ))\n\n # Now insert the gaps\n for segments in segment_list:\n gap = min(segments)\n spec = tuple(itertools.chain(*((seg, gap) for seg in segments)))\n dashes.append(spec)\n\n p += 1\n\n return dashes[:n]"},{"col":4,"comment":"Draw the model.","endLoc":426,"header":"def lineplot(self, ax, kws)","id":1373,"name":"lineplot","nodeType":"Function","startLoc":410,"text":"def lineplot(self, ax, kws):\n \"\"\"Draw the model.\"\"\"\n # Fit the regression model\n grid, yhat, err_bands = self.fit_regression(ax)\n edges = grid[0], grid[-1]\n\n # Get set default aesthetics\n fill_color = kws[\"color\"]\n lw = kws.pop(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.5)\n kws.setdefault(\"linewidth\", lw)\n\n # Draw the regression line and confidence interval\n line, = ax.plot(grid, yhat, **kws)\n if not self.truncate:\n line.sticky_edges.x[:] = edges # Prevent mpl from adding margin\n if err_bands is not None:\n ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15)"},{"col":4,"comment":"null","endLoc":57,"header":"def _postprocess_artist(self, artist, ax, orient)","id":1374,"name":"_postprocess_artist","nodeType":"Function","startLoc":56,"text":"def _postprocess_artist(self, artist, ax, orient):\n pass"},{"attributeType":"bool","col":8,"comment":"null","endLoc":94,"id":1375,"name":"robust","nodeType":"Attribute","startLoc":94,"text":"self.robust"},{"attributeType":"null","col":8,"comment":"null","endLoc":88,"id":1376,"name":"seed","nodeType":"Attribute","startLoc":88,"text":"self.seed"},{"attributeType":"null","col":8,"comment":"null","endLoc":99,"id":1377,"name":"color","nodeType":"Attribute","startLoc":99,"text":"self.color"},{"attributeType":"null","col":4,"comment":"null","endLoc":8,"id":1378,"name":"regexp","nodeType":"Attribute","startLoc":8,"text":"regexp"},{"attributeType":"null","col":8,"comment":"null","endLoc":23,"id":1379,"name":"entries","nodeType":"Attribute","startLoc":23,"text":"self.entries"},{"attributeType":"null","col":8,"comment":"null","endLoc":761,"id":1380,"name":"ax_heatmap","nodeType":"Attribute","startLoc":761,"text":"self.ax_heatmap"},{"attributeType":"null","col":12,"comment":"null","endLoc":708,"id":1381,"name":"data","nodeType":"Attribute","startLoc":708,"text":"self.data"},{"attributeType":"int","col":8,"comment":"null","endLoc":85,"id":1382,"name":"ci","nodeType":"Attribute","startLoc":85,"text":"self.ci"},{"attributeType":"null","col":0,"comment":"null","endLoc":194,"id":1383,"name":"_core_docs","nodeType":"Attribute","startLoc":194,"text":"_core_docs"},{"className":"_RelationalPlotter","col":0,"comment":"null","endLoc":343,"id":1384,"nodeType":"Class","startLoc":184,"text":"class _RelationalPlotter(VectorPlotter):\n\n wide_structure = {\n \"x\": \"@index\", \"y\": \"@values\", \"hue\": \"@columns\", \"style\": \"@columns\",\n }\n\n # TODO where best to define default parameters?\n sort = True\n\n def add_legend_data(self, ax):\n \"\"\"Add labeled artists to represent the different plot semantics.\"\"\"\n verbosity = self.legend\n if isinstance(verbosity, str) and verbosity not in [\"auto\", \"brief\", \"full\"]:\n err = \"`legend` must be 'auto', 'brief', 'full', or a boolean.\"\n raise ValueError(err)\n elif verbosity is True:\n verbosity = \"auto\"\n\n legend_kwargs = {}\n keys = []\n\n # Assign a legend title if there is only going to be one sub-legend,\n # otherwise, subtitles will be inserted into the texts list with an\n # invisible handle (which is a hack)\n titles = {\n title for title in\n (self.variables.get(v, None) for v in [\"hue\", \"size\", \"style\"])\n if title is not None\n }\n if len(titles) == 1:\n legend_title = titles.pop()\n else:\n legend_title = \"\"\n\n title_kws = dict(\n visible=False, color=\"w\", s=0, linewidth=0, marker=\"\", dashes=\"\"\n )\n\n def update(var_name, val_name, **kws):\n\n key = var_name, val_name\n if key in legend_kwargs:\n legend_kwargs[key].update(**kws)\n else:\n keys.append(key)\n\n legend_kwargs[key] = dict(**kws)\n\n # Define the maximum number of ticks to use for \"brief\" legends\n brief_ticks = 6\n\n # -- Add a legend for hue semantics\n brief_hue = self._hue_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._hue_map.levels) > brief_ticks)\n )\n if brief_hue:\n if isinstance(self._hue_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n limits = min(self._hue_map.levels), max(self._hue_map.levels)\n hue_levels, hue_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"hue\"].infer_objects().dtype\n )\n elif self._hue_map.levels is None:\n hue_levels = hue_formatted_levels = []\n else:\n hue_levels = hue_formatted_levels = self._hue_map.levels\n\n # Add the hue semantic subtitle\n if not legend_title and self.variables.get(\"hue\", None) is not None:\n update((self.variables[\"hue\"], \"title\"),\n self.variables[\"hue\"], **title_kws)\n\n # Add the hue semantic labels\n for level, formatted_level in zip(hue_levels, hue_formatted_levels):\n if level is not None:\n color = self._hue_map(level)\n update(self.variables[\"hue\"], formatted_level, color=color)\n\n # -- Add a legend for size semantics\n brief_size = self._size_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._size_map.levels) > brief_ticks)\n )\n if brief_size:\n # Define how ticks will interpolate between the min/max data values\n if isinstance(self._size_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n # Define the min/max data values\n limits = min(self._size_map.levels), max(self._size_map.levels)\n size_levels, size_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"size\"].infer_objects().dtype\n )\n elif self._size_map.levels is None:\n size_levels = size_formatted_levels = []\n else:\n size_levels = size_formatted_levels = self._size_map.levels\n\n # Add the size semantic subtitle\n if not legend_title and self.variables.get(\"size\", None) is not None:\n update((self.variables[\"size\"], \"title\"),\n self.variables[\"size\"], **title_kws)\n\n # Add the size semantic labels\n for level, formatted_level in zip(size_levels, size_formatted_levels):\n if level is not None:\n size = self._size_map(level)\n update(\n self.variables[\"size\"],\n formatted_level,\n linewidth=size,\n s=size,\n )\n\n # -- Add a legend for style semantics\n\n # Add the style semantic title\n if not legend_title and self.variables.get(\"style\", None) is not None:\n update((self.variables[\"style\"], \"title\"),\n self.variables[\"style\"], **title_kws)\n\n # Add the style semantic labels\n if self._style_map.levels is not None:\n for level in self._style_map.levels:\n if level is not None:\n attrs = self._style_map(level)\n update(\n self.variables[\"style\"],\n level,\n marker=attrs.get(\"marker\", \"\"),\n dashes=attrs.get(\"dashes\", \"\"),\n )\n\n func = getattr(ax, self._legend_func)\n\n legend_data = {}\n legend_order = []\n\n for key in keys:\n\n _, label = key\n kws = legend_kwargs[key]\n kws.setdefault(\"color\", \".2\")\n use_kws = {}\n for attr in self._legend_attributes + [\"visible\"]:\n if attr in kws:\n use_kws[attr] = kws[attr]\n artist = func([], [], label=label, **use_kws)\n if self._legend_func == \"plot\":\n artist = artist[0]\n legend_data[key] = artist\n legend_order.append(key)\n\n self.legend_title = legend_title\n self.legend_data = legend_data\n self.legend_order = legend_order"},{"col":4,"comment":"Add labeled artists to represent the different plot semantics.","endLoc":343,"header":"def add_legend_data(self, ax)","id":1385,"name":"add_legend_data","nodeType":"Function","startLoc":193,"text":"def add_legend_data(self, ax):\n \"\"\"Add labeled artists to represent the different plot semantics.\"\"\"\n verbosity = self.legend\n if isinstance(verbosity, str) and verbosity not in [\"auto\", \"brief\", \"full\"]:\n err = \"`legend` must be 'auto', 'brief', 'full', or a boolean.\"\n raise ValueError(err)\n elif verbosity is True:\n verbosity = \"auto\"\n\n legend_kwargs = {}\n keys = []\n\n # Assign a legend title if there is only going to be one sub-legend,\n # otherwise, subtitles will be inserted into the texts list with an\n # invisible handle (which is a hack)\n titles = {\n title for title in\n (self.variables.get(v, None) for v in [\"hue\", \"size\", \"style\"])\n if title is not None\n }\n if len(titles) == 1:\n legend_title = titles.pop()\n else:\n legend_title = \"\"\n\n title_kws = dict(\n visible=False, color=\"w\", s=0, linewidth=0, marker=\"\", dashes=\"\"\n )\n\n def update(var_name, val_name, **kws):\n\n key = var_name, val_name\n if key in legend_kwargs:\n legend_kwargs[key].update(**kws)\n else:\n keys.append(key)\n\n legend_kwargs[key] = dict(**kws)\n\n # Define the maximum number of ticks to use for \"brief\" legends\n brief_ticks = 6\n\n # -- Add a legend for hue semantics\n brief_hue = self._hue_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._hue_map.levels) > brief_ticks)\n )\n if brief_hue:\n if isinstance(self._hue_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n limits = min(self._hue_map.levels), max(self._hue_map.levels)\n hue_levels, hue_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"hue\"].infer_objects().dtype\n )\n elif self._hue_map.levels is None:\n hue_levels = hue_formatted_levels = []\n else:\n hue_levels = hue_formatted_levels = self._hue_map.levels\n\n # Add the hue semantic subtitle\n if not legend_title and self.variables.get(\"hue\", None) is not None:\n update((self.variables[\"hue\"], \"title\"),\n self.variables[\"hue\"], **title_kws)\n\n # Add the hue semantic labels\n for level, formatted_level in zip(hue_levels, hue_formatted_levels):\n if level is not None:\n color = self._hue_map(level)\n update(self.variables[\"hue\"], formatted_level, color=color)\n\n # -- Add a legend for size semantics\n brief_size = self._size_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._size_map.levels) > brief_ticks)\n )\n if brief_size:\n # Define how ticks will interpolate between the min/max data values\n if isinstance(self._size_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n # Define the min/max data values\n limits = min(self._size_map.levels), max(self._size_map.levels)\n size_levels, size_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"size\"].infer_objects().dtype\n )\n elif self._size_map.levels is None:\n size_levels = size_formatted_levels = []\n else:\n size_levels = size_formatted_levels = self._size_map.levels\n\n # Add the size semantic subtitle\n if not legend_title and self.variables.get(\"size\", None) is not None:\n update((self.variables[\"size\"], \"title\"),\n self.variables[\"size\"], **title_kws)\n\n # Add the size semantic labels\n for level, formatted_level in zip(size_levels, size_formatted_levels):\n if level is not None:\n size = self._size_map(level)\n update(\n self.variables[\"size\"],\n formatted_level,\n linewidth=size,\n s=size,\n )\n\n # -- Add a legend for style semantics\n\n # Add the style semantic title\n if not legend_title and self.variables.get(\"style\", None) is not None:\n update((self.variables[\"style\"], \"title\"),\n self.variables[\"style\"], **title_kws)\n\n # Add the style semantic labels\n if self._style_map.levels is not None:\n for level in self._style_map.levels:\n if level is not None:\n attrs = self._style_map(level)\n update(\n self.variables[\"style\"],\n level,\n marker=attrs.get(\"marker\", \"\"),\n dashes=attrs.get(\"dashes\", \"\"),\n )\n\n func = getattr(ax, self._legend_func)\n\n legend_data = {}\n legend_order = []\n\n for key in keys:\n\n _, label = key\n kws = legend_kwargs[key]\n kws.setdefault(\"color\", \".2\")\n use_kws = {}\n for attr in self._legend_attributes + [\"visible\"]:\n if attr in kws:\n use_kws[attr] = kws[attr]\n artist = func([], [], label=label, **use_kws)\n if self._legend_func == \"plot\":\n artist = artist[0]\n legend_data[key] = artist\n legend_order.append(key)\n\n self.legend_title = legend_title\n self.legend_data = legend_data\n self.legend_order = legend_order"},{"attributeType":"null","col":8,"comment":"null","endLoc":742,"id":1386,"name":"gs","nodeType":"Attribute","startLoc":742,"text":"self.gs"},{"attributeType":"bool","col":8,"comment":"null","endLoc":95,"id":1387,"name":"logx","nodeType":"Attribute","startLoc":95,"text":"self.logx"},{"attributeType":"(Any, Any)","col":12,"comment":"null","endLoc":134,"id":1388,"name":"x_range","nodeType":"Attribute","startLoc":134,"text":"self.x_range"},{"attributeType":"null","col":8,"comment":"null","endLoc":710,"id":1389,"name":"data2d","nodeType":"Attribute","startLoc":710,"text":"self.data2d"},{"attributeType":"null","col":8,"comment":"null","endLoc":100,"id":1390,"name":"label","nodeType":"Attribute","startLoc":100,"text":"self.label"},{"attributeType":"list | list | None","col":8,"comment":"null","endLoc":717,"id":1391,"name":"row_colors","nodeType":"Attribute","startLoc":717,"text":"self.row_colors"},{"attributeType":"null","col":8,"comment":"null","endLoc":98,"id":1392,"name":"y_jitter","nodeType":"Attribute","startLoc":98,"text":"self.y_jitter"},{"col":4,"comment":"null","endLoc":274,"header":"def test_ticklabels_off(self)","id":1393,"name":"test_ticklabels_off","nodeType":"Function","startLoc":268,"text":"def test_ticklabels_off(self):\n kws = self.default_kws.copy()\n kws['xticklabels'] = False\n kws['yticklabels'] = False\n p = mat._HeatMapper(self.df_norm, **kws)\n assert p.xticklabels == []\n assert p.yticklabels == []"},{"col":4,"comment":"null","endLoc":86,"header":"def _legend_artist(self, variables, value, scales)","id":1394,"name":"_legend_artist","nodeType":"Function","startLoc":71,"text":"def _legend_artist(self, variables, value, scales):\n\n keys = {v: value for v in variables}\n resolved = resolve_properties(self, keys, scales)\n\n fc = resolve_color(self, keys, \"\", scales)\n if not resolved[\"fill\"]:\n fc = mpl.colors.to_rgba(fc, 0)\n\n return mpl.patches.Patch(\n facecolor=fc,\n edgecolor=resolve_color(self, keys, \"edge\", scales),\n linewidth=resolved[\"edgewidth\"],\n linestyle=resolved[\"edgestyle\"],\n **self.artist_kws,\n )"},{"col":4,"comment":"null","endLoc":284,"header":"def test_custom_ticklabels(self)","id":1395,"name":"test_custom_ticklabels","nodeType":"Function","startLoc":276,"text":"def test_custom_ticklabels(self):\n kws = self.default_kws.copy()\n xticklabels = list('iheartheatmaps'[:self.df_norm.shape[1]])\n yticklabels = list('heatmapsarecool'[:self.df_norm.shape[0]])\n kws['xticklabels'] = xticklabels\n kws['yticklabels'] = yticklabels\n p = mat._HeatMapper(self.df_norm, **kws)\n assert p.xticklabels == xticklabels\n assert p.yticklabels == yticklabels"},{"attributeType":"bool","col":8,"comment":"null","endLoc":93,"id":1396,"name":"lowess","nodeType":"Attribute","startLoc":93,"text":"self.lowess"},{"attributeType":"null","col":8,"comment":"null","endLoc":97,"id":1397,"name":"x_jitter","nodeType":"Attribute","startLoc":97,"text":"self.x_jitter"},{"className":"Area","col":0,"comment":"\n A fill mark drawn from a baseline to data values.\n\n See also\n --------\n Band : A fill mark representing an interval between values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Area.rst\n\n ","endLoc":136,"id":1398,"nodeType":"Class","startLoc":89,"text":"@document_properties\n@dataclass\nclass Area(AreaBase, Mark):\n \"\"\"\n A fill mark drawn from a baseline to data values.\n\n See also\n --------\n Band : A fill mark representing an interval between values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Area.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", )\n alpha: MappableFloat = Mappable(.2, )\n fill: MappableBool = Mappable(True, )\n edgecolor: MappableColor = Mappable(depend=\"color\")\n edgealpha: MappableFloat = Mappable(1, )\n edgewidth: MappableFloat = Mappable(rc=\"patch.linewidth\", )\n edgestyle: MappableStyle = Mappable(\"-\", )\n\n # TODO should this be settable / mappable?\n baseline: MappableFloat = Mappable(0, grouping=False)\n\n def _standardize_coordinate_parameters(self, data, orient):\n dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return data.rename(columns={\"baseline\": f\"{dv}min\", dv: f\"{dv}max\"})\n\n def _postprocess_artist(self, artist, ax, orient):\n\n # TODO copying a lot of code from Bar, let's abstract this\n # See comments there, I am not going to repeat them too\n\n artist.set_linewidth(artist.get_linewidth() * 2)\n\n linestyle = artist.get_linestyle()\n if linestyle[1]:\n linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1]))\n artist.set_linestyle(linestyle)\n\n artist.set_clip_path(artist.get_path(), artist.get_transform() + ax.transData)\n if self.artist_kws.get(\"clip_on\", True):\n artist.set_clip_box(ax.bbox)\n\n val_idx = [\"y\", \"x\"].index(orient)\n artist.sticky_edges[val_idx][:] = (0, np.inf)"},{"col":4,"comment":"null","endLoc":117,"header":"def _standardize_coordinate_parameters(self, data, orient)","id":1399,"name":"_standardize_coordinate_parameters","nodeType":"Function","startLoc":115,"text":"def _standardize_coordinate_parameters(self, data, orient):\n dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return data.rename(columns={\"baseline\": f\"{dv}min\", dv: f\"{dv}max\"})"},{"col":4,"comment":"null","endLoc":136,"header":"def _postprocess_artist(self, artist, ax, orient)","id":1400,"name":"_postprocess_artist","nodeType":"Function","startLoc":119,"text":"def _postprocess_artist(self, artist, ax, orient):\n\n # TODO copying a lot of code from Bar, let's abstract this\n # See comments there, I am not going to repeat them too\n\n artist.set_linewidth(artist.get_linewidth() * 2)\n\n linestyle = artist.get_linestyle()\n if linestyle[1]:\n linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1]))\n artist.set_linestyle(linestyle)\n\n artist.set_clip_path(artist.get_path(), artist.get_transform() + ax.transData)\n if self.artist_kws.get(\"clip_on\", True):\n artist.set_clip_box(ax.bbox)\n\n val_idx = [\"y\", \"x\"].index(orient)\n artist.sticky_edges[val_idx][:] = (0, np.inf)"},{"attributeType":"null","col":4,"comment":"null","endLoc":42,"id":1401,"name":"frame","nodeType":"Attribute","startLoc":42,"text":"frame"},{"attributeType":"dict","col":4,"comment":"null","endLoc":43,"id":1402,"name":"frames","nodeType":"Attribute","startLoc":43,"text":"frames"},{"attributeType":"dict","col":4,"comment":"null","endLoc":44,"id":1403,"name":"names","nodeType":"Attribute","startLoc":44,"text":"names"},{"attributeType":"null","col":12,"comment":"null","endLoc":122,"id":1404,"name":"x_estimator","nodeType":"Attribute","startLoc":122,"text":"self.x_estimator"},{"attributeType":"bool","col":8,"comment":"null","endLoc":92,"id":1405,"name":"logistic","nodeType":"Attribute","startLoc":92,"text":"self.logistic"},{"attributeType":"bool","col":8,"comment":"null","endLoc":96,"id":1406,"name":"truncate","nodeType":"Attribute","startLoc":96,"text":"self.truncate"},{"attributeType":"bool","col":8,"comment":"null","endLoc":89,"id":1407,"name":"scatter","nodeType":"Attribute","startLoc":89,"text":"self.scatter"},{"attributeType":"null","col":12,"comment":"null","endLoc":116,"id":1408,"name":"x","nodeType":"Attribute","startLoc":116,"text":"self.x"},{"attributeType":"null","col":12,"comment":"null","endLoc":118,"id":1409,"name":"y","nodeType":"Attribute","startLoc":118,"text":"self.y"},{"attributeType":"dict","col":4,"comment":"null","endLoc":45,"id":1410,"name":"ids","nodeType":"Attribute","startLoc":45,"text":"ids"},{"attributeType":"int | str","col":8,"comment":"null","endLoc":86,"id":1411,"name":"x_ci","nodeType":"Attribute","startLoc":86,"text":"self.x_ci"},{"attributeType":"null","col":12,"comment":"null","endLoc":126,"id":1412,"name":"x_discrete","nodeType":"Attribute","startLoc":126,"text":"self.x_discrete"},{"attributeType":"Mapping | None","col":4,"comment":"null","endLoc":46,"id":1413,"name":"source_data","nodeType":"Attribute","startLoc":46,"text":"source_data"},{"attributeType":"int","col":8,"comment":"null","endLoc":87,"id":1414,"name":"n_boot","nodeType":"Attribute","startLoc":87,"text":"self.n_boot"},{"attributeType":"bool","col":12,"comment":"null","endLoc":130,"id":1415,"name":"fit_reg","nodeType":"Attribute","startLoc":130,"text":"self.fit_reg"},{"attributeType":"int","col":8,"comment":"null","endLoc":91,"id":1416,"name":"order","nodeType":"Attribute","startLoc":91,"text":"self.order"},{"col":0,"comment":"null","endLoc":760,"header":"def regplot(\n data=None, *, x=None, y=None,\n x_estimator=None, x_bins=None, x_ci=\"ci\",\n scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None,\n seed=None, order=1, logistic=False, lowess=False, robust=False,\n logx=False, x_partial=None, y_partial=None,\n truncate=True, dropna=True, x_jitter=None, y_jitter=None,\n label=None, color=None, marker=\"o\",\n scatter_kws=None, line_kws=None, ax=None\n)","id":1417,"name":"regplot","nodeType":"Function","startLoc":736,"text":"def regplot(\n data=None, *, x=None, y=None,\n x_estimator=None, x_bins=None, x_ci=\"ci\",\n scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None,\n seed=None, order=1, logistic=False, lowess=False, robust=False,\n logx=False, x_partial=None, y_partial=None,\n truncate=True, dropna=True, x_jitter=None, y_jitter=None,\n label=None, color=None, marker=\"o\",\n scatter_kws=None, line_kws=None, ax=None\n):\n\n plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci,\n scatter, fit_reg, ci, n_boot, units, seed,\n order, logistic, lowess, robust, logx,\n x_partial, y_partial, truncate, dropna,\n x_jitter, y_jitter, color, label)\n\n if ax is None:\n ax = plt.gca()\n\n scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws)\n scatter_kws[\"marker\"] = marker\n line_kws = {} if line_kws is None else copy.copy(line_kws)\n plotter.plot(ax, scatter_kws, line_kws)\n return ax"},{"attributeType":"dict","col":4,"comment":"null","endLoc":47,"id":1418,"name":"source_vars","nodeType":"Attribute","startLoc":47,"text":"source_vars"},{"attributeType":"dict","col":8,"comment":"null","endLoc":58,"id":1419,"name":"names","nodeType":"Attribute","startLoc":58,"text":"self.names"},{"attributeType":"Mapping | None","col":8,"comment":"null","endLoc":63,"id":1420,"name":"source_data","nodeType":"Attribute","startLoc":63,"text":"self.source_data"},{"attributeType":"dict","col":8,"comment":"null","endLoc":61,"id":1421,"name":"frames","nodeType":"Attribute","startLoc":61,"text":"self.frames"},{"attributeType":"dict","col":8,"comment":"null","endLoc":64,"id":1422,"name":"source_vars","nodeType":"Attribute","startLoc":64,"text":"self.source_vars"},{"attributeType":"dict","col":8,"comment":"null","endLoc":59,"id":1423,"name":"ids","nodeType":"Attribute","startLoc":59,"text":"self.ids"},{"attributeType":"null","col":8,"comment":"null","endLoc":57,"id":1424,"name":"frame","nodeType":"Attribute","startLoc":57,"text":"self.frame"},{"attributeType":"null","col":17,"comment":"null","endLoc":9,"id":1425,"name":"pd","nodeType":"Attribute","startLoc":9,"text":"pd"},{"col":0,"comment":"","endLoc":3,"header":"data.py#","id":1426,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nComponents for parsing variable assignments and internally representing plot data.\n\"\"\""},{"col":4,"comment":"null","endLoc":300,"header":"def test_custom_ticklabel_interval(self)","id":1427,"name":"test_custom_ticklabel_interval","nodeType":"Function","startLoc":286,"text":"def test_custom_ticklabel_interval(self):\n\n kws = self.default_kws.copy()\n xstep, ystep = 2, 3\n kws['xticklabels'] = xstep\n kws['yticklabels'] = ystep\n p = mat._HeatMapper(self.df_norm, **kws)\n\n nx, ny = self.df_norm.T.shape\n npt.assert_array_equal(p.xticks, np.arange(0, nx, xstep) + .5)\n npt.assert_array_equal(p.yticks, np.arange(0, ny, ystep) + .5)\n npt.assert_array_equal(p.xticklabels,\n self.df_norm.columns[0:nx:xstep])\n npt.assert_array_equal(p.yticklabels,\n self.df_norm.index[0:ny:ystep])"},{"col":0,"comment":"Plot the residuals of a linear regression.\n\n This function will regress y on x (possibly as a robust or polynomial\n regression) and then draw a scatterplot of the residuals. You can\n optionally fit a lowess smoother to the residual plot, which can\n help in determining if there is structure to the residuals.\n\n Parameters\n ----------\n data : DataFrame, optional\n DataFrame to use if `x` and `y` are column names.\n x : vector or string\n Data or column name in `data` for the predictor variable.\n y : vector or string\n Data or column name in `data` for the response variable.\n {x, y}_partial : vectors or string(s) , optional\n These variables are treated as confounding and are removed from\n the `x` or `y` variables before plotting.\n lowess : boolean, optional\n Fit a lowess smoother to the residual scatterplot.\n order : int, optional\n Order of the polynomial to fit when calculating the residuals.\n robust : boolean, optional\n Fit a robust linear regression when calculating the residuals.\n dropna : boolean, optional\n If True, ignore observations with missing data when fitting and\n plotting.\n label : string, optional\n Label that will be used in any plot legends.\n color : matplotlib color, optional\n Color to use for all elements of the plot.\n {scatter, line}_kws : dictionaries, optional\n Additional keyword arguments passed to scatter() and plot() for drawing\n the components of the plot.\n ax : matplotlib axis, optional\n Plot into this axis, otherwise grab the current axis or make a new\n one if not existing.\n\n Returns\n -------\n ax: matplotlib axes\n Axes with the regression plot.\n\n See Also\n --------\n regplot : Plot a simple linear regression model.\n jointplot : Draw a :func:`residplot` with univariate marginal distributions\n (when used with ``kind=\"resid\"``).\n\n Examples\n --------\n\n .. include:: ../docstrings/residplot.rst\n\n ","endLoc":924,"header":"def residplot(\n data=None, *, x=None, y=None,\n x_partial=None, y_partial=None, lowess=False,\n order=1, robust=False, dropna=True, label=None, color=None,\n scatter_kws=None, line_kws=None, ax=None\n)","id":1428,"name":"residplot","nodeType":"Function","startLoc":838,"text":"def residplot(\n data=None, *, x=None, y=None,\n x_partial=None, y_partial=None, lowess=False,\n order=1, robust=False, dropna=True, label=None, color=None,\n scatter_kws=None, line_kws=None, ax=None\n):\n \"\"\"Plot the residuals of a linear regression.\n\n This function will regress y on x (possibly as a robust or polynomial\n regression) and then draw a scatterplot of the residuals. You can\n optionally fit a lowess smoother to the residual plot, which can\n help in determining if there is structure to the residuals.\n\n Parameters\n ----------\n data : DataFrame, optional\n DataFrame to use if `x` and `y` are column names.\n x : vector or string\n Data or column name in `data` for the predictor variable.\n y : vector or string\n Data or column name in `data` for the response variable.\n {x, y}_partial : vectors or string(s) , optional\n These variables are treated as confounding and are removed from\n the `x` or `y` variables before plotting.\n lowess : boolean, optional\n Fit a lowess smoother to the residual scatterplot.\n order : int, optional\n Order of the polynomial to fit when calculating the residuals.\n robust : boolean, optional\n Fit a robust linear regression when calculating the residuals.\n dropna : boolean, optional\n If True, ignore observations with missing data when fitting and\n plotting.\n label : string, optional\n Label that will be used in any plot legends.\n color : matplotlib color, optional\n Color to use for all elements of the plot.\n {scatter, line}_kws : dictionaries, optional\n Additional keyword arguments passed to scatter() and plot() for drawing\n the components of the plot.\n ax : matplotlib axis, optional\n Plot into this axis, otherwise grab the current axis or make a new\n one if not existing.\n\n Returns\n -------\n ax: matplotlib axes\n Axes with the regression plot.\n\n See Also\n --------\n regplot : Plot a simple linear regression model.\n jointplot : Draw a :func:`residplot` with univariate marginal distributions\n (when used with ``kind=\"resid\"``).\n\n Examples\n --------\n\n .. include:: ../docstrings/residplot.rst\n\n \"\"\"\n plotter = _RegressionPlotter(x, y, data, ci=None,\n order=order, robust=robust,\n x_partial=x_partial, y_partial=y_partial,\n dropna=dropna, color=color, label=label)\n\n if ax is None:\n ax = plt.gca()\n\n # Calculate the residual from a linear regression\n _, yhat, _ = plotter.fit_regression(grid=plotter.x)\n plotter.y = plotter.y - yhat\n\n # Set the regression option on the plotter\n if lowess:\n plotter.lowess = True\n else:\n plotter.fit_reg = False\n\n # Plot a horizontal line at 0\n ax.axhline(0, ls=\":\", c=\".2\")\n\n # Draw the scatterplot\n scatter_kws = {} if scatter_kws is None else scatter_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n plotter.plot(ax, scatter_kws, line_kws)\n return ax"},{"col":4,"comment":"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n ","endLoc":467,"header":"def _default_values(self, n: int) -> list[DashPatternWithOffset]","id":1429,"name":"_default_values","nodeType":"Function","startLoc":426,"text":"def _default_values(self, n: int) -> list[DashPatternWithOffset]:\n \"\"\"Build an arbitrarily long list of unique dash styles for lines.\n\n Parameters\n ----------\n n : int\n Number of unique dash specs to generate.\n\n Returns\n -------\n dashes : list of strings or tuples\n Valid arguments for the ``dashes`` parameter on\n :class:`matplotlib.lines.Line2D`. The first spec is a solid\n line (``\"\"``), the remainder are sequences of long and short\n dashes.\n\n \"\"\"\n # Start with dash specs that are well distinguishable\n dashes: list[str | DashPattern] = [\n \"-\", (4, 1.5), (1, 1), (3, 1.25, 1.5, 1.25), (5, 1, 1, 1),\n ]\n\n # Now programmatically build as many as we need\n p = 3\n while len(dashes) < n:\n\n # Take combinations of long and short dashes\n a = itertools.combinations_with_replacement([3, 1.25], p)\n b = itertools.combinations_with_replacement([4, 1], p)\n\n # Interleave the combinations, reversing one of the streams\n segment_list = itertools.chain(*zip(list(a)[1:-1][::-1], list(b)[1:-1]))\n\n # Now insert the gaps\n for segments in segment_list:\n gap = min(segments)\n spec = tuple(itertools.chain(*((seg, gap) for seg in segments)))\n dashes.append(spec)\n\n p += 1\n\n return [self._get_dash_pattern(x) for x in dashes]"},{"attributeType":"null","col":16,"comment":"null","endLoc":5,"id":1430,"name":"np","nodeType":"Attribute","startLoc":5,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":6,"id":1431,"name":"pd","nodeType":"Attribute","startLoc":6,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":7,"id":1432,"name":"mpl","nodeType":"Attribute","startLoc":7,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":1433,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"bool","col":4,"comment":"null","endLoc":13,"id":1434,"name":"_has_statsmodels","nodeType":"Attribute","startLoc":13,"text":"_has_statsmodels"},{"attributeType":"bool","col":4,"comment":"null","endLoc":15,"id":1435,"name":"_has_statsmodels","nodeType":"Attribute","startLoc":15,"text":"_has_statsmodels"},{"attributeType":"null","col":28,"comment":"null","endLoc":18,"id":1436,"name":"algo","nodeType":"Attribute","startLoc":18,"text":"algo"},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":1437,"name":"__all__","nodeType":"Attribute","startLoc":22,"text":"__all__"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":429,"id":1438,"name":"_regression_docs","nodeType":"Attribute","startLoc":429,"text":"_regression_docs"},{"col":4,"comment":"null","endLoc":308,"header":"def test_heatmap_annotation(self)","id":1439,"name":"test_heatmap_annotation","nodeType":"Function","startLoc":302,"text":"def test_heatmap_annotation(self):\n\n ax = mat.heatmap(self.df_norm, annot=True, fmt=\".1f\",\n annot_kws={\"fontsize\": 14})\n for val, text in zip(self.x_norm.flat, ax.texts):\n assert text.get_text() == f\"{val:.1f}\"\n assert text.get_fontsize() == 14"},{"attributeType":"str | None","col":0,"comment":"null","endLoc":644,"id":1440,"name":"__doc__","nodeType":"Attribute","startLoc":644,"text":"lmplot.__doc__"},{"attributeType":"str | None","col":0,"comment":"null","endLoc":763,"id":1441,"name":"__doc__","nodeType":"Attribute","startLoc":763,"text":"regplot.__doc__"},{"col":0,"comment":"","endLoc":1,"header":"regression.py#","id":1442,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Plotting functions for linear models (broadly construed).\"\"\"\n\ntry:\n import statsmodels\n assert statsmodels\n _has_statsmodels = True\nexcept ImportError:\n _has_statsmodels = False\n\n__all__ = [\"lmplot\", \"regplot\", \"residplot\"]\n\n_regression_docs = dict(\n\n model_api=dedent(\"\"\"\\\n There are a number of mutually exclusive options for estimating the\n regression model. See the :ref:`tutorial ` for more\n information.\\\n \"\"\"),\n regplot_vs_lmplot=dedent(\"\"\"\\\n The :func:`regplot` and :func:`lmplot` functions are closely related, but\n the former is an axes-level function while the latter is a figure-level\n function that combines :func:`regplot` and :class:`FacetGrid`.\\\n \"\"\"),\n x_estimator=dedent(\"\"\"\\\n x_estimator : callable that maps vector -> scalar, optional\n Apply this function to each unique value of ``x`` and plot the\n resulting estimate. This is useful when ``x`` is a discrete variable.\n If ``x_ci`` is given, this estimate will be bootstrapped and a\n confidence interval will be drawn.\\\n \"\"\"),\n x_bins=dedent(\"\"\"\\\n x_bins : int or vector, optional\n Bin the ``x`` variable into discrete bins and then estimate the central\n tendency and a confidence interval. This binning only influences how\n the scatterplot is drawn; the regression is still fit to the original\n data. This parameter is interpreted either as the number of\n evenly-sized (not necessary spaced) bins or the positions of the bin\n centers. When this parameter is used, it implies that the default of\n ``x_estimator`` is ``numpy.mean``.\\\n \"\"\"),\n x_ci=dedent(\"\"\"\\\n x_ci : \"ci\", \"sd\", int in [0, 100] or None, optional\n Size of the confidence interval used when plotting a central tendency\n for discrete values of ``x``. If ``\"ci\"``, defer to the value of the\n ``ci`` parameter. If ``\"sd\"``, skip bootstrapping and show the\n standard deviation of the observations in each bin.\\\n \"\"\"),\n scatter=dedent(\"\"\"\\\n scatter : bool, optional\n If ``True``, draw a scatterplot with the underlying observations (or\n the ``x_estimator`` values).\\\n \"\"\"),\n fit_reg=dedent(\"\"\"\\\n fit_reg : bool, optional\n If ``True``, estimate and plot a regression model relating the ``x``\n and ``y`` variables.\\\n \"\"\"),\n ci=dedent(\"\"\"\\\n ci : int in [0, 100] or None, optional\n Size of the confidence interval for the regression estimate. This will\n be drawn using translucent bands around the regression line. The\n confidence interval is estimated using a bootstrap; for large\n datasets, it may be advisable to avoid that computation by setting\n this parameter to None.\\\n \"\"\"),\n n_boot=dedent(\"\"\"\\\n n_boot : int, optional\n Number of bootstrap resamples used to estimate the ``ci``. The default\n value attempts to balance time and stability; you may want to increase\n this value for \"final\" versions of plots.\\\n \"\"\"),\n units=dedent(\"\"\"\\\n units : variable name in ``data``, optional\n If the ``x`` and ``y`` observations are nested within sampling units,\n those can be specified here. This will be taken into account when\n computing the confidence intervals by performing a multilevel bootstrap\n that resamples both units and observations (within unit). This does not\n otherwise influence how the regression is estimated or drawn.\\\n \"\"\"),\n seed=dedent(\"\"\"\\\n seed : int, numpy.random.Generator, or numpy.random.RandomState, optional\n Seed or random number generator for reproducible bootstrapping.\\\n \"\"\"),\n order=dedent(\"\"\"\\\n order : int, optional\n If ``order`` is greater than 1, use ``numpy.polyfit`` to estimate a\n polynomial regression.\\\n \"\"\"),\n logistic=dedent(\"\"\"\\\n logistic : bool, optional\n If ``True``, assume that ``y`` is a binary variable and use\n ``statsmodels`` to estimate a logistic regression model. Note that this\n is substantially more computationally intensive than linear regression,\n so you may wish to decrease the number of bootstrap resamples\n (``n_boot``) or set ``ci`` to None.\\\n \"\"\"),\n lowess=dedent(\"\"\"\\\n lowess : bool, optional\n If ``True``, use ``statsmodels`` to estimate a nonparametric lowess\n model (locally weighted linear regression). Note that confidence\n intervals cannot currently be drawn for this kind of model.\\\n \"\"\"),\n robust=dedent(\"\"\"\\\n robust : bool, optional\n If ``True``, use ``statsmodels`` to estimate a robust regression. This\n will de-weight outliers. Note that this is substantially more\n computationally intensive than standard linear regression, so you may\n wish to decrease the number of bootstrap resamples (``n_boot``) or set\n ``ci`` to None.\\\n \"\"\"),\n logx=dedent(\"\"\"\\\n logx : bool, optional\n If ``True``, estimate a linear regression of the form y ~ log(x), but\n plot the scatterplot and regression model in the input space. Note that\n ``x`` must be positive for this to work.\\\n \"\"\"),\n xy_partial=dedent(\"\"\"\\\n {x,y}_partial : strings in ``data`` or matrices\n Confounding variables to regress out of the ``x`` or ``y`` variables\n before plotting.\\\n \"\"\"),\n truncate=dedent(\"\"\"\\\n truncate : bool, optional\n If ``True``, the regression line is bounded by the data limits. If\n ``False``, it extends to the ``x`` axis limits.\n \"\"\"),\n xy_jitter=dedent(\"\"\"\\\n {x,y}_jitter : floats, optional\n Add uniform random noise of this size to either the ``x`` or ``y``\n variables. The noise is added to a copy of the data after fitting the\n regression, and only influences the look of the scatterplot. This can\n be helpful when plotting variables that take discrete values.\\\n \"\"\"),\n scatter_line_kws=dedent(\"\"\"\\\n {scatter,line}_kws : dictionaries\n Additional keyword arguments to pass to ``plt.scatter`` and\n ``plt.plot``.\\\n \"\"\"),\n)\n\n_regression_docs.update(_facet_docs)\n\nlmplot.__doc__ = dedent(\"\"\"\\\n Plot data and regression model fits across a FacetGrid.\n\n This function combines :func:`regplot` and :class:`FacetGrid`. It is\n intended as a convenient interface to fit regression models across\n conditional subsets of a dataset.\n\n When thinking about how to assign variables to different facets, a general\n rule is that it makes sense to use ``hue`` for the most important\n comparison, followed by ``col`` and ``row``. However, always think about\n your particular dataset and the goals of the visualization you are\n creating.\n\n {model_api}\n\n The parameters to this function span most of the options in\n :class:`FacetGrid`, although there may be occasional cases where you will\n want to use that class and :func:`regplot` directly.\n\n Parameters\n ----------\n {data}\n x, y : strings, optional\n Input variables; these should be column names in ``data``.\n hue, col, row : strings\n Variables that define subsets of the data, which will be drawn on\n separate facets in the grid. See the ``*_order`` parameters to control\n the order of levels of this variable.\n {palette}\n {col_wrap}\n {height}\n {aspect}\n markers : matplotlib marker code or list of marker codes, optional\n Markers for the scatterplot. If a list, each marker in the list will be\n used for each level of the ``hue`` variable.\n {share_xy}\n\n .. deprecated:: 0.12.0\n Pass using the `facet_kws` dictionary.\n\n {{hue,col,row}}_order : lists, optional\n Order for the levels of the faceting variables. By default, this will\n be the order that the levels appear in ``data`` or, if the variables\n are pandas categoricals, the category order.\n legend : bool, optional\n If ``True`` and there is a ``hue`` variable, add a legend.\n {legend_out}\n\n .. deprecated:: 0.12.0\n Pass using the `facet_kws` dictionary.\n\n {x_estimator}\n {x_bins}\n {x_ci}\n {scatter}\n {fit_reg}\n {ci}\n {n_boot}\n {units}\n {seed}\n {order}\n {logistic}\n {lowess}\n {robust}\n {logx}\n {xy_partial}\n {truncate}\n {xy_jitter}\n {scatter_line_kws}\n facet_kws : dict\n Dictionary of keyword arguments for :class:`FacetGrid`.\n\n See Also\n --------\n regplot : Plot data and a conditional model fit.\n FacetGrid : Subplot grid for plotting conditional relationships.\n pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with\n ``kind=\"reg\"``).\n\n Notes\n -----\n\n {regplot_vs_lmplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/lmplot.rst\n\n \"\"\").format(**_regression_docs)\n\nregplot.__doc__ = dedent(\"\"\"\\\n Plot data and a linear regression model fit.\n\n {model_api}\n\n Parameters\n ----------\n x, y: string, series, or vector array\n Input variables. If strings, these should correspond with column names\n in ``data``. When pandas objects are used, axes will be labeled with\n the series name.\n {data}\n {x_estimator}\n {x_bins}\n {x_ci}\n {scatter}\n {fit_reg}\n {ci}\n {n_boot}\n {units}\n {seed}\n {order}\n {logistic}\n {lowess}\n {robust}\n {logx}\n {xy_partial}\n {truncate}\n {xy_jitter}\n label : string\n Label to apply to either the scatterplot or regression line (if\n ``scatter`` is ``False``) for use in a legend.\n color : matplotlib color\n Color to apply to all plot elements; will be superseded by colors\n passed in ``scatter_kws`` or ``line_kws``.\n marker : matplotlib marker code\n Marker to use for the scatterplot glyphs.\n {scatter_line_kws}\n ax : matplotlib Axes, optional\n Axes object to draw the plot onto, otherwise uses the current Axes.\n\n Returns\n -------\n ax : matplotlib Axes\n The Axes object containing the plot.\n\n See Also\n --------\n lmplot : Combine :func:`regplot` and :class:`FacetGrid` to plot multiple\n linear relationships in a dataset.\n jointplot : Combine :func:`regplot` and :class:`JointGrid` (when used with\n ``kind=\"reg\"``).\n pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with\n ``kind=\"reg\"``).\n residplot : Plot the residuals of a linear regression model.\n\n Notes\n -----\n\n {regplot_vs_lmplot}\n\n\n It's also easy to combine :func:`regplot` and :class:`JointGrid` or\n :class:`PairGrid` through the :func:`jointplot` and :func:`pairplot`\n functions, although these do not directly accept all of :func:`regplot`'s\n parameters.\n\n Examples\n --------\n\n .. include: ../docstrings/regplot.rst\n\n \"\"\").format(**_regression_docs)"},{"col":4,"comment":"Draw a bivariate plot on the indicated axes.","endLoc":1572,"header":"def _map_bivariate(self, func, indices, **kwargs)","id":1443,"name":"_map_bivariate","nodeType":"Function","startLoc":1552,"text":"def _map_bivariate(self, func, indices, **kwargs):\n \"\"\"Draw a bivariate plot on the indicated axes.\"\"\"\n # This is a hack to handle the fact that new distribution plots don't add\n # their artists onto the axes. This is probably superior in general, but\n # we'll need a better way to handle it in the axisgrid functions.\n from .distributions import histplot, kdeplot\n if func is histplot or func is kdeplot:\n self._extract_legend_handles = True\n\n kws = kwargs.copy() # Use copy as we insert other kwargs\n for i, j in indices:\n x_var = self.x_vars[j]\n y_var = self.y_vars[i]\n ax = self.axes[i, j]\n if ax is None: # i.e. we are in corner mode\n continue\n self._plot_bivariate(x_var, y_var, ax, func, **kws)\n self._add_axis_labels()\n\n if \"hue\" in signature(func).parameters:\n self.hue_names = list(self._legend_data)"},{"col":4,"comment":"Draw a bivariate plot on the specified axes.","endLoc":1611,"header":"def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs)","id":1444,"name":"_plot_bivariate","nodeType":"Function","startLoc":1574,"text":"def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):\n \"\"\"Draw a bivariate plot on the specified axes.\"\"\"\n if \"hue\" not in signature(func).parameters:\n self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)\n return\n\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n if x_var == y_var:\n axes_vars = [x_var]\n else:\n axes_vars = [x_var, y_var]\n\n if self._hue_var is not None and self._hue_var not in axes_vars:\n axes_vars.append(self._hue_var)\n\n data = self.data[axes_vars]\n if self._dropna:\n data = data.dropna()\n\n x = data[x_var]\n y = data[y_var]\n if self._hue_var is None:\n hue = None\n else:\n hue = data.get(self._hue_var)\n\n if \"hue\" not in kwargs:\n kwargs.update({\n \"hue\": hue, \"hue_order\": self._hue_order, \"palette\": self._orig_palette,\n })\n func(x=x, y=y, **kwargs)\n\n self._update_legend_data(ax)"},{"col":4,"comment":"Draw a bivariate plot while iterating over hue subsets.","endLoc":1655,"header":"def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs)","id":1445,"name":"_plot_bivariate_iter_hue","nodeType":"Function","startLoc":1613,"text":"def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs):\n \"\"\"Draw a bivariate plot while iterating over hue subsets.\"\"\"\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n if x_var == y_var:\n axes_vars = [x_var]\n else:\n axes_vars = [x_var, y_var]\n\n hue_grouped = self.data.groupby(self.hue_vals)\n for k, label_k in enumerate(self._hue_order):\n\n kws = kwargs.copy()\n\n # Attempt to get data for this level, allowing for empty\n try:\n data_k = hue_grouped.get_group(label_k)\n except KeyError:\n data_k = pd.DataFrame(columns=axes_vars,\n dtype=float)\n\n if self._dropna:\n data_k = data_k[axes_vars].dropna()\n\n x = data_k[x_var]\n y = data_k[y_var]\n\n for kw, val_list in self.hue_kws.items():\n kws[kw] = val_list[k]\n kws.setdefault(\"color\", self.palette[k])\n if self._hue_var is not None:\n kws[\"label\"] = label_k\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=x, y=y, **kws)\n else:\n func(x, y, **kws)\n\n self._update_legend_data(ax)"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":104,"id":1446,"name":"color","nodeType":"Attribute","startLoc":104,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":105,"id":1447,"name":"alpha","nodeType":"Attribute","startLoc":105,"text":"alpha"},{"attributeType":"bool | Mappable","col":4,"comment":"null","endLoc":106,"id":1448,"name":"fill","nodeType":"Attribute","startLoc":106,"text":"fill"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":107,"id":1449,"name":"edgecolor","nodeType":"Attribute","startLoc":107,"text":"edgecolor"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":108,"id":1450,"name":"edgealpha","nodeType":"Attribute","startLoc":108,"text":"edgealpha"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":109,"id":1451,"name":"edgewidth","nodeType":"Attribute","startLoc":109,"text":"edgewidth"},{"attributeType":"str | (float, ...) | (float, (float, ...) | None) | Mappable","col":4,"comment":"null","endLoc":110,"id":1452,"name":"edgestyle","nodeType":"Attribute","startLoc":110,"text":"edgestyle"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":113,"id":1453,"name":"baseline","nodeType":"Attribute","startLoc":113,"text":"baseline"},{"className":"Band","col":0,"comment":"\n A fill mark representing an interval between values.\n\n See also\n --------\n Area : A fill mark drawn from a baseline to data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Band.rst\n\n ","endLoc":170,"id":1454,"nodeType":"Class","startLoc":139,"text":"@document_properties\n@dataclass\nclass Band(AreaBase, Mark):\n \"\"\"\n A fill mark representing an interval between values.\n\n See also\n --------\n Area : A fill mark drawn from a baseline to data values.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Band.rst\n\n \"\"\"\n color: MappableColor = Mappable(\"C0\", )\n alpha: MappableFloat = Mappable(.2, )\n fill: MappableBool = Mappable(True, )\n edgecolor: MappableColor = Mappable(depend=\"color\", )\n edgealpha: MappableFloat = Mappable(1, )\n edgewidth: MappableFloat = Mappable(0, )\n edgestyle: MappableFloat = Mappable(\"-\", )\n\n def _standardize_coordinate_parameters(self, data, orient):\n # dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n # TODO assert that all(ymax >= ymin)?\n # TODO what if only one exist?\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n if not set(data.columns) & {f\"{other}min\", f\"{other}max\"}:\n agg = {f\"{other}min\": (other, \"min\"), f\"{other}max\": (other, \"max\")}\n data = data.groupby(orient).agg(**agg).reset_index()\n return data"},{"fileName":"grouped_boxplot.py","filePath":"examples","id":1455,"nodeType":"File","text":"\"\"\"\nGrouped boxplots\n================\n\n_thumb: .66, .45\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\", palette=\"pastel\")\n\n# Load the example tips dataset\ntips = sns.load_dataset(\"tips\")\n\n# Draw a nested boxplot to show bills by day and time\nsns.boxplot(x=\"day\", y=\"total_bill\",\n hue=\"smoker\", palette=[\"m\", \"g\"],\n data=tips)\nsns.despine(offset=10, trim=True)\n"},{"col":4,"comment":"null","endLoc":170,"header":"def _standardize_coordinate_parameters(self, data, orient)","id":1456,"name":"_standardize_coordinate_parameters","nodeType":"Function","startLoc":162,"text":"def _standardize_coordinate_parameters(self, data, orient):\n # dv = {\"x\": \"y\", \"y\": \"x\"}[orient]\n # TODO assert that all(ymax >= ymin)?\n # TODO what if only one exist?\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n if not set(data.columns) & {f\"{other}min\", f\"{other}max\"}:\n agg = {f\"{other}min\": (other, \"min\"), f\"{other}max\": (other, \"max\")}\n data = data.groupby(orient).agg(**agg).reset_index()\n return data"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":1457,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"list | list | None","col":8,"comment":"null","endLoc":719,"id":1458,"name":"col_colors","nodeType":"Attribute","startLoc":719,"text":"self.col_colors"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":1459,"name":"tips","nodeType":"Attribute","startLoc":12,"text":"tips"},{"col":0,"comment":"","endLoc":7,"header":"grouped_boxplot.py#","id":1460,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nGrouped boxplots\n================\n\n_thumb: .66, .45\n\n\"\"\"\n\nsns.set_theme(style=\"ticks\", palette=\"pastel\")\n\ntips = sns.load_dataset(\"tips\")\n\nsns.boxplot(x=\"day\", y=\"total_bill\",\n hue=\"smoker\", palette=[\"m\", \"g\"],\n data=tips)\n\nsns.despine(offset=10, trim=True)"},{"attributeType":"null","col":12,"comment":"null","endLoc":767,"id":1461,"name":"ax_cbar","nodeType":"Attribute","startLoc":767,"text":"self.ax_cbar"},{"attributeType":"None","col":8,"comment":"null","endLoc":771,"id":1462,"name":"dendrogram_row","nodeType":"Attribute","startLoc":771,"text":"self.dendrogram_row"},{"attributeType":"null","col":8,"comment":"null","endLoc":715,"id":1463,"name":"_figure","nodeType":"Attribute","startLoc":715,"text":"self._figure"},{"attributeType":"None","col":8,"comment":"null","endLoc":769,"id":1464,"name":"cbar_pos","nodeType":"Attribute","startLoc":769,"text":"self.cbar_pos"},{"attributeType":"null","col":8,"comment":"null","endLoc":747,"id":1465,"name":"ax_col_dendrogram","nodeType":"Attribute","startLoc":747,"text":"self.ax_col_dendrogram"},{"attributeType":"null","col":12,"comment":"null","endLoc":755,"id":1466,"name":"ax_row_colors","nodeType":"Attribute","startLoc":755,"text":"self.ax_row_colors"},{"attributeType":"list | list | None","col":25,"comment":"null","endLoc":717,"id":1467,"name":"row_color_labels","nodeType":"Attribute","startLoc":717,"text":"self.row_color_labels"},{"attributeType":"None","col":12,"comment":"null","endLoc":768,"id":1468,"name":"cax","nodeType":"Attribute","startLoc":768,"text":"self.cax"},{"attributeType":"null","col":8,"comment":"null","endLoc":746,"id":1469,"name":"ax_row_dendrogram","nodeType":"Attribute","startLoc":746,"text":"self.ax_row_dendrogram"},{"attributeType":"list | list | None","col":25,"comment":"null","endLoc":719,"id":1470,"name":"col_color_labels","nodeType":"Attribute","startLoc":719,"text":"self.col_color_labels"},{"attributeType":"None","col":8,"comment":"null","endLoc":772,"id":1471,"name":"dendrogram_col","nodeType":"Attribute","startLoc":772,"text":"self.dendrogram_col"},{"col":0,"comment":"null","endLoc":2239,"header":"def boxplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None,\n **kwargs\n)","id":1472,"name":"boxplot","nodeType":"Function","startLoc":2223,"text":"def boxplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None,\n **kwargs\n):\n\n plotter = _BoxPlotter(x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth)\n\n if ax is None:\n ax = plt.gca()\n kwargs.update(dict(whis=whis))\n\n plotter.plot(ax, kwargs)\n return ax"},{"attributeType":"null","col":12,"comment":"null","endLoc":758,"id":1473,"name":"ax_col_colors","nodeType":"Attribute","startLoc":758,"text":"self.ax_col_colors"},{"attributeType":"null","col":8,"comment":"null","endLoc":713,"id":1474,"name":"mask","nodeType":"Attribute","startLoc":713,"text":"self.mask"},{"col":4,"comment":"null","endLoc":794,"header":"def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth)","id":1475,"name":"__init__","nodeType":"Function","startLoc":781,"text":"def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n\n self.dodge = dodge\n self.width = width\n self.fliersize = fliersize\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth"},{"attributeType":"bool","col":4,"comment":"null","endLoc":12,"id":1476,"name":"_no_scipy","nodeType":"Attribute","startLoc":12,"text":"_no_scipy"},{"attributeType":"null","col":0,"comment":"null","endLoc":28,"id":1477,"name":"__all__","nodeType":"Attribute","startLoc":28,"text":"__all__"},{"col":0,"comment":"","endLoc":1,"header":"matrix.py#","id":1478,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Functions to visualize matrices of data.\"\"\"\n\ntry:\n from scipy.cluster import hierarchy\n _no_scipy = False\nexcept ImportError:\n _no_scipy = True\n\n__all__ = [\"heatmap\", \"clustermap\"]"},{"fileName":"__init__.py","filePath":"tests","id":1479,"nodeType":"File","text":""},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":154,"id":1480,"name":"color","nodeType":"Attribute","startLoc":154,"text":"color"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":155,"id":1481,"name":"alpha","nodeType":"Attribute","startLoc":155,"text":"alpha"},{"attributeType":"bool | Mappable","col":4,"comment":"null","endLoc":156,"id":1482,"name":"fill","nodeType":"Attribute","startLoc":156,"text":"fill"},{"fileName":"test_objects.py","filePath":"tests","id":1483,"nodeType":"File","text":"import seaborn.objects\nfrom seaborn._core.plot import Plot\nfrom seaborn._core.moves import Move\nfrom seaborn._core.scales import Scale\nfrom seaborn._marks.base import Mark\nfrom seaborn._stats.base import Stat\n\n\ndef test_objects_namespace():\n\n for name in dir(seaborn.objects):\n if not name.startswith(\"__\"):\n obj = getattr(seaborn.objects, name)\n assert issubclass(obj, (Plot, Mark, Stat, Move, Scale))\n"},{"attributeType":"str | tuple | Mappable","col":4,"comment":"null","endLoc":157,"id":1484,"name":"edgecolor","nodeType":"Attribute","startLoc":157,"text":"edgecolor"},{"className":"Plot","col":0,"comment":"\n An interface for declaratively specifying statistical graphics.\n\n Plots are constructed by initializing this class and adding one or more\n layers, comprising a `Mark` and optional `Stat` or `Move`. Additionally,\n faceting variables or variable pairings may be defined to divide the space\n into multiple subplots. The mappings from data values to visual properties\n can be parametrized using scales, although the plot will try to infer good\n defaults when scales are not explicitly defined.\n\n The constructor accepts a data source (a :class:`pandas.DataFrame` or\n dictionary with columnar values) and variable assignments. Variables can be\n passed as keys to the data source or directly as data vectors. If multiple\n data-containing objects are provided, they will be index-aligned.\n\n The data source and variables defined in the constructor will be used for\n all layers in the plot, unless overridden or disabled when adding a layer.\n\n The following variables can be defined in the constructor:\n {known_properties}\n\n The `data`, `x`, and `y` variables can be passed as positional arguments or\n using keywords. Whether the first positional argument is interpreted as a\n data source or `x` variable depends on its type.\n\n The methods of this class return a copy of the instance; use chaining to\n build up a plot through multiple calls. Methods can be called in any order.\n\n Most methods only add information to the plot spec; no actual processing\n happens until the plot is shown or saved. It is also possible to compile\n the plot without rendering it to access the lower-level representation.\n\n ","endLoc":856,"id":1485,"nodeType":"Class","startLoc":148,"text":"@build_plot_signature\nclass Plot:\n \"\"\"\n An interface for declaratively specifying statistical graphics.\n\n Plots are constructed by initializing this class and adding one or more\n layers, comprising a `Mark` and optional `Stat` or `Move`. Additionally,\n faceting variables or variable pairings may be defined to divide the space\n into multiple subplots. The mappings from data values to visual properties\n can be parametrized using scales, although the plot will try to infer good\n defaults when scales are not explicitly defined.\n\n The constructor accepts a data source (a :class:`pandas.DataFrame` or\n dictionary with columnar values) and variable assignments. Variables can be\n passed as keys to the data source or directly as data vectors. If multiple\n data-containing objects are provided, they will be index-aligned.\n\n The data source and variables defined in the constructor will be used for\n all layers in the plot, unless overridden or disabled when adding a layer.\n\n The following variables can be defined in the constructor:\n {known_properties}\n\n The `data`, `x`, and `y` variables can be passed as positional arguments or\n using keywords. Whether the first positional argument is interpreted as a\n data source or `x` variable depends on its type.\n\n The methods of this class return a copy of the instance; use chaining to\n build up a plot through multiple calls. Methods can be called in any order.\n\n Most methods only add information to the plot spec; no actual processing\n happens until the plot is shown or saved. It is also possible to compile\n the plot without rendering it to access the lower-level representation.\n\n \"\"\"\n _data: PlotData\n _layers: list[Layer]\n\n _scales: dict[str, Scale]\n _shares: dict[str, bool | str]\n _limits: dict[str, tuple[Any, Any]]\n _labels: dict[str, str | Callable[[str], str]]\n _theme: dict[str, Any]\n\n _facet_spec: FacetSpec\n _pair_spec: PairSpec\n\n _figure_spec: dict[str, Any]\n _subplot_spec: dict[str, Any]\n _layout_spec: dict[str, Any]\n\n def __init__(\n self,\n *args: DataSource | VariableSpec,\n data: DataSource = None,\n **variables: VariableSpec,\n ):\n\n if args:\n data, variables = self._resolve_positionals(args, data, variables)\n\n unknown = [x for x in variables if x not in PROPERTIES]\n if unknown:\n err = f\"Plot() got unexpected keyword argument(s): {', '.join(unknown)}\"\n raise TypeError(err)\n\n self._data = PlotData(data, variables)\n\n self._layers = []\n\n self._scales = {}\n self._shares = {}\n self._limits = {}\n self._labels = {}\n self._theme = {}\n\n self._facet_spec = {}\n self._pair_spec = {}\n\n self._figure_spec = {}\n self._subplot_spec = {}\n self._layout_spec = {}\n\n self._target = None\n\n def _resolve_positionals(\n self,\n args: tuple[DataSource | VariableSpec, ...],\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataSource, dict[str, VariableSpec]]:\n \"\"\"Handle positional arguments, which may contain data / x / y.\"\"\"\n if len(args) > 3:\n err = \"Plot() accepts no more than 3 positional arguments (data, x, y).\"\n raise TypeError(err)\n\n # TODO need some clearer way to differentiate data / vector here\n # (There might be an abstract DataFrame class to use here?)\n if isinstance(args[0], (abc.Mapping, pd.DataFrame)):\n if data is not None:\n raise TypeError(\"`data` given by both name and position.\")\n data, args = args[0], args[1:]\n\n if len(args) == 2:\n x, y = args\n elif len(args) == 1:\n x, y = *args, None\n else:\n x = y = None\n\n for name, var in zip(\"yx\", (y, x)):\n if var is not None:\n if name in variables:\n raise TypeError(f\"`{name}` given by both name and position.\")\n # Keep coordinates at the front of the variables dict\n # Cast type because we know this isn't a DataSource at this point\n variables = {name: cast(VariableSpec, var), **variables}\n\n return data, variables\n\n def __add__(self, other):\n\n if isinstance(other, Mark) or isinstance(other, Stat):\n raise TypeError(\"Sorry, this isn't ggplot! Perhaps try Plot.add?\")\n\n other_type = other.__class__.__name__\n raise TypeError(f\"Unsupported operand type(s) for +: 'Plot' and '{other_type}\")\n\n def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n\n return self.plot()._repr_png_()\n\n # TODO _repr_svg_?\n\n def _clone(self) -> Plot:\n \"\"\"Generate a new object with the same information as the current spec.\"\"\"\n new = Plot()\n\n # TODO any way to enforce that data does not get mutated?\n new._data = self._data\n\n new._layers.extend(self._layers)\n\n new._scales.update(self._scales)\n new._shares.update(self._shares)\n new._limits.update(self._limits)\n new._labels.update(self._labels)\n new._theme.update(self._theme)\n\n new._facet_spec.update(self._facet_spec)\n new._pair_spec.update(self._pair_spec)\n\n new._figure_spec.update(self._figure_spec)\n new._subplot_spec.update(self._subplot_spec)\n new._layout_spec.update(self._layout_spec)\n\n new._target = self._target\n\n return new\n\n def _theme_with_defaults(self) -> dict[str, Any]:\n\n style_groups = [\n \"axes\", \"figure\", \"font\", \"grid\", \"hatch\", \"legend\", \"lines\",\n \"mathtext\", \"markers\", \"patch\", \"savefig\", \"scatter\",\n \"xaxis\", \"xtick\", \"yaxis\", \"ytick\",\n ]\n base = {\n k: mpl.rcParamsDefault[k] for k in mpl.rcParams\n if any(k.startswith(p) for p in style_groups)\n }\n theme = {\n **base,\n **axes_style(\"darkgrid\"),\n **plotting_context(\"notebook\"),\n \"axes.prop_cycle\": cycler(\"color\", color_palette(\"deep\")),\n }\n theme.update(self._theme)\n return theme\n\n @property\n def _variables(self) -> list[str]:\n\n variables = (\n list(self._data.frame)\n + list(self._pair_spec.get(\"variables\", []))\n + list(self._facet_spec.get(\"variables\", []))\n )\n for layer in self._layers:\n variables.extend(v for v in layer[\"vars\"] if v not in variables)\n\n # Coerce to str in return to appease mypy; we know these will only\n # ever be strings but I don't think we can type a DataFrame that way yet\n return [str(v) for v in variables]\n\n def on(self, target: Axes | SubFigure | Figure) -> Plot:\n \"\"\"\n Provide existing Matplotlib figure or axes for drawing the plot.\n\n When using this method, you will also need to explicitly call a method that\n triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you\n want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot`\n first to compile the plot without rendering it.\n\n Parameters\n ----------\n target : Axes, SubFigure, or Figure\n Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add\n artists without otherwise modifying the figure. Otherwise, subplots will be\n created within the space of the given :class:`matplotlib.figure.Figure` or\n :class:`matplotlib.figure.SubFigure`.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.on.rst\n\n \"\"\"\n accepted_types: tuple # Allow tuple of various length\n if hasattr(mpl.figure, \"SubFigure\"): # Added in mpl 3.4\n accepted_types = (\n mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure\n )\n accepted_types_str = (\n f\"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}\"\n )\n else:\n accepted_types = mpl.axes.Axes, mpl.figure.Figure\n accepted_types_str = f\"{mpl.axes.Axes} or {mpl.figure.Figure}\"\n\n if not isinstance(target, accepted_types):\n err = (\n f\"The `Plot.on` target must be an instance of {accepted_types_str}. \"\n f\"You passed an instance of {target.__class__} instead.\"\n )\n raise TypeError(err)\n\n new = self._clone()\n new._target = target\n\n return new\n\n def add(\n self,\n mark: Mark,\n *transforms: Stat | Mark,\n orient: str | None = None,\n legend: bool = True,\n data: DataSource = None,\n **variables: VariableSpec,\n ) -> Plot:\n \"\"\"\n Specify a layer of the visualization in terms of mark and data transform(s).\n\n This is the main method for specifying how the data should be visualized.\n It can be called multiple times with different arguments to define\n a plot with multiple layers.\n\n Parameters\n ----------\n mark : :class:`Mark`\n The visual representation of the data to use in this layer.\n transforms : :class:`Stat` or :class:`Move`\n Objects representing transforms to be applied before plotting the data.\n Currently, at most one :class:`Stat` can be used, and it\n must be passed first. This constraint will be relaxed in the future.\n orient : \"x\", \"y\", \"v\", or \"h\"\n The orientation of the mark, which also affects how transforms are computed.\n Typically corresponds to the axis that defines groups for aggregation.\n The \"v\" (vertical) and \"h\" (horizontal) options are synonyms for \"x\" / \"y\",\n but may be more intuitive with some marks. When not provided, an\n orientation will be inferred from characteristics of the data and scales.\n legend : bool\n Option to suppress the mark/mappings for this layer from the legend.\n data : DataFrame or dict\n Data source to override the global source provided in the constructor.\n variables : data vectors or identifiers\n Additional layer-specific variables, including variables that will be\n passed directly to the transforms without scaling.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.add.rst\n\n \"\"\"\n if not isinstance(mark, Mark):\n msg = f\"mark must be a Mark instance, not {type(mark)!r}.\"\n raise TypeError(msg)\n\n # TODO This API for transforms was a late decision, and previously Plot.add\n # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances.\n # It will take some work to refactor the internals so that Stat and Move are\n # treated identically, and until then well need to \"unpack\" the transforms\n # here and enforce limitations on the order / types.\n\n stat: Optional[Stat]\n move: Optional[List[Move]]\n error = False\n if not transforms:\n stat, move = None, None\n elif isinstance(transforms[0], Stat):\n stat = transforms[0]\n move = [m for m in transforms[1:] if isinstance(m, Move)]\n error = len(move) != len(transforms) - 1\n else:\n stat = None\n move = [m for m in transforms if isinstance(m, Move)]\n error = len(move) != len(transforms)\n\n if error:\n msg = \" \".join([\n \"Transforms must have at most one Stat type (in the first position),\",\n \"and all others must be a Move type. Given transform type(s):\",\n \", \".join(str(type(t).__name__) for t in transforms) + \".\"\n ])\n raise TypeError(msg)\n\n new = self._clone()\n new._layers.append({\n \"mark\": mark,\n \"stat\": stat,\n \"move\": move,\n # TODO it doesn't work to supply scalars to variables, but it should\n \"vars\": variables,\n \"source\": data,\n \"legend\": legend,\n \"orient\": {\"v\": \"x\", \"h\": \"y\"}.get(orient, orient), # type: ignore\n })\n\n return new\n\n def pair(\n self,\n x: VariableSpecList = None,\n y: VariableSpecList = None,\n wrap: int | None = None,\n cross: bool = True,\n ) -> Plot:\n \"\"\"\n Produce subplots by pairing multiple `x` and/or `y` variables.\n\n Parameters\n ----------\n x, y : sequence(s) of data vectors or identifiers\n Variables that will define the grid of subplots.\n wrap : int\n When using only `x` or `y`, \"wrap\" subplots across a two-dimensional grid\n with this many columns (when using `x`) or rows (when using `y`).\n cross : bool\n When False, zip the `x` and `y` lists such that the first subplot gets the\n first pair, the second gets the second pair, etc. Otherwise, create a\n two-dimensional grid from the cartesian product of the lists.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.pair.rst\n\n \"\"\"\n # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows\n # This may also be possible by setting `wrap=1`, but is that too unobvious?\n # TODO PairGrid features not currently implemented: diagonals, corner\n\n pair_spec: PairSpec = {}\n\n axes = {\"x\": [] if x is None else x, \"y\": [] if y is None else y}\n for axis, arg in axes.items():\n if isinstance(arg, (str, int)):\n err = f\"You must pass a sequence of variable keys to `{axis}`\"\n raise TypeError(err)\n\n pair_spec[\"variables\"] = {}\n pair_spec[\"structure\"] = {}\n\n for axis in \"xy\":\n keys = []\n for i, col in enumerate(axes[axis]):\n key = f\"{axis}{i}\"\n keys.append(key)\n pair_spec[\"variables\"][key] = col\n\n if keys:\n pair_spec[\"structure\"][axis] = keys\n\n if not cross and len(axes[\"x\"]) != len(axes[\"y\"]):\n err = \"Lengths of the `x` and `y` lists must match with cross=False\"\n raise ValueError(err)\n\n pair_spec[\"cross\"] = cross\n pair_spec[\"wrap\"] = wrap\n\n new = self._clone()\n new._pair_spec.update(pair_spec)\n return new\n\n def facet(\n self,\n col: VariableSpec = None,\n row: VariableSpec = None,\n order: OrderSpec | dict[str, OrderSpec] = None,\n wrap: int | None = None,\n ) -> Plot:\n \"\"\"\n Produce subplots with conditional subsets of the data.\n\n Parameters\n ----------\n col, row : data vectors or identifiers\n Variables used to define subsets along the columns and/or rows of the grid.\n Can be references to the global data source passed in the constructor.\n order : list of strings, or dict with dimensional keys\n Define the order of the faceting variables.\n wrap : int\n When using only `col` or `row`, wrap subplots across a two-dimensional\n grid with this many subplots on the faceting dimension.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.facet.rst\n\n \"\"\"\n variables: dict[str, VariableSpec] = {}\n if col is not None:\n variables[\"col\"] = col\n if row is not None:\n variables[\"row\"] = row\n\n structure = {}\n if isinstance(order, dict):\n for dim in [\"col\", \"row\"]:\n dim_order = order.get(dim)\n if dim_order is not None:\n structure[dim] = list(dim_order)\n elif order is not None:\n if col is not None and row is not None:\n err = \" \".join([\n \"When faceting on both col= and row=, passing `order` as a list\"\n \"is ambiguous. Use a dict with 'col' and/or 'row' keys instead.\"\n ])\n raise RuntimeError(err)\n elif col is not None:\n structure[\"col\"] = list(order)\n elif row is not None:\n structure[\"row\"] = list(order)\n\n spec: FacetSpec = {\n \"variables\": variables,\n \"structure\": structure,\n \"wrap\": wrap,\n }\n\n new = self._clone()\n new._facet_spec.update(spec)\n\n return new\n\n # TODO def twin()?\n\n def scale(self, **scales: Scale) -> Plot:\n \"\"\"\n Specify mappings from data units to visual properties.\n\n Keywords correspond to variables defined in the plot, including coordinate\n variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).\n\n A number of \"magic\" arguments are accepted, including:\n - The name of a transform (e.g., `\"log\"`, `\"sqrt\"`)\n - The name of a palette (e.g., `\"viridis\"`, `\"muted\"`)\n - A tuple of values, defining the output range (e.g. `(1, 5)`)\n - A dict, implying a :class:`Nominal` scale (e.g. `{\"a\": .2, \"b\": .5}`)\n - A list of values, implying a :class:`Nominal` scale (e.g. `[\"b\", \"r\"]`)\n\n For more explicit control, pass a scale spec object such as :class:`Continuous`\n or :class:`Nominal`. Or use `None` to use an \"identity\" scale, which treats data\n values as literally encoding visual properties.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.scale.rst\n\n \"\"\"\n new = self._clone()\n new._scales.update(scales)\n return new\n\n def share(self, **shares: bool | str) -> Plot:\n \"\"\"\n Control sharing of axis limits and ticks across subplots.\n\n Keywords correspond to variables defined in the plot, and values can be\n boolean (to share across all subplots), or one of \"row\" or \"col\" (to share\n more selectively across one dimension of a grid).\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.share.rst\n\n \"\"\"\n new = self._clone()\n new._shares.update(shares)\n return new\n\n def limit(self, **limits: tuple[Any, Any]) -> Plot:\n \"\"\"\n Control the range of visible data.\n\n Keywords correspond to variables defined in the plot, and values are a\n `(min, max)` tuple (where either can be `None` to leave unset).\n\n Limits apply only to the axis; data outside the visible range are\n still used for any stat transforms and added to the plot.\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.limit.rst\n\n \"\"\"\n new = self._clone()\n new._limits.update(limits)\n return new\n\n def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot:\n \"\"\"\n Control the labels and titles for axes, legends, and subplots.\n\n Additional keywords correspond to variables defined in the plot.\n Values can be one of the following types:\n\n - string (used literally; pass \"\" to clear the default label)\n - function (called on the default label)\n\n For coordinate variables, the value sets the axis label.\n For semantic variables, the value sets the legend title.\n For faceting variables, `title=` modifies the subplot-specific label,\n while `col=` and/or `row=` add a label for the faceting variable.\n When using a single subplot, `title=` sets its title.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.label.rst\n\n\n \"\"\"\n new = self._clone()\n if title is not None:\n new._labels[\"title\"] = title\n new._labels.update(variables)\n return new\n\n def layout(\n self,\n *,\n size: tuple[float, float] | Default = default,\n engine: str | None | Default = default,\n ) -> Plot:\n \"\"\"\n Control the figure size and layout.\n\n .. note::\n\n Default figure sizes and the API for specifying the figure size are subject\n to change in future \"experimental\" releases of the objects API. The default\n layout engine may also change.\n\n Parameters\n ----------\n size : (width, height)\n Size of the resulting figure, in inches. Size is inclusive of legend when\n using pyplot, but not otherwise.\n engine : {{\"tight\", \"constrained\", None}}\n Name of method for automatically adjusting the layout to remove overlap.\n The default depends on whether :meth:`Plot.on` is used.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.layout.rst\n\n \"\"\"\n # TODO add an \"auto\" mode for figsize that roughly scales with the rcParams\n # figsize (so that works), but expands to prevent subplots from being squished\n # Also should we have height=, aspect=, exclusive with figsize? Or working\n # with figsize when only one is defined?\n\n new = self._clone()\n\n if size is not default:\n new._figure_spec[\"figsize\"] = size\n if engine is not default:\n new._layout_spec[\"engine\"] = engine\n\n return new\n\n # TODO def legend (ugh)\n\n def theme(self, *args: dict[str, Any]) -> Plot:\n \"\"\"\n Control the default appearance of elements in the plot.\n\n .. note::\n\n The API for customizing plot appearance is not yet finalized.\n Currently, the only valid argument is a dict of matplotlib rc parameters.\n (This dict must be passed as a positional argument.)\n\n It is likely that this method will be enhanced in future releases.\n\n Matplotlib rc parameters are documented on the following page:\n https://matplotlib.org/stable/tutorials/introductory/customizing.html\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.theme.rst\n\n \"\"\"\n new = self._clone()\n\n # We can skip this whole block on Python 3.8+ with positional-only syntax\n nargs = len(args)\n if nargs != 1:\n err = f\"theme() takes 1 positional argument, but {nargs} were given\"\n raise TypeError(err)\n\n rc = args[0]\n new._theme.update(rc)\n\n return new\n\n def save(self, loc, **kwargs) -> Plot:\n \"\"\"\n Compile the plot and write it to a buffer or file on disk.\n\n Parameters\n ----------\n loc : str, path, or buffer\n Location on disk to save the figure, or a buffer to write into.\n kwargs\n Other keyword arguments are passed through to\n :meth:`matplotlib.figure.Figure.savefig`.\n\n \"\"\"\n # TODO expose important keyword arguments in our signature?\n with theme_context(self._theme_with_defaults()):\n self._plot().save(loc, **kwargs)\n return self\n\n def show(self, **kwargs) -> None:\n \"\"\"\n Compile the plot and display it by hooking into pyplot.\n\n Calling this method is not necessary to render a plot in notebook context,\n but it may be in other environments (e.g., in a terminal). After compiling the\n plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters).\n\n Unlike other :class:`Plot` methods, there is no return value. This should be\n the last method you call when specifying a plot.\n\n \"\"\"\n # TODO make pyplot configurable at the class level, and when not using,\n # import IPython.display and call on self to populate cell output?\n\n # Keep an eye on whether matplotlib implements \"attaching\" an existing\n # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024\n\n self.plot(pyplot=True).show(**kwargs)\n\n def plot(self, pyplot: bool = False) -> Plotter:\n \"\"\"\n Compile the plot spec and return the Plotter object.\n \"\"\"\n with theme_context(self._theme_with_defaults()):\n return self._plot(pyplot)\n\n def _plot(self, pyplot: bool = False) -> Plotter:\n\n # TODO if we have _target object, pyplot should be determined by whether it\n # is hooked into the pyplot state machine (how do we check?)\n\n plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults())\n\n # Process the variable assignments and initialize the figure\n common, layers = plotter._extract_data(self)\n plotter._setup_figure(self, common, layers)\n\n # Process the scale spec for coordinate variables and transform their data\n coord_vars = [v for v in self._variables if re.match(r\"^x|y\", v)]\n plotter._setup_scales(self, common, layers, coord_vars)\n\n # Apply statistical transform(s)\n plotter._compute_stats(self, layers)\n\n # Process scale spec for semantic variables and coordinates computed by stat\n plotter._setup_scales(self, common, layers)\n\n # TODO Remove these after updating other methods\n # ---- Maybe have debug= param that attaches these when True?\n plotter._data = common\n plotter._layers = layers\n\n # Process the data for each layer and add matplotlib artists\n for layer in layers:\n plotter._plot_layer(self, layer)\n\n # Add various figure decorations\n plotter._make_legend(self)\n plotter._finalize_figure(self)\n\n return plotter"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":158,"id":1486,"name":"edgealpha","nodeType":"Attribute","startLoc":158,"text":"edgealpha"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":159,"id":1487,"name":"edgewidth","nodeType":"Attribute","startLoc":159,"text":"edgewidth"},{"attributeType":"float | Mappable","col":4,"comment":"null","endLoc":160,"id":1488,"name":"edgestyle","nodeType":"Attribute","startLoc":160,"text":"edgestyle"},{"col":4,"comment":"null","endLoc":231,"header":"def __init__(\n self,\n *args: DataSource | VariableSpec,\n data: DataSource = None,\n **variables: VariableSpec,\n )","id":1489,"name":"__init__","nodeType":"Function","startLoc":199,"text":"def __init__(\n self,\n *args: DataSource | VariableSpec,\n data: DataSource = None,\n **variables: VariableSpec,\n ):\n\n if args:\n data, variables = self._resolve_positionals(args, data, variables)\n\n unknown = [x for x in variables if x not in PROPERTIES]\n if unknown:\n err = f\"Plot() got unexpected keyword argument(s): {', '.join(unknown)}\"\n raise TypeError(err)\n\n self._data = PlotData(data, variables)\n\n self._layers = []\n\n self._scales = {}\n self._shares = {}\n self._limits = {}\n self._labels = {}\n self._theme = {}\n\n self._facet_spec = {}\n self._pair_spec = {}\n\n self._figure_spec = {}\n self._subplot_spec = {}\n self._layout_spec = {}\n\n self._target = None"},{"attributeType":"null","col":16,"comment":"null","endLoc":5,"id":1490,"name":"np","nodeType":"Attribute","startLoc":5,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":6,"id":1491,"name":"mpl","nodeType":"Attribute","startLoc":6,"text":"mpl"},{"fileName":"errorband_lineplots.py","filePath":"examples","id":1492,"nodeType":"File","text":"\"\"\"\nTimeseries plot with error bands\n================================\n\n_thumb: .48, .45\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"darkgrid\")\n\n# Load an example dataset with long-form data\nfmri = sns.load_dataset(\"fmri\")\n\n# Plot the responses for different events and regions\nsns.lineplot(x=\"timepoint\", y=\"signal\",\n hue=\"region\", style=\"event\",\n data=fmri)\n"},{"col":4,"comment":"Handle positional arguments, which may contain data / x / y.","endLoc":266,"header":"def _resolve_positionals(\n self,\n args: tuple[DataSource | VariableSpec, ...],\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataSource, dict[str, VariableSpec]]","id":1493,"name":"_resolve_positionals","nodeType":"Function","startLoc":233,"text":"def _resolve_positionals(\n self,\n args: tuple[DataSource | VariableSpec, ...],\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataSource, dict[str, VariableSpec]]:\n \"\"\"Handle positional arguments, which may contain data / x / y.\"\"\"\n if len(args) > 3:\n err = \"Plot() accepts no more than 3 positional arguments (data, x, y).\"\n raise TypeError(err)\n\n # TODO need some clearer way to differentiate data / vector here\n # (There might be an abstract DataFrame class to use here?)\n if isinstance(args[0], (abc.Mapping, pd.DataFrame)):\n if data is not None:\n raise TypeError(\"`data` given by both name and position.\")\n data, args = args[0], args[1:]\n\n if len(args) == 2:\n x, y = args\n elif len(args) == 1:\n x, y = *args, None\n else:\n x = y = None\n\n for name, var in zip(\"yx\", (y, x)):\n if var is not None:\n if name in variables:\n raise TypeError(f\"`{name}` given by both name and position.\")\n # Keep coordinates at the front of the variables dict\n # Cast type because we know this isn't a DataSource at this point\n variables = {name: cast(VariableSpec, var), **variables}\n\n return data, variables"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":1494,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":1495,"name":"fmri","nodeType":"Attribute","startLoc":12,"text":"fmri"},{"col":0,"comment":"","endLoc":7,"header":"errorband_lineplots.py#","id":1496,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nTimeseries plot with error bands\n================================\n\n_thumb: .48, .45\n\n\"\"\"\n\nsns.set_theme(style=\"darkgrid\")\n\nfmri = sns.load_dataset(\"fmri\")\n\nsns.lineplot(x=\"timepoint\", y=\"signal\",\n hue=\"region\", style=\"event\",\n data=fmri)"},{"col":0,"comment":"null","endLoc":640,"header":"def lineplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None, units=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n dashes=True, markers=None, style_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, seed=None,\n orient=\"x\", sort=True, err_style=\"band\", err_kws=None,\n legend=\"auto\", ci=\"deprecated\", ax=None, **kwargs\n)","id":1497,"name":"lineplot","nodeType":"Function","startLoc":597,"text":"def lineplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None, units=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n dashes=True, markers=None, style_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, seed=None,\n orient=\"x\", sort=True, err_style=\"band\", err_kws=None,\n legend=\"auto\", ci=\"deprecated\", ax=None, **kwargs\n):\n\n # Handle deprecation of ci parameter\n errorbar = _deprecate_ci(errorbar, ci)\n\n variables = _LinePlotter.get_semantics(locals())\n p = _LinePlotter(\n data=data, variables=variables,\n estimator=estimator, n_boot=n_boot, seed=seed, errorbar=errorbar,\n sort=sort, orient=orient, err_style=err_style, err_kws=err_kws,\n legend=legend,\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, dashes=dashes, order=style_order)\n\n if ax is None:\n ax = plt.gca()\n\n if style is None and not {\"ls\", \"linestyle\"} & set(kwargs): # XXX\n kwargs[\"dashes\"] = \"\" if dashes is None or isinstance(dashes, bool) else dashes\n\n if not p.has_xy_data:\n return ax\n\n p._attach(ax)\n\n # Other functions have color as an explicit param,\n # and we should probably do that here too\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n p.plot(ax, kwargs)\n return ax"},{"col":4,"comment":"null","endLoc":899,"header":"def plot_bivariate_histogram(\n self,\n common_bins, common_norm,\n thresh, pthresh, pmax,\n color, legend,\n cbar, cbar_ax, cbar_kws,\n estimate_kws,\n **plot_kws,\n )","id":1498,"name":"plot_bivariate_histogram","nodeType":"Function","startLoc":744,"text":"def plot_bivariate_histogram(\n self,\n common_bins, common_norm,\n thresh, pthresh, pmax,\n color, legend,\n cbar, cbar_ax, cbar_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # Default keyword dicts\n cbar_kws = {} if cbar_kws is None else cbar_kws.copy()\n\n # Now initialize the Histogram estimator\n estimator = Histogram(**estimate_kws)\n\n # Do pre-compute housekeeping related to multiple groups\n if set(self.variables) - {\"x\", \"y\"}:\n all_data = self.comp_data.dropna()\n if common_bins:\n estimator.define_bin_params(\n all_data[\"x\"],\n all_data[\"y\"],\n all_data.get(\"weights\", None),\n )\n else:\n common_norm = False\n\n # -- Determine colormap threshold and norm based on the full data\n\n full_heights = []\n for _, sub_data in self.iter_data(from_comp_data=True):\n sub_heights, _ = estimator(\n sub_data[\"x\"], sub_data[\"y\"], sub_data.get(\"weights\", None)\n )\n full_heights.append(sub_heights)\n\n common_color_norm = not set(self.variables) - {\"x\", \"y\"} or common_norm\n\n if pthresh is not None and common_color_norm:\n thresh = self._quantile_to_level(full_heights, pthresh)\n\n plot_kws.setdefault(\"vmin\", 0)\n if common_color_norm:\n if pmax is not None:\n vmax = self._quantile_to_level(full_heights, pmax)\n else:\n vmax = plot_kws.pop(\"vmax\", max(map(np.max, full_heights)))\n else:\n vmax = None\n\n # Get a default color\n # (We won't follow the color cycle here, as multiple plots are unlikely)\n if color is None:\n color = \"C0\"\n\n # --- Loop over data (subsets) and draw the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n if sub_data.empty:\n continue\n\n # Do the histogram computation\n heights, (x_edges, y_edges) = estimator(\n sub_data[\"x\"],\n sub_data[\"y\"],\n weights=sub_data.get(\"weights\", None),\n )\n\n # Check for log scaling on the data axis\n if self._log_scaled(\"x\"):\n x_edges = np.power(10, x_edges)\n if self._log_scaled(\"y\"):\n y_edges = np.power(10, y_edges)\n\n # Apply scaling to normalize across groups\n if estimator.stat != \"count\" and common_norm:\n heights *= len(sub_data) / len(all_data)\n\n # Define the specific kwargs for this artist\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n color = self._hue_map(sub_vars[\"hue\"])\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n else:\n cmap = artist_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n elif cmap is None:\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n\n # Set the upper norm on the colormap\n if not common_color_norm and pmax is not None:\n vmax = self._quantile_to_level(heights, pmax)\n if vmax is not None:\n artist_kws[\"vmax\"] = vmax\n\n # Make cells at or below the threshold transparent\n if not common_color_norm and pthresh:\n thresh = self._quantile_to_level(heights, pthresh)\n if thresh is not None:\n heights = np.ma.masked_less_equal(heights, thresh)\n\n # Get the axes for this plot\n ax = self._get_axes(sub_vars)\n\n # pcolormesh is going to turn the grid off, but we want to keep it\n # I'm not sure if there's a better way to get the grid state\n x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()])\n y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()])\n\n mesh = ax.pcolormesh(\n x_edges,\n y_edges,\n heights.T,\n **artist_kws,\n )\n\n # pcolormesh sets sticky edges, but we only want them if not thresholding\n if thresh is not None:\n mesh.sticky_edges.x[:] = []\n mesh.sticky_edges.y[:] = []\n\n # Add an optional colorbar\n # Note, we want to improve this. When hue is used, it will stack\n # multiple colorbars with redundant ticks in an ugly way.\n # But it's going to take some work to have multiple colorbars that\n # share ticks nicely.\n if cbar:\n ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws)\n\n # Reset the grid state\n if x_grid:\n ax.grid(True, axis=\"x\")\n if y_grid:\n ax.grid(True, axis=\"y\")\n\n # --- Finalize the plot\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n artist = partial(mpl.patches.Patch)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, True, False, \"layer\", 1, artist_kws, {},\n )"},{"col":4,"comment":"null","endLoc":376,"header":"def __init__(\n self, *,\n data=None, variables={},\n estimator=None, n_boot=None, seed=None, errorbar=None,\n sort=True, orient=\"x\", err_style=None, err_kws=None, legend=None\n )","id":1499,"name":"__init__","nodeType":"Function","startLoc":351,"text":"def __init__(\n self, *,\n data=None, variables={},\n estimator=None, n_boot=None, seed=None, errorbar=None,\n sort=True, orient=\"x\", err_style=None, err_kws=None, legend=None\n ):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * mpl.rcParams[\"lines.linewidth\"]\n )\n\n super().__init__(data=data, variables=variables)\n\n self.estimator = estimator\n self.errorbar = errorbar\n self.n_boot = n_boot\n self.seed = seed\n self.sort = sort\n self.orient = orient\n self.err_style = err_style\n self.err_kws = {} if err_kws is None else err_kws\n\n self.legend = legend"},{"col":4,"comment":"null","endLoc":318,"header":"def test_heatmap_annotation_overwrite_kws(self)","id":1500,"name":"test_heatmap_annotation_overwrite_kws","nodeType":"Function","startLoc":310,"text":"def test_heatmap_annotation_overwrite_kws(self):\n\n annot_kws = dict(color=\"0.3\", va=\"bottom\", ha=\"left\")\n ax = mat.heatmap(self.df_norm, annot=True, fmt=\".1f\",\n annot_kws=annot_kws)\n for text in ax.texts:\n assert text.get_color() == \"0.3\"\n assert text.get_ha() == \"left\"\n assert text.get_va() == \"bottom\""},{"col":4,"comment":"null","endLoc":330,"header":"def test_heatmap_annotation_with_mask(self)","id":1508,"name":"test_heatmap_annotation_with_mask","nodeType":"Function","startLoc":320,"text":"def test_heatmap_annotation_with_mask(self):\n\n df = pd.DataFrame(data={'a': [1, 1, 1],\n 'b': [2, np.nan, 2],\n 'c': [3, 3, np.nan]})\n mask = np.isnan(df.values)\n df_masked = np.ma.masked_where(mask, df)\n ax = mat.heatmap(df, annot=True, fmt='.1f', mask=mask)\n assert len(df_masked.compressed()) == len(ax.texts)\n for val, text in zip(df_masked.compressed(), ax.texts):\n assert f\"{val:.1f}\" == text.get_text()"},{"col":4,"comment":"null","endLoc":338,"header":"def test_heatmap_annotation_mesh_colors(self)","id":1509,"name":"test_heatmap_annotation_mesh_colors","nodeType":"Function","startLoc":332,"text":"def test_heatmap_annotation_mesh_colors(self):\n\n ax = mat.heatmap(self.df_norm, annot=True)\n mesh = ax.collections[0]\n assert len(mesh.get_facecolors()) == self.df_norm.values.size\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":348,"header":"def test_heatmap_annotation_other_data(self)","id":1510,"name":"test_heatmap_annotation_other_data","nodeType":"Function","startLoc":340,"text":"def test_heatmap_annotation_other_data(self):\n annot_data = self.df_norm + 10\n\n ax = mat.heatmap(self.df_norm, annot=annot_data, fmt=\".1f\",\n annot_kws={\"fontsize\": 14})\n\n for val, text in zip(annot_data.values.flat, ax.texts):\n assert text.get_text() == f\"{val:.1f}\"\n assert text.get_fontsize() == 14"},{"col":4,"comment":"null","endLoc":354,"header":"def test_heatmap_annotation_different_shapes(self)","id":1511,"name":"test_heatmap_annotation_different_shapes","nodeType":"Function","startLoc":350,"text":"def test_heatmap_annotation_different_shapes(self):\n\n annot_data = self.df_norm.iloc[:-1]\n with pytest.raises(ValueError):\n mat.heatmap(self.df_norm, annot=annot_data)"},{"col":4,"comment":"null","endLoc":360,"header":"def test_heatmap_annotation_with_limited_ticklabels(self)","id":1512,"name":"test_heatmap_annotation_with_limited_ticklabels","nodeType":"Function","startLoc":356,"text":"def test_heatmap_annotation_with_limited_ticklabels(self):\n ax = mat.heatmap(self.df_norm, fmt=\".2f\", annot=True,\n xticklabels=False, yticklabels=False)\n for val, text in zip(self.x_norm.flat, ax.texts):\n assert text.get_text() == f\"{val:.2f}\""},{"col":4,"comment":"null","endLoc":377,"header":"def test_heatmap_cbar(self)","id":1513,"name":"test_heatmap_cbar","nodeType":"Function","startLoc":362,"text":"def test_heatmap_cbar(self):\n\n f = plt.figure()\n mat.heatmap(self.df_norm)\n assert len(f.axes) == 2\n plt.close(f)\n\n f = plt.figure()\n mat.heatmap(self.df_norm, cbar=False)\n assert len(f.axes) == 1\n plt.close(f)\n\n f, (ax1, ax2) = plt.subplots(2)\n mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2)\n assert len(f.axes) == 2\n plt.close(f)"},{"col":4,"comment":"null","endLoc":394,"header":"@pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_heatmap_axes(self)","id":1514,"name":"test_heatmap_axes","nodeType":"Function","startLoc":379,"text":"@pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_heatmap_axes(self):\n\n ax = mat.heatmap(self.df_norm)\n\n xtl = [int(l.get_text()) for l in ax.get_xticklabels()]\n assert xtl == list(self.df_norm.columns)\n ytl = [l.get_text() for l in ax.get_yticklabels()]\n assert ytl == list(self.df_norm.index)\n\n assert ax.get_xlabel() == \"\"\n assert ax.get_ylabel() == \"letters\"\n\n assert ax.get_xlim() == (0, 8)\n assert ax.get_ylim() == (4, 0)"},{"id":1515,"name":"doc/sphinxext","nodeType":"Package"},{"fileName":"tutorial_builder.py","filePath":"doc/sphinxext","id":1516,"nodeType":"File","text":"from pathlib import Path\nimport warnings\n\nfrom jinja2 import Environment\nimport yaml\n\nimport numpy as np\nimport matplotlib as mpl\nimport seaborn as sns\nimport seaborn.objects as so\n\n\nTEMPLATE = \"\"\"\n:notoc:\n\n.. _tutorial:\n\nUser guide and tutorial\n=======================\n{% for section in sections %}\n{{ section.header }}\n{% for page in section.pages %}\n.. grid:: 1\n :gutter: 2\n\n .. grid-item-card::\n\n .. grid:: 2\n\n .. grid-item::\n :columns: 3\n\n .. image:: ./tutorial/{{ page }}.svg\n :target: ./tutorial/{{ page }}.html\n\n .. grid-item::\n :columns: 9\n :margin: auto\n\n .. toctree::\n :maxdepth: 2\n\n tutorial/{{ page }}\n{% endfor %}\n{% endfor %}\n\"\"\"\n\n\ndef main(app):\n\n content_yaml = Path(app.builder.srcdir) / \"tutorial.yaml\"\n tutorial_rst = Path(app.builder.srcdir) / \"tutorial.rst\"\n\n tutorial_dir = Path(app.builder.srcdir) / \"tutorial\"\n tutorial_dir.mkdir(exist_ok=True)\n\n with open(content_yaml) as fid:\n sections = yaml.load(fid, yaml.BaseLoader)\n\n for section in sections:\n title = section[\"title\"]\n section[\"header\"] = \"\\n\".join([title, \"-\" * len(title)]) if title else \"\"\n\n env = Environment().from_string(TEMPLATE)\n content = env.render(sections=sections)\n\n with open(tutorial_rst, \"w\") as fid:\n fid.write(content)\n\n for section in sections:\n for page in section[\"pages\"]:\n if (\n not (svg_path := tutorial_dir / f\"{page}.svg\").exists()\n or svg_path.stat().st_mtime < Path(__file__).stat().st_mtime\n ):\n write_thumbnail(svg_path, page)\n\n\ndef write_thumbnail(svg_path, page):\n\n with (\n sns.axes_style(\"dark\"),\n sns.plotting_context(\"notebook\"),\n sns.color_palette(\"deep\")\n ):\n fig = globals()[page]()\n for ax in fig.axes:\n ax.set(xticklabels=[], yticklabels=[], xlabel=\"\", ylabel=\"\", title=\"\")\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n fig.tight_layout()\n fig.savefig(svg_path, format=\"svg\")\n\n\ndef introduction():\n\n tips = sns.load_dataset(\"tips\")\n fmri = sns.load_dataset(\"fmri\").query(\"region == 'parietal'\")\n penguins = sns.load_dataset(\"penguins\")\n\n f = mpl.figure.Figure(figsize=(5, 5))\n with sns.axes_style(\"whitegrid\"):\n f.subplots(2, 2)\n\n sns.scatterplot(\n tips, x=\"total_bill\", y=\"tip\", hue=\"sex\", size=\"size\",\n alpha=.75, palette=[\"C0\", \".5\"], legend=False, ax=f.axes[0],\n )\n sns.kdeplot(\n tips.query(\"size != 5\"), x=\"total_bill\", hue=\"size\",\n palette=\"blend:C0,.5\", fill=True, linewidth=.5,\n legend=False, common_norm=False, ax=f.axes[1],\n )\n sns.lineplot(\n fmri, x=\"timepoint\", y=\"signal\", hue=\"event\",\n errorbar=(\"se\", 2), legend=False, palette=[\"C0\", \".5\"], ax=f.axes[2],\n )\n sns.boxplot(\n penguins, x=\"bill_depth_mm\", y=\"species\", hue=\"sex\",\n whiskerprops=dict(linewidth=1.5), medianprops=dict(linewidth=1.5),\n boxprops=dict(linewidth=1.5), capprops=dict(linewidth=0),\n width=.5, palette=[\"C0\", \".8\"], whis=5, ax=f.axes[3],\n )\n f.axes[3].legend_ = None\n for ax in f.axes:\n ax.set(xticks=[], yticks=[])\n return f\n\n\ndef function_overview():\n\n from matplotlib.patches import FancyBboxPatch\n\n f = mpl.figure.Figure(figsize=(7, 5))\n with sns.axes_style(\"white\"):\n ax = f.subplots()\n f.subplots_adjust(0, 0, 1, 1)\n ax.set_axis_off()\n ax.set(xlim=(0, 1), ylim=(0, 1))\n\n deep = sns.color_palette(\"deep\")\n colors = dict(relational=deep[0], distributions=deep[1], categorical=deep[2])\n dark = sns.color_palette(\"dark\")\n text_colors = dict(relational=dark[0], distributions=dark[1], categorical=dark[2])\n\n functions = dict(\n relational=[\"scatterplot\", \"lineplot\"],\n distributions=[\"histplot\", \"kdeplot\", \"ecdfplot\", \"rugplot\"],\n categorical=[\n \"stripplot\", \"swarmplot\", \"boxplot\", \"violinplot\", \"pointplot\", \"barplot\"\n ],\n )\n pad, w, h = .06, .2, .15\n xs, y = np.arange(0, 1, 1 / 3) + pad * 1.05, .7\n for x, mod in zip(xs, functions):\n color = colors[mod] + (.2,)\n text_color = text_colors[mod]\n ax.add_artist(FancyBboxPatch((x, y), w, h, f\"round,pad={pad}\", color=\"white\"))\n ax.add_artist(FancyBboxPatch(\n (x, y), w, h, f\"round,pad={pad}\",\n linewidth=1, edgecolor=text_color, facecolor=color,\n ))\n ax.text(\n x + w / 2, y + h / 2, f\"{mod[:3]}plot\\n({mod})\",\n ha=\"center\", va=\"center\", size=20, color=text_color\n )\n for i, func in enumerate(functions[mod]):\n x_i, y_i = x + w / 2, y - i * .1 - h / 2 - pad\n xy = x_i - w / 2, y_i - pad / 3\n ax.add_artist(\n FancyBboxPatch(xy, w, h / 4, f\"round,pad={pad / 3}\", color=\"white\")\n )\n ax.add_artist(FancyBboxPatch(\n xy, w, h / 4, f\"round,pad={pad / 3}\",\n linewidth=1, edgecolor=text_color, facecolor=color\n ))\n ax.text(x_i, y_i, func, ha=\"center\", va=\"center\", size=16, color=text_color)\n ax.plot([x_i, x_i], [y, y_i], zorder=-100, color=text_color, lw=1)\n return f\n\n\ndef data_structure():\n\n f = mpl.figure.Figure(figsize=(7, 5))\n gs = mpl.gridspec.GridSpec(\n figure=f, ncols=6, nrows=2, height_ratios=(1, 20),\n left=0, right=.35, bottom=0, top=.9, wspace=.1, hspace=.01\n )\n colors = [c + (.5,) for c in sns.color_palette(\"deep\")]\n f.add_subplot(gs[0, :], facecolor=\".8\")\n for i in range(gs.ncols):\n f.add_subplot(gs[1:, i], facecolor=colors[i])\n\n gs = mpl.gridspec.GridSpec(\n figure=f, ncols=2, nrows=2, height_ratios=(1, 8), width_ratios=(1, 11),\n left=.4, right=1, bottom=.2, top=.8, wspace=.015, hspace=.02\n )\n f.add_subplot(gs[0, 1:], facecolor=colors[2])\n f.add_subplot(gs[1:, 0], facecolor=colors[1])\n f.add_subplot(gs[1, 1], facecolor=colors[0])\n return f\n\n\ndef error_bars():\n\n diamonds = sns.load_dataset(\"diamonds\")\n with sns.axes_style(\"whitegrid\"):\n g = sns.catplot(\n diamonds, x=\"carat\", y=\"clarity\", hue=\"clarity\", kind=\"point\",\n errorbar=(\"sd\", .5), join=False, legend=False, facet_kws={\"despine\": False},\n palette=\"ch:s=-.2,r=-.2,d=.4,l=.6_r\", scale=.75, capsize=.3,\n )\n g.ax.yaxis.set_inverted(False)\n return g.figure\n\n\ndef properties():\n\n f = mpl.figure.Figure(figsize=(5, 5))\n\n x = np.arange(1, 11)\n y = np.zeros_like(x)\n\n p = so.Plot(x, y)\n ps = 14\n plots = [\n p.add(so.Dot(pointsize=ps), color=map(str, x)),\n p.add(so.Dot(color=\".3\", pointsize=ps), alpha=x),\n p.add(so.Dot(color=\".9\", pointsize=ps, edgewidth=2), edgecolor=x),\n p.add(so.Dot(color=\".3\"), pointsize=x).scale(pointsize=(4, 18)),\n p.add(so.Dot(pointsize=ps, color=\".9\", edgecolor=\".2\"), edgewidth=x),\n p.add(so.Dot(pointsize=ps, color=\".3\"), marker=map(str, x)),\n p.add(so.Dot(pointsize=ps, color=\".3\", marker=\"x\"), stroke=x),\n ]\n\n with sns.axes_style(\"ticks\"):\n axs = f.subplots(len(plots))\n for p, ax in zip(plots, axs):\n p.on(ax).plot()\n ax.set(xticks=x, yticks=[], xticklabels=[], ylim=(-.2, .3))\n sns.despine(ax=ax, left=True)\n f.legends = []\n return f\n\n\ndef objects_interface():\n\n f = mpl.figure.Figure(figsize=(5, 4))\n C = sns.color_palette(\"deep\")\n ax = f.subplots()\n fontsize = 22\n rects = [((.135, .50), .69), ((.275, .38), .26), ((.59, .38), .40)]\n for i, (xy, w) in enumerate(rects):\n ax.add_artist(mpl.patches.Rectangle(xy, w, .09, color=C[i], alpha=.2, lw=0))\n ax.text(0, .52, \"Plot(data, 'x', 'y', color='var1')\", size=fontsize, color=\".2\")\n ax.text(0, .40, \".add(Dot(alpha=.5), marker='var2')\", size=fontsize, color=\".2\")\n annots = [\n (\"Mapped\\nin all layers\", (.48, .62), (0, 55)),\n (\"Set directly\", (.41, .35), (0, -55)),\n (\"Mapped\\nin this layer\", (.80, .35), (0, -55)),\n ]\n for i, (text, xy, xytext) in enumerate(annots):\n ax.annotate(\n text, xy, xytext,\n textcoords=\"offset points\", fontsize=18, ha=\"center\", va=\"center\",\n arrowprops=dict(arrowstyle=\"->\", linewidth=1.5, color=C[i]), color=C[i],\n )\n ax.set_axis_off()\n f.subplots_adjust(0, 0, 1, 1)\n\n return f\n\n\ndef relational():\n\n mpg = sns.load_dataset(\"mpg\")\n with sns.axes_style(\"ticks\"):\n g = sns.relplot(\n data=mpg, x=\"horsepower\", y=\"mpg\", size=\"displacement\", hue=\"weight\",\n sizes=(50, 500), hue_norm=(2000, 4500), alpha=.75, legend=False,\n palette=\"ch:start=-.5,rot=.7,dark=.3,light=.7_r\",\n )\n g.figure.set_size_inches(5, 5)\n return g.figure\n\n\ndef distributions():\n\n penguins = sns.load_dataset(\"penguins\").dropna()\n with sns.axes_style(\"white\"):\n g = sns.displot(\n penguins, x=\"flipper_length_mm\", row=\"island\",\n binwidth=4, kde=True, line_kws=dict(linewidth=2), legend=False,\n )\n sns.despine(left=True)\n g.figure.set_size_inches(5, 5)\n return g.figure\n\n\ndef categorical():\n\n penguins = sns.load_dataset(\"penguins\").dropna()\n with sns.axes_style(\"whitegrid\"):\n g = sns.catplot(\n penguins, x=\"sex\", y=\"body_mass_g\", hue=\"island\", col=\"sex\",\n kind=\"box\", whis=np.inf, legend=False, sharex=False,\n )\n sns.despine(left=True)\n g.figure.set_size_inches(5, 5)\n return g.figure\n\n\ndef regression():\n\n anscombe = sns.load_dataset(\"anscombe\")\n with sns.axes_style(\"white\"):\n g = sns.lmplot(\n anscombe, x=\"x\", y=\"y\", hue=\"dataset\", col=\"dataset\", col_wrap=2,\n scatter_kws=dict(edgecolor=\".2\", facecolor=\".7\", s=80),\n line_kws=dict(lw=4), ci=None,\n )\n g.set(xlim=(2, None), ylim=(2, None))\n g.figure.set_size_inches(5, 5)\n return g.figure\n\n\ndef axis_grids():\n\n penguins = sns.load_dataset(\"penguins\").sample(200, random_state=0)\n with sns.axes_style(\"ticks\"):\n g = sns.pairplot(\n penguins.drop(\"flipper_length_mm\", axis=1),\n diag_kind=\"kde\", diag_kws=dict(fill=False),\n plot_kws=dict(s=40, fc=\"none\", ec=\"C0\", alpha=.75, linewidth=.75),\n )\n g.figure.set_size_inches(5, 5)\n return g.figure\n\n\ndef aesthetics():\n\n f = mpl.figure.Figure(figsize=(5, 5))\n for i, style in enumerate([\"darkgrid\", \"white\", \"ticks\", \"whitegrid\"], 1):\n with sns.axes_style(style):\n ax = f.add_subplot(2, 2, i)\n ax.set(xticks=[0, .25, .5, .75, 1], yticks=[0, .25, .5, .75, 1])\n sns.despine(ax=f.axes[1])\n sns.despine(ax=f.axes[2])\n return f\n\n\ndef color_palettes():\n\n f = mpl.figure.Figure(figsize=(5, 5))\n palettes = [\"deep\", \"husl\", \"gray\", \"ch:\", \"mako\", \"vlag\", \"icefire\"]\n axs = f.subplots(len(palettes))\n x = np.arange(10)\n for ax, name in zip(axs, palettes):\n cmap = mpl.colors.ListedColormap(sns.color_palette(name, x.size))\n ax.pcolormesh(x[None, :], linewidth=.5, edgecolor=\"w\", alpha=.8, cmap=cmap)\n ax.set_axis_off()\n return f\n\n\ndef setup(app):\n app.connect(\"builder-inited\", main)\n"},{"col":4,"comment":"null","endLoc":1034,"header":"def plot_univariate_density(\n self,\n multiple,\n common_norm,\n common_grid,\n warn_singular,\n fill,\n color,\n legend,\n estimate_kws,\n **plot_kws,\n )","id":1517,"name":"plot_univariate_density","nodeType":"Function","startLoc":901,"text":"def plot_univariate_density(\n self,\n multiple,\n common_norm,\n common_grid,\n warn_singular,\n fill,\n color,\n legend,\n estimate_kws,\n **plot_kws,\n ):\n\n # Handle conditional defaults\n if fill is None:\n fill = multiple in (\"stack\", \"fill\")\n\n # Preprocess the matplotlib keyword dictionaries\n if fill:\n artist = mpl.collections.PolyCollection\n else:\n artist = mpl.lines.Line2D\n plot_kws = _normalize_kwargs(plot_kws, artist)\n\n # Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\"], multiple)\n\n # Always share the evaluation grid when stacking\n subsets = bool(set(self.variables) - {\"x\", \"y\"})\n if subsets and multiple in (\"stack\", \"fill\"):\n common_grid = True\n\n # Check if the data axis is log scaled\n log_scale = self._log_scaled(self.data_variable)\n\n # Do the computation\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular,\n )\n\n # Adjust densities based on the `multiple` rule\n densities, baselines = self._resolve_multiple(densities, multiple)\n\n # Control the interaction with autoscaling by defining sticky_edges\n # i.e. we don't want autoscale margins below the density curve\n sticky_density = (0, 1) if multiple == \"fill\" else (0, np.inf)\n\n if multiple == \"fill\":\n # Filled plots should not have any margins\n sticky_support = densities.index.min(), densities.index.max()\n else:\n sticky_support = []\n\n if fill:\n if multiple == \"layer\":\n default_alpha = .25\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n # Now iterate through the subsets and draw the densities\n # We go backwards so stacked densities read from top-to-bottom\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n # Extract the support grid and density curve for this level\n key = tuple(sub_vars.items())\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n fill_from = baselines[key]\n\n ax = self._get_axes(sub_vars)\n\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, False, multiple, sub_color, alpha\n )\n\n # Either plot a curve with observation values on the x axis\n if \"x\" in self.variables:\n\n if fill:\n artist = ax.fill_between(support, fill_from, density, **artist_kws)\n\n else:\n artist, = ax.plot(support, density, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_support\n artist.sticky_edges.y[:] = sticky_density\n\n # Or plot a curve with observation values on the y axis\n else:\n if fill:\n artist = ax.fill_betweenx(support, fill_from, density, **artist_kws)\n else:\n artist, = ax.plot(density, support, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_density\n artist.sticky_edges.y[:] = sticky_support\n\n # --- Finalize the plot ----\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = \"Density\"\n if self.data_variable == \"y\":\n default_x = \"Density\"\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, multiple, alpha, plot_kws, {},\n )"},{"fileName":"grouped_barplot.py","filePath":"examples","id":1518,"nodeType":"File","text":"\"\"\"\nGrouped barplots\n================\n\n_thumb: .36, .5\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\npenguins = sns.load_dataset(\"penguins\")\n\n# Draw a nested barplot by species and sex\ng = sns.catplot(\n data=penguins, kind=\"bar\",\n x=\"species\", y=\"body_mass_g\", hue=\"sex\",\n errorbar=\"sd\", palette=\"dark\", alpha=.6, height=6\n)\ng.despine(left=True)\ng.set_axis_labels(\"\", \"Body mass (g)\")\ng.legend.set_title(\"\")\n"},{"attributeType":"str","col":4,"comment":"null","endLoc":421,"id":1519,"name":"null_value","nodeType":"Attribute","startLoc":421,"text":"null_value"},{"className":"TextAlignment","col":0,"comment":"null","endLoc":517,"id":1520,"nodeType":"Class","startLoc":516,"text":"class TextAlignment(ObjectProperty):\n legend = False"},{"attributeType":"bool","col":4,"comment":"null","endLoc":517,"id":1521,"name":"legend","nodeType":"Attribute","startLoc":517,"text":"legend"},{"className":"Path","col":0,"comment":"null","endLoc":267,"id":1522,"nodeType":"Class","startLoc":103,"text":"class Path(PurePath):\n if sys.version_info >= (3, 12):\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor]\n else:\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n\n @classmethod\n def cwd(cls) -> Self: ...\n if sys.version_info >= (3, 10):\n def stat(self, *, follow_symlinks: bool = True) -> stat_result: ...\n def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ...\n else:\n def stat(self) -> stat_result: ...\n def chmod(self, mode: int) -> None: ...\n\n if sys.version_info >= (3, 13):\n @classmethod\n def from_uri(cls, uri: str) -> Self: ...\n def is_dir(self, *, follow_symlinks: bool = True) -> bool: ...\n def is_file(self, *, follow_symlinks: bool = True) -> bool: ...\n def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: ...\n else:\n def __enter__(self) -> Self: ...\n def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n def is_dir(self) -> bool: ...\n def is_file(self) -> bool: ...\n def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ...\n\n if sys.version_info >= (3, 13):\n def glob(\n self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n ) -> Generator[Self, None, None]: ...\n def rglob(\n self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n ) -> Generator[Self, None, None]: ...\n elif sys.version_info >= (3, 12):\n def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n else:\n def glob(self, pattern: str) -> Generator[Self, None, None]: ...\n def rglob(self, pattern: str) -> Generator[Self, None, None]: ...\n\n if sys.version_info >= (3, 12):\n def exists(self, *, follow_symlinks: bool = True) -> bool: ...\n else:\n def exists(self) -> bool: ...\n\n def is_symlink(self) -> bool: ...\n def is_socket(self) -> bool: ...\n def is_fifo(self) -> bool: ...\n def is_block_device(self) -> bool: ...\n def is_char_device(self) -> bool: ...\n if sys.version_info >= (3, 12):\n def is_junction(self) -> bool: ...\n\n def iterdir(self) -> Generator[Self, None, None]: ...\n def lchmod(self, mode: int) -> None: ...\n def lstat(self) -> stat_result: ...\n def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ...\n # Adapted from builtins.open\n # Text mode: always returns a TextIOWrapper\n # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this.\n @overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper: ...\n # Unbuffered binary mode: returns a FileIO\n @overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO: ...\n # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter\n @overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom: ...\n @overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter: ...\n @overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader: ...\n # Buffering cannot be determined: fall back to BinaryIO\n @overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO: ...\n # Fallback if mode is not specified\n @overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]: ...\n if sys.platform != \"win32\":\n # These methods do \"exist\" on Windows, but they always raise NotImplementedError,\n # so it's safer to pretend they don't exist\n if sys.version_info >= (3, 13):\n def owner(self, *, follow_symlinks: bool = True) -> str: ...\n def group(self, *, follow_symlinks: bool = True) -> str: ...\n else:\n def owner(self) -> str: ...\n def group(self) -> str: ...\n\n # This method does \"exist\" on Windows on <3.12, but always raises NotImplementedError\n # On py312+, it works properly on Windows, as with all other platforms\n if sys.platform != \"win32\" or sys.version_info >= (3, 12):\n def is_mount(self) -> bool: ...\n\n if sys.version_info >= (3, 9):\n def readlink(self) -> Self: ...\n\n def rename(self, target: str | PurePath) -> Self: ...\n def replace(self, target: str | PurePath) -> Self: ...\n def resolve(self, strict: bool = False) -> Self: ...\n def rmdir(self) -> None: ...\n def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ...\n if sys.version_info >= (3, 10):\n def hardlink_to(self, target: StrOrBytesPath) -> None: ...\n\n def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ...\n def unlink(self, missing_ok: bool = False) -> None: ...\n @classmethod\n def home(cls) -> Self: ...\n def absolute(self) -> Self: ...\n def expanduser(self) -> Self: ...\n def read_bytes(self) -> bytes: ...\n def samefile(self, other_path: StrPath) -> bool: ...\n def write_bytes(self, data: ReadableBuffer) -> int: ...\n if sys.version_info >= (3, 10):\n def write_text(\n self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> int: ...\n else:\n def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ...\n if sys.version_info < (3, 12):\n if sys.version_info >= (3, 10):\n @deprecated(\"Deprecated as of Python 3.10 and removed in Python 3.12. Use hardlink_to() instead.\")\n def link_to(self, target: StrOrBytesPath) -> None: ...\n else:\n def link_to(self, target: StrOrBytesPath) -> None: ...\n if sys.version_info >= (3, 12):\n def walk(\n self, top_down: bool = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ...\n ) -> Iterator[tuple[Self, list[str], list[str]]]: ..."},{"className":"HorizontalAlignment","col":0,"comment":"null","endLoc":524,"id":1523,"nodeType":"Class","startLoc":520,"text":"class HorizontalAlignment(TextAlignment):\n\n def _default_values(self, n: int) -> list:\n vals = itertools.cycle([\"left\", \"right\"])\n return [next(vals) for _ in range(n)]"},{"col":4,"comment":"null","endLoc":524,"header":"def _default_values(self, n: int) -> list","id":1524,"name":"_default_values","nodeType":"Function","startLoc":522,"text":"def _default_values(self, n: int) -> list:\n vals = itertools.cycle([\"left\", \"right\"])\n return [next(vals) for _ in range(n)]"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":1525,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":1526,"name":"penguins","nodeType":"Attribute","startLoc":10,"text":"penguins"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":1527,"name":"g","nodeType":"Attribute","startLoc":13,"text":"g"},{"col":4,"comment":"null","endLoc":1220,"header":"def plot_bivariate_density(\n self,\n common_norm,\n fill,\n levels,\n thresh,\n color,\n legend,\n cbar,\n warn_singular,\n cbar_ax,\n cbar_kws,\n estimate_kws,\n **contour_kws,\n )","id":1528,"name":"plot_bivariate_density","nodeType":"Function","startLoc":1036,"text":"def plot_bivariate_density(\n self,\n common_norm,\n fill,\n levels,\n thresh,\n color,\n legend,\n cbar,\n warn_singular,\n cbar_ax,\n cbar_kws,\n estimate_kws,\n **contour_kws,\n ):\n\n contour_kws = contour_kws.copy()\n\n estimator = KDE(**estimate_kws)\n\n if not set(self.variables) - {\"x\", \"y\"}:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n\n # Loop through the subsets and estimate the KDEs\n densities, supports = {}, {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set\n observations = sub_data[[\"x\", \"y\"]]\n min_variance = observations.var().fillna(0).min()\n observations = observations[\"x\"], observations[\"y\"]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n else:\n weights = None\n\n # Estimate the density of observations at this level\n singular = math.isclose(min_variance, 0)\n try:\n if not singular:\n density, support = estimator(*observations, weights=weights)\n except np.linalg.LinAlgError:\n # Testing for 0 variance doesn't catch all cases where scipy raises,\n # but we can also get a ValueError, so we need this convoluted approach\n singular = True\n\n if singular:\n msg = (\n \"KDE cannot be estimated (0 variance or perfect covariance). \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning, stacklevel=3)\n continue\n\n # Transform the support grid back to the original scale\n xx, yy = support\n if self._log_scaled(\"x\"):\n xx = np.power(10, xx)\n if self._log_scaled(\"y\"):\n yy = np.power(10, yy)\n support = xx, yy\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= len(sub_data) / len(all_data)\n\n key = tuple(sub_vars.items())\n densities[key] = density\n supports[key] = support\n\n # Define a grid of iso-proportion levels\n if thresh is None:\n thresh = 0\n if isinstance(levels, Number):\n levels = np.linspace(thresh, 1, levels)\n else:\n if min(levels) < 0 or max(levels) > 1:\n raise ValueError(\"levels must be in [0, 1]\")\n\n # Transform from iso-proportions to iso-densities\n if common_norm:\n common_levels = self._quantile_to_level(\n list(densities.values()), levels,\n )\n draw_levels = {k: common_levels for k in densities}\n else:\n draw_levels = {\n k: self._quantile_to_level(d, levels)\n for k, d in densities.items()\n }\n\n # Define the coloring of the contours\n if \"hue\" in self.variables:\n for param in [\"cmap\", \"colors\"]:\n if param in contour_kws:\n msg = f\"{param} parameter ignored when using hue mapping.\"\n warnings.warn(msg, UserWarning)\n contour_kws.pop(param)\n else:\n\n # Work out a default coloring of the contours\n coloring_given = set(contour_kws) & {\"cmap\", \"colors\"}\n if fill and not coloring_given:\n cmap = self._cmap_from_color(color)\n contour_kws[\"cmap\"] = cmap\n if not fill and not coloring_given:\n contour_kws[\"colors\"] = [color]\n\n # Use our internal colormap lookup\n cmap = contour_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n if cmap is not None:\n contour_kws[\"cmap\"] = cmap\n\n # Loop through the subsets again and plot the data\n for sub_vars, _ in self.iter_data(\"hue\"):\n\n if \"hue\" in sub_vars:\n color = self._hue_map(sub_vars[\"hue\"])\n if fill:\n contour_kws[\"cmap\"] = self._cmap_from_color(color)\n else:\n contour_kws[\"colors\"] = [color]\n\n ax = self._get_axes(sub_vars)\n\n # Choose the function to plot with\n # TODO could add a pcolormesh based option as well\n # Which would look something like element=\"raster\"\n if fill:\n contour_func = ax.contourf\n else:\n contour_func = ax.contour\n\n key = tuple(sub_vars.items())\n if key not in densities:\n continue\n density = densities[key]\n xx, yy = supports[key]\n\n label = contour_kws.pop(\"label\", None)\n\n cset = contour_func(\n xx, yy, density,\n levels=draw_levels[key],\n **contour_kws,\n )\n\n if \"hue\" not in self.variables:\n cset.collections[0].set_label(label)\n\n # Add a color bar representing the contour heights\n # Note: this shows iso densities, not iso proportions\n # See more notes in histplot about how this could be improved\n if cbar:\n cbar_kws = {} if cbar_kws is None else cbar_kws\n ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)\n\n # --- Finalize the plot\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, \"layer\", 1, artist_kws, {},\n )"},{"className":"PurePath","col":0,"comment":"null","endLoc":98,"id":1529,"nodeType":"Class","startLoc":29,"text":"class PurePath(PathLike[str]):\n if sys.version_info >= (3, 13):\n parser: ClassVar[types.ModuleType]\n def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ...\n\n @property\n def parts(self) -> tuple[str, ...]: ...\n @property\n def drive(self) -> str: ...\n @property\n def root(self) -> str: ...\n @property\n def anchor(self) -> str: ...\n @property\n def name(self) -> str: ...\n @property\n def suffix(self) -> str: ...\n @property\n def suffixes(self) -> list[str]: ...\n @property\n def stem(self) -> str: ...\n if sys.version_info >= (3, 12):\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n def __init__(self, *args: StrPath) -> None: ... # pyright: ignore[reportInconsistentConstructor]\n else:\n def __new__(cls, *args: StrPath) -> Self: ...\n\n def __hash__(self) -> int: ...\n def __fspath__(self) -> str: ...\n def __lt__(self, other: PurePath) -> bool: ...\n def __le__(self, other: PurePath) -> bool: ...\n def __gt__(self, other: PurePath) -> bool: ...\n def __ge__(self, other: PurePath) -> bool: ...\n def __truediv__(self, key: StrPath) -> Self: ...\n def __rtruediv__(self, key: StrPath) -> Self: ...\n def __bytes__(self) -> bytes: ...\n def as_posix(self) -> str: ...\n def as_uri(self) -> str: ...\n def is_absolute(self) -> bool: ...\n def is_reserved(self) -> bool: ...\n if sys.version_info >= (3, 12):\n def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ...\n elif sys.version_info >= (3, 9):\n def is_relative_to(self, *other: StrPath) -> bool: ...\n\n if sys.version_info >= (3, 12):\n def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ...\n else:\n def match(self, path_pattern: str) -> bool: ...\n\n if sys.version_info >= (3, 12):\n def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: ...\n else:\n def relative_to(self, *other: StrPath) -> Self: ...\n\n def with_name(self, name: str) -> Self: ...\n if sys.version_info >= (3, 9):\n def with_stem(self, stem: str) -> Self: ...\n\n def with_suffix(self, suffix: str) -> Self: ...\n def joinpath(self, *other: StrPath) -> Self: ...\n @property\n def parents(self) -> Sequence[Self]: ...\n @property\n def parent(self) -> Self: ...\n if sys.version_info >= (3, 9) and sys.version_info < (3, 11):\n def __class_getitem__(cls, type: Any) -> GenericAlias: ...\n\n if sys.version_info >= (3, 12):\n def with_segments(self, *args: StrPath) -> Self: ..."},{"id":1530,"name":"light_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5cd1cbb8-ba1a-460b-8e3a-bc285867f1d1\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b157eb25-015f-4dd6-9785-83ba19cf4f94\",\n \"metadata\": {},\n \"source\": [\n \"Define a sequential ramp from a light gray to a specified color:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"851a4742-6276-4383-b17e-480beb896877\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.light_palette(\\\"seagreen\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"50053b26-112a-4378-8ef0-9be0fb565ec7\",\n \"metadata\": {},\n \"source\": [\n \"Specify the color with a hex code:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"74ae0d17-f65b-4bcf-ae66-d97d46964d5c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.light_palette(\\\"#79C\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"eea376a2-fdf5-40e4-a187-3a28af529072\",\n \"metadata\": {},\n \"source\": [\n \"Specify the color from the husl system:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"66e451ee-869a-41ea-8dc5-4240b11e7be5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.light_palette((20, 60, 50), input=\\\"husl\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e4f44dcd-cf49-4920-ac05-b4db67870363\",\n \"metadata\": {},\n \"source\": [\n \"Increase the number of colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"75985f07-de92-4d8b-89d5-caf445b9375e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.light_palette(\\\"xkcd:copper\\\", 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"34687ae8-fd6d-427a-a639-208f19e61122\",\n \"metadata\": {},\n \"source\": [\n \"Return a continuous colormap rather than a discrete palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2c342db4-7f97-40f5-934e-9a82201890d1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.light_palette(\\\"#a275ac\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e7ebe64b-25fa-4c52-9ebe-fdcbba0ee51e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":1531,"name":"objects.Paths.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"networks = (\\n\",\n \" load_dataset(\\\"brain_networks\\\", header=[0, 1, 2], index_col=0)\\n\",\n \" .rename_axis(\\\"timepoint\\\")\\n\",\n \" .stack([0, 1, 2])\\n\",\n \" .groupby([\\\"timepoint\\\", \\\"network\\\", \\\"hemi\\\"])\\n\",\n \" .mean()\\n\",\n \" .unstack(\\\"network\\\")\\n\",\n \" .reset_index()\\n\",\n \" .query(\\\"timepoint < 100\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"50646936-5236-413f-b79b-6c3b640ade04\",\n \"metadata\": {},\n \"source\": [\n \"Unlike :class:`Lines`, this mark does not sort observations before plotting, making it suitable for plotting trajectories through a variable space:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4a3ed115-cc47-4ea8-be46-2c99f7453941\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = (\\n\",\n \" so.Plot(networks)\\n\",\n \" .pair(\\n\",\n \" x=[\\\"5\\\", \\\"8\\\", \\\"12\\\", \\\"15\\\"],\\n\",\n \" y=[\\\"6\\\", \\\"13\\\", \\\"16\\\"],\\n\",\n \" )\\n\",\n \" .layout(size=(8, 5))\\n\",\n \" .share(x=True, y=True)\\n\",\n \")\\n\",\n \"p.add(so.Paths())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5bf502eb-feb3-4b2e-882b-3e915bf5d041\",\n \"metadata\": {},\n \"source\": [\n \"The mark has the same set of properties as :class:`Lines`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"326a765b-59f0-46ef-91c2-6705c6893740\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Paths(linewidth=1, alpha=.8), color=\\\"hemi\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"175b836d-d328-4b6c-ad36-dde18c19e3bf\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"Get attribute(s) for a given data point.","endLoc":586,"header":"def _lookup_single(self, key, attr=None)","id":1532,"name":"_lookup_single","nodeType":"Function","startLoc":580,"text":"def _lookup_single(self, key, attr=None):\n \"\"\"Get attribute(s) for a given data point.\"\"\"\n if attr is None:\n value = self.lookup_table[key]\n else:\n value = self.lookup_table[key][attr]\n return value"},{"attributeType":"str","col":4,"comment":"null","endLoc":518,"id":1533,"name":"map_type","nodeType":"Attribute","startLoc":518,"text":"map_type"},{"attributeType":"dict","col":12,"comment":"null","endLoc":578,"id":1534,"name":"lookup_table","nodeType":"Attribute","startLoc":578,"text":"self.lookup_table"},{"id":1535,"name":"doc","nodeType":"Package"},{"id":1536,"name":"make.bat","nodeType":"TextFile","path":"doc","text":"@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-build\n)\nset SOURCEDIR=.\nset BUILDDIR=_build\n\n%SPHINXBUILD% >NUL 2>NUL\nif errorlevel 9009 (\n\techo.\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\n\techo.installed, then set the SPHINXBUILD environment variable to point\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\n\techo.may add the Sphinx directory to PATH.\n\techo.\n\techo.If you don't have Sphinx installed, grab it from\n\techo.https://www.sphinx-doc.org/\n\texit /b 1\n)\n\nif \"%1\" == \"\" goto help\n\n%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\ngoto end\n\n:help\n%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\n\n:end\npopd\n"},{"id":1537,"name":"installing.rst","nodeType":"TextFile","path":"doc","text":".. _installing:\n\n.. currentmodule:: seaborn\n\nInstalling and getting started\n------------------------------\n\nOfficial releases of seaborn can be installed from `PyPI `_::\n\n pip install seaborn\n\nThe basic invocation of `pip` will install seaborn and, if necessary, its mandatory dependencies.\nIt is possible to include optional dependencies that give access to a few advanced features::\n\n pip install seaborn[stats]\n\nThe library is also included as part of the `Anaconda `_ distribution,\nand it can be installed with `conda`::\n\n conda install seaborn\n\nAs the main Anaconda repository can be slow to add new releaes, you may prefer using the\n`conda-forge `_ channel::\n\n conda install seaborn -c conda-forge\n\nDependencies\n~~~~~~~~~~~~\n\nSupported Python versions\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- Python 3.7+\n\nMandatory dependencies\n^^^^^^^^^^^^^^^^^^^^^^\n\n- `numpy `__\n\n- `pandas `__\n\n- `matplotlib `__\n\nOptional dependencies\n^^^^^^^^^^^^^^^^^^^^^\n\n- `statsmodels `__, for advanced regression plots\n\n- `scipy `__, for clustering matrices and some advanced options\n\n- `fastcluster `__, faster clustering of large matrices\n\nQuickstart\n~~~~~~~~~~\n\nOnce you have seaborn installed, you're ready to get started.\nTo test it out, you could load and plot one of the example datasets::\n\n import seaborn as sns\n df = sns.load_dataset(\"penguins\")\n sns.pairplot(df, hue=\"species\")\n\nIf you're working in a Jupyter notebook or an IPython terminal with\n`matplotlib mode `_\nenabled, you should immediately see :ref:`the plot `.\nOtherwise, you may need to explicitly call :func:`matplotlib.pyplot.show`::\n\n import matplotlib.pyplot as plt\n plt.show()\n\nWhile you can get pretty far with only seaborn imported, having access to\nmatplotlib functions is often useful. The tutorials and API documentation\ntypically assume the following imports::\n\n import numpy as np\n import pandas as pd\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n\n import seaborn as sns\n import seaborn.objects as so\n\nDebugging install issues\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe seaborn codebase is pure Python, and the library should generally install\nwithout issue. Occasionally, difficulties will arise because the dependencies\ninclude compiled code and link to system libraries. These difficulties\ntypically manifest as errors on import with messages such as ``\"DLL load\nfailed\"``. To debug such problems, read through the exception trace to\nfigure out which specific library failed to import, and then consult the\ninstallation docs for that package to see if they have tips for your particular\nsystem.\n\nIn some cases, an installation of seaborn will appear to succeed, but trying\nto import it will raise an error with the message ``\"No module named\nseaborn\"``. This usually means that you have multiple Python installations on\nyour system and that your ``pip`` or ``conda`` points towards a different\ninstallation than where your interpreter lives. Resolving this issue\nwill involve sorting out the paths on your system, but it can sometimes be\navoided by invoking ``pip`` with ``python -m pip install seaborn``.\n\nGetting help\n~~~~~~~~~~~~\n\nIf you think you've encountered a bug in seaborn, please report it on the\n`GitHub issue tracker `_.\nTo be useful, bug reports must include the following information:\n\n- A reproducible code example that demonstrates the problem\n- The output that you are seeing (an image of a plot, or the error message)\n- A clear explanation of why you think something is wrong\n- The specific versions of seaborn and matplotlib that you are working with\n\nBug reports are easiest to address if they can be demonstrated using one of the\nexample datasets from the seaborn docs (i.e. with :func:`load_dataset`).\nOtherwise, it is preferable that your example generate synthetic data to\nreproduce the problem. If you can only demonstrate the issue with your\nactual dataset, you will need to share it, ideally as a csv.\n\nIf you've encountered an error, searching the specific text of the message\nbefore opening a new issue can often help you solve the problem quickly and\navoid making a duplicate report.\n\nBecause matplotlib handles the actual rendering, errors or incorrect outputs\nmay be due to a problem in matplotlib rather than one in seaborn. It can save time\nif you try to reproduce the issue in an example that uses only matplotlib,\nso that you can report it in the right place. But it is alright to skip this\nstep if it's not obvious how to do it.\n\nGeneral support questions are more at home on either `stackoverflow\n`_, where there is a\nlarger audience of people who will see your post and may be able to offer\nassistance. Your chance of getting a quick answer will be higher if you include\n`runnable code `_,\na precise statement of what you are hoping to achieve, and a clear explanation\nof the problems that you have encountered.\n"},{"fileName":"residplot.py","filePath":"examples","id":1538,"nodeType":"File","text":"\"\"\"\nPlotting model residuals\n========================\n\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Make an example dataset with y ~ x\nrs = np.random.RandomState(7)\nx = rs.normal(2, 1, 75)\ny = 2 + 1.5 * x + rs.normal(0, 2, 75)\n\n# Plot the residuals after fitting a linear model\nsns.residplot(x=x, y=y, lowess=True, color=\"g\")\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":6,"id":1539,"name":"np","nodeType":"Attribute","startLoc":6,"text":"np"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":1540,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":1541,"name":"rs","nodeType":"Attribute","startLoc":11,"text":"rs"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":1542,"name":"x","nodeType":"Attribute","startLoc":12,"text":"x"},{"attributeType":"int | float","col":0,"comment":"null","endLoc":13,"id":1543,"name":"y","nodeType":"Attribute","startLoc":13,"text":"y"},{"col":4,"comment":"null","endLoc":35,"header":"@property\n def parts(self) -> tuple[str, ...]","id":1544,"name":"parts","nodeType":"Function","startLoc":34,"text":"@property\n def parts(self) -> tuple[str, ...]: ..."},{"col":4,"comment":"null","endLoc":37,"header":"@property\n def drive(self) -> str","id":1545,"name":"drive","nodeType":"Function","startLoc":36,"text":"@property\n def drive(self) -> str: ..."},{"col":4,"comment":"null","endLoc":39,"header":"@property\n def root(self) -> str","id":1546,"name":"root","nodeType":"Function","startLoc":38,"text":"@property\n def root(self) -> str: ..."},{"col":4,"comment":"null","endLoc":41,"header":"@property\n def anchor(self) -> str","id":1547,"name":"anchor","nodeType":"Function","startLoc":40,"text":"@property\n def anchor(self) -> str: ..."},{"col":4,"comment":"null","endLoc":43,"header":"@property\n def name(self) -> str","id":1548,"name":"name","nodeType":"Function","startLoc":42,"text":"@property\n def name(self) -> str: ..."},{"col":4,"comment":"null","endLoc":45,"header":"@property\n def suffix(self) -> str","id":1549,"name":"suffix","nodeType":"Function","startLoc":44,"text":"@property\n def suffix(self) -> str: ..."},{"col":4,"comment":"null","endLoc":47,"header":"@property\n def suffixes(self) -> list[str]","id":1550,"name":"suffixes","nodeType":"Function","startLoc":46,"text":"@property\n def suffixes(self) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":49,"header":"@property\n def stem(self) -> str","id":1551,"name":"stem","nodeType":"Function","startLoc":48,"text":"@property\n def stem(self) -> str: ..."},{"col":8,"comment":"null","endLoc":54,"header":"def __new__(cls, *args: StrPath) -> Self","id":1552,"name":"__new__","nodeType":"Function","startLoc":54,"text":"def __new__(cls, *args: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":56,"header":"def __hash__(self) -> int","id":1553,"name":"__hash__","nodeType":"Function","startLoc":56,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":57,"header":"def __fspath__(self) -> str","id":1554,"name":"__fspath__","nodeType":"Function","startLoc":57,"text":"def __fspath__(self) -> str: ..."},{"col":4,"comment":"null","endLoc":58,"header":"def __lt__(self, other: PurePath) -> bool","id":1555,"name":"__lt__","nodeType":"Function","startLoc":58,"text":"def __lt__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def __le__(self, other: PurePath) -> bool","id":1556,"name":"__le__","nodeType":"Function","startLoc":59,"text":"def __le__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def __gt__(self, other: PurePath) -> bool","id":1557,"name":"__gt__","nodeType":"Function","startLoc":60,"text":"def __gt__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":61,"header":"def __ge__(self, other: PurePath) -> bool","id":1558,"name":"__ge__","nodeType":"Function","startLoc":61,"text":"def __ge__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":62,"header":"def __truediv__(self, key: StrPath) -> Self","id":1559,"name":"__truediv__","nodeType":"Function","startLoc":62,"text":"def __truediv__(self, key: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":63,"header":"def __rtruediv__(self, key: StrPath) -> Self","id":1560,"name":"__rtruediv__","nodeType":"Function","startLoc":63,"text":"def __rtruediv__(self, key: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":64,"header":"def __bytes__(self) -> bytes","id":1561,"name":"__bytes__","nodeType":"Function","startLoc":64,"text":"def __bytes__(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":65,"header":"def as_posix(self) -> str","id":1562,"name":"as_posix","nodeType":"Function","startLoc":65,"text":"def as_posix(self) -> str: ..."},{"col":4,"comment":"null","endLoc":66,"header":"def as_uri(self) -> str","id":1563,"name":"as_uri","nodeType":"Function","startLoc":66,"text":"def as_uri(self) -> str: ..."},{"col":4,"comment":"null","endLoc":67,"header":"def is_absolute(self) -> bool","id":1564,"name":"is_absolute","nodeType":"Function","startLoc":67,"text":"def is_absolute(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":68,"header":"def is_reserved(self) -> bool","id":1565,"name":"is_reserved","nodeType":"Function","startLoc":68,"text":"def is_reserved(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":72,"header":"def is_relative_to(self, *other: StrPath) -> bool","id":1566,"name":"is_relative_to","nodeType":"Function","startLoc":72,"text":"def is_relative_to(self, *other: StrPath) -> bool: ..."},{"col":8,"comment":"null","endLoc":77,"header":"def match(self, path_pattern: str) -> bool","id":1567,"name":"match","nodeType":"Function","startLoc":77,"text":"def match(self, path_pattern: str) -> bool: ..."},{"col":8,"comment":"null","endLoc":82,"header":"def relative_to(self, *other: StrPath) -> Self","id":1568,"name":"relative_to","nodeType":"Function","startLoc":82,"text":"def relative_to(self, *other: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":84,"header":"def with_name(self, name: str) -> Self","id":1569,"name":"with_name","nodeType":"Function","startLoc":84,"text":"def with_name(self, name: str) -> Self: ..."},{"col":0,"comment":"","endLoc":6,"header":"grouped_barplot.py#","id":1570,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nGrouped barplots\n================\n\n_thumb: .36, .5\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\npenguins = sns.load_dataset(\"penguins\")\n\ng = sns.catplot(\n data=penguins, kind=\"bar\",\n x=\"species\", y=\"body_mass_g\", hue=\"sex\",\n errorbar=\"sd\", palette=\"dark\", alpha=.6, height=6\n)\n\ng.despine(left=True)\n\ng.set_axis_labels(\"\", \"Body mass (g)\")\n\ng.legend.set_title(\"\")"},{"col":8,"comment":"null","endLoc":86,"header":"def with_stem(self, stem: str) -> Self","id":1571,"name":"with_stem","nodeType":"Function","startLoc":86,"text":"def with_stem(self, stem: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":88,"header":"def with_suffix(self, suffix: str) -> Self","id":1572,"name":"with_suffix","nodeType":"Function","startLoc":88,"text":"def with_suffix(self, suffix: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":89,"header":"def joinpath(self, *other: StrPath) -> Self","id":1573,"name":"joinpath","nodeType":"Function","startLoc":89,"text":"def joinpath(self, *other: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":91,"header":"@property\n def parents(self) -> Sequence[Self]","id":1574,"name":"parents","nodeType":"Function","startLoc":90,"text":"@property\n def parents(self) -> Sequence[Self]: ..."},{"col":4,"comment":"null","endLoc":93,"header":"@property\n def parent(self) -> Self","id":1575,"name":"parent","nodeType":"Function","startLoc":92,"text":"@property\n def parent(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":95,"header":"def __class_getitem__(cls, type: Any) -> GenericAlias","id":1576,"name":"__class_getitem__","nodeType":"Function","startLoc":95,"text":"def __class_getitem__(cls, type: Any) -> GenericAlias: ..."},{"col":8,"comment":"null","endLoc":107,"header":"def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self","id":1577,"name":"__new__","nodeType":"Function","startLoc":107,"text":"def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ..."},{"col":4,"comment":"null","endLoc":110,"header":"@classmethod\n def cwd(cls) -> Self","id":1578,"name":"cwd","nodeType":"Function","startLoc":109,"text":"@classmethod\n def cwd(cls) -> Self: ..."},{"col":8,"comment":"null","endLoc":115,"header":"def stat(self) -> stat_result","id":1579,"name":"stat","nodeType":"Function","startLoc":115,"text":"def stat(self) -> stat_result: ..."},{"col":8,"comment":"null","endLoc":116,"header":"def chmod(self, mode: int) -> None","id":1580,"name":"chmod","nodeType":"Function","startLoc":116,"text":"def chmod(self, mode: int) -> None: ..."},{"col":8,"comment":"null","endLoc":125,"header":"def __enter__(self) -> Self","id":1581,"name":"__enter__","nodeType":"Function","startLoc":125,"text":"def __enter__(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":126,"header":"def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None","id":1582,"name":"__exit__","nodeType":"Function","startLoc":126,"text":"def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ..."},{"col":8,"comment":"null","endLoc":127,"header":"def is_dir(self) -> bool","id":1583,"name":"is_dir","nodeType":"Function","startLoc":127,"text":"def is_dir(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":128,"header":"def is_file(self) -> bool","id":1584,"name":"is_file","nodeType":"Function","startLoc":128,"text":"def is_file(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":129,"header":"def read_text(self, encoding: str | None = None, errors: str | None = None) -> str","id":1585,"name":"read_text","nodeType":"Function","startLoc":129,"text":"def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ..."},{"col":8,"comment":"null","endLoc":142,"header":"def glob(self, pattern: str) -> Generator[Self, None, None]","id":1586,"name":"glob","nodeType":"Function","startLoc":142,"text":"def glob(self, pattern: str) -> Generator[Self, None, None]: ..."},{"col":8,"comment":"null","endLoc":143,"header":"def rglob(self, pattern: str) -> Generator[Self, None, None]","id":1587,"name":"rglob","nodeType":"Function","startLoc":143,"text":"def rglob(self, pattern: str) -> Generator[Self, None, None]: ..."},{"col":8,"comment":"null","endLoc":148,"header":"def exists(self) -> bool","id":1588,"name":"exists","nodeType":"Function","startLoc":148,"text":"def exists(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":150,"header":"def is_symlink(self) -> bool","id":1589,"name":"is_symlink","nodeType":"Function","startLoc":150,"text":"def is_symlink(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":151,"header":"def is_socket(self) -> bool","id":1590,"name":"is_socket","nodeType":"Function","startLoc":151,"text":"def is_socket(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":152,"header":"def is_fifo(self) -> bool","id":1591,"name":"is_fifo","nodeType":"Function","startLoc":152,"text":"def is_fifo(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":153,"header":"def is_block_device(self) -> bool","id":1592,"name":"is_block_device","nodeType":"Function","startLoc":153,"text":"def is_block_device(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":154,"header":"def is_char_device(self) -> bool","id":1593,"name":"is_char_device","nodeType":"Function","startLoc":154,"text":"def is_char_device(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":158,"header":"def iterdir(self) -> Generator[Self, None, None]","id":1594,"name":"iterdir","nodeType":"Function","startLoc":158,"text":"def iterdir(self) -> Generator[Self, None, None]: ..."},{"col":4,"comment":"null","endLoc":159,"header":"def lchmod(self, mode: int) -> None","id":1595,"name":"lchmod","nodeType":"Function","startLoc":159,"text":"def lchmod(self, mode: int) -> None: ..."},{"col":4,"comment":"null","endLoc":160,"header":"def lstat(self) -> stat_result","id":1596,"name":"lstat","nodeType":"Function","startLoc":160,"text":"def lstat(self) -> stat_result: ..."},{"col":4,"comment":"null","endLoc":161,"header":"def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None","id":1597,"name":"mkdir","nodeType":"Function","startLoc":161,"text":"def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":173,"header":"@overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper","id":1598,"name":"open","nodeType":"Function","startLoc":165,"text":"@overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper: ..."},{"col":4,"comment":"null","endLoc":178,"header":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO","id":1599,"name":"open","nodeType":"Function","startLoc":175,"text":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO: ..."},{"col":4,"comment":"null","endLoc":188,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom","id":1600,"name":"open","nodeType":"Function","startLoc":180,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom: ..."},{"col":4,"comment":"null","endLoc":197,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter","id":1601,"name":"open","nodeType":"Function","startLoc":189,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter: ..."},{"col":4,"comment":"null","endLoc":206,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader","id":1602,"name":"open","nodeType":"Function","startLoc":198,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader: ..."},{"col":4,"comment":"null","endLoc":211,"header":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO","id":1603,"name":"open","nodeType":"Function","startLoc":208,"text":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":216,"header":"@overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]","id":1604,"name":"open","nodeType":"Function","startLoc":213,"text":"@overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]: ..."},{"col":12,"comment":"null","endLoc":224,"header":"def owner(self) -> str","id":1605,"name":"owner","nodeType":"Function","startLoc":224,"text":"def owner(self) -> str: ..."},{"col":12,"comment":"null","endLoc":225,"header":"def group(self) -> str","id":1606,"name":"group","nodeType":"Function","startLoc":225,"text":"def group(self) -> str: ..."},{"col":8,"comment":"null","endLoc":230,"header":"def is_mount(self) -> bool","id":1607,"name":"is_mount","nodeType":"Function","startLoc":230,"text":"def is_mount(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":233,"header":"def readlink(self) -> Self","id":1608,"name":"readlink","nodeType":"Function","startLoc":233,"text":"def readlink(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":235,"header":"def rename(self, target: str | PurePath) -> Self","id":1609,"name":"rename","nodeType":"Function","startLoc":235,"text":"def rename(self, target: str | PurePath) -> Self: ..."},{"col":4,"comment":"null","endLoc":236,"header":"def replace(self, target: str | PurePath) -> Self","id":1610,"name":"replace","nodeType":"Function","startLoc":236,"text":"def replace(self, target: str | PurePath) -> Self: ..."},{"col":4,"comment":"null","endLoc":237,"header":"def resolve(self, strict: bool = False) -> Self","id":1611,"name":"resolve","nodeType":"Function","startLoc":237,"text":"def resolve(self, strict: bool = False) -> Self: ..."},{"col":4,"comment":"null","endLoc":238,"header":"def rmdir(self) -> None","id":1612,"name":"rmdir","nodeType":"Function","startLoc":238,"text":"def rmdir(self) -> None: ..."},{"col":4,"comment":"null","endLoc":239,"header":"def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None","id":1613,"name":"symlink_to","nodeType":"Function","startLoc":239,"text":"def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":243,"header":"def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None","id":1614,"name":"touch","nodeType":"Function","startLoc":243,"text":"def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ..."},{"col":4,"comment":"null","endLoc":244,"header":"def unlink(self, missing_ok: bool = False) -> None","id":1615,"name":"unlink","nodeType":"Function","startLoc":244,"text":"def unlink(self, missing_ok: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":246,"header":"@classmethod\n def home(cls) -> Self","id":1616,"name":"home","nodeType":"Function","startLoc":245,"text":"@classmethod\n def home(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":247,"header":"def absolute(self) -> Self","id":1617,"name":"absolute","nodeType":"Function","startLoc":247,"text":"def absolute(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":248,"header":"def expanduser(self) -> Self","id":1618,"name":"expanduser","nodeType":"Function","startLoc":248,"text":"def expanduser(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":249,"header":"def read_bytes(self) -> bytes","id":1619,"name":"read_bytes","nodeType":"Function","startLoc":249,"text":"def read_bytes(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":250,"header":"def samefile(self, other_path: StrPath) -> bool","id":1620,"name":"samefile","nodeType":"Function","startLoc":250,"text":"def samefile(self, other_path: StrPath) -> bool: ..."},{"className":"VerticalAlignment","col":0,"comment":"null","endLoc":531,"id":1621,"nodeType":"Class","startLoc":527,"text":"class VerticalAlignment(TextAlignment):\n\n def _default_values(self, n: int) -> list:\n vals = itertools.cycle([\"top\", \"bottom\"])\n return [next(vals) for _ in range(n)]"},{"col":4,"comment":"null","endLoc":531,"header":"def _default_values(self, n: int) -> list","id":1622,"name":"_default_values","nodeType":"Function","startLoc":529,"text":"def _default_values(self, n: int) -> list:\n vals = itertools.cycle([\"top\", \"bottom\"])\n return [next(vals) for _ in range(n)]"},{"id":1623,"name":"scatterplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import pandas as pd\\n\",\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"These examples will use the \\\"tips\\\" dataset, which has a mixture of numeric and categorical variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"tips.head()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Passing long-form data and assigning ``x`` and ``y`` will draw a scatter plot between two variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a variable to ``hue`` will map its levels to the color of the points:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"time\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning the same variable to ``style`` will also vary the markers and create a more accessible plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"time\\\", style=\\\"time\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning ``hue`` and ``style`` to different variables will vary colors and markers independently:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"day\\\", style=\\\"time\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If the variable assigned to ``hue`` is numeric, the semantic mapping will be quantitative and use a different default palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Pass the name of a categorical palette or explicit colors (as a Python list of dictionary) to force categorical mapping of the ``hue`` variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"size\\\", palette=\\\"deep\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If there are a large number of unique numeric values, the legend will show a representative, evenly-spaced set:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tip_rate = tips.eval(\\\"tip / total_bill\\\").rename(\\\"tip_rate\\\")\\n\",\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=tip_rate)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A numeric variable can also be assigned to ``size`` to apply a semantic mapping to the areas of the points:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"size\\\", size=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Control the range of marker areas with ``sizes``, and set ``lengend=\\\"full\\\"`` to force every unique value to appear in the legend:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"size\\\", size=\\\"size\\\",\\n\",\n \" sizes=(20, 200), legend=\\\"full\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Pass a tuple of values or a :class:`matplotlib.colors.Normalize` object to ``hue_norm`` to control the quantitative hue mapping:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"size\\\", size=\\\"size\\\",\\n\",\n \" sizes=(20, 200), hue_norm=(0, 7), legend=\\\"full\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Control the specific markers used to map the ``style`` variable by passing a Python list or dictionary of marker codes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"markers = {\\\"Lunch\\\": \\\"s\\\", \\\"Dinner\\\": \\\"X\\\"}\\n\",\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", style=\\\"time\\\", markers=markers)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Additional keyword arguments are passed to :meth:`matplotlib.axes.Axes.scatter`, allowing you to directly set the attributes of the plot that are not semantically mapped:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", s=100, color=\\\".2\\\", marker=\\\"+\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The previous examples used a long-form dataset. When working with wide-form data, each column will be plotted against its index using both ``hue`` and ``style`` mapping:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"index = pd.date_range(\\\"1 1 2000\\\", periods=100, freq=\\\"m\\\", name=\\\"date\\\")\\n\",\n \"data = np.random.randn(100, 4).cumsum(axis=0)\\n\",\n \"wide_df = pd.DataFrame(data, index, [\\\"a\\\", \\\"b\\\", \\\"c\\\", \\\"d\\\"])\\n\",\n \"sns.scatterplot(data=wide_df)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Use :func:`relplot` to combine :func:`scatterplot` and :class:`FacetGrid`. This allows grouping within additional categorical variables, and plotting them across multiple subplots.\\n\",\n \"\\n\",\n \"Using :func:`relplot` is safer than using :class:`FacetGrid` directly, as it ensures synchronization of the semantic mappings across facets.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\",\\n\",\n \" col=\\\"time\\\", hue=\\\"day\\\", style=\\\"day\\\",\\n\",\n \" kind=\\\"scatter\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"col":4,"comment":"null","endLoc":251,"header":"def write_bytes(self, data: ReadableBuffer) -> int","id":1624,"name":"write_bytes","nodeType":"Function","startLoc":251,"text":"def write_bytes(self, data: ReadableBuffer) -> int: ..."},{"col":8,"comment":"null","endLoc":257,"header":"def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int","id":1625,"name":"write_text","nodeType":"Function","startLoc":257,"text":"def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ..."},{"col":12,"comment":"null","endLoc":263,"header":"def link_to(self, target: StrOrBytesPath) -> None","id":1626,"name":"link_to","nodeType":"Function","startLoc":263,"text":"def link_to(self, target: StrOrBytesPath) -> None: ..."},{"id":1627,"name":".gitignore","nodeType":"TextFile","path":"doc","text":"*_files/\n_build/\ngenerated/\nexamples/\nexample_thumbs/*.png\ndocstrings/\ntutorial/\ntutorial/_images\ntutorial.rst\n"},{"attributeType":"list","col":12,"comment":"null","endLoc":577,"id":1628,"name":"levels","nodeType":"Attribute","startLoc":577,"text":"self.levels"},{"col":0,"comment":"null","endLoc":76,"header":"def main(app)","id":1629,"name":"main","nodeType":"Function","startLoc":49,"text":"def main(app):\n\n content_yaml = Path(app.builder.srcdir) / \"tutorial.yaml\"\n tutorial_rst = Path(app.builder.srcdir) / \"tutorial.rst\"\n\n tutorial_dir = Path(app.builder.srcdir) / \"tutorial\"\n tutorial_dir.mkdir(exist_ok=True)\n\n with open(content_yaml) as fid:\n sections = yaml.load(fid, yaml.BaseLoader)\n\n for section in sections:\n title = section[\"title\"]\n section[\"header\"] = \"\\n\".join([title, \"-\" * len(title)]) if title else \"\"\n\n env = Environment().from_string(TEMPLATE)\n content = env.render(sections=sections)\n\n with open(tutorial_rst, \"w\") as fid:\n fid.write(content)\n\n for section in sections:\n for page in section[\"pages\"]:\n if (\n not (svg_path := tutorial_dir / f\"{page}.svg\").exists()\n or svg_path.stat().st_mtime < Path(__file__).stat().st_mtime\n ):\n write_thumbnail(svg_path, page)"},{"id":1630,"name":"Makefile","nodeType":"TextFile","path":"doc","text":"# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS =\nSPHINXBUILD = sphinx-build\nPAPER =\nBUILDDIR = _build\n\n# Internal variables.\nPAPEROPT_a4 = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\nhelp:\n\t@echo \"Please use \\`make ' where is one of\"\n\t@echo \" clean to remove generated output\"\n\t@echo \" html to make standalone HTML files\"\n\t@echo \" notebooks to make the Jupyter notebook-based tutorials\"\n\t@echo \" dirhtml to make HTML files named index.html in directories\"\n\t@echo \" singlehtml to make a single large HTML file\"\n\t@echo \" pickle to make pickle files\"\n\t@echo \" json to make JSON files\"\n\t@echo \" htmlhelp to make HTML files and a HTML help project\"\n\t@echo \" qthelp to make HTML files and a qthelp project\"\n\t@echo \" devhelp to make HTML files and a Devhelp project\"\n\t@echo \" epub to make an epub\"\n\t@echo \" latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \" latexpdf to make LaTeX files and run them through pdflatex\"\n\t@echo \" text to make text files\"\n\t@echo \" man to make manual pages\"\n\t@echo \" texinfo to make Texinfo files\"\n\t@echo \" info to make Texinfo files and run them through makeinfo\"\n\t@echo \" gettext to make PO message catalogs\"\n\t@echo \" changes to make an overview of all changed/added/deprecated items\"\n\t@echo \" linkcheck to check all external links for integrity\"\n\t@echo \" doctest to run all doctests embedded in the documentation (if enabled)\"\n\nclean:\n\t-rm -rf $(BUILDDIR)/*\n\t-rm -rf examples/*\n\t-rm -rf example_thumbs/*\n\t-rm -rf generated/*\n\t-rm -rf tutorial.rst\n\t-$(MAKE) -C _docstrings clean\n\t-$(MAKE) -C _tutorial clean\n\n.PHONY: tutorials\ntutorials:\n\t@mkdir -p tutorial\n\t@$(MAKE) -C _tutorial\n\n.PHONY: docstrings\ndocstrings:\n\t@mkdir -p docstrings\n\t@$(MAKE) -C _docstrings\n\nnotebooks: tutorials docstrings\n\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/lyman.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/lyman.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/lyman\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/lyman\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t \"(use \\`make info' here to do that automatically).\"\n\ninfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t \"results in $(BUILDDIR)/doctest/output.txt.\"\n"},{"className":"VariableType","col":0,"comment":"\n Prevent comparisons elsewhere in the library from using the wrong name.\n\n Errors are simple assertions because users should not be able to trigger\n them. If that changes, they should be more verbose.\n\n ","endLoc":1470,"id":1631,"nodeType":"Class","startLoc":1453,"text":"class VariableType(UserString):\n \"\"\"\n Prevent comparisons elsewhere in the library from using the wrong name.\n\n Errors are simple assertions because users should not be able to trigger\n them. If that changes, they should be more verbose.\n\n \"\"\"\n # TODO we can replace this with typing.Literal on Python 3.8+\n allowed = \"numeric\", \"datetime\", \"categorical\"\n\n def __init__(self, data):\n assert data in self.allowed, data\n super().__init__(data)\n\n def __eq__(self, other):\n assert other in self.allowed, other\n return self.data == other"},{"col":4,"comment":"null","endLoc":1470,"header":"def __eq__(self, other)","id":1632,"name":"__eq__","nodeType":"Function","startLoc":1468,"text":"def __eq__(self, other):\n assert other in self.allowed, other\n return self.data == other"},{"attributeType":"(str, str, str)","col":4,"comment":"null","endLoc":1462,"id":1633,"name":"allowed","nodeType":"Attribute","startLoc":1462,"text":"allowed"},{"id":1634,"name":"api.rst","nodeType":"TextFile","path":"doc","text":".. _api_ref:\n\nAPI reference\n=============\n\n.. currentmodule:: seaborn.objects\n\n.. _objects_api:\n\nObjects interface\n-----------------\n\nPlot object\n~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :template: plot\n :nosignatures:\n\n Plot\n\nMark objects\n~~~~~~~~~~~~\n\n.. rubric:: Dot marks\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Dot\n Dots\n\n.. rubric:: Line marks\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Line\n Lines\n Path\n Paths\n Range\n\n.. rubric:: Bar marks\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Bar\n Bars\n\n.. rubric:: Fill marks\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Area\n Band\n\n.. rubric:: Text marks\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Text\n\nStat objects\n~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Agg\n Est\n Hist\n Perc\n PolyFit\n\nMove objects\n~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Dodge\n Jitter\n Norm\n Stack\n Shift\n\nScale objects\n~~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :template: scale\n :nosignatures:\n\n Continuous\n Nominal\n Temporal\n\nBase classes\n~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :template: object\n :nosignatures:\n\n Mark\n Stat\n Move\n Scale\n\n.. currentmodule:: seaborn\n\nFunction interface\n------------------\n\n.. _relational_api:\n\nRelational plots\n~~~~~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n relplot\n scatterplot\n lineplot\n\n.. _distribution_api:\n\nDistribution plots\n~~~~~~~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n displot\n histplot\n kdeplot\n ecdfplot\n rugplot\n distplot\n\n.. _categorical_api:\n\nCategorical plots\n~~~~~~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n catplot\n stripplot\n swarmplot\n boxplot\n violinplot\n boxenplot\n pointplot\n barplot\n countplot\n\n.. _regression_api:\n\nRegression plots\n~~~~~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n lmplot\n regplot\n residplot\n\n.. _matrix_api:\n\nMatrix plots\n~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n heatmap\n clustermap\n\n.. _grid_api:\n\nMulti-plot grids\n----------------\n\nFacet grids\n~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n FacetGrid\n\nPair grids\n~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n pairplot\n PairGrid\n\nJoint grids\n~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n jointplot\n JointGrid\n\n.. _style_api:\n\nThemeing\n--------\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n set_theme\n axes_style\n set_style\n plotting_context\n set_context\n set_color_codes\n reset_defaults\n reset_orig\n set\n\n.. _palette_api:\n\nColor palettes\n--------------\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n set_palette\n color_palette\n husl_palette\n hls_palette\n cubehelix_palette\n dark_palette\n light_palette\n diverging_palette\n blend_palette\n xkcd_palette\n crayon_palette\n mpl_palette\n\nPalette widgets\n~~~~~~~~~~~~~~~\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n choose_colorbrewer_palette\n choose_cubehelix_palette\n choose_light_palette\n choose_dark_palette\n choose_diverging_palette\n\n\nUtility functions\n-----------------\n\n.. autosummary::\n :toctree: generated/\n :nosignatures:\n\n despine\n move_legend\n saturate\n desaturate\n set_hls_values\n load_dataset\n get_dataset_names\n get_data_home\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":10,"id":1635,"name":"np","nodeType":"Attribute","startLoc":10,"text":"np"},{"id":1636,"name":"tests/_core","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/_core","id":1637,"nodeType":"File","text":""},{"attributeType":"null","col":17,"comment":"null","endLoc":11,"id":1638,"name":"pd","nodeType":"Attribute","startLoc":11,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":12,"id":1639,"name":"mpl","nodeType":"Attribute","startLoc":12,"text":"mpl"},{"id":1640,"name":"copybutton.js","nodeType":"TextFile","path":"doc/_static","text":"// originally taken from scikit-learn's Sphinx theme\n$(document).ready(function() {\n /* Add a [>>>] button on the top-right corner of code samples to hide\n * the >>> and ... prompts and the output and thus make the code\n * copyable.\n * Note: This JS snippet was taken from the official python.org\n * documentation site.*/\n var div = $('.highlight-python .highlight,' +\n '.highlight-python3 .highlight,' +\n '.highlight-pycon .highlight')\n var pre = div.find('pre');\n\n // get the styles from the current theme\n pre.parent().parent().css('position', 'relative');\n var hide_text = 'Hide the prompts and output';\n var show_text = 'Show the prompts and output';\n var border_width = pre.css('border-top-width');\n var border_style = pre.css('border-top-style');\n var border_color = pre.css('border-top-color');\n var button_styles = {\n 'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0',\n 'border-color': border_color, 'border-style': border_style,\n 'border-width': border_width, 'color': border_color, 'text-size': '75%',\n 'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em'\n }\n\n // create and add the button to all the code blocks that contain >>>\n div.each(function(index) {\n var jthis = $(this);\n if (jthis.find('.gp').length > 0) {\n var button = $('>>>');\n button.css(button_styles)\n button.attr('title', hide_text);\n jthis.prepend(button);\n }\n // tracebacks (.gt) contain bare text elements that need to be\n // wrapped in a span to work with .nextUntil() (see later)\n jthis.find('pre:has(.gt)').contents().filter(function() {\n return ((this.nodeType == 3) && (this.data.trim().length > 0));\n }).wrap('');\n });\n\n // define the behavior of the button when it's clicked\n $('.copybutton').toggle(\n function() {\n var button = $(this);\n button.parent().find('.go, .gp, .gt').hide();\n button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');\n button.css('text-decoration', 'line-through');\n button.attr('title', show_text);\n },\n function() {\n var button = $(this);\n button.parent().find('.go, .gp, .gt').show();\n button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');\n button.css('text-decoration', 'none');\n button.attr('title', hide_text);\n });\n});\n"},{"col":0,"comment":"","endLoc":5,"header":"residplot.py#","id":1641,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPlotting model residuals\n========================\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\nrs = np.random.RandomState(7)\n\nx = rs.normal(2, 1, 75)\n\ny = 2 + 1.5 * x + rs.normal(0, 2, 75)\n\nsns.residplot(x=x, y=y, lowess=True, color=\"g\")"},{"id":1642,"name":"README.md","nodeType":"TextFile","path":"doc","text":"Building the seaborn docs\n=========================\n\nBuilding the docs requires additional dependencies; they can be installed with `pip install seaborn[stats,docs]`.\n\nThe build process involves conversion of Jupyter notebooks to `rst` files. To facilitate this, you may need to set `NB_KERNEL` environment variable to the name of a kernel on your machine (e.g. `export NB_KERNEL=\"python3\"`). To get a list of available Python kernels, run `jupyter kernelspec list`.\n\nAfter you're set up, run `make notebooks html` from the `doc` directory to convert all notebooks, generate all gallery examples, and build the documentation itself. The site will live in `_build/html`.\n\nRun `make clean` to delete the built site and all intermediate files. Run `make -C docstrings clean` or `make -C tutorial clean` to remove intermediate files for the API or tutorial components.\n\nIf your goal is to obtain an offline copy of the docs for a released version, it may be easier to clone the [website repository](https://github.com/seaborn/seaborn.github.io) or to download a zipfile corresponding to a [specific version](https://github.com/seaborn/seaborn.github.io/tags).\n"},{"fileName":"conftest.py","filePath":"tests","id":1643,"nodeType":"File","text":"import numpy as np\nimport pandas as pd\n\nimport pytest\n\n\n@pytest.fixture(autouse=True)\ndef close_figs():\n yield\n import matplotlib.pyplot as plt\n plt.close(\"all\")\n\n\n@pytest.fixture(autouse=True)\ndef random_seed():\n seed = sum(map(ord, \"seaborn random global\"))\n np.random.seed(seed)\n\n\n@pytest.fixture()\ndef rng():\n seed = sum(map(ord, \"seaborn random object\"))\n return np.random.RandomState(seed)\n\n\n@pytest.fixture\ndef wide_df(rng):\n\n columns = list(\"abc\")\n index = pd.RangeIndex(10, 50, 2, name=\"wide_index\")\n values = rng.normal(size=(len(index), len(columns)))\n return pd.DataFrame(values, index=index, columns=columns)\n\n\n@pytest.fixture\ndef wide_array(wide_df):\n\n return wide_df.to_numpy()\n\n\n# TODO s/flat/thin?\n@pytest.fixture\ndef flat_series(rng):\n\n index = pd.RangeIndex(10, 30, name=\"t\")\n return pd.Series(rng.normal(size=20), index, name=\"s\")\n\n\n@pytest.fixture\ndef flat_array(flat_series):\n\n return flat_series.to_numpy()\n\n\n@pytest.fixture\ndef flat_list(flat_series):\n\n return flat_series.to_list()\n\n\n@pytest.fixture(params=[\"series\", \"array\", \"list\"])\ndef flat_data(rng, request):\n\n index = pd.RangeIndex(10, 30, name=\"t\")\n series = pd.Series(rng.normal(size=20), index, name=\"s\")\n if request.param == \"series\":\n data = series\n elif request.param == \"array\":\n data = series.to_numpy()\n elif request.param == \"list\":\n data = series.to_list()\n return data\n\n\n@pytest.fixture\ndef wide_list_of_series(rng):\n\n return [pd.Series(rng.normal(size=20), np.arange(20), name=\"a\"),\n pd.Series(rng.normal(size=10), np.arange(5, 15), name=\"b\")]\n\n\n@pytest.fixture\ndef wide_list_of_arrays(wide_list_of_series):\n\n return [s.to_numpy() for s in wide_list_of_series]\n\n\n@pytest.fixture\ndef wide_list_of_lists(wide_list_of_series):\n\n return [s.to_list() for s in wide_list_of_series]\n\n\n@pytest.fixture\ndef wide_dict_of_series(wide_list_of_series):\n\n return {s.name: s for s in wide_list_of_series}\n\n\n@pytest.fixture\ndef wide_dict_of_arrays(wide_list_of_series):\n\n return {s.name: s.to_numpy() for s in wide_list_of_series}\n\n\n@pytest.fixture\ndef wide_dict_of_lists(wide_list_of_series):\n\n return {s.name: s.to_list() for s in wide_list_of_series}\n\n\n@pytest.fixture\ndef long_df(rng):\n\n n = 100\n df = pd.DataFrame(dict(\n x=rng.uniform(0, 20, n).round().astype(\"int\"),\n y=rng.normal(size=n),\n z=rng.lognormal(size=n),\n a=rng.choice(list(\"abc\"), n),\n b=rng.choice(list(\"mnop\"), n),\n c=rng.choice([0, 1], n, [.3, .7]),\n d=rng.choice(np.arange(\"2004-07-30\", \"2007-07-30\", dtype=\"datetime64[Y]\"), n),\n t=rng.choice(np.arange(\"2004-07-30\", \"2004-07-31\", dtype=\"datetime64[m]\"), n),\n s=rng.choice([2, 4, 8], n),\n f=rng.choice([0.2, 0.3], n),\n ))\n\n a_cat = df[\"a\"].astype(\"category\")\n new_categories = np.roll(a_cat.cat.categories, 1)\n df[\"a_cat\"] = a_cat.cat.reorder_categories(new_categories)\n\n df[\"s_cat\"] = df[\"s\"].astype(\"category\")\n df[\"s_str\"] = df[\"s\"].astype(str)\n\n return df\n\n\n@pytest.fixture\ndef long_dict(long_df):\n\n return long_df.to_dict()\n\n\n@pytest.fixture\ndef repeated_df(rng):\n\n n = 100\n return pd.DataFrame(dict(\n x=np.tile(np.arange(n // 2), 2),\n y=rng.normal(size=n),\n a=rng.choice(list(\"abc\"), n),\n u=np.repeat(np.arange(2), n // 2),\n ))\n\n\n@pytest.fixture\ndef missing_df(rng, long_df):\n\n df = long_df.copy()\n for col in df:\n idx = rng.permutation(df.index)[:10]\n df.loc[idx, col] = np.nan\n return df\n\n\n@pytest.fixture\ndef object_df(rng, long_df):\n\n df = long_df.copy()\n # objectify numeric columns\n for col in [\"c\", \"s\", \"f\"]:\n df[col] = df[col].astype(object)\n return df\n\n\n@pytest.fixture\ndef null_series(flat_series):\n\n return pd.Series(index=flat_series.index, dtype='float64')\n"},{"col":0,"comment":"null","endLoc":11,"header":"@pytest.fixture(autouse=True)\ndef close_figs()","id":1644,"name":"close_figs","nodeType":"Function","startLoc":7,"text":"@pytest.fixture(autouse=True)\ndef close_figs():\n yield\n import matplotlib.pyplot as plt\n plt.close(\"all\")"},{"col":0,"comment":"null","endLoc":17,"header":"@pytest.fixture(autouse=True)\ndef random_seed()","id":1645,"name":"random_seed","nodeType":"Function","startLoc":14,"text":"@pytest.fixture(autouse=True)\ndef random_seed():\n seed = sum(map(ord, \"seaborn random global\"))\n np.random.seed(seed)"},{"col":4,"comment":"null","endLoc":422,"header":"def test_heatmap_ticklabel_rotation(self)","id":1646,"name":"test_heatmap_ticklabel_rotation","nodeType":"Function","startLoc":396,"text":"def test_heatmap_ticklabel_rotation(self):\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.heatmap(self.df_norm, xticklabels=1, yticklabels=1, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 0\n\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 90\n\n plt.close(f)\n\n df = self.df_norm.copy()\n df.columns = [str(c) * 10 for c in df.columns]\n df.index = [i * 10 for i in df.index]\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.heatmap(df, xticklabels=1, yticklabels=1, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 90\n\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 0\n\n plt.close(f)"},{"id":1647,"name":"tests/_stats","nodeType":"Package"},{"fileName":"test_regression.py","filePath":"tests/_stats","id":1648,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\n\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nfrom pandas.testing import assert_frame_equal\n\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.regression import PolyFit\n\n\nclass TestPolyFit:\n\n @pytest.fixture\n def df(self, rng):\n\n n = 100\n return pd.DataFrame(dict(\n x=rng.normal(0, 1, n),\n y=rng.normal(0, 1, n),\n color=rng.choice([\"a\", \"b\", \"c\"], n),\n group=rng.choice([\"x\", \"y\"], n),\n ))\n\n def test_no_grouper(self, df):\n\n groupby = GroupBy([\"group\"])\n res = PolyFit(order=1, gridsize=100)(df[[\"x\", \"y\"]], groupby, \"x\", {})\n\n assert_array_equal(res.columns, [\"x\", \"y\"])\n\n grid = np.linspace(df[\"x\"].min(), df[\"x\"].max(), 100)\n assert_array_equal(res[\"x\"], grid)\n assert_array_almost_equal(\n res[\"y\"].diff().diff().dropna(), np.zeros(grid.size - 2)\n )\n\n def test_one_grouper(self, df):\n\n groupby = GroupBy([\"group\"])\n gridsize = 50\n res = PolyFit(gridsize=gridsize)(df, groupby, \"x\", {})\n\n assert res.columns.to_list() == [\"x\", \"y\", \"group\"]\n\n ngroups = df[\"group\"].nunique()\n assert_array_equal(res.index, np.arange(ngroups * gridsize))\n\n for _, part in res.groupby(\"group\"):\n grid = np.linspace(part[\"x\"].min(), part[\"x\"].max(), gridsize)\n assert_array_equal(part[\"x\"], grid)\n assert part[\"y\"].diff().diff().dropna().abs().gt(0).all()\n\n def test_missing_data(self, df):\n\n groupby = GroupBy([\"group\"])\n df.iloc[5:10] = np.nan\n res1 = PolyFit()(df[[\"x\", \"y\"]], groupby, \"x\", {})\n res2 = PolyFit()(df[[\"x\", \"y\"]].dropna(), groupby, \"x\", {})\n assert_frame_equal(res1, res2)"},{"className":"Color","col":0,"comment":"Color, as RGB(A), scalable with nominal palettes or continuous gradients.","endLoc":690,"id":1649,"nodeType":"Class","startLoc":539,"text":"class Color(Property):\n \"\"\"Color, as RGB(A), scalable with nominal palettes or continuous gradients.\"\"\"\n legend = True\n normed = True\n\n def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple:\n # Return color with alpha channel only if the input spec has it\n # This is so that RGBA colors can override the Alpha property\n if to_rgba(val) != to_rgba(val, 1):\n return to_rgba(val)\n else:\n return to_rgb(val)\n\n def _standardize_color_sequence(self, colors: ArrayLike) -> ArrayLike:\n \"\"\"Convert color sequence to RGB(A) array, preserving but not adding alpha.\"\"\"\n def has_alpha(x):\n return to_rgba(x) != to_rgba(x, 1)\n\n if isinstance(colors, np.ndarray):\n needs_alpha = colors.shape[1] == 4\n else:\n needs_alpha = any(has_alpha(x) for x in colors)\n\n if needs_alpha:\n return to_rgba_array(colors)\n else:\n return to_rgba_array(colors)[:, :3]\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n # TODO when inferring Continuous without data, verify type\n\n # TODO need to rethink the variable type system\n # (e.g. boolean, ordered categories as Ordinal, etc)..\n var_type = variable_type(data, boolean_type=\"categorical\")\n\n if isinstance(arg, (dict, list)):\n return Nominal(arg)\n\n if isinstance(arg, tuple):\n if var_type == \"categorical\":\n # TODO It seems reasonable to allow a gradient mapping for nominal\n # scale but it also feels \"technically\" wrong. Should this infer\n # Ordinal with categorical data and, if so, verify orderedness?\n return Nominal(arg)\n return Continuous(arg)\n\n if callable(arg):\n return Continuous(arg)\n\n # TODO Do we accept str like \"log\", \"pow\", etc. for semantics?\n\n # TODO what about\n # - Temporal? (i.e. datetime)\n # - Boolean?\n\n if not isinstance(arg, str):\n msg = \" \".join([\n f\"A single scale argument for {self.variable} variables must be\",\n f\"a string, dict, tuple, list, or callable, not {type(arg)}.\"\n ])\n raise TypeError(msg)\n\n if arg in QUAL_PALETTES:\n return Nominal(arg)\n elif var_type == \"numeric\":\n return Continuous(arg)\n # TODO implement scales for date variables and any others.\n else:\n return Nominal(arg)\n\n def _get_categorical_mapping(self, scale, data):\n \"\"\"Define mapping as lookup in list of discrete color values.\"\"\"\n levels = categorical_order(data, scale.order)\n n = len(levels)\n values = scale.values\n\n if isinstance(values, dict):\n self._check_dict_entries(levels, values)\n # TODO where to ensure that dict values have consistent representation?\n colors = [values[x] for x in levels]\n elif isinstance(values, list):\n colors = self._check_list_length(levels, scale.values)\n elif isinstance(values, tuple):\n colors = blend_palette(values, n)\n elif isinstance(values, str):\n colors = color_palette(values, n)\n elif values is None:\n if n <= len(get_color_cycle()):\n # Use current (global) default palette\n colors = color_palette(n_colors=n)\n else:\n colors = color_palette(\"husl\", n)\n else:\n scale_class = scale.__class__.__name__\n msg = \" \".join([\n f\"Scale values for {self.variable} with a {scale_class} mapping\",\n f\"must be string, list, tuple, or dict; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n # If color specified here has alpha channel, it will override alpha property\n colors = self._standardize_color_sequence(colors)\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n use = np.isfinite(x)\n out = np.full((len(ixs), colors.shape[1]), np.nan)\n out[use] = np.take(colors, ixs[use], axis=0)\n return out\n\n return mapping\n\n def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to color values.\"\"\"\n # TODO what is best way to do this conditional?\n # Should it be class-based or should classes have behavioral attributes?\n if isinstance(scale, Nominal):\n return self._get_categorical_mapping(scale, data)\n\n if scale.values is None:\n # TODO Rethink best default continuous color gradient\n mapping = color_palette(\"ch:\", as_cmap=True)\n elif isinstance(scale.values, tuple):\n # TODO blend_palette will strip alpha, but we should support\n # interpolation on all four channels\n mapping = blend_palette(scale.values, as_cmap=True)\n elif isinstance(scale.values, str):\n # TODO for matplotlib colormaps this will clip extremes, which is\n # different from what using the named colormap directly would do\n # This may or may not be desireable.\n mapping = color_palette(scale.values, as_cmap=True)\n elif callable(scale.values):\n mapping = scale.values\n else:\n scale_class = scale.__class__.__name__\n msg = \" \".join([\n f\"Scale values for {self.variable} with a {scale_class} mapping\",\n f\"must be string, tuple, or callable; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n def _mapping(x):\n # Remove alpha channel so it does not override alpha property downstream\n # TODO this will need to be more flexible to support RGBA tuples (see above)\n invalid = ~np.isfinite(x)\n out = mapping(x)[:, :3]\n out[invalid] = np.nan\n return out\n\n return _mapping"},{"col":4,"comment":"null","endLoc":550,"header":"def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple","id":1650,"name":"standardize","nodeType":"Function","startLoc":544,"text":"def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple:\n # Return color with alpha channel only if the input spec has it\n # This is so that RGBA colors can override the Alpha property\n if to_rgba(val) != to_rgba(val, 1):\n return to_rgba(val)\n else:\n return to_rgb(val)"},{"col":4,"comment":"Convert color sequence to RGB(A) array, preserving but not adding alpha.","endLoc":565,"header":"def _standardize_color_sequence(self, colors: ArrayLike) -> ArrayLike","id":1651,"name":"_standardize_color_sequence","nodeType":"Function","startLoc":552,"text":"def _standardize_color_sequence(self, colors: ArrayLike) -> ArrayLike:\n \"\"\"Convert color sequence to RGB(A) array, preserving but not adding alpha.\"\"\"\n def has_alpha(x):\n return to_rgba(x) != to_rgba(x, 1)\n\n if isinstance(colors, np.ndarray):\n needs_alpha = colors.shape[1] == 4\n else:\n needs_alpha = any(has_alpha(x) for x in colors)\n\n if needs_alpha:\n return to_rgba_array(colors)\n else:\n return to_rgba_array(colors)[:, :3]"},{"col":4,"comment":"null","endLoc":607,"header":"def infer_scale(self, arg: Any, data: Series) -> Scale","id":1653,"name":"infer_scale","nodeType":"Function","startLoc":567,"text":"def infer_scale(self, arg: Any, data: Series) -> Scale:\n # TODO when inferring Continuous without data, verify type\n\n # TODO need to rethink the variable type system\n # (e.g. boolean, ordered categories as Ordinal, etc)..\n var_type = variable_type(data, boolean_type=\"categorical\")\n\n if isinstance(arg, (dict, list)):\n return Nominal(arg)\n\n if isinstance(arg, tuple):\n if var_type == \"categorical\":\n # TODO It seems reasonable to allow a gradient mapping for nominal\n # scale but it also feels \"technically\" wrong. Should this infer\n # Ordinal with categorical data and, if so, verify orderedness?\n return Nominal(arg)\n return Continuous(arg)\n\n if callable(arg):\n return Continuous(arg)\n\n # TODO Do we accept str like \"log\", \"pow\", etc. for semantics?\n\n # TODO what about\n # - Temporal? (i.e. datetime)\n # - Boolean?\n\n if not isinstance(arg, str):\n msg = \" \".join([\n f\"A single scale argument for {self.variable} variables must be\",\n f\"a string, dict, tuple, list, or callable, not {type(arg)}.\"\n ])\n raise TypeError(msg)\n\n if arg in QUAL_PALETTES:\n return Nominal(arg)\n elif var_type == \"numeric\":\n return Continuous(arg)\n # TODO implement scales for date variables and any others.\n else:\n return Nominal(arg)"},{"className":"GroupBy","col":0,"comment":"\n Interface for Pandas GroupBy operations allowing specified group order.\n\n Writing our own class to do this has a few advantages:\n - It constrains the interface between Plot and Stat/Move objects\n - It allows control over the row order of the GroupBy result, which is\n important when using in the context of some Move operations (dodge, stack, ...)\n - It simplifies some complexities regarding the return type and Index contents\n one encounters with Pandas, especially for DataFrame -> DataFrame applies\n - It increases future flexibility regarding alternate DataFrame libraries\n\n ","endLoc":129,"id":1654,"nodeType":"Class","startLoc":16,"text":"class GroupBy:\n \"\"\"\n Interface for Pandas GroupBy operations allowing specified group order.\n\n Writing our own class to do this has a few advantages:\n - It constrains the interface between Plot and Stat/Move objects\n - It allows control over the row order of the GroupBy result, which is\n important when using in the context of some Move operations (dodge, stack, ...)\n - It simplifies some complexities regarding the return type and Index contents\n one encounters with Pandas, especially for DataFrame -> DataFrame applies\n - It increases future flexibility regarding alternate DataFrame libraries\n\n \"\"\"\n def __init__(self, order: list[str] | dict[str, list | None]):\n \"\"\"\n Initialize the GroupBy from grouping variables and optional level orders.\n\n Parameters\n ----------\n order\n List of variable names or dict mapping names to desired level orders.\n Level order values can be None to use default ordering rules. The\n variables can include names that are not expected to appear in the\n data; these will be dropped before the groups are defined.\n\n \"\"\"\n if not order:\n raise ValueError(\"GroupBy requires at least one grouping variable\")\n\n if isinstance(order, list):\n order = {k: None for k in order}\n self.order = order\n\n def _get_groups(\n self, data: DataFrame\n ) -> tuple[str | list[str], Index | MultiIndex]:\n \"\"\"Return index with Cartesian product of ordered grouping variable levels.\"\"\"\n levels = {}\n for var, order in self.order.items():\n if var in data:\n if order is None:\n order = categorical_order(data[var])\n levels[var] = order\n\n grouper: str | list[str]\n groups: Index | MultiIndex\n if not levels:\n grouper = []\n groups = pd.Index([])\n elif len(levels) > 1:\n grouper = list(levels)\n groups = pd.MultiIndex.from_product(levels.values(), names=grouper)\n else:\n grouper, = list(levels)\n groups = pd.Index(levels[grouper], name=grouper)\n return grouper, groups\n\n def _reorder_columns(self, res, data):\n \"\"\"Reorder result columns to match original order with new columns appended.\"\"\"\n cols = [c for c in data if c in res]\n cols += [c for c in res if c not in data]\n return res.reindex(columns=pd.Index(cols))\n\n def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame:\n \"\"\"\n Reduce each group to a single row in the output.\n\n The output will have a row for each unique combination of the grouping\n variable levels with null values for the aggregated variable(s) where\n those combinations do not appear in the dataset.\n\n \"\"\"\n grouper, groups = self._get_groups(data)\n\n if not grouper:\n # We will need to see whether there are valid usecases that end up here\n raise ValueError(\"No grouping variables are present in dataframe\")\n\n res = (\n data\n .groupby(grouper, sort=False, observed=True)\n .agg(*args, **kwargs)\n .reindex(groups)\n .reset_index()\n .pipe(self._reorder_columns, data)\n )\n\n return res\n\n def apply(\n self, data: DataFrame, func: Callable[..., DataFrame],\n *args, **kwargs,\n ) -> DataFrame:\n \"\"\"Apply a DataFrame -> DataFrame mapping to each group.\"\"\"\n grouper, groups = self._get_groups(data)\n\n if not grouper:\n return self._reorder_columns(func(data, *args, **kwargs), data)\n\n parts = {}\n for key, part_df in data.groupby(grouper, sort=False):\n parts[key] = func(part_df, *args, **kwargs)\n stack = []\n for key in groups:\n if key in parts:\n if isinstance(grouper, list):\n # Implies that we had a MultiIndex so key is iterable\n group_ids = dict(zip(grouper, cast(Iterable, key)))\n else:\n group_ids = {grouper: key}\n stack.append(parts[key].assign(**group_ids))\n\n res = pd.concat(stack, ignore_index=True)\n return self._reorder_columns(res, data)"},{"col":4,"comment":"\n Initialize the GroupBy from grouping variables and optional level orders.\n\n Parameters\n ----------\n order\n List of variable names or dict mapping names to desired level orders.\n Level order values can be None to use default ordering rules. The\n variables can include names that are not expected to appear in the\n data; these will be dropped before the groups are defined.\n\n ","endLoc":47,"header":"def __init__(self, order: list[str] | dict[str, list | None])","id":1655,"name":"__init__","nodeType":"Function","startLoc":29,"text":"def __init__(self, order: list[str] | dict[str, list | None]):\n \"\"\"\n Initialize the GroupBy from grouping variables and optional level orders.\n\n Parameters\n ----------\n order\n List of variable names or dict mapping names to desired level orders.\n Level order values can be None to use default ordering rules. The\n variables can include names that are not expected to appear in the\n data; these will be dropped before the groups are defined.\n\n \"\"\"\n if not order:\n raise ValueError(\"GroupBy requires at least one grouping variable\")\n\n if isinstance(order, list):\n order = {k: None for k in order}\n self.order = order"},{"col":4,"comment":"Return index with Cartesian product of ordered grouping variable levels.","endLoc":71,"header":"def _get_groups(\n self, data: DataFrame\n ) -> tuple[str | list[str], Index | MultiIndex]","id":1656,"name":"_get_groups","nodeType":"Function","startLoc":49,"text":"def _get_groups(\n self, data: DataFrame\n ) -> tuple[str | list[str], Index | MultiIndex]:\n \"\"\"Return index with Cartesian product of ordered grouping variable levels.\"\"\"\n levels = {}\n for var, order in self.order.items():\n if var in data:\n if order is None:\n order = categorical_order(data[var])\n levels[var] = order\n\n grouper: str | list[str]\n groups: Index | MultiIndex\n if not levels:\n grouper = []\n groups = pd.Index([])\n elif len(levels) > 1:\n grouper = list(levels)\n groups = pd.MultiIndex.from_product(levels.values(), names=grouper)\n else:\n grouper, = list(levels)\n groups = pd.Index(levels[grouper], name=grouper)\n return grouper, groups"},{"col":4,"comment":"null","endLoc":1289,"header":"def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws)","id":1657,"name":"plot_univariate_ecdf","nodeType":"Function","startLoc":1222,"text":"def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws):\n\n estimator = ECDF(**estimate_kws)\n\n # Set the draw style to step the right way for the data variable\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n plot_kws[\"drawstyle\"] = drawstyles[self.data_variable]\n\n # Loop through the subsets, transform and plot the data\n for sub_vars, sub_data in self.iter_data(\n \"hue\", reverse=True, from_comp_data=True,\n ):\n\n # Compute the ECDF\n if sub_data.empty:\n continue\n\n observations = sub_data[self.data_variable]\n weights = sub_data.get(\"weights\", None)\n stat, vals = estimator(observations, weights=weights)\n\n # Assign attributes based on semantic mapping\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n artist_kws[\"color\"] = self._hue_map(sub_vars[\"hue\"])\n\n # Return the data variable to the linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(self.data_variable):\n vals = np.power(10, vals)\n vals[0] = -np.inf\n\n # Work out the orientation of the plot\n if self.data_variable == \"x\":\n plot_args = vals, stat\n stat_variable = \"y\"\n else:\n plot_args = stat, vals\n stat_variable = \"x\"\n\n if estimator.stat == \"count\":\n top_edge = len(observations)\n else:\n top_edge = 1\n\n # Draw the line for this subset\n ax = self._get_axes(sub_vars)\n artist, = ax.plot(*plot_args, **artist_kws)\n sticky_edges = getattr(artist.sticky_edges, stat_variable)\n sticky_edges[:] = 0, top_edge\n\n # --- Finalize the plot ----\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n stat = estimator.stat.capitalize()\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = stat\n if self.data_variable == \"y\":\n default_x = stat\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n artist = partial(mpl.lines.Line2D, [], [])\n alpha = plot_kws.get(\"alpha\", 1)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, False, False, None, alpha, plot_kws, {},\n )"},{"col":4,"comment":"Initialize the class with its parameters\n\n Parameters\n ----------\n stat : {{\"proportion\", \"count\"}}\n Distribution statistic to compute.\n complementary : bool\n If True, use the complementary CDF (1 - CDF)\n\n ","endLoc":416,"header":"def __init__(self, stat=\"proportion\", complementary=False)","id":1658,"name":"__init__","nodeType":"Function","startLoc":403,"text":"def __init__(self, stat=\"proportion\", complementary=False):\n \"\"\"Initialize the class with its parameters\n\n Parameters\n ----------\n stat : {{\"proportion\", \"count\"}}\n Distribution statistic to compute.\n complementary : bool\n If True, use the complementary CDF (1 - CDF)\n\n \"\"\"\n _check_argument(\"stat\", [\"count\", \"proportion\"], stat)\n self.stat = stat\n self.complementary = complementary"},{"col":4,"comment":"Define mapping as lookup in list of discrete color values.","endLoc":649,"header":"def _get_categorical_mapping(self, scale, data)","id":1659,"name":"_get_categorical_mapping","nodeType":"Function","startLoc":609,"text":"def _get_categorical_mapping(self, scale, data):\n \"\"\"Define mapping as lookup in list of discrete color values.\"\"\"\n levels = categorical_order(data, scale.order)\n n = len(levels)\n values = scale.values\n\n if isinstance(values, dict):\n self._check_dict_entries(levels, values)\n # TODO where to ensure that dict values have consistent representation?\n colors = [values[x] for x in levels]\n elif isinstance(values, list):\n colors = self._check_list_length(levels, scale.values)\n elif isinstance(values, tuple):\n colors = blend_palette(values, n)\n elif isinstance(values, str):\n colors = color_palette(values, n)\n elif values is None:\n if n <= len(get_color_cycle()):\n # Use current (global) default palette\n colors = color_palette(n_colors=n)\n else:\n colors = color_palette(\"husl\", n)\n else:\n scale_class = scale.__class__.__name__\n msg = \" \".join([\n f\"Scale values for {self.variable} with a {scale_class} mapping\",\n f\"must be string, list, tuple, or dict; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n # If color specified here has alpha channel, it will override alpha property\n colors = self._standardize_color_sequence(colors)\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n use = np.isfinite(x)\n out = np.full((len(ixs), colors.shape[1]), np.nan)\n out[use] = np.take(colors, ixs[use], axis=0)\n return out\n\n return mapping"},{"col":4,"comment":"null","endLoc":1323,"header":"def plot_rug(self, height, expand_margins, legend, **kws)","id":1660,"name":"plot_rug","nodeType":"Function","startLoc":1291,"text":"def plot_rug(self, height, expand_margins, legend, **kws):\n\n for sub_vars, sub_data, in self.iter_data(from_comp_data=True):\n\n ax = self._get_axes(sub_vars)\n\n kws.setdefault(\"linewidth\", 1)\n\n if expand_margins:\n xmarg, ymarg = ax.margins()\n if \"x\" in self.variables:\n ymarg += height * 2\n if \"y\" in self.variables:\n xmarg += height * 2\n ax.margins(x=xmarg, y=ymarg)\n\n if \"hue\" in self.variables:\n kws.pop(\"c\", None)\n kws.pop(\"color\", None)\n\n if \"x\" in self.variables:\n self._plot_single_rug(sub_data, \"x\", height, ax, kws)\n if \"y\" in self.variables:\n self._plot_single_rug(sub_data, \"y\", height, ax, kws)\n\n # --- Finalize the plot\n self._add_axis_labels(ax)\n if \"hue\" in self.variables and legend:\n # TODO ideally i'd like the legend artist to look like a rug\n legend_artist = partial(mpl.lines.Line2D, [], [])\n self._add_legend(\n ax, legend_artist, False, False, None, 1, {}, {},\n )"},{"col":4,"comment":"Draw a rugplot along one axis of the plot.","endLoc":1362,"header":"def _plot_single_rug(self, sub_data, var, height, ax, kws)","id":1661,"name":"_plot_single_rug","nodeType":"Function","startLoc":1325,"text":"def _plot_single_rug(self, sub_data, var, height, ax, kws):\n \"\"\"Draw a rugplot along one axis of the plot.\"\"\"\n vector = sub_data[var]\n n = len(vector)\n\n # Return data to linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(var):\n vector = np.power(10, vector)\n\n # We'll always add a single collection with varying colors\n if \"hue\" in self.variables:\n colors = self._hue_map(sub_data[\"hue\"])\n else:\n colors = None\n\n # Build the array of values for the LineCollection\n if var == \"x\":\n\n trans = tx.blended_transform_factory(ax.transData, ax.transAxes)\n xy_pairs = np.column_stack([\n np.repeat(vector, 2), np.tile([0, height], n)\n ])\n\n if var == \"y\":\n\n trans = tx.blended_transform_factory(ax.transAxes, ax.transData)\n xy_pairs = np.column_stack([\n np.tile([0, height], n), np.repeat(vector, 2)\n ])\n\n # Draw the lines on the plot\n line_segs = xy_pairs.reshape([n, 2, 2])\n ax.add_collection(LineCollection(\n line_segs, transform=trans, colors=colors, **kws\n ))\n\n ax.autoscale_view(scalex=var == \"x\", scaley=var == \"y\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":102,"id":1669,"name":"semantics","nodeType":"Attribute","startLoc":102,"text":"semantics"},{"attributeType":"null","col":4,"comment":"null","endLoc":104,"id":1670,"name":"wide_structure","nodeType":"Attribute","startLoc":104,"text":"wide_structure"},{"attributeType":"null","col":4,"comment":"null","endLoc":105,"id":1671,"name":"flat_structure","nodeType":"Attribute","startLoc":105,"text":"flat_structure"},{"col":0,"comment":"null","endLoc":2300,"header":"def displot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, row=None, col=None, weights=None,\n # Other plot parameters\n kind=\"hist\", rug=False, rug_kws=None, log_scale=None, legend=True,\n # Hue-mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Faceting parameters\n col_wrap=None, row_order=None, col_order=None,\n height=5, aspect=1, facet_kws=None,\n **kwargs,\n)","id":1672,"name":"displot","nodeType":"Function","startLoc":2111,"text":"def displot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, row=None, col=None, weights=None,\n # Other plot parameters\n kind=\"hist\", rug=False, rug_kws=None, log_scale=None, legend=True,\n # Hue-mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Faceting parameters\n col_wrap=None, row_order=None, col_order=None,\n height=5, aspect=1, facet_kws=None,\n **kwargs,\n):\n\n p = _DistributionFacetPlotter(\n data=data,\n variables=_DistributionFacetPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n _check_argument(\"kind\", [\"hist\", \"kde\", \"ecdf\"], kind)\n\n # --- Initialize the FacetGrid object\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\n \"`displot` is a figure-level function and does not accept \"\n \"the ax= parameter. You may wish to try {}plot.\".format(kind)\n )\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n\n # Adapt the plot_data dataframe for use with FacetGrid\n grid_data = p.plot_data.rename(columns=p.variables)\n grid_data = grid_data.loc[:, ~grid_data.columns.duplicated()]\n\n col_name = p.variables.get(\"col\")\n row_name = p.variables.get(\"row\")\n\n if facet_kws is None:\n facet_kws = {}\n\n g = FacetGrid(\n data=grid_data, row=row_name, col=col_name,\n col_wrap=col_wrap, row_order=row_order,\n col_order=col_order, height=height,\n aspect=aspect,\n **facet_kws,\n )\n\n # Now attach the axes object to the plotter object\n if kind == \"kde\":\n allowed_types = [\"numeric\", \"datetime\"]\n else:\n allowed_types = None\n p._attach(g, allowed_types=allowed_types, log_scale=log_scale)\n\n # Check for a specification that lacks x/y data and return early\n if not p.has_xy_data:\n return g\n\n if color is None and hue is None:\n color = \"C0\"\n # XXX else warn if hue is not None?\n\n kwargs[\"legend\"] = legend\n\n # --- Draw the plots\n\n if kind == \"hist\":\n\n hist_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to Histogram\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, Histogram.__init__, histplot)\n\n estimate_kws = {}\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = hist_kws.pop(key, default_val)\n\n # Handle derivative defaults\n if estimate_kws[\"discrete\"] is None:\n estimate_kws[\"discrete\"] = p._default_discrete()\n\n hist_kws[\"estimate_kws\"] = estimate_kws\n\n hist_kws.setdefault(\"color\", color)\n\n if p.univariate:\n\n _assign_default_kwargs(hist_kws, p.plot_univariate_histogram, histplot)\n p.plot_univariate_histogram(**hist_kws)\n\n else:\n\n _assign_default_kwargs(hist_kws, p.plot_bivariate_histogram, histplot)\n p.plot_bivariate_histogram(**hist_kws)\n\n elif kind == \"kde\":\n\n kde_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to KDE\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, KDE.__init__, kdeplot)\n\n estimate_kws = {}\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = kde_kws.pop(key, default_val)\n\n kde_kws[\"estimate_kws\"] = estimate_kws\n kde_kws[\"color\"] = color\n\n if p.univariate:\n\n _assign_default_kwargs(kde_kws, p.plot_univariate_density, kdeplot)\n p.plot_univariate_density(**kde_kws)\n\n else:\n\n _assign_default_kwargs(kde_kws, p.plot_bivariate_density, kdeplot)\n p.plot_bivariate_density(**kde_kws)\n\n elif kind == \"ecdf\":\n\n ecdf_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to the estimator\n estimate_kws = {}\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, ECDF.__init__, ecdfplot)\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = ecdf_kws.pop(key, default_val)\n\n ecdf_kws[\"estimate_kws\"] = estimate_kws\n ecdf_kws[\"color\"] = color\n\n if p.univariate:\n\n _assign_default_kwargs(ecdf_kws, p.plot_univariate_ecdf, ecdfplot)\n p.plot_univariate_ecdf(**ecdf_kws)\n\n else:\n\n raise NotImplementedError(\"Bivariate ECDF plots are not implemented\")\n\n # All plot kinds can include a rug\n if rug:\n # TODO with expand_margins=True, each facet expands margins... annoying!\n if rug_kws is None:\n rug_kws = {}\n _assign_default_kwargs(rug_kws, p.plot_rug, rugplot)\n rug_kws[\"legend\"] = False\n if color is not None:\n rug_kws[\"color\"] = color\n p.plot_rug(**rug_kws)\n\n # Call FacetGrid annotation methods\n # Note that the legend is currently set inside the plotting method\n g.set_axis_labels(\n x_var=p.variables.get(\"x\", g.axes.flat[0].get_xlabel()),\n y_var=p.variables.get(\"y\", g.axes.flat[0].get_ylabel()),\n )\n g.set_titles()\n g.tight_layout()\n\n if data is not None and (x is not None or y is not None):\n if not isinstance(data, pd.DataFrame):\n data = pd.DataFrame(data)\n g.data = pd.merge(\n data,\n g.data[g.data.columns.difference(data.columns)],\n left_index=True,\n right_index=True,\n )\n else:\n wide_cols = {\n k: f\"_{k}_\" if v is None else v for k, v in p.variables.items()\n }\n g.data = p.plot_data.rename(columns=wide_cols)\n\n return g"},{"col":4,"comment":"null","endLoc":274,"header":"def __add__(self, other)","id":1673,"name":"__add__","nodeType":"Function","startLoc":268,"text":"def __add__(self, other):\n\n if isinstance(other, Mark) or isinstance(other, Stat):\n raise TypeError(\"Sorry, this isn't ggplot! Perhaps try Plot.add?\")\n\n other_type = other.__class__.__name__\n raise TypeError(f\"Unsupported operand type(s) for +: 'Plot' and '{other_type}\")"},{"col":4,"comment":"null","endLoc":278,"header":"def _repr_png_(self) -> tuple[bytes, dict[str, float]]","id":1674,"name":"_repr_png_","nodeType":"Function","startLoc":276,"text":"def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n\n return self.plot()._repr_png_()"},{"col":4,"comment":"\n Compile the plot spec and return the Plotter object.\n ","endLoc":820,"header":"def plot(self, pyplot: bool = False) -> Plotter","id":1675,"name":"plot","nodeType":"Function","startLoc":815,"text":"def plot(self, pyplot: bool = False) -> Plotter:\n \"\"\"\n Compile the plot spec and return the Plotter object.\n \"\"\"\n with theme_context(self._theme_with_defaults()):\n return self._plot(pyplot)"},{"col":4,"comment":"null","endLoc":326,"header":"def _theme_with_defaults(self) -> dict[str, Any]","id":1676,"name":"_theme_with_defaults","nodeType":"Function","startLoc":308,"text":"def _theme_with_defaults(self) -> dict[str, Any]:\n\n style_groups = [\n \"axes\", \"figure\", \"font\", \"grid\", \"hatch\", \"legend\", \"lines\",\n \"mathtext\", \"markers\", \"patch\", \"savefig\", \"scatter\",\n \"xaxis\", \"xtick\", \"yaxis\", \"ytick\",\n ]\n base = {\n k: mpl.rcParamsDefault[k] for k in mpl.rcParams\n if any(k.startswith(p) for p in style_groups)\n }\n theme = {\n **base,\n **axes_style(\"darkgrid\"),\n **plotting_context(\"notebook\"),\n \"axes.prop_cycle\": cycler(\"color\", color_palette(\"deep\")),\n }\n theme.update(self._theme)\n return theme"},{"col":4,"comment":"Return a function that maps from data domain to color values.","endLoc":690,"header":"def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]","id":1677,"name":"get_mapping","nodeType":"Function","startLoc":651,"text":"def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps from data domain to color values.\"\"\"\n # TODO what is best way to do this conditional?\n # Should it be class-based or should classes have behavioral attributes?\n if isinstance(scale, Nominal):\n return self._get_categorical_mapping(scale, data)\n\n if scale.values is None:\n # TODO Rethink best default continuous color gradient\n mapping = color_palette(\"ch:\", as_cmap=True)\n elif isinstance(scale.values, tuple):\n # TODO blend_palette will strip alpha, but we should support\n # interpolation on all four channels\n mapping = blend_palette(scale.values, as_cmap=True)\n elif isinstance(scale.values, str):\n # TODO for matplotlib colormaps this will clip extremes, which is\n # different from what using the named colormap directly would do\n # This may or may not be desireable.\n mapping = color_palette(scale.values, as_cmap=True)\n elif callable(scale.values):\n mapping = scale.values\n else:\n scale_class = scale.__class__.__name__\n msg = \" \".join([\n f\"Scale values for {self.variable} with a {scale_class} mapping\",\n f\"must be string, tuple, or callable; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n def _mapping(x):\n # Remove alpha channel so it does not override alpha property downstream\n # TODO this will need to be more flexible to support RGBA tuples (see above)\n invalid = ~np.isfinite(x)\n out = mapping(x)[:, :3]\n out[invalid] = np.nan\n return out\n\n return _mapping"},{"col":4,"comment":"null","endLoc":856,"header":"def _plot(self, pyplot: bool = False) -> Plotter","id":1678,"name":"_plot","nodeType":"Function","startLoc":822,"text":"def _plot(self, pyplot: bool = False) -> Plotter:\n\n # TODO if we have _target object, pyplot should be determined by whether it\n # is hooked into the pyplot state machine (how do we check?)\n\n plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults())\n\n # Process the variable assignments and initialize the figure\n common, layers = plotter._extract_data(self)\n plotter._setup_figure(self, common, layers)\n\n # Process the scale spec for coordinate variables and transform their data\n coord_vars = [v for v in self._variables if re.match(r\"^x|y\", v)]\n plotter._setup_scales(self, common, layers, coord_vars)\n\n # Apply statistical transform(s)\n plotter._compute_stats(self, layers)\n\n # Process scale spec for semantic variables and coordinates computed by stat\n plotter._setup_scales(self, common, layers)\n\n # TODO Remove these after updating other methods\n # ---- Maybe have debug= param that attaches these when True?\n plotter._data = common\n plotter._layers = layers\n\n # Process the data for each layer and add matplotlib artists\n for layer in layers:\n plotter._plot_layer(self, layer)\n\n # Add various figure decorations\n plotter._make_legend(self)\n plotter._finalize_figure(self)\n\n return plotter"},{"col":4,"comment":"null","endLoc":430,"header":"def test_heatmap_inner_lines(self)","id":1679,"name":"test_heatmap_inner_lines","nodeType":"Function","startLoc":424,"text":"def test_heatmap_inner_lines(self):\n\n c = (0, 0, 1, 1)\n ax = mat.heatmap(self.df_norm, linewidths=2, linecolor=c)\n mesh = ax.collections[0]\n assert mesh.get_linewidths()[0] == 2\n assert tuple(mesh.get_edgecolor()[0]) == c"},{"col":4,"comment":"Reorder result columns to match original order with new columns appended.","endLoc":77,"header":"def _reorder_columns(self, res, data)","id":1680,"name":"_reorder_columns","nodeType":"Function","startLoc":73,"text":"def _reorder_columns(self, res, data):\n \"\"\"Reorder result columns to match original order with new columns appended.\"\"\"\n cols = [c for c in data if c in res]\n cols += [c for c in res if c not in data]\n return res.reindex(columns=pd.Index(cols))"},{"col":4,"comment":"null","endLoc":881,"header":"def __init__(self, pyplot: bool, theme: dict[str, Any])","id":1681,"name":"__init__","nodeType":"Function","startLoc":874,"text":"def __init__(self, pyplot: bool, theme: dict[str, Any]):\n\n self._pyplot = pyplot\n self._theme = theme\n self._legend_contents: list[tuple[\n tuple[str, str | int], list[Artist], list[str],\n ]] = []\n self._scales: dict[str, Scale] = {}"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":186,"id":1682,"name":"wide_structure","nodeType":"Attribute","startLoc":186,"text":"wide_structure"},{"attributeType":"bool","col":4,"comment":"null","endLoc":191,"id":1683,"name":"sort","nodeType":"Attribute","startLoc":191,"text":"sort"},{"attributeType":"list","col":8,"comment":"null","endLoc":343,"id":1684,"name":"legend_order","nodeType":"Attribute","startLoc":343,"text":"self.legend_order"},{"attributeType":"dict","col":8,"comment":"null","endLoc":342,"id":1685,"name":"legend_data","nodeType":"Attribute","startLoc":342,"text":"self.legend_data"},{"attributeType":"bool","col":4,"comment":"null","endLoc":541,"id":1686,"name":"legend","nodeType":"Attribute","startLoc":541,"text":"legend"},{"attributeType":"bool","col":4,"comment":"null","endLoc":542,"id":1687,"name":"normed","nodeType":"Attribute","startLoc":542,"text":"normed"},{"className":"Fill","col":0,"comment":"Boolean property of points/bars/patches that can be solid or outlined.","endLoc":762,"id":1688,"nodeType":"Class","startLoc":698,"text":"class Fill(Property):\n \"\"\"Boolean property of points/bars/patches that can be solid or outlined.\"\"\"\n legend = True\n normed = False\n\n # TODO default to Nominal scale always?\n # Actually this will just not work with Continuous (except 0/1), suggesting we need\n # an abstraction for failing gracefully on bad Property <> Scale interactions\n\n def standardize(self, val: Any) -> bool:\n return bool(val)\n\n def _default_values(self, n: int) -> list:\n \"\"\"Return a list of n values, alternating True and False.\"\"\"\n if n > 2:\n msg = \" \".join([\n f\"The variable assigned to {self.variable} has more than two levels,\",\n f\"so {self.variable} values will cycle and may be uninterpretable\",\n ])\n # TODO fire in a \"nice\" way (see above)\n warnings.warn(msg, UserWarning)\n return [x for x, _ in zip(itertools.cycle([True, False]), range(n))]\n\n def default_scale(self, data: Series) -> Nominal:\n \"\"\"Given data, initialize appropriate scale class.\"\"\"\n return Nominal()\n\n def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n # TODO infer Boolean where possible?\n return Nominal(arg)\n\n def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps each data value to True or False.\"\"\"\n # TODO categorical_order is going to return [False, True] for booleans,\n # and [0, 1] for binary, but the default values order is [True, False].\n # We should special case this to handle it properly, or change\n # categorical_order to not \"sort\" booleans. Note that we need to sync with\n # what's going to happen upstream in the scale, so we can't just do it here.\n order = getattr(scale, \"order\", None)\n levels = categorical_order(data, order)\n\n if isinstance(scale.values, list):\n values = [bool(x) for x in scale.values]\n elif isinstance(scale.values, dict):\n values = [bool(scale.values[x]) for x in levels]\n elif scale.values is None:\n values = self._default_values(len(levels))\n else:\n msg = \" \".join([\n f\"Scale values for {self.variable} must be passed in\",\n f\"a list or dict; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n return [\n values[ix] if np.isfinite(x_i) else False\n for x_i, ix in zip(x, ixs)\n ]\n\n return mapping"},{"col":4,"comment":"null","endLoc":708,"header":"def standardize(self, val: Any) -> bool","id":1689,"name":"standardize","nodeType":"Function","startLoc":707,"text":"def standardize(self, val: Any) -> bool:\n return bool(val)"},{"attributeType":"str","col":8,"comment":"null","endLoc":341,"id":1690,"name":"legend_title","nodeType":"Attribute","startLoc":341,"text":"self.legend_title"},{"col":0,"comment":"Assign default kwargs for call_func using values from source_func.","endLoc":804,"header":"def _assign_default_kwargs(kws, call_func, source_func)","id":1691,"name":"_assign_default_kwargs","nodeType":"Function","startLoc":788,"text":"def _assign_default_kwargs(kws, call_func, source_func):\n \"\"\"Assign default kwargs for call_func using values from source_func.\"\"\"\n # This exists so that axes-level functions and figure-level functions can\n # both call a Plotter method while having the default kwargs be defined in\n # the signature of the axes-level function.\n # An alternative would be to have a decorator on the method that sets its\n # defaults based on those defined in the axes-level function.\n # Then the figure-level function would not need to worry about defaults.\n # I am not sure which is better.\n needed = inspect.signature(call_func).parameters\n defaults = inspect.signature(source_func).parameters\n\n for param in needed:\n if param in defaults and param not in kws:\n kws[param] = defaults[param].default\n\n return kws"},{"col":4,"comment":"\n Reduce each group to a single row in the output.\n\n The output will have a row for each unique combination of the grouping\n variable levels with null values for the aggregated variable(s) where\n those combinations do not appear in the dataset.\n\n ","endLoc":103,"header":"def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame","id":1692,"name":"agg","nodeType":"Function","startLoc":79,"text":"def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame:\n \"\"\"\n Reduce each group to a single row in the output.\n\n The output will have a row for each unique combination of the grouping\n variable levels with null values for the aggregated variable(s) where\n those combinations do not appear in the dataset.\n\n \"\"\"\n grouper, groups = self._get_groups(data)\n\n if not grouper:\n # We will need to see whether there are valid usecases that end up here\n raise ValueError(\"No grouping variables are present in dataframe\")\n\n res = (\n data\n .groupby(grouper, sort=False, observed=True)\n .agg(*args, **kwargs)\n .reindex(groups)\n .reset_index()\n .pipe(self._reorder_columns, data)\n )\n\n return res"},{"col":4,"comment":"Apply a DataFrame -> DataFrame mapping to each group.","endLoc":129,"header":"def apply(\n self, data: DataFrame, func: Callable[..., DataFrame],\n *args, **kwargs,\n ) -> DataFrame","id":1693,"name":"apply","nodeType":"Function","startLoc":105,"text":"def apply(\n self, data: DataFrame, func: Callable[..., DataFrame],\n *args, **kwargs,\n ) -> DataFrame:\n \"\"\"Apply a DataFrame -> DataFrame mapping to each group.\"\"\"\n grouper, groups = self._get_groups(data)\n\n if not grouper:\n return self._reorder_columns(func(data, *args, **kwargs), data)\n\n parts = {}\n for key, part_df in data.groupby(grouper, sort=False):\n parts[key] = func(part_df, *args, **kwargs)\n stack = []\n for key in groups:\n if key in parts:\n if isinstance(grouper, list):\n # Implies that we had a MultiIndex so key is iterable\n group_ids = dict(zip(grouper, cast(Iterable, key)))\n else:\n group_ids = {grouper: key}\n stack.append(parts[key].assign(**group_ids))\n\n res = pd.concat(stack, ignore_index=True)\n return self._reorder_columns(res, data)"},{"col":4,"comment":"null","endLoc":438,"header":"def test_square_aspect(self)","id":1694,"name":"test_square_aspect","nodeType":"Function","startLoc":432,"text":"def test_square_aspect(self):\n\n ax = mat.heatmap(self.df_norm, square=True)\n obs_aspect = ax.get_aspect()\n # mpl>3.3 returns 1 for setting \"equal\" aspect\n # so test for the two possible equal outcomes\n assert obs_aspect == \"equal\" or obs_aspect == 1"},{"col":4,"comment":"Return a list of n values, alternating True and False.","endLoc":719,"header":"def _default_values(self, n: int) -> list","id":1695,"name":"_default_values","nodeType":"Function","startLoc":710,"text":"def _default_values(self, n: int) -> list:\n \"\"\"Return a list of n values, alternating True and False.\"\"\"\n if n > 2:\n msg = \" \".join([\n f\"The variable assigned to {self.variable} has more than two levels,\",\n f\"so {self.variable} values will cycle and may be uninterpretable\",\n ])\n # TODO fire in a \"nice\" way (see above)\n warnings.warn(msg, UserWarning)\n return [x for x, _ in zip(itertools.cycle([True, False]), range(n))]"},{"col":4,"comment":"null","endLoc":452,"header":"def test_mask_validation(self)","id":1696,"name":"test_mask_validation","nodeType":"Function","startLoc":440,"text":"def test_mask_validation(self):\n\n mask = mat._matrix_mask(self.df_norm, None)\n assert mask.shape == self.df_norm.shape\n assert mask.values.sum() == 0\n\n with pytest.raises(ValueError):\n bad_array_mask = self.rs.randn(3, 6) > 0\n mat._matrix_mask(self.df_norm, bad_array_mask)\n\n with pytest.raises(ValueError):\n bad_df_mask = pd.DataFrame(self.rs.randn(4, 8) > 0)\n mat._matrix_mask(self.df_norm, bad_df_mask)"},{"col":4,"comment":"null","endLoc":946,"header":"def _repr_png_(self) -> tuple[bytes, dict[str, float]]","id":1697,"name":"_repr_png_","nodeType":"Function","startLoc":909,"text":"def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n\n # TODO better to do this through a Jupyter hook? e.g.\n # ipy = IPython.core.formatters.get_ipython()\n # fmt = ipy.display_formatter.formatters[\"text/html\"]\n # fmt.for_type(Plot, ...)\n # Would like to have a svg option too, not sure how to make that flexible\n\n # TODO use matplotlib backend directly instead of going through savefig?\n\n # TODO perhaps have self.show() flip a switch to disable this, so that\n # user does not end up with two versions of the figure in the output\n\n # TODO use bbox_inches=\"tight\" like the inline backend?\n # pro: better results, con: (sometimes) confusing results\n # Better solution would be to default (with option to change)\n # to using constrained/tight layout.\n\n # TODO need to decide what the right default behavior here is:\n # - Use dpi=72 to match default InlineBackend figure size?\n # - Accept a generic \"scaling\" somewhere and scale DPI from that,\n # either with 1x -> 72 or 1x -> 96 and the default scaling be .75?\n # - Listen to rcParams? InlineBackend behavior makes that so complicated :(\n # - Do we ever want to *not* use retina mode at this point?\n\n from PIL import Image\n\n dpi = 96\n buffer = io.BytesIO()\n\n with theme_context(self._theme):\n self._figure.savefig(buffer, dpi=dpi * 2, format=\"png\", bbox_inches=\"tight\")\n data = buffer.getvalue()\n\n scaling = .85 / 2\n w, h = Image.open(buffer).size\n metadata = {\"width\": w * scaling, \"height\": h * scaling}\n return data, metadata"},{"col":4,"comment":"null","endLoc":463,"header":"def test_missing_data_mask(self)","id":1698,"name":"test_missing_data_mask","nodeType":"Function","startLoc":454,"text":"def test_missing_data_mask(self):\n\n data = pd.DataFrame(np.arange(4, dtype=float).reshape(2, 2))\n data.loc[0, 0] = np.nan\n mask = mat._matrix_mask(data, None)\n npt.assert_array_equal(mask, [[True, False], [False, False]])\n\n mask_in = np.array([[False, True], [False, False]])\n mask_out = mat._matrix_mask(data, mask_in)\n npt.assert_array_equal(mask_out, [[True, True], [False, False]])"},{"col":4,"comment":"null","endLoc":470,"header":"def test_cbar_ticks(self)","id":1699,"name":"test_cbar_ticks","nodeType":"Function","startLoc":465,"text":"def test_cbar_ticks(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n mat.heatmap(self.df_norm, ax=ax1, cbar_ax=ax2,\n cbar_kws=dict(drawedges=True))\n assert len(ax2.collections) == 2"},{"className":"_LinePlotter","col":0,"comment":"null","endLoc":515,"id":1700,"nodeType":"Class","startLoc":346,"text":"class _LinePlotter(_RelationalPlotter):\n\n _legend_attributes = [\"color\", \"linewidth\", \"marker\", \"dashes\"]\n _legend_func = \"plot\"\n\n def __init__(\n self, *,\n data=None, variables={},\n estimator=None, n_boot=None, seed=None, errorbar=None,\n sort=True, orient=\"x\", err_style=None, err_kws=None, legend=None\n ):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * mpl.rcParams[\"lines.linewidth\"]\n )\n\n super().__init__(data=data, variables=variables)\n\n self.estimator = estimator\n self.errorbar = errorbar\n self.n_boot = n_boot\n self.seed = seed\n self.sort = sort\n self.orient = orient\n self.err_style = err_style\n self.err_kws = {} if err_kws is None else err_kws\n\n self.legend = legend\n\n def plot(self, ax, kws):\n \"\"\"Draw the plot onto an axes, passing matplotlib kwargs.\"\"\"\n\n # Draw a test plot, using the passed in kwargs. The goal here is to\n # honor both (a) the current state of the plot cycler and (b) the\n # specified kwargs on all the lines we will draw, overriding when\n # relevant with the data semantics. Note that we won't cycle\n # internally; in other words, if `hue` is not used, all elements will\n # have the same color, but they will have the color that you would have\n # gotten from the corresponding matplotlib function, and calling the\n # function will advance the axes property cycle.\n\n kws.setdefault(\"markeredgewidth\", kws.pop(\"mew\", .75))\n kws.setdefault(\"markeredgecolor\", kws.pop(\"mec\", \"w\"))\n\n # Set default error kwargs\n err_kws = self.err_kws.copy()\n if self.err_style == \"band\":\n err_kws.setdefault(\"alpha\", .2)\n elif self.err_style == \"bars\":\n pass\n elif self.err_style is not None:\n err = \"`err_style` must be 'band' or 'bars', not {}\"\n raise ValueError(err.format(self.err_style))\n\n # Initialize the aggregation object\n agg = EstimateAggregator(\n self.estimator, self.errorbar, n_boot=self.n_boot, seed=self.seed,\n )\n\n # TODO abstract variable to aggregate over here-ish. Better name?\n orient = self.orient\n if orient not in {\"x\", \"y\"}:\n err = f\"`orient` must be either 'x' or 'y', not {orient!r}.\"\n raise ValueError(err)\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n\n # TODO How to handle NA? We don't want NA to propagate through to the\n # estimate/CI when some values are present, but we would also like\n # matplotlib to show \"gaps\" in the line when all values are missing.\n # This is straightforward absent aggregation, but complicated with it.\n # If we want to use nas, we need to conditionalize dropna in iter_data.\n\n # Loop over the semantic subsets and add to the plot\n grouping_vars = \"hue\", \"size\", \"style\"\n for sub_vars, sub_data in self.iter_data(grouping_vars, from_comp_data=True):\n\n if self.sort:\n sort_vars = [\"units\", orient, other]\n sort_cols = [var for var in sort_vars if var in self.variables]\n sub_data = sub_data.sort_values(sort_cols)\n\n if self.estimator is not None:\n if \"units\" in self.variables:\n # TODO eventually relax this constraint\n err = \"estimator must be None when specifying units\"\n raise ValueError(err)\n grouped = sub_data.groupby(orient, sort=self.sort)\n # Could pass as_index=False instead of reset_index,\n # but that fails on a corner case with older pandas.\n sub_data = grouped.apply(agg, other).reset_index()\n\n # TODO this is pretty ad hoc ; see GH2409\n for var in \"xy\":\n if self._log_scaled(var):\n for col in sub_data.filter(regex=f\"^{var}\"):\n sub_data[col] = np.power(10, sub_data[col])\n\n # --- Draw the main line(s)\n\n if \"units\" in self.variables: # XXX why not add to grouping variables?\n lines = []\n for _, unit_data in sub_data.groupby(\"units\"):\n lines.extend(ax.plot(unit_data[\"x\"], unit_data[\"y\"], **kws))\n else:\n lines = ax.plot(sub_data[\"x\"], sub_data[\"y\"], **kws)\n\n for line in lines:\n\n if \"hue\" in sub_vars:\n line.set_color(self._hue_map(sub_vars[\"hue\"]))\n\n if \"size\" in sub_vars:\n line.set_linewidth(self._size_map(sub_vars[\"size\"]))\n\n if \"style\" in sub_vars:\n attributes = self._style_map(sub_vars[\"style\"])\n if \"dashes\" in attributes:\n line.set_dashes(attributes[\"dashes\"])\n if \"marker\" in attributes:\n line.set_marker(attributes[\"marker\"])\n\n line_color = line.get_color()\n line_alpha = line.get_alpha()\n line_capstyle = line.get_solid_capstyle()\n\n # --- Draw the confidence intervals\n\n if self.estimator is not None and self.errorbar is not None:\n\n # TODO handling of orientation will need to happen here\n\n if self.err_style == \"band\":\n\n func = {\"x\": ax.fill_between, \"y\": ax.fill_betweenx}[orient]\n func(\n sub_data[orient],\n sub_data[f\"{other}min\"], sub_data[f\"{other}max\"],\n color=line_color, **err_kws\n )\n\n elif self.err_style == \"bars\":\n\n error_param = {\n f\"{other}err\": (\n sub_data[other] - sub_data[f\"{other}min\"],\n sub_data[f\"{other}max\"] - sub_data[other],\n )\n }\n ebars = ax.errorbar(\n sub_data[\"x\"], sub_data[\"y\"], **error_param,\n linestyle=\"\", color=line_color, alpha=line_alpha,\n **err_kws\n )\n\n # Set the capstyle properly on the error bars\n for obj in ebars.get_children():\n if isinstance(obj, mpl.collections.LineCollection):\n obj.set_capstyle(line_capstyle)\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)"},{"col":4,"comment":"Draw the plot onto an axes, passing matplotlib kwargs.","endLoc":515,"header":"def plot(self, ax, kws)","id":1701,"name":"plot","nodeType":"Function","startLoc":378,"text":"def plot(self, ax, kws):\n \"\"\"Draw the plot onto an axes, passing matplotlib kwargs.\"\"\"\n\n # Draw a test plot, using the passed in kwargs. The goal here is to\n # honor both (a) the current state of the plot cycler and (b) the\n # specified kwargs on all the lines we will draw, overriding when\n # relevant with the data semantics. Note that we won't cycle\n # internally; in other words, if `hue` is not used, all elements will\n # have the same color, but they will have the color that you would have\n # gotten from the corresponding matplotlib function, and calling the\n # function will advance the axes property cycle.\n\n kws.setdefault(\"markeredgewidth\", kws.pop(\"mew\", .75))\n kws.setdefault(\"markeredgecolor\", kws.pop(\"mec\", \"w\"))\n\n # Set default error kwargs\n err_kws = self.err_kws.copy()\n if self.err_style == \"band\":\n err_kws.setdefault(\"alpha\", .2)\n elif self.err_style == \"bars\":\n pass\n elif self.err_style is not None:\n err = \"`err_style` must be 'band' or 'bars', not {}\"\n raise ValueError(err.format(self.err_style))\n\n # Initialize the aggregation object\n agg = EstimateAggregator(\n self.estimator, self.errorbar, n_boot=self.n_boot, seed=self.seed,\n )\n\n # TODO abstract variable to aggregate over here-ish. Better name?\n orient = self.orient\n if orient not in {\"x\", \"y\"}:\n err = f\"`orient` must be either 'x' or 'y', not {orient!r}.\"\n raise ValueError(err)\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n\n # TODO How to handle NA? We don't want NA to propagate through to the\n # estimate/CI when some values are present, but we would also like\n # matplotlib to show \"gaps\" in the line when all values are missing.\n # This is straightforward absent aggregation, but complicated with it.\n # If we want to use nas, we need to conditionalize dropna in iter_data.\n\n # Loop over the semantic subsets and add to the plot\n grouping_vars = \"hue\", \"size\", \"style\"\n for sub_vars, sub_data in self.iter_data(grouping_vars, from_comp_data=True):\n\n if self.sort:\n sort_vars = [\"units\", orient, other]\n sort_cols = [var for var in sort_vars if var in self.variables]\n sub_data = sub_data.sort_values(sort_cols)\n\n if self.estimator is not None:\n if \"units\" in self.variables:\n # TODO eventually relax this constraint\n err = \"estimator must be None when specifying units\"\n raise ValueError(err)\n grouped = sub_data.groupby(orient, sort=self.sort)\n # Could pass as_index=False instead of reset_index,\n # but that fails on a corner case with older pandas.\n sub_data = grouped.apply(agg, other).reset_index()\n\n # TODO this is pretty ad hoc ; see GH2409\n for var in \"xy\":\n if self._log_scaled(var):\n for col in sub_data.filter(regex=f\"^{var}\"):\n sub_data[col] = np.power(10, sub_data[col])\n\n # --- Draw the main line(s)\n\n if \"units\" in self.variables: # XXX why not add to grouping variables?\n lines = []\n for _, unit_data in sub_data.groupby(\"units\"):\n lines.extend(ax.plot(unit_data[\"x\"], unit_data[\"y\"], **kws))\n else:\n lines = ax.plot(sub_data[\"x\"], sub_data[\"y\"], **kws)\n\n for line in lines:\n\n if \"hue\" in sub_vars:\n line.set_color(self._hue_map(sub_vars[\"hue\"]))\n\n if \"size\" in sub_vars:\n line.set_linewidth(self._size_map(sub_vars[\"size\"]))\n\n if \"style\" in sub_vars:\n attributes = self._style_map(sub_vars[\"style\"])\n if \"dashes\" in attributes:\n line.set_dashes(attributes[\"dashes\"])\n if \"marker\" in attributes:\n line.set_marker(attributes[\"marker\"])\n\n line_color = line.get_color()\n line_alpha = line.get_alpha()\n line_capstyle = line.get_solid_capstyle()\n\n # --- Draw the confidence intervals\n\n if self.estimator is not None and self.errorbar is not None:\n\n # TODO handling of orientation will need to happen here\n\n if self.err_style == \"band\":\n\n func = {\"x\": ax.fill_between, \"y\": ax.fill_betweenx}[orient]\n func(\n sub_data[orient],\n sub_data[f\"{other}min\"], sub_data[f\"{other}max\"],\n color=line_color, **err_kws\n )\n\n elif self.err_style == \"bars\":\n\n error_param = {\n f\"{other}err\": (\n sub_data[other] - sub_data[f\"{other}min\"],\n sub_data[f\"{other}max\"] - sub_data[other],\n )\n }\n ebars = ax.errorbar(\n sub_data[\"x\"], sub_data[\"y\"], **error_param,\n linestyle=\"\", color=line_color, alpha=line_alpha,\n **err_kws\n )\n\n # Set the capstyle properly on the error bars\n for obj in ebars.get_children():\n if isinstance(obj, mpl.collections.LineCollection):\n obj.set_capstyle(line_capstyle)\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)"},{"col":0,"comment":"null","endLoc":23,"header":"@pytest.fixture()\ndef rng()","id":1702,"name":"rng","nodeType":"Function","startLoc":20,"text":"@pytest.fixture()\ndef rng():\n seed = sum(map(ord, \"seaborn random object\"))\n return np.random.RandomState(seed)"},{"col":0,"comment":"null","endLoc":32,"header":"@pytest.fixture\ndef wide_df(rng)","id":1704,"name":"wide_df","nodeType":"Function","startLoc":26,"text":"@pytest.fixture\ndef wide_df(rng):\n\n columns = list(\"abc\")\n index = pd.RangeIndex(10, 50, 2, name=\"wide_index\")\n values = rng.normal(size=(len(index), len(columns)))\n return pd.DataFrame(values, index=index, columns=columns)"},{"col":4,"comment":"Generate a new object with the same information as the current spec.","endLoc":306,"header":"def _clone(self) -> Plot","id":1705,"name":"_clone","nodeType":"Function","startLoc":282,"text":"def _clone(self) -> Plot:\n \"\"\"Generate a new object with the same information as the current spec.\"\"\"\n new = Plot()\n\n # TODO any way to enforce that data does not get mutated?\n new._data = self._data\n\n new._layers.extend(self._layers)\n\n new._scales.update(self._scales)\n new._shares.update(self._shares)\n new._limits.update(self._limits)\n new._labels.update(self._labels)\n new._theme.update(self._theme)\n\n new._facet_spec.update(self._facet_spec)\n new._pair_spec.update(self._pair_spec)\n\n new._figure_spec.update(self._figure_spec)\n new._subplot_spec.update(self._subplot_spec)\n new._layout_spec.update(self._layout_spec)\n\n new._target = self._target\n\n return new"},{"attributeType":"null","col":4,"comment":"null","endLoc":37,"id":1706,"name":"rs","nodeType":"Attribute","startLoc":37,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":39,"id":1707,"name":"x_norm","nodeType":"Attribute","startLoc":39,"text":"x_norm"},{"attributeType":"null","col":4,"comment":"null","endLoc":40,"id":1708,"name":"letters","nodeType":"Attribute","startLoc":40,"text":"letters"},{"attributeType":"null","col":4,"comment":"null","endLoc":41,"id":1709,"name":"df_norm","nodeType":"Attribute","startLoc":41,"text":"df_norm"},{"attributeType":"null","col":4,"comment":"null","endLoc":43,"id":1710,"name":"x_unif","nodeType":"Attribute","startLoc":43,"text":"x_unif"},{"attributeType":"null","col":4,"comment":"null","endLoc":44,"id":1711,"name":"df_unif","nodeType":"Attribute","startLoc":44,"text":"df_unif"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":46,"id":1712,"name":"default_kws","nodeType":"Attribute","startLoc":46,"text":"default_kws"},{"className":"TestDendrogram","col":0,"comment":"null","endLoc":715,"id":1713,"nodeType":"Class","startLoc":473,"text":"@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\nclass TestDendrogram:\n\n rs = np.random.RandomState(sum(map(ord, \"dendrogram\")))\n\n default_kws = dict(linkage=None, metric='euclidean', method='single',\n axis=1, label=True, rotate=False)\n\n x_norm = rs.randn(4, 8) + np.arange(8)\n x_norm = (x_norm.T + np.arange(4)).T\n letters = pd.Series([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"],\n name=\"letters\")\n\n df_norm = pd.DataFrame(x_norm, columns=letters)\n\n if not _no_scipy:\n if _no_fastcluster:\n x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')\n x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')\n else:\n x_norm_linkage = fastcluster.linkage_vector(x_norm.T,\n metric='euclidean',\n method='single')\n\n x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,\n color_threshold=-np.inf)\n x_norm_leaves = x_norm_dendrogram['leaves']\n df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])\n\n def test_ndarray_input(self):\n p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)\n npt.assert_array_equal(p.array.T, self.x_norm)\n pdt.assert_frame_equal(p.data.T, pd.DataFrame(self.x_norm))\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)\n\n npt.assert_array_equal(p.xticklabels, self.x_norm_leaves)\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel is None\n assert p.ylabel == ''\n\n def test_df_input(self):\n p = mat._DendrogramPlotter(self.df_norm, **self.default_kws)\n npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))\n pdt.assert_frame_equal(p.data.T, self.df_norm)\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.xticklabels,\n np.asarray(self.df_norm.columns)[\n self.x_norm_leaves])\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel == 'letters'\n assert p.ylabel == ''\n\n def test_df_multindex_input(self):\n\n df = self.df_norm.copy()\n index = pd.MultiIndex.from_tuples([(\"A\", 1), (\"B\", 2),\n (\"C\", 3), (\"D\", 4)],\n names=[\"letter\", \"number\"])\n index.name = \"letter-number\"\n df.index = index\n kws = self.default_kws.copy()\n kws['label'] = True\n\n p = mat._DendrogramPlotter(df.T, **kws)\n\n xticklabels = [\"A-1\", \"B-2\", \"C-3\", \"D-4\"]\n xticklabels = [xticklabels[i] for i in p.reordered_ind]\n npt.assert_array_equal(p.xticklabels, xticklabels)\n npt.assert_array_equal(p.yticklabels, [])\n assert p.xlabel == \"letter-number\"\n\n def test_axis0_input(self):\n kws = self.default_kws.copy()\n kws['axis'] = 0\n p = mat._DendrogramPlotter(self.df_norm.T, **kws)\n\n npt.assert_array_equal(p.array, np.asarray(self.df_norm.T))\n pdt.assert_frame_equal(p.data, self.df_norm.T)\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.xticklabels, self.df_norm_leaves)\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel == 'letters'\n assert p.ylabel == ''\n\n def test_rotate_input(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))\n pdt.assert_frame_equal(p.data.T, self.df_norm)\n\n npt.assert_array_equal(p.xticklabels, [])\n npt.assert_array_equal(p.yticklabels, self.df_norm_leaves)\n\n assert p.xlabel == ''\n assert p.ylabel == 'letters'\n\n def test_rotate_axis0_input(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n kws['axis'] = 0\n p = mat._DendrogramPlotter(self.df_norm.T, **kws)\n\n npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)\n\n def test_custom_linkage(self):\n kws = self.default_kws.copy()\n\n try:\n import fastcluster\n\n linkage = fastcluster.linkage_vector(self.x_norm, method='single',\n metric='euclidean')\n except ImportError:\n d = distance.pdist(self.x_norm, metric='euclidean')\n linkage = hierarchy.linkage(d, method='single')\n dendrogram = hierarchy.dendrogram(linkage, no_plot=True,\n color_threshold=-np.inf)\n kws['linkage'] = linkage\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n\n npt.assert_array_equal(p.linkage, linkage)\n assert p.dendrogram == dendrogram\n\n def test_label_false(self):\n kws = self.default_kws.copy()\n kws['label'] = False\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n assert p.xticks == []\n assert p.yticks == []\n assert p.xticklabels == []\n assert p.yticklabels == []\n assert p.xlabel == \"\"\n assert p.ylabel == \"\"\n\n def test_linkage_scipy(self):\n p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)\n\n scipy_linkage = p._calculate_linkage_scipy()\n\n from scipy.spatial import distance\n from scipy.cluster import hierarchy\n\n dists = distance.pdist(self.x_norm.T,\n metric=self.default_kws['metric'])\n linkage = hierarchy.linkage(dists, method=self.default_kws['method'])\n\n npt.assert_array_equal(scipy_linkage, linkage)\n\n @pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_other_method(self):\n import fastcluster\n\n kws = self.default_kws.copy()\n kws['method'] = 'average'\n linkage = fastcluster.linkage(self.x_norm.T, method='average',\n metric='euclidean')\n p = mat._DendrogramPlotter(self.x_norm, **kws)\n npt.assert_array_equal(p.linkage, linkage)\n\n @pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_non_euclidean(self):\n import fastcluster\n\n kws = self.default_kws.copy()\n kws['metric'] = 'cosine'\n kws['method'] = 'average'\n linkage = fastcluster.linkage(self.x_norm.T, method=kws['method'],\n metric=kws['metric'])\n p = mat._DendrogramPlotter(self.x_norm, **kws)\n npt.assert_array_equal(p.linkage, linkage)\n\n def test_dendrogram_plot(self):\n d = mat.dendrogram(self.x_norm, **self.default_kws)\n\n ax = plt.gca()\n xlim = ax.get_xlim()\n # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy\n xmax = len(d.reordered_ind) * 10\n\n assert xlim[0] == 0\n assert xlim[1] == xmax\n\n assert len(ax.collections[0].get_paths()) == len(d.dependent_coord)\n\n @pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_dendrogram_rotate(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n\n d = mat.dendrogram(self.x_norm, **kws)\n\n ax = plt.gca()\n ylim = ax.get_ylim()\n\n # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy\n ymax = len(d.reordered_ind) * 10\n\n # Since y axis is inverted, ylim is (80, 0)\n # and therefore not (0, 80) as usual:\n assert ylim[1] == 0\n assert ylim[0] == ymax\n\n def test_dendrogram_ticklabel_rotation(self):\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(self.df_norm, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 0\n\n plt.close(f)\n\n df = self.df_norm.copy()\n df.columns = [str(c) * 10 for c in df.columns]\n df.index = [i * 10 for i in df.index]\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(df, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 90\n\n plt.close(f)\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(df.T, axis=0, rotate=True)\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 0\n plt.close(f)"},{"col":4,"comment":"null","endLoc":516,"header":"def test_ndarray_input(self)","id":1714,"name":"test_ndarray_input","nodeType":"Function","startLoc":502,"text":"def test_ndarray_input(self):\n p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)\n npt.assert_array_equal(p.array.T, self.x_norm)\n pdt.assert_frame_equal(p.data.T, pd.DataFrame(self.x_norm))\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)\n\n npt.assert_array_equal(p.xticklabels, self.x_norm_leaves)\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel is None\n assert p.ylabel == ''"},{"col":4,"comment":"null","endLoc":532,"header":"def test_df_input(self)","id":1715,"name":"test_df_input","nodeType":"Function","startLoc":518,"text":"def test_df_input(self):\n p = mat._DendrogramPlotter(self.df_norm, **self.default_kws)\n npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))\n pdt.assert_frame_equal(p.data.T, self.df_norm)\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.xticklabels,\n np.asarray(self.df_norm.columns)[\n self.x_norm_leaves])\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel == 'letters'\n assert p.ylabel == ''"},{"col":4,"comment":"Given data, initialize appropriate scale class.","endLoc":723,"header":"def default_scale(self, data: Series) -> Nominal","id":1716,"name":"default_scale","nodeType":"Function","startLoc":721,"text":"def default_scale(self, data: Series) -> Nominal:\n \"\"\"Given data, initialize appropriate scale class.\"\"\"\n return Nominal()"},{"col":4,"comment":"Given data and a scaling argument, initialize appropriate scale class.","endLoc":728,"header":"def infer_scale(self, arg: Any, data: Series) -> Scale","id":1717,"name":"infer_scale","nodeType":"Function","startLoc":725,"text":"def infer_scale(self, arg: Any, data: Series) -> Scale:\n \"\"\"Given data and a scaling argument, initialize appropriate scale class.\"\"\"\n # TODO infer Boolean where possible?\n return Nominal(arg)"},{"col":4,"comment":"null","endLoc":551,"header":"def test_df_multindex_input(self)","id":1718,"name":"test_df_multindex_input","nodeType":"Function","startLoc":534,"text":"def test_df_multindex_input(self):\n\n df = self.df_norm.copy()\n index = pd.MultiIndex.from_tuples([(\"A\", 1), (\"B\", 2),\n (\"C\", 3), (\"D\", 4)],\n names=[\"letter\", \"number\"])\n index.name = \"letter-number\"\n df.index = index\n kws = self.default_kws.copy()\n kws['label'] = True\n\n p = mat._DendrogramPlotter(df.T, **kws)\n\n xticklabels = [\"A-1\", \"B-2\", \"C-3\", \"D-4\"]\n xticklabels = [xticklabels[i] for i in p.reordered_ind]\n npt.assert_array_equal(p.xticklabels, xticklabels)\n npt.assert_array_equal(p.yticklabels, [])\n assert p.xlabel == \"letter-number\""},{"col":4,"comment":"Return a function that maps each data value to True or False.","endLoc":762,"header":"def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]","id":1719,"name":"get_mapping","nodeType":"Function","startLoc":730,"text":"def get_mapping(\n self, scale: Scale, data: Series\n ) -> Callable[[ArrayLike], ArrayLike]:\n \"\"\"Return a function that maps each data value to True or False.\"\"\"\n # TODO categorical_order is going to return [False, True] for booleans,\n # and [0, 1] for binary, but the default values order is [True, False].\n # We should special case this to handle it properly, or change\n # categorical_order to not \"sort\" booleans. Note that we need to sync with\n # what's going to happen upstream in the scale, so we can't just do it here.\n order = getattr(scale, \"order\", None)\n levels = categorical_order(data, order)\n\n if isinstance(scale.values, list):\n values = [bool(x) for x in scale.values]\n elif isinstance(scale.values, dict):\n values = [bool(scale.values[x]) for x in levels]\n elif scale.values is None:\n values = self._default_values(len(levels))\n else:\n msg = \" \".join([\n f\"Scale values for {self.variable} must be passed in\",\n f\"a list or dict; not {type(scale.values)}.\"\n ])\n raise TypeError(msg)\n\n def mapping(x):\n ixs = np.asarray(x, np.intp)\n return [\n values[ix] if np.isfinite(x_i) else False\n for x_i, ix in zip(x, ixs)\n ]\n\n return mapping"},{"col":4,"comment":"null","endLoc":341,"header":"@property\n def _variables(self) -> list[str]","id":1720,"name":"_variables","nodeType":"Function","startLoc":328,"text":"@property\n def _variables(self) -> list[str]:\n\n variables = (\n list(self._data.frame)\n + list(self._pair_spec.get(\"variables\", []))\n + list(self._facet_spec.get(\"variables\", []))\n )\n for layer in self._layers:\n variables.extend(v for v in layer[\"vars\"] if v not in variables)\n\n # Coerce to str in return to appease mypy; we know these will only\n # ever be strings but I don't think we can type a DataFrame that way yet\n return [str(v) for v in variables]"},{"col":4,"comment":"null","endLoc":568,"header":"def test_axis0_input(self)","id":1721,"name":"test_axis0_input","nodeType":"Function","startLoc":553,"text":"def test_axis0_input(self):\n kws = self.default_kws.copy()\n kws['axis'] = 0\n p = mat._DendrogramPlotter(self.df_norm.T, **kws)\n\n npt.assert_array_equal(p.array, np.asarray(self.df_norm.T))\n pdt.assert_frame_equal(p.data, self.df_norm.T)\n\n npt.assert_array_equal(p.linkage, self.x_norm_linkage)\n assert p.dendrogram == self.x_norm_dendrogram\n\n npt.assert_array_equal(p.xticklabels, self.df_norm_leaves)\n npt.assert_array_equal(p.yticklabels, [])\n\n assert p.xlabel == 'letters'\n assert p.ylabel == ''"},{"fileName":"test_subplots.py","filePath":"tests/_core","id":1722,"nodeType":"File","text":"import itertools\n\nimport numpy as np\nimport pytest\n\nfrom seaborn._core.subplots import Subplots\n\n\nclass TestSpecificationChecks:\n\n def test_both_facets_and_wrap(self):\n\n err = \"Cannot wrap facets when specifying both `col` and `row`.\"\n facet_spec = {\"wrap\": 3, \"variables\": {\"col\": \"a\", \"row\": \"b\"}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, {})\n\n def test_cross_xy_pairing_and_wrap(self):\n\n err = \"Cannot wrap subplots when pairing on both `x` and `y`.\"\n pair_spec = {\"wrap\": 3, \"structure\": {\"x\": [\"a\", \"b\"], \"y\": [\"y\", \"z\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, {}, pair_spec)\n\n def test_col_facets_and_x_pairing(self):\n\n err = \"Cannot facet the columns while pairing on `x`.\"\n facet_spec = {\"variables\": {\"col\": \"a\"}}\n pair_spec = {\"structure\": {\"x\": [\"x\", \"y\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)\n\n def test_wrapped_columns_and_y_pairing(self):\n\n err = \"Cannot wrap the columns while pairing on `y`.\"\n facet_spec = {\"variables\": {\"col\": \"a\"}, \"wrap\": 2}\n pair_spec = {\"structure\": {\"y\": [\"x\", \"y\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)\n\n def test_wrapped_x_pairing_and_facetd_rows(self):\n\n err = \"Cannot wrap the columns while faceting the rows.\"\n facet_spec = {\"variables\": {\"row\": \"a\"}}\n pair_spec = {\"structure\": {\"x\": [\"x\", \"y\"]}, \"wrap\": 2}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)\n\n\nclass TestSubplotSpec:\n\n def test_single_subplot(self):\n\n s = Subplots({}, {}, {})\n\n assert s.n_subplots == 1\n assert s.subplot_spec[\"ncols\"] == 1\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_single_facet(self):\n\n key = \"a\"\n order = list(\"abc\")\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_two_facets(self):\n\n col_key = \"a\"\n row_key = \"b\"\n col_order = list(\"xy\")\n row_order = list(\"xyz\")\n spec = {\n \"variables\": {\"col\": col_key, \"row\": row_key},\n \"structure\": {\"col\": col_order, \"row\": row_order},\n\n }\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(col_order) * len(row_order)\n assert s.subplot_spec[\"ncols\"] == len(col_order)\n assert s.subplot_spec[\"nrows\"] == len(row_order)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_col_facet_wrapped(self):\n\n key = \"b\"\n wrap = 3\n order = list(\"abcde\")\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(order) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_row_facet_wrapped(self):\n\n key = \"b\"\n wrap = 3\n order = list(\"abcde\")\n spec = {\"variables\": {\"row\": key}, \"structure\": {\"row\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order) // wrap + 1\n assert s.subplot_spec[\"nrows\"] == wrap\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_col_facet_wrapped_single_row(self):\n\n key = \"b\"\n order = list(\"abc\")\n wrap = len(order) + 2\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_x_and_y_paired(self):\n\n x = [\"x\", \"y\", \"z\"]\n y = [\"a\", \"b\"]\n s = Subplots({}, {}, {\"structure\": {\"x\": x, \"y\": y}})\n\n assert s.n_subplots == len(x) * len(y)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n def test_x_paired(self):\n\n x = [\"x\", \"y\", \"z\"]\n s = Subplots({}, {}, {\"structure\": {\"x\": x}})\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_y_paired(self):\n\n y = [\"x\", \"y\", \"z\"]\n s = Subplots({}, {}, {\"structure\": {\"y\": y}})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == 1\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n def test_x_paired_and_wrapped(self):\n\n x = [\"a\", \"b\", \"x\", \"y\", \"z\"]\n wrap = 3\n s = Subplots({}, {}, {\"structure\": {\"x\": x}, \"wrap\": wrap})\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(x) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_y_paired_and_wrapped(self):\n\n y = [\"a\", \"b\", \"x\", \"y\", \"z\"]\n wrap = 2\n s = Subplots({}, {}, {\"structure\": {\"y\": y}, \"wrap\": wrap})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == len(y) // wrap + 1\n assert s.subplot_spec[\"nrows\"] == wrap\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_y_paired_and_wrapped_single_row(self):\n\n y = [\"x\", \"y\", \"z\"]\n wrap = 1\n s = Subplots({}, {}, {\"structure\": {\"y\": y}, \"wrap\": wrap})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == len(y)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_col_faceted_y_paired(self):\n\n y = [\"x\", \"y\", \"z\"]\n key = \"a\"\n order = list(\"abc\")\n facet_spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}}\n pair_spec = {\"structure\": {\"y\": y}}\n s = Subplots({}, facet_spec, pair_spec)\n\n assert s.n_subplots == len(order) * len(y)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n def test_row_faceted_x_paired(self):\n\n x = [\"f\", \"s\"]\n key = \"a\"\n order = list(\"abc\")\n facet_spec = {\"variables\": {\"row\": key}, \"structure\": {\"row\": order}}\n pair_spec = {\"structure\": {\"x\": x}}\n s = Subplots({}, facet_spec, pair_spec)\n\n assert s.n_subplots == len(order) * len(x)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == len(order)\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_x_any_y_paired_non_cross(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [\"x\", \"y\", \"z\"]\n spec = {\"structure\": {\"x\": x, \"y\": y}, \"cross\": False}\n s = Subplots({}, {}, spec)\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == len(y)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_x_any_y_paired_non_cross_wrapped(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [\"x\", \"y\", \"z\"]\n wrap = 2\n spec = {\"structure\": {\"x\": x, \"y\": y}, \"cross\": False, \"wrap\": wrap}\n s = Subplots({}, {}, spec)\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(x) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_forced_unshared_facets(self):\n\n s = Subplots({\"sharex\": False, \"sharey\": \"row\"}, {}, {})\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n\nclass TestSubplotElements:\n\n def test_single_subplot(self):\n\n s = Subplots({}, {}, {})\n f = s.init_figure({}, {})\n\n assert len(s) == 1\n for i, e in enumerate(s):\n for side in [\"left\", \"right\", \"bottom\", \"top\"]:\n assert e[side]\n for dim in [\"col\", \"row\"]:\n assert e[dim] is None\n for axis in \"xy\":\n assert e[axis] == axis\n assert e[\"ax\"] == f.axes[i]\n\n @pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim(self, dim):\n\n key = \"a\"\n order = list(\"abc\")\n spec = {\"variables\": {dim: key}, \"structure\": {dim: order}}\n s = Subplots({}, spec, {})\n s.init_figure(spec, {})\n\n assert len(s) == len(order)\n\n for i, e in enumerate(s):\n assert e[dim] == order[i]\n for axis in \"xy\":\n assert e[axis] == axis\n assert e[\"top\"] == (dim == \"col\" or i == 0)\n assert e[\"bottom\"] == (dim == \"col\" or i == len(order) - 1)\n assert e[\"left\"] == (dim == \"row\" or i == 0)\n assert e[\"right\"] == (dim == \"row\" or i == len(order) - 1)\n\n @pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim_wrapped(self, dim):\n\n key = \"b\"\n order = list(\"abc\")\n wrap = len(order) - 1\n spec = {\"variables\": {dim: key}, \"structure\": {dim: order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n s.init_figure(spec, {})\n\n assert len(s) == len(order)\n\n for i, e in enumerate(s):\n assert e[dim] == order[i]\n for axis in \"xy\":\n assert e[axis] == axis\n\n sides = {\n \"col\": [\"top\", \"bottom\", \"left\", \"right\"],\n \"row\": [\"left\", \"right\", \"top\", \"bottom\"],\n }\n tests = (\n i < wrap,\n i >= wrap or i >= len(s) % wrap,\n i % wrap == 0,\n i % wrap == wrap - 1 or i + 1 == len(s),\n )\n\n for side, expected in zip(sides[dim], tests):\n assert e[side] == expected\n\n def test_both_facet_dims(self):\n\n col = \"a\"\n row = \"b\"\n col_order = list(\"ab\")\n row_order = list(\"xyz\")\n facet_spec = {\n \"variables\": {\"col\": col, \"row\": row},\n \"structure\": {\"col\": col_order, \"row\": row_order},\n }\n s = Subplots({}, facet_spec, {})\n s.init_figure(facet_spec, {})\n\n n_cols = len(col_order)\n n_rows = len(row_order)\n assert len(s) == n_cols * n_rows\n es = list(s)\n\n for e in es[:n_cols]:\n assert e[\"top\"]\n for e in es[::n_cols]:\n assert e[\"left\"]\n for e in es[n_cols - 1::n_cols]:\n assert e[\"right\"]\n for e in es[-n_cols:]:\n assert e[\"bottom\"]\n\n for e, (row_, col_) in zip(es, itertools.product(row_order, col_order)):\n assert e[\"col\"] == col_\n assert e[\"row\"] == row_\n\n for e in es:\n assert e[\"x\"] == \"x\"\n assert e[\"y\"] == \"y\"\n\n @pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_single_paired_var(self, var):\n\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n pairings = [\"x\", \"y\", \"z\"]\n pair_spec = {\n \"variables\": {f\"{var}{i}\": v for i, v in enumerate(pairings)},\n \"structure\": {var: [f\"{var}{i}\" for i, _ in enumerate(pairings)]},\n }\n\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n assert len(s) == len(pair_spec[\"structure\"][var])\n\n for i, e in enumerate(s):\n assert e[var] == f\"{var}{i}\"\n assert e[other_var] == other_var\n assert e[\"col\"] is e[\"row\"] is None\n\n tests = i == 0, True, True, i == len(s) - 1\n sides = {\n \"x\": [\"left\", \"right\", \"top\", \"bottom\"],\n \"y\": [\"top\", \"bottom\", \"left\", \"right\"],\n }\n\n for side, expected in zip(sides[var], tests):\n assert e[side] == expected\n\n @pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_single_paired_var_wrapped(self, var):\n\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n pairings = [\"x\", \"y\", \"z\", \"a\", \"b\"]\n wrap = len(pairings) - 2\n pair_spec = {\n \"variables\": {f\"{var}{i}\": val for i, val in enumerate(pairings)},\n \"structure\": {var: [f\"{var}{i}\" for i, _ in enumerate(pairings)]},\n \"wrap\": wrap\n }\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n assert len(s) == len(pairings)\n\n for i, e in enumerate(s):\n assert e[var] == f\"{var}{i}\"\n assert e[other_var] == other_var\n assert e[\"col\"] is e[\"row\"] is None\n\n tests = (\n i < wrap,\n i >= wrap or i >= len(s) % wrap,\n i % wrap == 0,\n i % wrap == wrap - 1 or i + 1 == len(s),\n )\n sides = {\n \"x\": [\"top\", \"bottom\", \"left\", \"right\"],\n \"y\": [\"left\", \"right\", \"top\", \"bottom\"],\n }\n for side, expected in zip(sides[var], tests):\n assert e[side] == expected\n\n def test_both_paired_variables(self):\n\n x = [\"x0\", \"x1\"]\n y = [\"y0\", \"y1\", \"y2\"]\n pair_spec = {\"structure\": {\"x\": x, \"y\": y}}\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n n_cols = len(x)\n n_rows = len(y)\n assert len(s) == n_cols * n_rows\n es = list(s)\n\n for e in es[:n_cols]:\n assert e[\"top\"]\n for e in es[::n_cols]:\n assert e[\"left\"]\n for e in es[n_cols - 1::n_cols]:\n assert e[\"right\"]\n for e in es[-n_cols:]:\n assert e[\"bottom\"]\n\n for e in es:\n assert e[\"col\"] is e[\"row\"] is None\n\n for i in range(len(y)):\n for j in range(len(x)):\n e = es[i * len(x) + j]\n assert e[\"x\"] == f\"x{j}\"\n assert e[\"y\"] == f\"y{i}\"\n\n def test_both_paired_non_cross(self):\n\n pair_spec = {\n \"structure\": {\"x\": [\"x0\", \"x1\", \"x2\"], \"y\": [\"y0\", \"y1\", \"y2\"]},\n \"cross\": False\n }\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n for i, e in enumerate(s):\n assert e[\"x\"] == f\"x{i}\"\n assert e[\"y\"] == f\"y{i}\"\n assert e[\"col\"] is e[\"row\"] is None\n assert e[\"left\"] == (i == 0)\n assert e[\"right\"] == (i == (len(s) - 1))\n assert e[\"top\"]\n assert e[\"bottom\"]\n\n @pytest.mark.parametrize(\"dim,var\", [(\"col\", \"y\"), (\"row\", \"x\")])\n def test_one_facet_one_paired(self, dim, var):\n\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n other_dim = {\"col\": \"row\", \"row\": \"col\"}[dim]\n order = list(\"abc\")\n facet_spec = {\"variables\": {dim: \"s\"}, \"structure\": {dim: order}}\n\n pairings = [\"x\", \"y\", \"t\"]\n pair_spec = {\n \"variables\": {f\"{var}{i}\": val for i, val in enumerate(pairings)},\n \"structure\": {var: [f\"{var}{i}\" for i, _ in enumerate(pairings)]},\n }\n\n s = Subplots({}, facet_spec, pair_spec)\n s.init_figure(pair_spec)\n\n n_cols = len(order) if dim == \"col\" else len(pairings)\n n_rows = len(order) if dim == \"row\" else len(pairings)\n\n assert len(s) == len(order) * len(pairings)\n\n es = list(s)\n\n for e in es[:n_cols]:\n assert e[\"top\"]\n for e in es[::n_cols]:\n assert e[\"left\"]\n for e in es[n_cols - 1::n_cols]:\n assert e[\"right\"]\n for e in es[-n_cols:]:\n assert e[\"bottom\"]\n\n if dim == \"row\":\n es = np.reshape(es, (n_rows, n_cols)).T.ravel()\n\n for i, e in enumerate(es):\n assert e[dim] == order[i % len(pairings)]\n assert e[other_dim] is None\n assert e[var] == f\"{var}{i // len(order)}\"\n assert e[other_var] == other_var\n"},{"className":"TestSpecificationChecks","col":0,"comment":"null","endLoc":47,"id":1723,"nodeType":"Class","startLoc":9,"text":"class TestSpecificationChecks:\n\n def test_both_facets_and_wrap(self):\n\n err = \"Cannot wrap facets when specifying both `col` and `row`.\"\n facet_spec = {\"wrap\": 3, \"variables\": {\"col\": \"a\", \"row\": \"b\"}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, {})\n\n def test_cross_xy_pairing_and_wrap(self):\n\n err = \"Cannot wrap subplots when pairing on both `x` and `y`.\"\n pair_spec = {\"wrap\": 3, \"structure\": {\"x\": [\"a\", \"b\"], \"y\": [\"y\", \"z\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, {}, pair_spec)\n\n def test_col_facets_and_x_pairing(self):\n\n err = \"Cannot facet the columns while pairing on `x`.\"\n facet_spec = {\"variables\": {\"col\": \"a\"}}\n pair_spec = {\"structure\": {\"x\": [\"x\", \"y\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)\n\n def test_wrapped_columns_and_y_pairing(self):\n\n err = \"Cannot wrap the columns while pairing on `y`.\"\n facet_spec = {\"variables\": {\"col\": \"a\"}, \"wrap\": 2}\n pair_spec = {\"structure\": {\"y\": [\"x\", \"y\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)\n\n def test_wrapped_x_pairing_and_facetd_rows(self):\n\n err = \"Cannot wrap the columns while faceting the rows.\"\n facet_spec = {\"variables\": {\"row\": \"a\"}}\n pair_spec = {\"structure\": {\"x\": [\"x\", \"y\"]}, \"wrap\": 2}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)"},{"col":4,"comment":"null","endLoc":16,"header":"def test_both_facets_and_wrap(self)","id":1724,"name":"test_both_facets_and_wrap","nodeType":"Function","startLoc":11,"text":"def test_both_facets_and_wrap(self):\n\n err = \"Cannot wrap facets when specifying both `col` and `row`.\"\n facet_spec = {\"wrap\": 3, \"variables\": {\"col\": \"a\", \"row\": \"b\"}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, {})"},{"col":4,"comment":"null","endLoc":23,"header":"def test_cross_xy_pairing_and_wrap(self)","id":1725,"name":"test_cross_xy_pairing_and_wrap","nodeType":"Function","startLoc":18,"text":"def test_cross_xy_pairing_and_wrap(self):\n\n err = \"Cannot wrap subplots when pairing on both `x` and `y`.\"\n pair_spec = {\"wrap\": 3, \"structure\": {\"x\": [\"a\", \"b\"], \"y\": [\"y\", \"z\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, {}, pair_spec)"},{"col":4,"comment":"null","endLoc":31,"header":"def test_col_facets_and_x_pairing(self)","id":1726,"name":"test_col_facets_and_x_pairing","nodeType":"Function","startLoc":25,"text":"def test_col_facets_and_x_pairing(self):\n\n err = \"Cannot facet the columns while pairing on `x`.\"\n facet_spec = {\"variables\": {\"col\": \"a\"}}\n pair_spec = {\"structure\": {\"x\": [\"x\", \"y\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)"},{"col":4,"comment":"null","endLoc":581,"header":"def test_rotate_input(self)","id":1727,"name":"test_rotate_input","nodeType":"Function","startLoc":570,"text":"def test_rotate_input(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n npt.assert_array_equal(p.array.T, np.asarray(self.df_norm))\n pdt.assert_frame_equal(p.data.T, self.df_norm)\n\n npt.assert_array_equal(p.xticklabels, [])\n npt.assert_array_equal(p.yticklabels, self.df_norm_leaves)\n\n assert p.xlabel == ''\n assert p.ylabel == 'letters'"},{"col":0,"comment":"\n DEPRECATED\n\n This function has been deprecated and will be removed in seaborn v0.14.0.\n It has been replaced by :func:`histplot` and :func:`displot`, two functions\n with a modern API and many more capabilities.\n\n For a guide to updating, please see this notebook:\n\n https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751\n\n ","endLoc":2546,"header":"def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None,\n hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,\n color=None, vertical=False, norm_hist=False, axlabel=None,\n label=None, ax=None, x=None)","id":1728,"name":"distplot","nodeType":"Function","startLoc":2405,"text":"def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None,\n hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,\n color=None, vertical=False, norm_hist=False, axlabel=None,\n label=None, ax=None, x=None):\n \"\"\"\n DEPRECATED\n\n This function has been deprecated and will be removed in seaborn v0.14.0.\n It has been replaced by :func:`histplot` and :func:`displot`, two functions\n with a modern API and many more capabilities.\n\n For a guide to updating, please see this notebook:\n\n https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751\n\n \"\"\"\n\n if kde and not hist:\n axes_level_suggestion = (\n \"`kdeplot` (an axes-level function for kernel density plots)\"\n )\n else:\n axes_level_suggestion = (\n \"`histplot` (an axes-level function for histograms)\"\n )\n\n msg = textwrap.dedent(f\"\"\"\n\n `distplot` is a deprecated function and will be removed in seaborn v0.14.0.\n\n Please adapt your code to use either `displot` (a figure-level function with\n similar flexibility) or {axes_level_suggestion}.\n\n For a guide to updating your code to use the new functions, please see\n https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n if ax is None:\n ax = plt.gca()\n\n # Intelligently label the support axis\n label_ax = bool(axlabel)\n if axlabel is None and hasattr(a, \"name\"):\n axlabel = a.name\n if axlabel is not None:\n label_ax = True\n\n # Support new-style API\n if x is not None:\n a = x\n\n # Make a a 1-d float array\n a = np.asarray(a, float)\n if a.ndim > 1:\n a = a.squeeze()\n\n # Drop null values from array\n a = remove_na(a)\n\n # Decide if the hist is normed\n norm_hist = norm_hist or kde or (fit is not None)\n\n # Handle dictionary defaults\n hist_kws = {} if hist_kws is None else hist_kws.copy()\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n rug_kws = {} if rug_kws is None else rug_kws.copy()\n fit_kws = {} if fit_kws is None else fit_kws.copy()\n\n # Get the color from the current color cycle\n if color is None:\n if vertical:\n line, = ax.plot(0, a.mean())\n else:\n line, = ax.plot(a.mean(), 0)\n color = line.get_color()\n line.remove()\n\n # Plug the label into the right kwarg dictionary\n if label is not None:\n if hist:\n hist_kws[\"label\"] = label\n elif kde:\n kde_kws[\"label\"] = label\n elif rug:\n rug_kws[\"label\"] = label\n elif fit:\n fit_kws[\"label\"] = label\n\n if hist:\n if bins is None:\n bins = min(_freedman_diaconis_bins(a), 50)\n hist_kws.setdefault(\"alpha\", 0.4)\n hist_kws.setdefault(\"density\", norm_hist)\n\n orientation = \"horizontal\" if vertical else \"vertical\"\n hist_color = hist_kws.pop(\"color\", color)\n ax.hist(a, bins, orientation=orientation,\n color=hist_color, **hist_kws)\n if hist_color != color:\n hist_kws[\"color\"] = hist_color\n\n axis = \"y\" if vertical else \"x\"\n\n if kde:\n kde_color = kde_kws.pop(\"color\", color)\n kdeplot(**{axis: a}, ax=ax, color=kde_color, **kde_kws)\n if kde_color != color:\n kde_kws[\"color\"] = kde_color\n\n if rug:\n rug_color = rug_kws.pop(\"color\", color)\n rugplot(**{axis: a}, ax=ax, color=rug_color, **rug_kws)\n if rug_color != color:\n rug_kws[\"color\"] = rug_color\n\n if fit is not None:\n\n def pdf(x):\n return fit.pdf(x, *params)\n\n fit_color = fit_kws.pop(\"color\", \"#282828\")\n gridsize = fit_kws.pop(\"gridsize\", 200)\n cut = fit_kws.pop(\"cut\", 3)\n clip = fit_kws.pop(\"clip\", (-np.inf, np.inf))\n bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1)\n x = _kde_support(a, bw, gridsize, cut, clip)\n params = fit.fit(a)\n y = pdf(x)\n if vertical:\n x, y = y, x\n ax.plot(x, y, color=fit_color, **fit_kws)\n if fit_color != \"#282828\":\n fit_kws[\"color\"] = fit_color\n\n if label_ax:\n if vertical:\n ax.set_ylabel(axlabel)\n else:\n ax.set_xlabel(axlabel)\n\n return ax"},{"col":4,"comment":"null","endLoc":39,"header":"def test_wrapped_columns_and_y_pairing(self)","id":1729,"name":"test_wrapped_columns_and_y_pairing","nodeType":"Function","startLoc":33,"text":"def test_wrapped_columns_and_y_pairing(self):\n\n err = \"Cannot wrap the columns while pairing on `y`.\"\n facet_spec = {\"variables\": {\"col\": \"a\"}, \"wrap\": 2}\n pair_spec = {\"structure\": {\"y\": [\"x\", \"y\"]}}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)"},{"col":4,"comment":"null","endLoc":47,"header":"def test_wrapped_x_pairing_and_facetd_rows(self)","id":1730,"name":"test_wrapped_x_pairing_and_facetd_rows","nodeType":"Function","startLoc":41,"text":"def test_wrapped_x_pairing_and_facetd_rows(self):\n\n err = \"Cannot wrap the columns while faceting the rows.\"\n facet_spec = {\"variables\": {\"row\": \"a\"}}\n pair_spec = {\"structure\": {\"x\": [\"x\", \"y\"]}, \"wrap\": 2}\n with pytest.raises(RuntimeError, match=err):\n Subplots({}, facet_spec, pair_spec)"},{"className":"TestSubplotSpec","col":0,"comment":"null","endLoc":267,"id":1731,"nodeType":"Class","startLoc":50,"text":"class TestSubplotSpec:\n\n def test_single_subplot(self):\n\n s = Subplots({}, {}, {})\n\n assert s.n_subplots == 1\n assert s.subplot_spec[\"ncols\"] == 1\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_single_facet(self):\n\n key = \"a\"\n order = list(\"abc\")\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_two_facets(self):\n\n col_key = \"a\"\n row_key = \"b\"\n col_order = list(\"xy\")\n row_order = list(\"xyz\")\n spec = {\n \"variables\": {\"col\": col_key, \"row\": row_key},\n \"structure\": {\"col\": col_order, \"row\": row_order},\n\n }\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(col_order) * len(row_order)\n assert s.subplot_spec[\"ncols\"] == len(col_order)\n assert s.subplot_spec[\"nrows\"] == len(row_order)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_col_facet_wrapped(self):\n\n key = \"b\"\n wrap = 3\n order = list(\"abcde\")\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(order) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_row_facet_wrapped(self):\n\n key = \"b\"\n wrap = 3\n order = list(\"abcde\")\n spec = {\"variables\": {\"row\": key}, \"structure\": {\"row\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order) // wrap + 1\n assert s.subplot_spec[\"nrows\"] == wrap\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_col_facet_wrapped_single_row(self):\n\n key = \"b\"\n order = list(\"abc\")\n wrap = len(order) + 2\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_x_and_y_paired(self):\n\n x = [\"x\", \"y\", \"z\"]\n y = [\"a\", \"b\"]\n s = Subplots({}, {}, {\"structure\": {\"x\": x, \"y\": y}})\n\n assert s.n_subplots == len(x) * len(y)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n def test_x_paired(self):\n\n x = [\"x\", \"y\", \"z\"]\n s = Subplots({}, {}, {\"structure\": {\"x\": x}})\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_y_paired(self):\n\n y = [\"x\", \"y\", \"z\"]\n s = Subplots({}, {}, {\"structure\": {\"y\": y}})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == 1\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n def test_x_paired_and_wrapped(self):\n\n x = [\"a\", \"b\", \"x\", \"y\", \"z\"]\n wrap = 3\n s = Subplots({}, {}, {\"structure\": {\"x\": x}, \"wrap\": wrap})\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(x) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_y_paired_and_wrapped(self):\n\n y = [\"a\", \"b\", \"x\", \"y\", \"z\"]\n wrap = 2\n s = Subplots({}, {}, {\"structure\": {\"y\": y}, \"wrap\": wrap})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == len(y) // wrap + 1\n assert s.subplot_spec[\"nrows\"] == wrap\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_y_paired_and_wrapped_single_row(self):\n\n y = [\"x\", \"y\", \"z\"]\n wrap = 1\n s = Subplots({}, {}, {\"structure\": {\"y\": y}, \"wrap\": wrap})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == len(y)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_col_faceted_y_paired(self):\n\n y = [\"x\", \"y\", \"z\"]\n key = \"a\"\n order = list(\"abc\")\n facet_spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}}\n pair_spec = {\"structure\": {\"y\": y}}\n s = Subplots({}, facet_spec, pair_spec)\n\n assert s.n_subplots == len(order) * len(y)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] == \"row\"\n\n def test_row_faceted_x_paired(self):\n\n x = [\"f\", \"s\"]\n key = \"a\"\n order = list(\"abc\")\n facet_spec = {\"variables\": {\"row\": key}, \"structure\": {\"row\": order}}\n pair_spec = {\"structure\": {\"x\": x}}\n s = Subplots({}, facet_spec, pair_spec)\n\n assert s.n_subplots == len(order) * len(x)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == len(order)\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] is True\n\n def test_x_any_y_paired_non_cross(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [\"x\", \"y\", \"z\"]\n spec = {\"structure\": {\"x\": x, \"y\": y}, \"cross\": False}\n s = Subplots({}, {}, spec)\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == len(y)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_x_any_y_paired_non_cross_wrapped(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [\"x\", \"y\", \"z\"]\n wrap = 2\n spec = {\"structure\": {\"x\": x, \"y\": y}, \"cross\": False, \"wrap\": wrap}\n s = Subplots({}, {}, spec)\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(x) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is False\n\n def test_forced_unshared_facets(self):\n\n s = Subplots({\"sharex\": False, \"sharey\": \"row\"}, {}, {})\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] == \"row\""},{"col":4,"comment":"null","endLoc":60,"header":"def test_single_subplot(self)","id":1732,"name":"test_single_subplot","nodeType":"Function","startLoc":52,"text":"def test_single_subplot(self):\n\n s = Subplots({}, {}, {})\n\n assert s.n_subplots == 1\n assert s.subplot_spec[\"ncols\"] == 1\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True"},{"col":4,"comment":"null","endLoc":73,"header":"def test_single_facet(self)","id":1733,"name":"test_single_facet","nodeType":"Function","startLoc":62,"text":"def test_single_facet(self):\n\n key = \"a\"\n order = list(\"abc\")\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True"},{"col":4,"comment":"null","endLoc":589,"header":"def test_rotate_axis0_input(self)","id":1734,"name":"test_rotate_axis0_input","nodeType":"Function","startLoc":583,"text":"def test_rotate_axis0_input(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n kws['axis'] = 0\n p = mat._DendrogramPlotter(self.df_norm.T, **kws)\n\n npt.assert_array_equal(p.reordered_ind, self.x_norm_leaves)"},{"col":0,"comment":"null","endLoc":1746,"header":"def kdeplot(\n data=None, *, x=None, y=None, hue=None, weights=None,\n palette=None, hue_order=None, hue_norm=None, color=None, fill=None,\n multiple=\"layer\", common_norm=True, common_grid=False, cumulative=False,\n bw_method=\"scott\", bw_adjust=1, warn_singular=True, log_scale=None,\n levels=10, thresh=.05, gridsize=200, cut=3, clip=None,\n legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None,\n **kwargs,\n)","id":1735,"name":"kdeplot","nodeType":"Function","startLoc":1597,"text":"def kdeplot(\n data=None, *, x=None, y=None, hue=None, weights=None,\n palette=None, hue_order=None, hue_norm=None, color=None, fill=None,\n multiple=\"layer\", common_norm=True, common_grid=False, cumulative=False,\n bw_method=\"scott\", bw_adjust=1, warn_singular=True, log_scale=None,\n levels=10, thresh=.05, gridsize=200, cut=3, clip=None,\n legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None,\n **kwargs,\n):\n\n # --- Start with backwards compatability for versions < 0.11.0 ----------------\n\n # Handle (past) deprecation of `data2`\n if \"data2\" in kwargs:\n msg = \"`data2` has been removed (replaced by `y`); please update your code.\"\n TypeError(msg)\n\n # Handle deprecation of `vertical`\n vertical = kwargs.pop(\"vertical\", None)\n if vertical is not None:\n if vertical:\n action_taken = \"assigning data to `y`.\"\n if x is None:\n data, y = y, data\n else:\n x, y = y, x\n else:\n action_taken = \"assigning data to `x`.\"\n msg = textwrap.dedent(f\"\"\"\\n\n The `vertical` parameter is deprecated; {action_taken}\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Handle deprecation of `bw`\n bw = kwargs.pop(\"bw\", None)\n if bw is not None:\n msg = textwrap.dedent(f\"\"\"\\n\n The `bw` parameter is deprecated in favor of `bw_method` and `bw_adjust`.\n Setting `bw_method={bw}`, but please see the docs for the new parameters\n and update your code. This will become an error in seaborn v0.13.0.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n bw_method = bw\n\n # Handle deprecation of `kernel`\n if kwargs.pop(\"kernel\", None) is not None:\n msg = textwrap.dedent(\"\"\"\\n\n Support for alternate kernels has been removed; using Gaussian kernel.\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Handle deprecation of shade_lowest\n shade_lowest = kwargs.pop(\"shade_lowest\", None)\n if shade_lowest is not None:\n if shade_lowest:\n thresh = 0\n msg = textwrap.dedent(f\"\"\"\\n\n `shade_lowest` has been replaced by `thresh`; setting `thresh={thresh}.\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Handle \"soft\" deprecation of shade `shade` is not really the right\n # terminology here, but unlike some of the other deprecated parameters it\n # is probably very commonly used and much hard to remove. This is therefore\n # going to be a longer process where, first, `fill` will be introduced and\n # be used throughout the documentation. In 0.12, when kwarg-only\n # enforcement hits, we can remove the shade/shade_lowest out of the\n # function signature all together and pull them out of the kwargs. Then we\n # can actually fire a FutureWarning, and eventually remove.\n shade = kwargs.pop(\"shade\", None)\n if shade is not None:\n fill = shade\n msg = textwrap.dedent(f\"\"\"\\n\n `shade` is now deprecated in favor of `fill`; setting `fill={shade}`.\n This will become an error in seaborn v0.14.0; please update your code.\n \"\"\")\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n # Handle `n_levels`\n # This was never in the formal API but it was processed, and appeared in an\n # example. We can treat as an alias for `levels` now and deprecate later.\n levels = kwargs.pop(\"n_levels\", levels)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals()),\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, allowed_types=[\"numeric\", \"datetime\"], log_scale=log_scale)\n\n method = ax.fill_between if fill else ax.plot\n color = _default_color(method, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # Pack the kwargs for statistics.KDE\n estimate_kws = dict(\n bw_method=bw_method,\n bw_adjust=bw_adjust,\n gridsize=gridsize,\n cut=cut,\n clip=clip,\n cumulative=cumulative,\n )\n\n if p.univariate:\n\n plot_kws = kwargs.copy()\n\n p.plot_univariate_density(\n multiple=multiple,\n common_norm=common_norm,\n common_grid=common_grid,\n fill=fill,\n color=color,\n legend=legend,\n warn_singular=warn_singular,\n estimate_kws=estimate_kws,\n **plot_kws,\n )\n\n else:\n\n p.plot_bivariate_density(\n common_norm=common_norm,\n fill=fill,\n levels=levels,\n thresh=thresh,\n legend=legend,\n color=color,\n warn_singular=warn_singular,\n cbar=cbar,\n cbar_ax=cbar_ax,\n cbar_kws=cbar_kws,\n estimate_kws=estimate_kws,\n **kwargs,\n )\n\n return ax"},{"col":4,"comment":"null","endLoc":608,"header":"def test_custom_linkage(self)","id":1736,"name":"test_custom_linkage","nodeType":"Function","startLoc":591,"text":"def test_custom_linkage(self):\n kws = self.default_kws.copy()\n\n try:\n import fastcluster\n\n linkage = fastcluster.linkage_vector(self.x_norm, method='single',\n metric='euclidean')\n except ImportError:\n d = distance.pdist(self.x_norm, metric='euclidean')\n linkage = hierarchy.linkage(d, method='single')\n dendrogram = hierarchy.dendrogram(linkage, no_plot=True,\n color_threshold=-np.inf)\n kws['linkage'] = linkage\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n\n npt.assert_array_equal(p.linkage, linkage)\n assert p.dendrogram == dendrogram"},{"col":4,"comment":"null","endLoc":619,"header":"def test_label_false(self)","id":1737,"name":"test_label_false","nodeType":"Function","startLoc":610,"text":"def test_label_false(self):\n kws = self.default_kws.copy()\n kws['label'] = False\n p = mat._DendrogramPlotter(self.df_norm, **kws)\n assert p.xticks == []\n assert p.yticks == []\n assert p.xticklabels == []\n assert p.yticklabels == []\n assert p.xlabel == \"\"\n assert p.ylabel == \"\""},{"col":0,"comment":"null","endLoc":2066,"header":"def rugplot(\n data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True,\n palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs\n)","id":1738,"name":"rugplot","nodeType":"Function","startLoc":1989,"text":"def rugplot(\n data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True,\n palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs\n):\n\n # A note: I think it would make sense to add multiple= to rugplot and allow\n # rugs for different hue variables to be shifted orthogonal to the data axis\n # But is this stacking, or dodging?\n\n # A note: if we want to add a style semantic to rugplot,\n # we could make an option that draws the rug using scatterplot\n\n # A note, it would also be nice to offer some kind of histogram/density\n # rugplot, since alpha blending doesn't work great in the large n regime\n\n # --- Start with backwards compatability for versions < 0.11.0 ----------------\n\n a = kwargs.pop(\"a\", None)\n axis = kwargs.pop(\"axis\", None)\n\n if a is not None:\n data = a\n msg = textwrap.dedent(\"\"\"\\n\n The `a` parameter has been replaced; use `x`, `y`, and/or `data` instead.\n Please update your code; This will become an error in seaborn v0.13.0.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n if axis is not None:\n if axis == \"x\":\n x = data\n elif axis == \"y\":\n y = data\n msg = textwrap.dedent(f\"\"\"\\n\n The `axis` parameter has been deprecated; use the `{axis}` parameter instead.\n Please update your code; this will become an error in seaborn v0.13.0.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n vertical = kwargs.pop(\"vertical\", None)\n if vertical is not None:\n if vertical:\n action_taken = \"assigning data to `y`.\"\n if x is None:\n data, y = y, data\n else:\n x, y = y, x\n else:\n action_taken = \"assigning data to `x`.\"\n msg = textwrap.dedent(f\"\"\"\\n\n The `vertical` parameter is deprecated; {action_taken}\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n\n weights = None\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals()),\n )\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax)\n\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n p.plot_rug(height, expand_margins, legend, **kwargs)\n\n return ax"},{"col":4,"comment":"null","endLoc":633,"header":"def test_linkage_scipy(self)","id":1739,"name":"test_linkage_scipy","nodeType":"Function","startLoc":621,"text":"def test_linkage_scipy(self):\n p = mat._DendrogramPlotter(self.x_norm, **self.default_kws)\n\n scipy_linkage = p._calculate_linkage_scipy()\n\n from scipy.spatial import distance\n from scipy.cluster import hierarchy\n\n dists = distance.pdist(self.x_norm.T,\n metric=self.default_kws['metric'])\n linkage = hierarchy.linkage(dists, method=self.default_kws['method'])\n\n npt.assert_array_equal(scipy_linkage, linkage)"},{"col":4,"comment":"null","endLoc":644,"header":"@pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_other_method(self)","id":1740,"name":"test_fastcluster_other_method","nodeType":"Function","startLoc":635,"text":"@pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_other_method(self):\n import fastcluster\n\n kws = self.default_kws.copy()\n kws['method'] = 'average'\n linkage = fastcluster.linkage(self.x_norm.T, method='average',\n metric='euclidean')\n p = mat._DendrogramPlotter(self.x_norm, **kws)\n npt.assert_array_equal(p.linkage, linkage)"},{"attributeType":"bool","col":4,"comment":"null","endLoc":700,"id":1741,"name":"legend","nodeType":"Attribute","startLoc":700,"text":"legend"},{"attributeType":"bool","col":4,"comment":"null","endLoc":701,"id":1742,"name":"normed","nodeType":"Attribute","startLoc":701,"text":"normed"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":25,"id":1743,"name":"RGBTuple","nodeType":"Attribute","startLoc":25,"text":"RGBTuple"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":26,"id":1744,"name":"RGBATuple","nodeType":"Attribute","startLoc":26,"text":"RGBATuple"},{"attributeType":"tuple | str","col":0,"comment":"null","endLoc":27,"id":1745,"name":"ColorSpec","nodeType":"Attribute","startLoc":27,"text":"ColorSpec"},{"col":0,"comment":"Establish support for a kernel density estimate.","endLoc":492,"header":"def _kde_support(data, bw, gridsize, cut, clip)","id":1746,"name":"_kde_support","nodeType":"Function","startLoc":486,"text":"def _kde_support(data, bw, gridsize, cut, clip):\n \"\"\"Establish support for a kernel density estimate.\"\"\"\n support_min = max(data.min() - bw * cut, clip[0])\n support_max = min(data.max() + bw * cut, clip[1])\n support = np.linspace(support_min, support_max, gridsize)\n\n return support"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":29,"id":1747,"name":"DashPattern","nodeType":"Attribute","startLoc":29,"text":"DashPattern"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":30,"id":1748,"name":"DashPatternWithOffset","nodeType":"Attribute","startLoc":30,"text":"DashPatternWithOffset"},{"fileName":"test_relational.py","filePath":"tests","id":1749,"nodeType":"File","text":"from itertools import product\nimport warnings\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import same_color, to_rgba\n\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom seaborn.external.version import Version\nfrom seaborn.palettes import color_palette\nfrom seaborn._oldcore import categorical_order\n\nfrom seaborn.relational import (\n _RelationalPlotter,\n _LinePlotter,\n _ScatterPlotter,\n relplot,\n lineplot,\n scatterplot\n)\n\nfrom seaborn.utils import _draw_figure\nfrom seaborn._compat import get_colormap\nfrom seaborn._testing import assert_plots_equal\n\n\n@pytest.fixture(params=[\n dict(x=\"x\", y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"a\", y=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"a\"),\n dict(x=\"x\", y=\"y\", size=\"a\"),\n dict(x=\"x\", y=\"y\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"s\"),\n dict(x=\"x\", y=\"y\", size=\"s\"),\n dict(x=\"x\", y=\"y\", style=\"s\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", size=\"b\", style=\"b\"),\n])\ndef long_semantics(request):\n return request.param\n\n\nclass Helpers:\n\n # TODO Better place for these?\n\n def scatter_rgbs(self, collections):\n rgbs = []\n for col in collections:\n rgb = tuple(col.get_facecolor().squeeze()[:3])\n rgbs.append(rgb)\n return rgbs\n\n def paths_equal(self, *args):\n\n equal = all([len(a) == len(args[0]) for a in args])\n\n for p1, p2 in zip(*args):\n equal &= np.array_equal(p1.vertices, p2.vertices)\n equal &= np.array_equal(p1.codes, p2.codes)\n return equal\n\n\nclass SharedAxesLevelTests:\n\n def test_color(self, long_df):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C0\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C1\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", color=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", c=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n\nclass TestRelationalPlotter(Helpers):\n\n def test_wide_df_variables(self, wide_df):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_df)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n assert len(p.plot_data) == np.product(wide_df.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(wide_df.index, wide_df.shape[1])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = wide_df.to_numpy().ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(wide_df.columns.to_numpy(), wide_df.shape[0])\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] == wide_df.index.name\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] == wide_df.columns.name\n assert p.variables[\"style\"] == wide_df.columns.name\n\n def test_wide_df_with_nonnumeric_variables(self, long_df):\n\n p = _RelationalPlotter()\n p.assign_variables(data=long_df)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n numeric_df = long_df.select_dtypes(\"number\")\n\n assert len(p.plot_data) == np.product(numeric_df.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(numeric_df.index, numeric_df.shape[1])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = numeric_df.to_numpy().ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(\n numeric_df.columns.to_numpy(), numeric_df.shape[0]\n )\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] == numeric_df.index.name\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] == numeric_df.columns.name\n assert p.variables[\"style\"] == numeric_df.columns.name\n\n def test_wide_array_variables(self, wide_array):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_array)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n assert len(p.plot_data) == np.product(wide_array.shape)\n\n nrow, ncol = wide_array.shape\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(nrow), ncol)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = wide_array.ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(ncol), nrow)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_flat_array_variables(self, flat_array):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_array)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == np.product(flat_array.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.arange(flat_array.shape[0])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_array\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n\n def test_flat_list_variables(self, flat_list):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_list)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_list)\n\n x = p.plot_data[\"x\"]\n expected_x = np.arange(len(flat_list))\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_list\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n\n def test_flat_series_variables(self, flat_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_series)\n\n x = p.plot_data[\"x\"]\n expected_x = flat_series.index\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_series\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is flat_series.index.name\n assert p.variables[\"y\"] is flat_series.name\n\n def test_wide_list_of_series_variables(self, wide_list_of_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_series)\n chunk_size = max(len(l) for l in wide_list_of_series)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n index_union = np.unique(\n np.concatenate([s.index for s in wide_list_of_series])\n )\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(index_union, chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = np.concatenate([\n s.reindex(index_union) for s in wide_list_of_series\n ])\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n series_names = [s.name for s in wide_list_of_series]\n expected_hue = np.repeat(series_names, chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_list_of_arrays_variables(self, wide_list_of_arrays):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_arrays)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_arrays)\n chunk_size = max(len(l) for l in wide_list_of_arrays)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(wide_list_of_arrays)\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(chunks), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_list_of_list_variables(self, wide_list_of_lists):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_lists)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_lists)\n chunk_size = max(len(l) for l in wide_list_of_lists)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(wide_list_of_lists)\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(chunks), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_dict_of_series_variables(self, wide_dict_of_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_series)\n chunk_size = max(len(l) for l in wide_dict_of_series.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_series.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_series), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_dict_of_arrays_variables(self, wide_dict_of_arrays):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_arrays)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_arrays)\n chunk_size = max(len(l) for l in wide_dict_of_arrays.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_arrays.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_arrays), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_dict_of_lists_variables(self, wide_dict_of_lists):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_lists)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_lists)\n chunk_size = max(len(l) for l in wide_dict_of_lists.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_lists.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_lists), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_relplot_simple(self, long_df):\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"scatter\")\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(x, long_df[\"x\"])\n assert_array_equal(y, long_df[\"y\"])\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"line\")\n x, y = g.ax.lines[0].get_xydata().T\n expected = long_df.groupby(\"x\").y.mean()\n assert_array_equal(x, expected.index)\n assert y == pytest.approx(expected.values)\n\n with pytest.raises(ValueError):\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"not_a_kind\")\n\n def test_relplot_complex(self, long_df):\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(data=long_df, x=\"x\", y=\"y\", **{sem: \"a\"})\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(x, long_df[\"x\"])\n assert_array_equal(y, long_df[\"y\"])\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(\n data=long_df, x=\"x\", y=\"y\", col=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n for sem in [\"size\", \"style\"]:\n g = relplot(\n data=long_df, x=\"x\", y=\"y\", hue=\"b\", col=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(\n data=long_df.sort_values([\"c\", \"b\"]),\n x=\"x\", y=\"y\", col=\"b\", row=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby([\"c\", \"b\"])\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n @pytest.mark.parametrize(\"vector_type\", [\"series\", \"numpy\", \"list\"])\n def test_relplot_vectors(self, long_df, vector_type):\n\n semantics = dict(x=\"x\", y=\"y\", hue=\"f\", col=\"c\")\n kws = {key: long_df[val] for key, val in semantics.items()}\n if vector_type == \"numpy\":\n kws = {k: v.to_numpy() for k, v in kws.items()}\n elif vector_type == \"list\":\n kws = {k: v.to_list() for k, v in kws.items()}\n g = relplot(data=long_df, **kws)\n grouped = long_df.groupby(\"c\")\n assert len(g.axes_dict) == len(grouped)\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n def test_relplot_wide(self, wide_df):\n\n g = relplot(data=wide_df)\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(y, wide_df.to_numpy().T.ravel())\n assert not g.ax.get_ylabel()\n\n def test_relplot_hues(self, long_df):\n\n palette = [\"r\", \"b\", \"g\"]\n g = relplot(\n x=\"x\", y=\"y\", hue=\"a\", style=\"b\", col=\"c\",\n palette=palette, data=long_df\n )\n\n palette = dict(zip(long_df[\"a\"].unique(), palette))\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n points = ax.collections[0]\n expected_hues = [palette[val] for val in grp_df[\"a\"]]\n assert same_color(points.get_facecolors(), expected_hues)\n\n def test_relplot_sizes(self, long_df):\n\n sizes = [5, 12, 7]\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", size=\"a\", hue=\"b\", col=\"c\",\n sizes=sizes,\n )\n\n sizes = dict(zip(long_df[\"a\"].unique(), sizes))\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n points = ax.collections[0]\n expected_sizes = [sizes[val] for val in grp_df[\"a\"]]\n assert_array_equal(points.get_sizes(), expected_sizes)\n\n def test_relplot_styles(self, long_df):\n\n markers = [\"o\", \"d\", \"s\"]\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", style=\"a\", hue=\"b\", col=\"c\",\n markers=markers,\n )\n\n paths = []\n for m in markers:\n m = mpl.markers.MarkerStyle(m)\n paths.append(m.get_path().transformed(m.get_transform()))\n paths = dict(zip(long_df[\"a\"].unique(), paths))\n\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n points = ax.collections[0]\n expected_paths = [paths[val] for val in grp_df[\"a\"]]\n assert self.paths_equal(points.get_paths(), expected_paths)\n\n def test_relplot_stringy_numerics(self, long_df):\n\n long_df[\"x_str\"] = long_df[\"x\"].astype(str)\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"x_str\")\n points = g.ax.collections[0]\n xys = points.get_offsets()\n mask = np.ma.getmask(xys)\n assert not mask.any()\n assert_array_equal(xys, long_df[[\"x\", \"y\"]])\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", size=\"x_str\")\n points = g.ax.collections[0]\n xys = points.get_offsets()\n mask = np.ma.getmask(xys)\n assert not mask.any()\n assert_array_equal(xys, long_df[[\"x\", \"y\"]])\n\n def test_relplot_legend(self, long_df):\n\n g = relplot(data=long_df, x=\"x\", y=\"y\")\n assert g._legend is None\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\")\n texts = [t.get_text() for t in g._legend.texts]\n expected_texts = long_df[\"a\"].unique()\n assert_array_equal(texts, expected_texts)\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"s\", size=\"s\")\n texts = [t.get_text() for t in g._legend.texts]\n assert_array_equal(texts, np.sort(texts))\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", legend=False)\n assert g._legend is None\n\n palette = color_palette(\"deep\", len(long_df[\"b\"].unique()))\n a_like_b = dict(zip(long_df[\"a\"].unique(), long_df[\"b\"].unique()))\n long_df[\"a_like_b\"] = long_df[\"a\"].map(a_like_b)\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", hue=\"b\", style=\"a_like_b\",\n palette=palette, kind=\"line\", estimator=None,\n )\n lines = g._legend.get_lines()[1:] # Chop off title dummy\n for line, color in zip(lines, palette):\n assert line.get_color() == color\n\n def test_relplot_data(self, long_df):\n\n g = relplot(\n data=long_df.to_dict(orient=\"list\"),\n x=\"x\",\n y=long_df[\"y\"].rename(\"y_var\"),\n hue=long_df[\"a\"].to_numpy(),\n col=\"c\",\n )\n expected_cols = set(long_df.columns.to_list() + [\"_hue_\", \"y_var\"])\n assert set(g.data.columns) == expected_cols\n assert_array_equal(g.data[\"y_var\"], long_df[\"y\"])\n assert_array_equal(g.data[\"_hue_\"], long_df[\"a\"])\n\n def test_facet_variable_collision(self, long_df):\n\n # https://github.com/mwaskom/seaborn/issues/2488\n col_data = long_df[\"c\"]\n long_df = long_df.assign(size=col_data)\n\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", col=\"size\",\n )\n assert g.axes.shape == (1, len(col_data.unique()))\n\n def test_ax_kwarg_removal(self, long_df):\n\n f, ax = plt.subplots()\n with pytest.warns(UserWarning):\n g = relplot(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert len(ax.collections) == 0\n assert len(g.ax.collections) > 0\n\n\nclass TestLinePlotter(SharedAxesLevelTests, Helpers):\n\n func = staticmethod(lineplot)\n\n def get_last_color(self, ax):\n\n return to_rgba(ax.lines[-1].get_color())\n\n def test_legend_data(self, long_df):\n\n f, ax = plt.subplots()\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert handles == []\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n assert labels == p._hue_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n markers = [h.get_marker() for h in handles]\n assert labels == p._hue_map.levels\n assert labels == p._style_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n assert markers == p._style_map(p._style_map.levels, \"marker\")\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n markers = [h.get_marker() for h in handles]\n expected_labels = (\n [\"a\"]\n + p._hue_map.levels\n + [\"b\"] + p._style_map.levels\n )\n expected_colors = (\n [\"w\"] + p._hue_map(p._hue_map.levels)\n + [\"w\"] + [\".2\" for _ in p._style_map.levels]\n )\n expected_markers = (\n [\"\"] + [\"None\" for _ in p._hue_map.levels]\n + [\"\"] + p._style_map(p._style_map.levels, \"marker\")\n )\n assert labels == expected_labels\n assert colors == expected_colors\n assert markers == expected_markers\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"a\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n widths = [h.get_linewidth() for h in handles]\n assert labels == p._hue_map.levels\n assert labels == p._size_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n assert widths == p._size_map(p._size_map.levels)\n\n # --\n\n x, y = np.random.randn(2, 40)\n z = np.tile(np.arange(20), 2)\n\n p = _LinePlotter(variables=dict(x=x, y=y, hue=z))\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._hue_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._hue_map.levels)\n\n p = _LinePlotter(variables=dict(x=x, y=y, size=z))\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._size_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"auto\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = True\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"bad_value\"\n with pytest.raises(ValueError):\n p.add_legend_data(ax)\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, hue=z + 1),\n legend=\"brief\"\n )\n p.map_hue(norm=mpl.colors.LogNorm()),\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert float(labels[1]) / float(labels[0]) == 10\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, hue=z % 2),\n legend=\"auto\"\n )\n p.map_hue(norm=mpl.colors.LogNorm()),\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [\"0\", \"1\"]\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, size=z + 1),\n legend=\"brief\"\n )\n p.map_size(norm=mpl.colors.LogNorm())\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert float(labels[1]) / float(labels[0]) == 10\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"f\"),\n legend=\"brief\",\n )\n p.add_legend_data(ax)\n expected_labels = ['0.20', '0.22', '0.24', '0.26', '0.28']\n handles, labels = ax.get_legend_handles_labels()\n assert labels == expected_labels\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"f\"),\n legend=\"brief\",\n )\n p.add_legend_data(ax)\n expected_levels = ['0.20', '0.22', '0.24', '0.26', '0.28']\n handles, labels = ax.get_legend_handles_labels()\n assert labels == expected_levels\n\n def test_plot(self, long_df, repeated_df):\n\n f, ax = plt.subplots()\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n sort=False,\n estimator=None\n )\n p.plot(ax, {})\n line, = ax.lines\n assert_array_equal(line.get_xdata(), long_df.x.to_numpy())\n assert_array_equal(line.get_ydata(), long_df.y.to_numpy())\n\n ax.clear()\n p.plot(ax, {\"color\": \"k\", \"label\": \"test\"})\n line, = ax.lines\n assert line.get_color() == \"k\"\n assert line.get_label() == \"test\"\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n sort=True, estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n sorted_data = long_df.sort_values([\"x\", \"y\"])\n assert_array_equal(line.get_xdata(), sorted_data.x.to_numpy())\n assert_array_equal(line.get_ydata(), sorted_data.y.to_numpy())\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._hue_map.levels)\n for line, level in zip(ax.lines, p._hue_map.levels):\n assert line.get_color() == p._hue_map(level)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._size_map.levels)\n for line, level in zip(ax.lines, p._size_map.levels):\n assert line.get_linewidth() == p._size_map(level)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._hue_map.levels)\n assert len(ax.lines) == len(p._style_map.levels)\n for line, level in zip(ax.lines, p._hue_map.levels):\n assert line.get_color() == p._hue_map(level)\n assert line.get_marker() == p._style_map(level, \"marker\")\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n levels = product(p._hue_map.levels, p._style_map.levels)\n expected_line_count = len(p._hue_map.levels) * len(p._style_map.levels)\n assert len(ax.lines) == expected_line_count\n for line, (hue, style) in zip(ax.lines, levels):\n assert line.get_color() == p._hue_map(hue)\n assert line.get_marker() == p._style_map(style, \"marker\")\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n estimator=\"mean\", err_style=\"band\", errorbar=\"sd\", sort=True\n )\n\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n expected_data = long_df.groupby(\"x\").y.mean()\n assert_array_equal(line.get_xdata(), expected_data.index.to_numpy())\n assert np.allclose(line.get_ydata(), expected_data.to_numpy())\n assert len(ax.collections) == 1\n\n # Test that nans do not propagate to means or CIs\n\n p = _LinePlotter(\n variables=dict(\n x=[1, 1, 1, 2, 2, 2, 3, 3, 3],\n y=[1, 2, 3, 3, np.nan, 5, 4, 5, 6],\n ),\n estimator=\"mean\", err_style=\"band\", errorbar=\"ci\", n_boot=100, sort=True,\n )\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n assert line.get_xdata().tolist() == [1, 2, 3]\n err_band = ax.collections[0].get_paths()\n assert len(err_band) == 1\n assert len(err_band[0].vertices) == 9\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n estimator=\"mean\", err_style=\"band\", errorbar=\"sd\"\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(ax.collections) == len(p._hue_map.levels)\n for c in ax.collections:\n assert isinstance(c, mpl.collections.PolyCollection)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n estimator=\"mean\", err_style=\"bars\", errorbar=\"sd\"\n )\n\n ax.clear()\n p.plot(ax, {})\n n_lines = len(ax.lines)\n assert n_lines / 2 == len(ax.collections) == len(p._hue_map.levels)\n assert len(ax.collections) == len(p._hue_map.levels)\n for c in ax.collections:\n assert isinstance(c, mpl.collections.LineCollection)\n\n p = _LinePlotter(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", units=\"u\"),\n estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n n_units = len(repeated_df[\"u\"].unique())\n assert len(ax.lines) == n_units\n\n p = _LinePlotter(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", units=\"u\"),\n estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n n_units *= len(repeated_df[\"a\"].unique())\n assert len(ax.lines) == n_units\n\n p.estimator = \"mean\"\n with pytest.raises(ValueError):\n p.plot(ax, {})\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n err_style=\"band\", err_kws={\"alpha\": .5},\n )\n\n ax.clear()\n p.plot(ax, {})\n for band in ax.collections:\n assert band.get_alpha() == .5\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n err_style=\"bars\", err_kws={\"elinewidth\": 2},\n )\n\n ax.clear()\n p.plot(ax, {})\n for lines in ax.collections:\n assert lines.get_linestyles() == 2\n\n p.err_style = \"invalid\"\n with pytest.raises(ValueError):\n p.plot(ax, {})\n\n x_str = long_df[\"x\"].astype(str)\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n def test_orient(self, long_df):\n\n long_df = long_df.drop(\"x\", axis=1).rename(columns={\"s\": \"y\", \"y\": \"x\"})\n\n ax1 = plt.figure().subplots()\n lineplot(data=long_df, x=\"x\", y=\"y\", orient=\"y\", errorbar=\"sd\")\n assert len(ax1.lines) == len(ax1.collections)\n line, = ax1.lines\n expected = long_df.groupby(\"y\").agg({\"x\": \"mean\"}).reset_index()\n assert_array_almost_equal(line.get_xdata(), expected[\"x\"])\n assert_array_almost_equal(line.get_ydata(), expected[\"y\"])\n ribbon_y = ax1.collections[0].get_paths()[0].vertices[:, 1]\n assert_array_equal(np.unique(ribbon_y), long_df[\"y\"].sort_values().unique())\n\n ax2 = plt.figure().subplots()\n lineplot(\n data=long_df, x=\"x\", y=\"y\", orient=\"y\", errorbar=\"sd\", err_style=\"bars\"\n )\n segments = ax2.collections[0].get_segments()\n for i, val in enumerate(sorted(long_df[\"y\"].unique())):\n assert (segments[i][:, 1] == val).all()\n\n with pytest.raises(ValueError, match=\"`orient` must be either 'x' or 'y'\"):\n lineplot(long_df, x=\"y\", y=\"x\", orient=\"bad\")\n\n def test_log_scale(self):\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n\n x = [1, 10, 100]\n y = [1, 2, 3]\n\n lineplot(x=x, y=y)\n line = ax.lines[0]\n assert_array_equal(line.get_xdata(), x)\n assert_array_equal(line.get_ydata(), y)\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n\n x = [1, 1, 2, 2]\n y = [1, 10, 1, 100]\n\n lineplot(x=x, y=y, err_style=\"bars\", errorbar=(\"pi\", 100))\n line = ax.lines[0]\n assert line.get_ydata()[1] == 10\n\n ebars = ax.collections[0].get_segments()\n assert_array_equal(ebars[0][:, 1], y[:2])\n assert_array_equal(ebars[1][:, 1], y[2:])\n\n def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n\n p.plot(ax1, {})\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n\n p.plot(ax2, {})\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()\n\n def test_matplotlib_kwargs(self, long_df):\n\n kws = {\n \"linestyle\": \"--\",\n \"linewidth\": 3,\n \"color\": (1, .5, .2),\n \"markeredgecolor\": (.2, .5, .2),\n \"markeredgewidth\": 1,\n }\n ax = lineplot(data=long_df, x=\"x\", y=\"y\", **kws)\n\n line, *_ = ax.lines\n for key, val in kws.items():\n plot_val = getattr(line, f\"get_{key}\")()\n assert plot_val == val\n\n def test_nonmapped_dashes(self):\n\n ax = lineplot(x=[1, 2], y=[1, 2], dashes=(2, 1))\n line = ax.lines[0]\n # Not a great test, but lines don't expose the dash style publicly\n assert line.get_linestyle() == \"--\"\n\n def test_lineplot_axes(self, wide_df):\n\n f1, ax1 = plt.subplots()\n f2, ax2 = plt.subplots()\n\n ax = lineplot(data=wide_df)\n assert ax is ax2\n\n ax = lineplot(data=wide_df, ax=ax1)\n assert ax is ax1\n\n def test_lineplot_vs_relplot(self, long_df, long_semantics):\n\n ax = lineplot(data=long_df, **long_semantics)\n g = relplot(data=long_df, kind=\"line\", **long_semantics)\n\n lin_lines = ax.lines\n rel_lines = g.ax.lines\n\n for l1, l2 in zip(lin_lines, rel_lines):\n assert_array_equal(l1.get_xydata(), l2.get_xydata())\n assert same_color(l1.get_color(), l2.get_color())\n assert l1.get_linewidth() == l2.get_linewidth()\n assert l1.get_linestyle() == l2.get_linestyle()\n\n def test_lineplot_smoke(\n self,\n wide_df, wide_array,\n wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n flat_array, flat_series, flat_list,\n long_df, missing_df, object_df\n ):\n\n f, ax = plt.subplots()\n\n lineplot(x=[], y=[])\n ax.clear()\n\n lineplot(data=wide_df)\n ax.clear()\n\n lineplot(data=wide_array)\n ax.clear()\n\n lineplot(data=wide_list_of_series)\n ax.clear()\n\n lineplot(data=wide_list_of_arrays)\n ax.clear()\n\n lineplot(data=wide_list_of_lists)\n ax.clear()\n\n lineplot(data=flat_series)\n ax.clear()\n\n lineplot(data=flat_array)\n ax.clear()\n\n lineplot(data=flat_list)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", data=long_df)\n ax.clear()\n\n lineplot(x=long_df.x, y=long_df.y)\n ax.clear()\n\n lineplot(x=long_df.x, y=\"y\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=long_df.y.to_numpy(), data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"t\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"f\", data=object_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"c\", size=\"f\", data=object_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"f\", size=\"s\", data=object_df)\n ax.clear()\n\n def test_ci_deprecation(self, long_df):\n\n axs = plt.figure().subplots(2)\n lineplot(data=long_df, x=\"x\", y=\"y\", errorbar=(\"ci\", 95), seed=0, ax=axs[0])\n with pytest.warns(FutureWarning, match=\"\\n\\nThe `ci` parameter is deprecated\"):\n lineplot(data=long_df, x=\"x\", y=\"y\", ci=95, seed=0, ax=axs[1])\n assert_plots_equal(*axs)\n\n axs = plt.figure().subplots(2)\n lineplot(data=long_df, x=\"x\", y=\"y\", errorbar=\"sd\", ax=axs[0])\n with pytest.warns(FutureWarning, match=\"\\n\\nThe `ci` parameter is deprecated\"):\n lineplot(data=long_df, x=\"x\", y=\"y\", ci=\"sd\", ax=axs[1])\n assert_plots_equal(*axs)\n\n\nclass TestScatterPlotter(SharedAxesLevelTests, Helpers):\n\n func = staticmethod(scatterplot)\n\n def get_last_color(self, ax):\n\n colors = ax.collections[-1].get_facecolors()\n unique_colors = np.unique(colors, axis=0)\n assert len(unique_colors) == 1\n return to_rgba(unique_colors.squeeze())\n\n def test_color(self, long_df):\n\n super().test_color(long_df)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", facecolor=\"C5\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C5\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", facecolors=\"C6\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C6\")\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", fc=\"C4\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C4\")\n\n def test_legend_data(self, long_df):\n\n m = mpl.markers.MarkerStyle(\"o\")\n default_mark = m.get_path().transformed(m.get_transform())\n\n m = mpl.markers.MarkerStyle(\"\")\n null = m.get_path().transformed(m.get_transform())\n\n f, ax = plt.subplots()\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert handles == []\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n assert labels == p._hue_map.levels\n assert same_color(colors, expected_colors)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n paths = [h.get_paths()[0] for h in handles]\n expected_paths = p._style_map(p._style_map.levels, \"path\")\n assert labels == p._hue_map.levels\n assert labels == p._style_map.levels\n assert same_color(colors, expected_colors)\n assert self.paths_equal(paths, expected_paths)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n paths = [h.get_paths()[0] for h in handles]\n expected_colors = (\n [\"w\"] + p._hue_map(p._hue_map.levels)\n + [\"w\"] + [\".2\" for _ in p._style_map.levels]\n )\n expected_paths = (\n [null] + [default_mark for _ in p._hue_map.levels]\n + [null] + p._style_map(p._style_map.levels, \"path\")\n )\n assert labels == (\n [\"a\"] + p._hue_map.levels + [\"b\"] + p._style_map.levels\n )\n assert same_color(colors, expected_colors)\n assert self.paths_equal(paths, expected_paths)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"a\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == p._hue_map.levels\n assert labels == p._size_map.levels\n assert same_color(colors, expected_colors)\n assert sizes == expected_sizes\n\n # --\n\n ax.clear()\n sizes_list = [10, 100, 200]\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n legend=\"full\",\n )\n p.map_size(sizes=sizes_list)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == [str(l) for l in p._size_map.levels]\n assert sizes == expected_sizes\n\n # --\n\n ax.clear()\n sizes_dict = {2: 10, 4: 100, 8: 200}\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n legend=\"full\"\n )\n p.map_size(sizes=sizes_dict)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == [str(l) for l in p._size_map.levels]\n assert sizes == expected_sizes\n\n # --\n\n x, y = np.random.randn(2, 40)\n z = np.tile(np.arange(20), 2)\n\n p = _ScatterPlotter(\n variables=dict(x=x, y=y, hue=z),\n )\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._hue_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._hue_map.levels)\n\n p = _ScatterPlotter(\n variables=dict(x=x, y=y, size=z),\n )\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._size_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"bad_value\"\n with pytest.raises(ValueError):\n p.add_legend_data(ax)\n\n def test_plot(self, long_df, repeated_df):\n\n f, ax = plt.subplots()\n\n p = _ScatterPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p.plot(ax, {})\n points = ax.collections[0]\n assert_array_equal(points.get_offsets(), long_df[[\"x\", \"y\"]].to_numpy())\n\n ax.clear()\n p.plot(ax, {\"color\": \"k\", \"label\": \"test\"})\n points = ax.collections[0]\n assert same_color(points.get_facecolor(), \"k\")\n assert points.get_label() == \"test\"\n\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_colors = p._hue_map(p.plot_data[\"hue\"])\n assert same_color(points.get_facecolors(), expected_colors)\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"c\"),\n )\n p.map_style(markers=[\"+\", \"x\"])\n\n ax.clear()\n color = (1, .3, .8)\n p.plot(ax, {\"color\": color})\n points = ax.collections[0]\n assert same_color(points.get_edgecolors(), [color])\n\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_sizes = p._size_map(p.plot_data[\"size\"])\n assert_array_equal(points.get_sizes(), expected_sizes)\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_colors = p._hue_map(p.plot_data[\"hue\"])\n expected_paths = p._style_map(p.plot_data[\"style\"], \"path\")\n assert same_color(points.get_facecolors(), expected_colors)\n assert self.paths_equal(points.get_paths(), expected_paths)\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_colors = p._hue_map(p.plot_data[\"hue\"])\n expected_paths = p._style_map(p.plot_data[\"style\"], \"path\")\n assert same_color(points.get_facecolors(), expected_colors)\n assert self.paths_equal(points.get_paths(), expected_paths)\n\n x_str = long_df[\"x\"].astype(str)\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", size=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n p = _ScatterPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p.plot(ax1, {})\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n\n p.plot(ax2, {})\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()\n\n def test_scatterplot_axes(self, wide_df):\n\n f1, ax1 = plt.subplots()\n f2, ax2 = plt.subplots()\n\n ax = scatterplot(data=wide_df)\n assert ax is ax2\n\n ax = scatterplot(data=wide_df, ax=ax1)\n assert ax is ax1\n\n def test_literal_attribute_vectors(self):\n\n f, ax = plt.subplots()\n\n x = y = [1, 2, 3]\n s = [5, 10, 15]\n c = [(1, 1, 0, 1), (1, 0, 1, .5), (.5, 1, 0, 1)]\n\n scatterplot(x=x, y=y, c=c, s=s, ax=ax)\n\n points, = ax.collections\n\n assert_array_equal(points.get_sizes().squeeze(), s)\n assert_array_equal(points.get_facecolors(), c)\n\n def test_supplied_color_array(self, long_df):\n\n cmap = get_colormap(\"Blues\")\n norm = mpl.colors.Normalize()\n colors = cmap(norm(long_df[\"y\"].to_numpy()))\n\n keys = [\"c\", \"facecolor\", \"facecolors\"]\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n keys.append(\"fc\")\n\n for key in keys:\n\n ax = plt.figure().subplots()\n scatterplot(data=long_df, x=\"x\", y=\"y\", **{key: colors})\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n ax = plt.figure().subplots()\n scatterplot(data=long_df, x=\"x\", y=\"y\", c=long_df[\"y\"], cmap=cmap)\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n def test_hue_order(self, long_df):\n\n order = categorical_order(long_df[\"a\"])\n unused = order.pop()\n\n ax = scatterplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", hue_order=order)\n points = ax.collections[0]\n assert (points.get_facecolors()[long_df[\"a\"] == unused] == 0).all()\n assert [t.get_text() for t in ax.legend_.texts] == order\n\n def test_linewidths(self, long_df):\n\n f, ax = plt.subplots()\n\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=10)\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=20)\n points1, points2 = ax.collections\n assert (\n points1.get_linewidths().item() < points2.get_linewidths().item()\n )\n\n ax.clear()\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=long_df[\"x\"])\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=long_df[\"x\"] * 2)\n points1, points2 = ax.collections\n assert (\n points1.get_linewidths().item() < points2.get_linewidths().item()\n )\n\n ax.clear()\n scatterplot(data=long_df, x=\"x\", y=\"y\", size=long_df[\"x\"])\n scatterplot(data=long_df, x=\"x\", y=\"y\", size=long_df[\"x\"] * 2)\n points1, points2, *_ = ax.collections\n assert (\n points1.get_linewidths().item() < points2.get_linewidths().item()\n )\n\n ax.clear()\n lw = 2\n scatterplot(data=long_df, x=\"x\", y=\"y\", linewidth=lw)\n assert ax.collections[0].get_linewidths().item() == lw\n\n def test_size_norm_extrapolation(self):\n\n # https://github.com/mwaskom/seaborn/issues/2539\n x = np.arange(0, 20, 2)\n f, axs = plt.subplots(1, 2, sharex=True, sharey=True)\n\n slc = 5\n kws = dict(sizes=(50, 200), size_norm=(0, x.max()), legend=\"brief\")\n\n scatterplot(x=x, y=x, size=x, ax=axs[0], **kws)\n scatterplot(x=x[:slc], y=x[:slc], size=x[:slc], ax=axs[1], **kws)\n\n assert np.allclose(\n axs[0].collections[0].get_sizes()[:slc],\n axs[1].collections[0].get_sizes()\n )\n\n legends = [ax.legend_ for ax in axs]\n legend_data = [\n {\n label.get_text(): handle.get_sizes().item()\n for label, handle in zip(legend.get_texts(), legend.legendHandles)\n } for legend in legends\n ]\n\n for key in set(legend_data[0]) & set(legend_data[1]):\n if key == \"y\":\n # At some point (circa 3.0) matplotlib auto-added pandas series\n # with a valid name into the legend, which messes up this test.\n # I can't track down when that was added (or removed), so let's\n # just anticipate and ignore it here.\n continue\n assert legend_data[0][key] == legend_data[1][key]\n\n def test_datetime_scale(self, long_df):\n\n ax = scatterplot(data=long_df, x=\"t\", y=\"y\")\n # Check that we avoid weird matplotlib default auto scaling\n # https://github.com/matplotlib/matplotlib/issues/17586\n ax.get_xlim()[0] > ax.xaxis.convert_units(np.datetime64(\"2002-01-01\"))\n\n def test_unfilled_marker_edgecolor_warning(self, long_df): # GH2636\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n scatterplot(data=long_df, x=\"x\", y=\"y\", marker=\"+\")\n\n def test_scatterplot_vs_relplot(self, long_df, long_semantics):\n\n ax = scatterplot(data=long_df, **long_semantics)\n g = relplot(data=long_df, kind=\"scatter\", **long_semantics)\n\n for s_pts, r_pts in zip(ax.collections, g.ax.collections):\n\n assert_array_equal(s_pts.get_offsets(), r_pts.get_offsets())\n assert_array_equal(s_pts.get_sizes(), r_pts.get_sizes())\n assert_array_equal(s_pts.get_facecolors(), r_pts.get_facecolors())\n assert self.paths_equal(s_pts.get_paths(), r_pts.get_paths())\n\n def test_scatterplot_smoke(\n self,\n wide_df, wide_array,\n flat_series, flat_array, flat_list,\n wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n long_df, missing_df, object_df\n ):\n\n f, ax = plt.subplots()\n\n scatterplot(x=[], y=[])\n ax.clear()\n\n scatterplot(data=wide_df)\n ax.clear()\n\n scatterplot(data=wide_array)\n ax.clear()\n\n scatterplot(data=wide_list_of_series)\n ax.clear()\n\n scatterplot(data=wide_list_of_arrays)\n ax.clear()\n\n scatterplot(data=wide_list_of_lists)\n ax.clear()\n\n scatterplot(data=flat_series)\n ax.clear()\n\n scatterplot(data=flat_array)\n ax.clear()\n\n scatterplot(data=flat_list)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", data=long_df)\n ax.clear()\n\n scatterplot(x=long_df.x, y=long_df.y)\n ax.clear()\n\n scatterplot(x=long_df.x, y=\"y\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=long_df.y.to_numpy(), data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"f\", data=object_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"c\", size=\"f\", data=object_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"f\", size=\"s\", data=object_df)\n ax.clear()\n"},{"className":"product","col":0,"comment":"null","endLoc":277,"id":1750,"nodeType":"Class","startLoc":194,"text":"class product(Iterator[_T_co]):\n @overload\n def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ...\n @overload\n def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]: ...\n @overload\n def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]: ...\n @overload\n def __new__(\n cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /\n ) -> product[tuple[_T1, _T2, _T3, _T4]]: ...\n @overload\n def __new__(\n cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], /\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n @overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ...\n @overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ...\n @overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]: ...\n @overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n iter9: Iterable[_T9],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]: ...\n @overload\n def __new__(\n cls,\n iter1: Iterable[_T1],\n iter2: Iterable[_T2],\n iter3: Iterable[_T3],\n iter4: Iterable[_T4],\n iter5: Iterable[_T5],\n iter6: Iterable[_T6],\n iter7: Iterable[_T7],\n iter8: Iterable[_T8],\n iter9: Iterable[_T9],\n iter10: Iterable[_T10],\n /,\n ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]: ...\n @overload\n def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ...\n def __iter__(self) -> Self: ...\n def __next__(self) -> _T_co: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":32,"id":1751,"name":"MarkerPattern","nodeType":"Attribute","startLoc":32,"text":"MarkerPattern"},{"col":4,"comment":"null","endLoc":92,"header":"def test_two_facets(self)","id":1752,"name":"test_two_facets","nodeType":"Function","startLoc":75,"text":"def test_two_facets(self):\n\n col_key = \"a\"\n row_key = \"b\"\n col_order = list(\"xy\")\n row_order = list(\"xyz\")\n spec = {\n \"variables\": {\"col\": col_key, \"row\": row_key},\n \"structure\": {\"col\": col_order, \"row\": row_order},\n\n }\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(col_order) * len(row_order)\n assert s.subplot_spec[\"ncols\"] == len(col_order)\n assert s.subplot_spec[\"nrows\"] == len(row_order)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True"},{"col":0,"comment":"null","endLoc":1930,"header":"def ecdfplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Computation parameters\n stat=\"proportion\", complementary=False,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n)","id":1754,"name":"ecdfplot","nodeType":"Function","startLoc":1877,"text":"def ecdfplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Computation parameters\n stat=\"proportion\", complementary=False,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n):\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # We could support other semantics (size, style) here fairly easily\n # But it would make distplot a bit more complicated.\n # It's always possible to add features like that later, so I am going to defer.\n # It will be even easier to wait until after there is a more general/abstract\n # way to go from semantic specs to artist attributes.\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, log_scale=log_scale)\n\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # We could add this one day, but it's of dubious value\n if not p.univariate:\n raise NotImplementedError(\"Bivariate ECDF plots are not implemented\")\n\n estimate_kws = dict(\n stat=stat,\n complementary=complementary,\n )\n\n p.plot_univariate_ecdf(\n estimate_kws=estimate_kws,\n legend=legend,\n **kwargs,\n )\n\n return ax"},{"col":4,"comment":"null","endLoc":276,"header":"def __iter__(self) -> Self","id":1755,"name":"__iter__","nodeType":"Function","startLoc":276,"text":"def __iter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":277,"header":"def __next__(self) -> _T_co","id":1756,"name":"__next__","nodeType":"Function","startLoc":277,"text":"def __next__(self) -> _T_co: ..."},{"className":"product","col":0,"comment":"\n product(*iterables, repeat=1) --> product object\n \n Cartesian product of input iterables. Equivalent to nested for-loops.\n \n For example, product(A, B) returns the same as: ((x,y) for x in A for y in B).\n The leftmost iterators are in the outermost for-loop, so the output tuples\n cycle in a manner similar to an odometer (with the rightmost element changing\n on every iteration).\n \n To compute the product of an iterable with itself, specify the number\n of repetitions with the optional repeat keyword argument. For example,\n product(A, repeat=4) means the same as product(A, A, A, A).\n \n product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\n product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...\n ","endLoc":539,"id":1757,"nodeType":"Class","startLoc":490,"text":"class product(object):\n \"\"\"\n product(*iterables, repeat=1) --> product object\n \n Cartesian product of input iterables. Equivalent to nested for-loops.\n \n For example, product(A, B) returns the same as: ((x,y) for x in A for y in B).\n The leftmost iterators are in the outermost for-loop, so the output tuples\n cycle in a manner similar to an odometer (with the rightmost element changing\n on every iteration).\n \n To compute the product of an iterable with itself, specify the number\n of repetitions with the optional repeat keyword argument. For example,\n product(A, repeat=4) means the same as product(A, A, A, A).\n \n product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\n product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...\n \"\"\"\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __init__(self, *iterables, repeat=1): # known case of itertools.product.__init__\n \"\"\" Initialize self. See help(type(self)) for accurate signature. \"\"\"\n return []\n\n def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass\n\n @staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass\n\n def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass\n\n def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass\n\n def __setstate__(self, *args, **kwargs): # real signature unknown\n \"\"\" Set state information for unpickling. \"\"\"\n pass\n\n def __sizeof__(self, *args, **kwargs): # real signature unknown\n \"\"\" Returns size in memory, in bytes. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":656,"header":"@pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_non_euclidean(self)","id":1758,"name":"test_fastcluster_non_euclidean","nodeType":"Function","startLoc":646,"text":"@pytest.mark.skipif(_no_fastcluster, reason=\"fastcluster not installed\")\n def test_fastcluster_non_euclidean(self):\n import fastcluster\n\n kws = self.default_kws.copy()\n kws['metric'] = 'cosine'\n kws['method'] = 'average'\n linkage = fastcluster.linkage(self.x_norm.T, method=kws['method'],\n metric=kws['metric'])\n p = mat._DendrogramPlotter(self.x_norm, **kws)\n npt.assert_array_equal(p.linkage, linkage)"},{"col":4,"comment":"null","endLoc":106,"header":"def test_col_facet_wrapped(self)","id":1759,"name":"test_col_facet_wrapped","nodeType":"Function","startLoc":94,"text":"def test_col_facet_wrapped(self):\n\n key = \"b\"\n wrap = 3\n order = list(\"abcde\")\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(order) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True"},{"attributeType":"dict","col":0,"comment":"null","endLoc":772,"id":1760,"name":"PROPERTY_CLASSES","nodeType":"Attribute","startLoc":772,"text":"PROPERTY_CLASSES"},{"col":4,"comment":"null","endLoc":669,"header":"def test_dendrogram_plot(self)","id":1761,"name":"test_dendrogram_plot","nodeType":"Function","startLoc":658,"text":"def test_dendrogram_plot(self):\n d = mat.dendrogram(self.x_norm, **self.default_kws)\n\n ax = plt.gca()\n xlim = ax.get_xlim()\n # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy\n xmax = len(d.reordered_ind) * 10\n\n assert xlim[0] == 0\n assert xlim[1] == xmax\n\n assert len(ax.collections[0].get_paths()) == len(d.dependent_coord)"},{"col":4,"comment":"null","endLoc":120,"header":"def test_row_facet_wrapped(self)","id":1762,"name":"test_row_facet_wrapped","nodeType":"Function","startLoc":108,"text":"def test_row_facet_wrapped(self):\n\n key = \"b\"\n wrap = 3\n order = list(\"abcde\")\n spec = {\"variables\": {\"row\": key}, \"structure\": {\"row\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order) // wrap + 1\n assert s.subplot_spec[\"nrows\"] == wrap\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True"},{"col":0,"comment":"null","endLoc":72,"header":"def assert_plots_equal(ax1, ax2, labels=True)","id":1763,"name":"assert_plots_equal","nodeType":"Function","startLoc":64,"text":"def assert_plots_equal(ax1, ax2, labels=True):\n\n assert_artists_equal(ax1.patches, ax2.patches)\n assert_artists_equal(ax1.lines, ax2.lines)\n assert_artists_equal(ax1.collections, ax2.collections)\n\n if labels:\n assert ax1.get_xlabel() == ax2.get_xlabel()\n assert ax1.get_ylabel() == ax2.get_ylabel()"},{"col":0,"comment":"null","endLoc":47,"header":"def assert_artists_equal(list1, list2)","id":1764,"name":"assert_artists_equal","nodeType":"Function","startLoc":24,"text":"def assert_artists_equal(list1, list2):\n\n assert len(list1) == len(list2)\n for a1, a2 in zip(list1, list2):\n assert a1.__class__ == a2.__class__\n prop1 = a1.properties()\n prop2 = a2.properties()\n for key in USE_PROPS:\n if key not in prop1:\n continue\n v1 = prop1[key]\n v2 = prop2[key]\n if key == \"paths\":\n for p1, p2 in zip(v1, v2):\n assert_array_equal(p1.vertices, p2.vertices)\n assert_array_equal(p1.codes, p2.codes)\n elif key == \"color\":\n v1 = mpl.colors.to_rgba(v1)\n v2 = mpl.colors.to_rgba(v2)\n assert v1 == v2\n elif isinstance(v1, np.ndarray):\n assert_array_equal(v1, v2)\n else:\n assert v1 == v2"},{"col":4,"comment":"null","endLoc":688,"header":"@pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_dendrogram_rotate(self)","id":1765,"name":"test_dendrogram_rotate","nodeType":"Function","startLoc":671,"text":"@pytest.mark.xfail(mpl.__version__ == \"3.1.1\",\n reason=\"matplotlib 3.1.1 bug\")\n def test_dendrogram_rotate(self):\n kws = self.default_kws.copy()\n kws['rotate'] = True\n\n d = mat.dendrogram(self.x_norm, **kws)\n\n ax = plt.gca()\n ylim = ax.get_ylim()\n\n # 10 comes from _plot_dendrogram in scipy.cluster.hierarchy\n ymax = len(d.reordered_ind) * 10\n\n # Since y axis is inverted, ylim is (80, 0)\n # and therefore not (0, 80) as usual:\n assert ylim[1] == 0\n assert ylim[0] == ymax"},{"col":4,"comment":"null","endLoc":134,"header":"def test_col_facet_wrapped_single_row(self)","id":1766,"name":"test_col_facet_wrapped_single_row","nodeType":"Function","startLoc":122,"text":"def test_col_facet_wrapped_single_row(self):\n\n key = \"b\"\n order = list(\"abc\")\n wrap = len(order) + 2\n spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n\n assert s.n_subplots == len(order)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is True"},{"col":4,"comment":"null","endLoc":715,"header":"def test_dendrogram_ticklabel_rotation(self)","id":1767,"name":"test_dendrogram_ticklabel_rotation","nodeType":"Function","startLoc":690,"text":"def test_dendrogram_ticklabel_rotation(self):\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(self.df_norm, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 0\n\n plt.close(f)\n\n df = self.df_norm.copy()\n df.columns = [str(c) * 10 for c in df.columns]\n df.index = [i * 10 for i in df.index]\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(df, ax=ax)\n\n for t in ax.get_xticklabels():\n assert t.get_rotation() == 90\n\n plt.close(f)\n\n f, ax = plt.subplots(figsize=(2, 2))\n mat.dendrogram(df.T, axis=0, rotate=True)\n for t in ax.get_yticklabels():\n assert t.get_rotation() == 0\n plt.close(f)"},{"attributeType":"dict","col":0,"comment":"null","endLoc":803,"id":1768,"name":"PROPERTIES","nodeType":"Attribute","startLoc":803,"text":"PROPERTIES"},{"col":4,"comment":"null","endLoc":146,"header":"def test_x_and_y_paired(self)","id":1769,"name":"test_x_and_y_paired","nodeType":"Function","startLoc":136,"text":"def test_x_and_y_paired(self):\n\n x = [\"x\", \"y\", \"z\"]\n y = [\"a\", \"b\"]\n s = Subplots({}, {}, {\"structure\": {\"x\": x, \"y\": y}})\n\n assert s.n_subplots == len(x) * len(y)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] == \"row\""},{"col":4,"comment":"null","endLoc":157,"header":"def test_x_paired(self)","id":1770,"name":"test_x_paired","nodeType":"Function","startLoc":148,"text":"def test_x_paired(self):\n\n x = [\"x\", \"y\", \"z\"]\n s = Subplots({}, {}, {\"structure\": {\"x\": x}})\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] is True"},{"col":4,"comment":"null","endLoc":168,"header":"def test_y_paired(self)","id":1771,"name":"test_y_paired","nodeType":"Function","startLoc":159,"text":"def test_y_paired(self):\n\n y = [\"x\", \"y\", \"z\"]\n s = Subplots({}, {}, {\"structure\": {\"y\": y}})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == 1\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] == \"row\""},{"col":4,"comment":"null","endLoc":180,"header":"def test_x_paired_and_wrapped(self)","id":1772,"name":"test_x_paired_and_wrapped","nodeType":"Function","startLoc":170,"text":"def test_x_paired_and_wrapped(self):\n\n x = [\"a\", \"b\", \"x\", \"y\", \"z\"]\n wrap = 3\n s = Subplots({}, {}, {\"structure\": {\"x\": x}, \"wrap\": wrap})\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(x) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is True"},{"col":4,"comment":"null","endLoc":192,"header":"def test_y_paired_and_wrapped(self)","id":1773,"name":"test_y_paired_and_wrapped","nodeType":"Function","startLoc":182,"text":"def test_y_paired_and_wrapped(self):\n\n y = [\"a\", \"b\", \"x\", \"y\", \"z\"]\n wrap = 2\n s = Subplots({}, {}, {\"structure\": {\"y\": y}, \"wrap\": wrap})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == len(y) // wrap + 1\n assert s.subplot_spec[\"nrows\"] == wrap\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is False"},{"col":4,"comment":"null","endLoc":204,"header":"def test_y_paired_and_wrapped_single_row(self)","id":1774,"name":"test_y_paired_and_wrapped_single_row","nodeType":"Function","startLoc":194,"text":"def test_y_paired_and_wrapped_single_row(self):\n\n y = [\"x\", \"y\", \"z\"]\n wrap = 1\n s = Subplots({}, {}, {\"structure\": {\"y\": y}, \"wrap\": wrap})\n\n assert s.n_subplots == len(y)\n assert s.subplot_spec[\"ncols\"] == len(y)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] is False"},{"col":4,"comment":"null","endLoc":219,"header":"def test_col_faceted_y_paired(self)","id":1775,"name":"test_col_faceted_y_paired","nodeType":"Function","startLoc":206,"text":"def test_col_faceted_y_paired(self):\n\n y = [\"x\", \"y\", \"z\"]\n key = \"a\"\n order = list(\"abc\")\n facet_spec = {\"variables\": {\"col\": key}, \"structure\": {\"col\": order}}\n pair_spec = {\"structure\": {\"y\": y}}\n s = Subplots({}, facet_spec, pair_spec)\n\n assert s.n_subplots == len(order) * len(y)\n assert s.subplot_spec[\"ncols\"] == len(order)\n assert s.subplot_spec[\"nrows\"] == len(y)\n assert s.subplot_spec[\"sharex\"] is True\n assert s.subplot_spec[\"sharey\"] == \"row\""},{"className":"object","col":0,"comment":"null","endLoc":127,"id":1776,"nodeType":"Class","startLoc":90,"text":"class object:\n __doc__: str | None\n __dict__: dict[str, Any]\n __module__: str\n __annotations__: dict[str, Any]\n @property\n def __class__(self) -> type[Self]: ...\n # Ignore errors about type mismatch between property getter and setter\n @__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811\n def __init__(self) -> None: ...\n def __new__(cls) -> Self: ...\n # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n def __delattr__(self, __name: str) -> None: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __str__(self) -> str: ... # noqa: Y029\n def __repr__(self) -> str: ... # noqa: Y029\n def __hash__(self) -> int: ...\n def __format__(self, __format_spec: str) -> str: ...\n def __getattribute__(self, __name: str) -> Any: ...\n def __sizeof__(self) -> int: ...\n # return type of pickle methods is rather hard to express in the current type system\n # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n def __reduce__(self) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 8):\n def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...\n else:\n def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 11):\n def __getstate__(self) -> object: ...\n\n def __dir__(self) -> Iterable[str]: ...\n def __init_subclass__(cls) -> None: ...\n @classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"col":4,"comment":"null","endLoc":96,"header":"@property\n def __class__(self) -> type[Self]","id":1777,"name":"__class__","nodeType":"Function","startLoc":95,"text":"@property\n def __class__(self) -> type[Self]: ..."},{"col":4,"comment":"null","endLoc":99,"header":"@__class__.setter\n def __class__(self, __type: type[object]) -> None","id":1778,"name":"__class__","nodeType":"Function","startLoc":98,"text":"@__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811"},{"col":4,"comment":"null","endLoc":101,"header":"def __new__(cls) -> Self","id":1779,"name":"__new__","nodeType":"Function","startLoc":101,"text":"def __new__(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":104,"header":"def __setattr__(self, __name: str, __value: Any) -> None","id":1780,"name":"__setattr__","nodeType":"Function","startLoc":104,"text":"def __setattr__(self, __name: str, __value: Any) -> None: ..."},{"col":4,"comment":"null","endLoc":105,"header":"def __delattr__(self, __name: str) -> None","id":1781,"name":"__delattr__","nodeType":"Function","startLoc":105,"text":"def __delattr__(self, __name: str) -> None: ..."},{"col":4,"comment":"null","endLoc":106,"header":"def __eq__(self, __value: object) -> bool","id":1782,"name":"__eq__","nodeType":"Function","startLoc":106,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":107,"header":"def __ne__(self, __value: object) -> bool","id":1783,"name":"__ne__","nodeType":"Function","startLoc":107,"text":"def __ne__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":108,"header":"def __str__(self) -> str","id":1784,"name":"__str__","nodeType":"Function","startLoc":108,"text":"def __str__(self) -> str: ... # noqa: Y029"},{"col":4,"comment":"null","endLoc":109,"header":"def __repr__(self) -> str","id":1785,"name":"__repr__","nodeType":"Function","startLoc":109,"text":"def __repr__(self) -> str: ... # noqa: Y029"},{"col":4,"comment":"null","endLoc":110,"header":"def __hash__(self) -> int","id":1786,"name":"__hash__","nodeType":"Function","startLoc":110,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":111,"header":"def __format__(self, __format_spec: str) -> str","id":1787,"name":"__format__","nodeType":"Function","startLoc":111,"text":"def __format__(self, __format_spec: str) -> str: ..."},{"col":4,"comment":"null","endLoc":113,"header":"def __sizeof__(self) -> int","id":1788,"name":"__sizeof__","nodeType":"Function","startLoc":113,"text":"def __sizeof__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":116,"header":"def __reduce__(self) -> str | tuple[Any, ...]","id":1789,"name":"__reduce__","nodeType":"Function","startLoc":116,"text":"def __reduce__(self) -> str | tuple[Any, ...]: ..."},{"col":8,"comment":"null","endLoc":118,"header":"def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]","id":1790,"name":"__reduce_ex__","nodeType":"Function","startLoc":118,"text":"def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":124,"header":"def __dir__(self) -> Iterable[str]","id":1791,"name":"__dir__","nodeType":"Function","startLoc":124,"text":"def __dir__(self) -> Iterable[str]: ..."},{"col":4,"comment":"null","endLoc":125,"header":"def __init_subclass__(cls) -> None","id":1792,"name":"__init_subclass__","nodeType":"Function","startLoc":125,"text":"def __init_subclass__(cls) -> None: ..."},{"col":4,"comment":"null","endLoc":127,"header":"@classmethod\n def __subclasshook__(cls, __subclass: type) -> bool","id":1793,"name":"__subclasshook__","nodeType":"Function","startLoc":126,"text":"@classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"attributeType":"str | None","col":4,"comment":"null","endLoc":91,"id":1794,"name":"__doc__","nodeType":"Attribute","startLoc":91,"text":"__doc__"},{"attributeType":"dict","col":4,"comment":"null","endLoc":92,"id":1795,"name":"__dict__","nodeType":"Attribute","startLoc":92,"text":"__dict__"},{"col":0,"comment":"null","endLoc":61,"header":"def assert_legends_equal(leg1, leg2)","id":1796,"name":"assert_legends_equal","nodeType":"Function","startLoc":50,"text":"def assert_legends_equal(leg1, leg2):\n\n assert leg1.get_title().get_text() == leg2.get_title().get_text()\n for t1, t2 in zip(leg1.get_texts(), leg2.get_texts()):\n assert t1.get_text() == t2.get_text()\n\n assert_artists_equal(\n leg1.get_patches(), leg2.get_patches(),\n )\n assert_artists_equal(\n leg1.get_lines(), leg2.get_lines(),\n )"},{"attributeType":"str","col":4,"comment":"null","endLoc":93,"id":1797,"name":"__module__","nodeType":"Attribute","startLoc":93,"text":"__module__"},{"attributeType":"dict","col":4,"comment":"null","endLoc":94,"id":1798,"name":"__annotations__","nodeType":"Attribute","startLoc":94,"text":"__annotations__"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":510,"header":"def __getattribute__(self, *args, **kwargs)","id":1799,"name":"__getattribute__","nodeType":"Function","startLoc":508,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":" Initialize self. See help(type(self)) for accurate signature. ","endLoc":514,"header":"def __init__(self, *iterables, repeat=1)","id":1800,"name":"__init__","nodeType":"Function","startLoc":512,"text":"def __init__(self, *iterables, repeat=1): # known case of itertools.product.__init__\n \"\"\" Initialize self. See help(type(self)) for accurate signature. \"\"\"\n return []"},{"col":4,"comment":" Implement iter(self). ","endLoc":518,"header":"def __iter__(self, *args, **kwargs)","id":1801,"name":"__iter__","nodeType":"Function","startLoc":516,"text":"def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass"},{"col":4,"comment":" Create and return a new object. See help(type) for accurate signature. ","endLoc":523,"header":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs)","id":1802,"name":"__new__","nodeType":"Function","startLoc":520,"text":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass"},{"col":4,"comment":" Implement next(self). ","endLoc":527,"header":"def __next__(self, *args, **kwargs)","id":1803,"name":"__next__","nodeType":"Function","startLoc":525,"text":"def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass"},{"col":4,"comment":" Return state information for pickling. ","endLoc":531,"header":"def __reduce__(self, *args, **kwargs)","id":1804,"name":"__reduce__","nodeType":"Function","startLoc":529,"text":"def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass"},{"col":4,"comment":" Set state information for unpickling. ","endLoc":535,"header":"def __setstate__(self, *args, **kwargs)","id":1805,"name":"__setstate__","nodeType":"Function","startLoc":533,"text":"def __setstate__(self, *args, **kwargs): # real signature unknown\n \"\"\" Set state information for unpickling. \"\"\"\n pass"},{"col":4,"comment":" Returns size in memory, in bytes. ","endLoc":539,"header":"def __sizeof__(self, *args, **kwargs)","id":1806,"name":"__sizeof__","nodeType":"Function","startLoc":537,"text":"def __sizeof__(self, *args, **kwargs): # real signature unknown\n \"\"\" Returns size in memory, in bytes. \"\"\"\n pass"},{"className":"_ScatterPlotter","col":0,"comment":"null","endLoc":594,"id":1807,"nodeType":"Class","startLoc":518,"text":"class _ScatterPlotter(_RelationalPlotter):\n\n _legend_attributes = [\"color\", \"s\", \"marker\"]\n _legend_func = \"scatter\"\n\n def __init__(self, *, data=None, variables={}, legend=None):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * np.square(mpl.rcParams[\"lines.markersize\"])\n )\n\n super().__init__(data=data, variables=variables)\n\n self.legend = legend\n\n def plot(self, ax, kws):\n\n # --- Determine the visual attributes of the plot\n\n data = self.plot_data.dropna()\n if data.empty:\n return\n\n # Define the vectors of x and y positions\n empty = np.full(len(data), np.nan)\n x = data.get(\"x\", empty)\n y = data.get(\"y\", empty)\n\n if \"style\" in self.variables:\n # Use a representative marker so scatter sets the edgecolor\n # properly for line art markers. We currently enforce either\n # all or none line art so this works.\n example_level = self._style_map.levels[0]\n example_marker = self._style_map(example_level, \"marker\")\n kws.setdefault(\"marker\", example_marker)\n\n # Conditionally set the marker edgecolor based on whether the marker is \"filled\"\n # See https://github.com/matplotlib/matplotlib/issues/17849 for context\n m = kws.get(\"marker\", mpl.rcParams.get(\"marker\", \"o\"))\n if not isinstance(m, mpl.markers.MarkerStyle):\n # TODO in more recent matplotlib (which?) can pass a MarkerStyle here\n m = mpl.markers.MarkerStyle(m)\n if m.is_filled():\n kws.setdefault(\"edgecolor\", \"w\")\n\n # Draw the scatter plot\n points = ax.scatter(x=x, y=y, **kws)\n\n # Apply the mapping from semantic variables to artist attributes\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(data[\"hue\"]))\n\n if \"size\" in self.variables:\n points.set_sizes(self._size_map(data[\"size\"]))\n\n if \"style\" in self.variables:\n p = [self._style_map(val, \"path\") for val in data[\"style\"]]\n points.set_paths(p)\n\n # Apply dependent default attributes\n\n if \"linewidth\" not in kws:\n sizes = points.get_sizes()\n points.set_linewidths(.08 * np.sqrt(np.percentile(sizes, 10)))\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)"},{"col":4,"comment":"null","endLoc":534,"header":"def __init__(self, *, data=None, variables={}, legend=None)","id":1808,"name":"__init__","nodeType":"Function","startLoc":523,"text":"def __init__(self, *, data=None, variables={}, legend=None):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * np.square(mpl.rcParams[\"lines.markersize\"])\n )\n\n super().__init__(data=data, variables=variables)\n\n self.legend = legend"},{"col":4,"comment":"null","endLoc":234,"header":"def test_row_faceted_x_paired(self)","id":1809,"name":"test_row_faceted_x_paired","nodeType":"Function","startLoc":221,"text":"def test_row_faceted_x_paired(self):\n\n x = [\"f\", \"s\"]\n key = \"a\"\n order = list(\"abc\")\n facet_spec = {\"variables\": {\"row\": key}, \"structure\": {\"row\": order}}\n pair_spec = {\"structure\": {\"x\": x}}\n s = Subplots({}, facet_spec, pair_spec)\n\n assert s.n_subplots == len(order) * len(x)\n assert s.subplot_spec[\"ncols\"] == len(x)\n assert s.subplot_spec[\"nrows\"] == len(order)\n assert s.subplot_spec[\"sharex\"] == \"col\"\n assert s.subplot_spec[\"sharey\"] is True"},{"col":4,"comment":"null","endLoc":594,"header":"def plot(self, ax, kws)","id":1810,"name":"plot","nodeType":"Function","startLoc":536,"text":"def plot(self, ax, kws):\n\n # --- Determine the visual attributes of the plot\n\n data = self.plot_data.dropna()\n if data.empty:\n return\n\n # Define the vectors of x and y positions\n empty = np.full(len(data), np.nan)\n x = data.get(\"x\", empty)\n y = data.get(\"y\", empty)\n\n if \"style\" in self.variables:\n # Use a representative marker so scatter sets the edgecolor\n # properly for line art markers. We currently enforce either\n # all or none line art so this works.\n example_level = self._style_map.levels[0]\n example_marker = self._style_map(example_level, \"marker\")\n kws.setdefault(\"marker\", example_marker)\n\n # Conditionally set the marker edgecolor based on whether the marker is \"filled\"\n # See https://github.com/matplotlib/matplotlib/issues/17849 for context\n m = kws.get(\"marker\", mpl.rcParams.get(\"marker\", \"o\"))\n if not isinstance(m, mpl.markers.MarkerStyle):\n # TODO in more recent matplotlib (which?) can pass a MarkerStyle here\n m = mpl.markers.MarkerStyle(m)\n if m.is_filled():\n kws.setdefault(\"edgecolor\", \"w\")\n\n # Draw the scatter plot\n points = ax.scatter(x=x, y=y, **kws)\n\n # Apply the mapping from semantic variables to artist attributes\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(data[\"hue\"]))\n\n if \"size\" in self.variables:\n points.set_sizes(self._size_map(data[\"size\"]))\n\n if \"style\" in self.variables:\n p = [self._style_map(val, \"path\") for val in data[\"style\"]]\n points.set_paths(p)\n\n # Apply dependent default attributes\n\n if \"linewidth\" not in kws:\n sizes = points.get_sizes()\n points.set_linewidths(.08 * np.sqrt(np.percentile(sizes, 10)))\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)"},{"className":"TestDistPlot","col":0,"comment":"null","endLoc":140,"id":1811,"nodeType":"Class","startLoc":64,"text":"class TestDistPlot:\n\n rs = np.random.RandomState(0)\n x = rs.randn(100)\n\n def test_hist_bins(self):\n\n fd_edges = np.histogram_bin_edges(self.x, \"fd\")\n with pytest.warns(UserWarning):\n ax = distplot(self.x)\n for edge, bar in zip(fd_edges, ax.patches):\n assert pytest.approx(edge) == bar.get_x()\n\n plt.close(ax.figure)\n n = 25\n n_edges = np.histogram_bin_edges(self.x, n)\n with pytest.warns(UserWarning):\n ax = distplot(self.x, bins=n)\n for edge, bar in zip(n_edges, ax.patches):\n assert pytest.approx(edge) == bar.get_x()\n\n def test_elements(self):\n\n with pytest.warns(UserWarning):\n\n n = 10\n ax = distplot(self.x, bins=n,\n hist=True, kde=False, rug=False, fit=None)\n assert len(ax.patches) == 10\n assert len(ax.lines) == 0\n assert len(ax.collections) == 0\n\n plt.close(ax.figure)\n ax = distplot(self.x,\n hist=False, kde=True, rug=False, fit=None)\n assert len(ax.patches) == 0\n assert len(ax.lines) == 1\n assert len(ax.collections) == 0\n\n plt.close(ax.figure)\n ax = distplot(self.x,\n hist=False, kde=False, rug=True, fit=None)\n assert len(ax.patches) == 0\n assert len(ax.lines) == 0\n assert len(ax.collections) == 1\n\n class Norm:\n \"\"\"Dummy object that looks like a scipy RV\"\"\"\n def fit(self, x):\n return ()\n\n def pdf(self, x, *params):\n return np.zeros_like(x)\n\n plt.close(ax.figure)\n ax = distplot(\n self.x, hist=False, kde=False, rug=False, fit=Norm())\n assert len(ax.patches) == 0\n assert len(ax.lines) == 1\n assert len(ax.collections) == 0\n\n def test_distplot_with_nans(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n x_null = np.append(self.x, [np.nan])\n\n with pytest.warns(UserWarning):\n distplot(self.x, ax=ax1)\n distplot(x_null, ax=ax2)\n\n line1 = ax1.lines[0]\n line2 = ax2.lines[0]\n assert np.array_equal(line1.get_xydata(), line2.get_xydata())\n\n for bar1, bar2 in zip(ax1.patches, ax2.patches):\n assert bar1.get_xy() == bar2.get_xy()\n assert bar1.get_height() == bar2.get_height()"},{"col":4,"comment":"null","endLoc":83,"header":"def test_hist_bins(self)","id":1812,"name":"test_hist_bins","nodeType":"Function","startLoc":69,"text":"def test_hist_bins(self):\n\n fd_edges = np.histogram_bin_edges(self.x, \"fd\")\n with pytest.warns(UserWarning):\n ax = distplot(self.x)\n for edge, bar in zip(fd_edges, ax.patches):\n assert pytest.approx(edge) == bar.get_x()\n\n plt.close(ax.figure)\n n = 25\n n_edges = np.histogram_bin_edges(self.x, n)\n with pytest.warns(UserWarning):\n ax = distplot(self.x, bins=n)\n for edge, bar in zip(n_edges, ax.patches):\n assert pytest.approx(edge) == bar.get_x()"},{"col":4,"comment":"null","endLoc":247,"header":"def test_x_any_y_paired_non_cross(self)","id":1813,"name":"test_x_any_y_paired_non_cross","nodeType":"Function","startLoc":236,"text":"def test_x_any_y_paired_non_cross(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [\"x\", \"y\", \"z\"]\n spec = {\"structure\": {\"x\": x, \"y\": y}, \"cross\": False}\n s = Subplots({}, {}, spec)\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == len(y)\n assert s.subplot_spec[\"nrows\"] == 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is False"},{"col":4,"comment":"null","endLoc":261,"header":"def test_x_any_y_paired_non_cross_wrapped(self)","id":1814,"name":"test_x_any_y_paired_non_cross_wrapped","nodeType":"Function","startLoc":249,"text":"def test_x_any_y_paired_non_cross_wrapped(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [\"x\", \"y\", \"z\"]\n wrap = 2\n spec = {\"structure\": {\"x\": x, \"y\": y}, \"cross\": False, \"wrap\": wrap}\n s = Subplots({}, {}, spec)\n\n assert s.n_subplots == len(x)\n assert s.subplot_spec[\"ncols\"] == wrap\n assert s.subplot_spec[\"nrows\"] == len(x) // wrap + 1\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] is False"},{"col":4,"comment":"null","endLoc":267,"header":"def test_forced_unshared_facets(self)","id":1815,"name":"test_forced_unshared_facets","nodeType":"Function","startLoc":263,"text":"def test_forced_unshared_facets(self):\n\n s = Subplots({\"sharex\": False, \"sharey\": \"row\"}, {}, {})\n assert s.subplot_spec[\"sharex\"] is False\n assert s.subplot_spec[\"sharey\"] == \"row\""},{"className":"TestSubplotElements","col":0,"comment":"null","endLoc":525,"id":1816,"nodeType":"Class","startLoc":270,"text":"class TestSubplotElements:\n\n def test_single_subplot(self):\n\n s = Subplots({}, {}, {})\n f = s.init_figure({}, {})\n\n assert len(s) == 1\n for i, e in enumerate(s):\n for side in [\"left\", \"right\", \"bottom\", \"top\"]:\n assert e[side]\n for dim in [\"col\", \"row\"]:\n assert e[dim] is None\n for axis in \"xy\":\n assert e[axis] == axis\n assert e[\"ax\"] == f.axes[i]\n\n @pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim(self, dim):\n\n key = \"a\"\n order = list(\"abc\")\n spec = {\"variables\": {dim: key}, \"structure\": {dim: order}}\n s = Subplots({}, spec, {})\n s.init_figure(spec, {})\n\n assert len(s) == len(order)\n\n for i, e in enumerate(s):\n assert e[dim] == order[i]\n for axis in \"xy\":\n assert e[axis] == axis\n assert e[\"top\"] == (dim == \"col\" or i == 0)\n assert e[\"bottom\"] == (dim == \"col\" or i == len(order) - 1)\n assert e[\"left\"] == (dim == \"row\" or i == 0)\n assert e[\"right\"] == (dim == \"row\" or i == len(order) - 1)\n\n @pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim_wrapped(self, dim):\n\n key = \"b\"\n order = list(\"abc\")\n wrap = len(order) - 1\n spec = {\"variables\": {dim: key}, \"structure\": {dim: order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n s.init_figure(spec, {})\n\n assert len(s) == len(order)\n\n for i, e in enumerate(s):\n assert e[dim] == order[i]\n for axis in \"xy\":\n assert e[axis] == axis\n\n sides = {\n \"col\": [\"top\", \"bottom\", \"left\", \"right\"],\n \"row\": [\"left\", \"right\", \"top\", \"bottom\"],\n }\n tests = (\n i < wrap,\n i >= wrap or i >= len(s) % wrap,\n i % wrap == 0,\n i % wrap == wrap - 1 or i + 1 == len(s),\n )\n\n for side, expected in zip(sides[dim], tests):\n assert e[side] == expected\n\n def test_both_facet_dims(self):\n\n col = \"a\"\n row = \"b\"\n col_order = list(\"ab\")\n row_order = list(\"xyz\")\n facet_spec = {\n \"variables\": {\"col\": col, \"row\": row},\n \"structure\": {\"col\": col_order, \"row\": row_order},\n }\n s = Subplots({}, facet_spec, {})\n s.init_figure(facet_spec, {})\n\n n_cols = len(col_order)\n n_rows = len(row_order)\n assert len(s) == n_cols * n_rows\n es = list(s)\n\n for e in es[:n_cols]:\n assert e[\"top\"]\n for e in es[::n_cols]:\n assert e[\"left\"]\n for e in es[n_cols - 1::n_cols]:\n assert e[\"right\"]\n for e in es[-n_cols:]:\n assert e[\"bottom\"]\n\n for e, (row_, col_) in zip(es, itertools.product(row_order, col_order)):\n assert e[\"col\"] == col_\n assert e[\"row\"] == row_\n\n for e in es:\n assert e[\"x\"] == \"x\"\n assert e[\"y\"] == \"y\"\n\n @pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_single_paired_var(self, var):\n\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n pairings = [\"x\", \"y\", \"z\"]\n pair_spec = {\n \"variables\": {f\"{var}{i}\": v for i, v in enumerate(pairings)},\n \"structure\": {var: [f\"{var}{i}\" for i, _ in enumerate(pairings)]},\n }\n\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n assert len(s) == len(pair_spec[\"structure\"][var])\n\n for i, e in enumerate(s):\n assert e[var] == f\"{var}{i}\"\n assert e[other_var] == other_var\n assert e[\"col\"] is e[\"row\"] is None\n\n tests = i == 0, True, True, i == len(s) - 1\n sides = {\n \"x\": [\"left\", \"right\", \"top\", \"bottom\"],\n \"y\": [\"top\", \"bottom\", \"left\", \"right\"],\n }\n\n for side, expected in zip(sides[var], tests):\n assert e[side] == expected\n\n @pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_single_paired_var_wrapped(self, var):\n\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n pairings = [\"x\", \"y\", \"z\", \"a\", \"b\"]\n wrap = len(pairings) - 2\n pair_spec = {\n \"variables\": {f\"{var}{i}\": val for i, val in enumerate(pairings)},\n \"structure\": {var: [f\"{var}{i}\" for i, _ in enumerate(pairings)]},\n \"wrap\": wrap\n }\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n assert len(s) == len(pairings)\n\n for i, e in enumerate(s):\n assert e[var] == f\"{var}{i}\"\n assert e[other_var] == other_var\n assert e[\"col\"] is e[\"row\"] is None\n\n tests = (\n i < wrap,\n i >= wrap or i >= len(s) % wrap,\n i % wrap == 0,\n i % wrap == wrap - 1 or i + 1 == len(s),\n )\n sides = {\n \"x\": [\"top\", \"bottom\", \"left\", \"right\"],\n \"y\": [\"left\", \"right\", \"top\", \"bottom\"],\n }\n for side, expected in zip(sides[var], tests):\n assert e[side] == expected\n\n def test_both_paired_variables(self):\n\n x = [\"x0\", \"x1\"]\n y = [\"y0\", \"y1\", \"y2\"]\n pair_spec = {\"structure\": {\"x\": x, \"y\": y}}\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n n_cols = len(x)\n n_rows = len(y)\n assert len(s) == n_cols * n_rows\n es = list(s)\n\n for e in es[:n_cols]:\n assert e[\"top\"]\n for e in es[::n_cols]:\n assert e[\"left\"]\n for e in es[n_cols - 1::n_cols]:\n assert e[\"right\"]\n for e in es[-n_cols:]:\n assert e[\"bottom\"]\n\n for e in es:\n assert e[\"col\"] is e[\"row\"] is None\n\n for i in range(len(y)):\n for j in range(len(x)):\n e = es[i * len(x) + j]\n assert e[\"x\"] == f\"x{j}\"\n assert e[\"y\"] == f\"y{i}\"\n\n def test_both_paired_non_cross(self):\n\n pair_spec = {\n \"structure\": {\"x\": [\"x0\", \"x1\", \"x2\"], \"y\": [\"y0\", \"y1\", \"y2\"]},\n \"cross\": False\n }\n s = Subplots({}, {}, pair_spec)\n s.init_figure(pair_spec)\n\n for i, e in enumerate(s):\n assert e[\"x\"] == f\"x{i}\"\n assert e[\"y\"] == f\"y{i}\"\n assert e[\"col\"] is e[\"row\"] is None\n assert e[\"left\"] == (i == 0)\n assert e[\"right\"] == (i == (len(s) - 1))\n assert e[\"top\"]\n assert e[\"bottom\"]\n\n @pytest.mark.parametrize(\"dim,var\", [(\"col\", \"y\"), (\"row\", \"x\")])\n def test_one_facet_one_paired(self, dim, var):\n\n other_var = {\"x\": \"y\", \"y\": \"x\"}[var]\n other_dim = {\"col\": \"row\", \"row\": \"col\"}[dim]\n order = list(\"abc\")\n facet_spec = {\"variables\": {dim: \"s\"}, \"structure\": {dim: order}}\n\n pairings = [\"x\", \"y\", \"t\"]\n pair_spec = {\n \"variables\": {f\"{var}{i}\": val for i, val in enumerate(pairings)},\n \"structure\": {var: [f\"{var}{i}\" for i, _ in enumerate(pairings)]},\n }\n\n s = Subplots({}, facet_spec, pair_spec)\n s.init_figure(pair_spec)\n\n n_cols = len(order) if dim == \"col\" else len(pairings)\n n_rows = len(order) if dim == \"row\" else len(pairings)\n\n assert len(s) == len(order) * len(pairings)\n\n es = list(s)\n\n for e in es[:n_cols]:\n assert e[\"top\"]\n for e in es[::n_cols]:\n assert e[\"left\"]\n for e in es[n_cols - 1::n_cols]:\n assert e[\"right\"]\n for e in es[-n_cols:]:\n assert e[\"bottom\"]\n\n if dim == \"row\":\n es = np.reshape(es, (n_rows, n_cols)).T.ravel()\n\n for i, e in enumerate(es):\n assert e[dim] == order[i % len(pairings)]\n assert e[other_dim] is None\n assert e[var] == f\"{var}{i // len(order)}\"\n assert e[other_var] == other_var"},{"col":4,"comment":"null","endLoc":285,"header":"def test_single_subplot(self)","id":1817,"name":"test_single_subplot","nodeType":"Function","startLoc":272,"text":"def test_single_subplot(self):\n\n s = Subplots({}, {}, {})\n f = s.init_figure({}, {})\n\n assert len(s) == 1\n for i, e in enumerate(s):\n for side in [\"left\", \"right\", \"bottom\", \"top\"]:\n assert e[side]\n for dim in [\"col\", \"row\"]:\n assert e[dim] is None\n for axis in \"xy\":\n assert e[axis] == axis\n assert e[\"ax\"] == f.axes[i]"},{"col":4,"comment":"null","endLoc":123,"header":"def test_elements(self)","id":1818,"name":"test_elements","nodeType":"Function","startLoc":85,"text":"def test_elements(self):\n\n with pytest.warns(UserWarning):\n\n n = 10\n ax = distplot(self.x, bins=n,\n hist=True, kde=False, rug=False, fit=None)\n assert len(ax.patches) == 10\n assert len(ax.lines) == 0\n assert len(ax.collections) == 0\n\n plt.close(ax.figure)\n ax = distplot(self.x,\n hist=False, kde=True, rug=False, fit=None)\n assert len(ax.patches) == 0\n assert len(ax.lines) == 1\n assert len(ax.collections) == 0\n\n plt.close(ax.figure)\n ax = distplot(self.x,\n hist=False, kde=False, rug=True, fit=None)\n assert len(ax.patches) == 0\n assert len(ax.lines) == 0\n assert len(ax.collections) == 1\n\n class Norm:\n \"\"\"Dummy object that looks like a scipy RV\"\"\"\n def fit(self, x):\n return ()\n\n def pdf(self, x, *params):\n return np.zeros_like(x)\n\n plt.close(ax.figure)\n ax = distplot(\n self.x, hist=False, kde=False, rug=False, fit=Norm())\n assert len(ax.patches) == 0\n assert len(ax.lines) == 1\n assert len(ax.collections) == 0"},{"attributeType":"null","col":4,"comment":"null","endLoc":476,"id":1819,"name":"rs","nodeType":"Attribute","startLoc":476,"text":"rs"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":478,"id":1820,"name":"default_kws","nodeType":"Attribute","startLoc":478,"text":"default_kws"},{"attributeType":"null","col":4,"comment":"null","endLoc":481,"id":1821,"name":"x_norm","nodeType":"Attribute","startLoc":481,"text":"x_norm"},{"attributeType":"null","col":4,"comment":"null","endLoc":482,"id":1824,"name":"x_norm","nodeType":"Attribute","startLoc":482,"text":"x_norm"},{"attributeType":"null","col":4,"comment":"null","endLoc":483,"id":1825,"name":"letters","nodeType":"Attribute","startLoc":483,"text":"letters"},{"attributeType":"null","col":4,"comment":"null","endLoc":486,"id":1826,"name":"df_norm","nodeType":"Attribute","startLoc":486,"text":"df_norm"},{"attributeType":"null","col":12,"comment":"null","endLoc":490,"id":1827,"name":"x_norm_distances","nodeType":"Attribute","startLoc":490,"text":"x_norm_distances"},{"attributeType":"null","col":12,"comment":"null","endLoc":491,"id":1828,"name":"x_norm_linkage","nodeType":"Attribute","startLoc":491,"text":"x_norm_linkage"},{"attributeType":"null","col":12,"comment":"null","endLoc":493,"id":1829,"name":"x_norm_linkage","nodeType":"Attribute","startLoc":493,"text":"x_norm_linkage"},{"attributeType":"null","col":8,"comment":"null","endLoc":497,"id":1830,"name":"x_norm_dendrogram","nodeType":"Attribute","startLoc":497,"text":"x_norm_dendrogram"},{"attributeType":"null","col":8,"comment":"null","endLoc":499,"id":1831,"name":"x_norm_leaves","nodeType":"Attribute","startLoc":499,"text":"x_norm_leaves"},{"attributeType":"null","col":8,"comment":"null","endLoc":500,"id":1832,"name":"df_norm_leaves","nodeType":"Attribute","startLoc":500,"text":"df_norm_leaves"},{"className":"TestClustermap","col":0,"comment":"null","endLoc":1327,"id":1833,"nodeType":"Class","startLoc":718,"text":"@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\nclass TestClustermap:\n\n rs = np.random.RandomState(sum(map(ord, \"clustermap\")))\n\n x_norm = rs.randn(4, 8) + np.arange(8)\n x_norm = (x_norm.T + np.arange(4)).T\n letters = pd.Series([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"],\n name=\"letters\")\n\n df_norm = pd.DataFrame(x_norm, columns=letters)\n\n default_kws = dict(pivot_kws=None, z_score=None, standard_scale=None,\n figsize=(10, 10), row_colors=None, col_colors=None,\n dendrogram_ratio=.2, colors_ratio=.03,\n cbar_pos=(0, .8, .05, .2))\n\n default_plot_kws = dict(metric='euclidean', method='average',\n colorbar_kws=None,\n row_cluster=True, col_cluster=True,\n row_linkage=None, col_linkage=None,\n tree_kws=None)\n\n row_colors = color_palette('Set2', df_norm.shape[0])\n col_colors = color_palette('Dark2', df_norm.shape[1])\n\n if not _no_scipy:\n if _no_fastcluster:\n x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')\n x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')\n else:\n x_norm_linkage = fastcluster.linkage_vector(x_norm.T,\n metric='euclidean',\n method='single')\n\n x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,\n color_threshold=-np.inf)\n x_norm_leaves = x_norm_dendrogram['leaves']\n df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])\n\n def test_ndarray_input(self):\n cg = mat.ClusterGrid(self.x_norm, **self.default_kws)\n pdt.assert_frame_equal(cg.data, pd.DataFrame(self.x_norm))\n assert len(cg.fig.axes) == 4\n assert cg.ax_row_colors is None\n assert cg.ax_col_colors is None\n\n def test_df_input(self):\n cg = mat.ClusterGrid(self.df_norm, **self.default_kws)\n pdt.assert_frame_equal(cg.data, self.df_norm)\n\n def test_corr_df_input(self):\n df = self.df_norm.corr()\n cg = mat.ClusterGrid(df, **self.default_kws)\n cg.plot(**self.default_plot_kws)\n diag = cg.data2d.values[np.diag_indices_from(cg.data2d)]\n npt.assert_array_almost_equal(diag, np.ones(cg.data2d.shape[0]))\n\n def test_pivot_input(self):\n df_norm = self.df_norm.copy()\n df_norm.index.name = 'numbers'\n df_long = pd.melt(df_norm.reset_index(), var_name='letters',\n id_vars='numbers')\n kws = self.default_kws.copy()\n kws['pivot_kws'] = dict(index='numbers', columns='letters',\n values='value')\n cg = mat.ClusterGrid(df_long, **kws)\n\n pdt.assert_frame_equal(cg.data2d, df_norm)\n\n def test_colors_input(self):\n kws = self.default_kws.copy()\n\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, self.row_colors)\n npt.assert_array_equal(cg.col_colors, self.col_colors)\n\n assert len(cg.fig.axes) == 6\n\n def test_categorical_colors_input(self):\n kws = self.default_kws.copy()\n\n row_colors = pd.Series(self.row_colors, dtype=\"category\")\n col_colors = pd.Series(\n self.col_colors, dtype=\"category\", index=self.df_norm.columns\n )\n\n kws['row_colors'] = row_colors\n kws['col_colors'] = col_colors\n\n exp_row_colors = list(map(mpl.colors.to_rgb, row_colors))\n exp_col_colors = list(map(mpl.colors.to_rgb, col_colors))\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, exp_row_colors)\n npt.assert_array_equal(cg.col_colors, exp_col_colors)\n\n assert len(cg.fig.axes) == 6\n\n def test_nested_colors_input(self):\n kws = self.default_kws.copy()\n\n row_colors = [self.row_colors, self.row_colors]\n col_colors = [self.col_colors, self.col_colors]\n kws['row_colors'] = row_colors\n kws['col_colors'] = col_colors\n\n cm = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cm.row_colors, row_colors)\n npt.assert_array_equal(cm.col_colors, col_colors)\n\n assert len(cm.fig.axes) == 6\n\n def test_colors_input_custom_cmap(self):\n kws = self.default_kws.copy()\n\n kws['cmap'] = mpl.cm.PRGn\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cg = mat.clustermap(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, self.row_colors)\n npt.assert_array_equal(cg.col_colors, self.col_colors)\n\n assert len(cg.fig.axes) == 6\n\n def test_z_score(self):\n df = self.df_norm.copy()\n df = (df - df.mean()) / df.std()\n kws = self.default_kws.copy()\n kws['z_score'] = 1\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_z_score_axis0(self):\n df = self.df_norm.copy()\n df = df.T\n df = (df - df.mean()) / df.std()\n df = df.T\n kws = self.default_kws.copy()\n kws['z_score'] = 0\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_standard_scale(self):\n df = self.df_norm.copy()\n df = (df - df.min()) / (df.max() - df.min())\n kws = self.default_kws.copy()\n kws['standard_scale'] = 1\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_standard_scale_axis0(self):\n df = self.df_norm.copy()\n df = df.T\n df = (df - df.min()) / (df.max() - df.min())\n df = df.T\n kws = self.default_kws.copy()\n kws['standard_scale'] = 0\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)\n\n def test_z_score_standard_scale(self):\n kws = self.default_kws.copy()\n kws['z_score'] = True\n kws['standard_scale'] = True\n with pytest.raises(ValueError):\n mat.ClusterGrid(self.df_norm, **kws)\n\n def test_color_list_to_matrix_and_cmap(self):\n # Note this uses the attribute named col_colors but tests row colors\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n self.col_colors, self.x_norm_leaves, axis=0)\n\n for i, leaf in enumerate(self.x_norm_leaves):\n color = self.col_colors[leaf]\n assert_colors_equal(cmap(matrix[i, 0]), color)\n\n def test_nested_color_list_to_matrix_and_cmap(self):\n # Note this uses the attribute named col_colors but tests row colors\n colors = [self.col_colors, self.col_colors[::-1]]\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n colors, self.x_norm_leaves, axis=0)\n\n for i, leaf in enumerate(self.x_norm_leaves):\n for j, color_row in enumerate(colors):\n color = color_row[leaf]\n assert_colors_equal(cmap(matrix[i, j]), color)\n\n def test_color_list_to_matrix_and_cmap_axis1(self):\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n self.col_colors, self.x_norm_leaves, axis=1)\n\n for j, leaf in enumerate(self.x_norm_leaves):\n color = self.col_colors[leaf]\n assert_colors_equal(cmap(matrix[0, j]), color)\n\n def test_color_list_to_matrix_and_cmap_different_sizes(self):\n colors = [self.col_colors, self.col_colors * 2]\n with pytest.raises(ValueError):\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n colors, self.x_norm_leaves, axis=1)\n\n def test_savefig(self):\n # Not sure if this is the right way to test....\n cg = mat.ClusterGrid(self.df_norm, **self.default_kws)\n cg.plot(**self.default_plot_kws)\n cg.savefig(tempfile.NamedTemporaryFile(), format='png')\n\n def test_plot_dendrograms(self):\n cm = mat.clustermap(self.df_norm, **self.default_kws)\n\n assert len(cm.ax_row_dendrogram.collections[0].get_paths()) == len(\n cm.dendrogram_row.independent_coord\n )\n assert len(cm.ax_col_dendrogram.collections[0].get_paths()) == len(\n cm.dendrogram_col.independent_coord\n )\n data2d = self.df_norm.iloc[cm.dendrogram_row.reordered_ind,\n cm.dendrogram_col.reordered_ind]\n pdt.assert_frame_equal(cm.data2d, data2d)\n\n def test_cluster_false(self):\n kws = self.default_kws.copy()\n kws['row_cluster'] = False\n kws['col_cluster'] = False\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert len(cm.ax_row_dendrogram.lines) == 0\n assert len(cm.ax_col_dendrogram.lines) == 0\n\n assert len(cm.ax_row_dendrogram.get_xticks()) == 0\n assert len(cm.ax_row_dendrogram.get_yticks()) == 0\n assert len(cm.ax_col_dendrogram.get_xticks()) == 0\n assert len(cm.ax_col_dendrogram.get_yticks()) == 0\n\n pdt.assert_frame_equal(cm.data2d, self.df_norm)\n\n def test_row_col_colors(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert len(cm.ax_row_colors.collections) == 1\n assert len(cm.ax_col_colors.collections) == 1\n\n def test_cluster_false_row_col_colors(self):\n kws = self.default_kws.copy()\n kws['row_cluster'] = False\n kws['col_cluster'] = False\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert len(cm.ax_row_dendrogram.lines) == 0\n assert len(cm.ax_col_dendrogram.lines) == 0\n\n assert len(cm.ax_row_dendrogram.get_xticks()) == 0\n assert len(cm.ax_row_dendrogram.get_yticks()) == 0\n assert len(cm.ax_col_dendrogram.get_xticks()) == 0\n assert len(cm.ax_col_dendrogram.get_yticks()) == 0\n assert len(cm.ax_row_colors.collections) == 1\n assert len(cm.ax_col_colors.collections) == 1\n\n pdt.assert_frame_equal(cm.data2d, self.df_norm)\n\n def test_row_col_colors_df(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),\n 'row_2': list(self.row_colors)},\n index=self.df_norm.index,\n columns=['row_1', 'row_2'])\n kws['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),\n 'col_2': list(self.col_colors)},\n index=self.df_norm.columns,\n columns=['col_1', 'col_2'])\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n row_labels = [l.get_text() for l in\n cm.ax_row_colors.get_xticklabels()]\n assert cm.row_color_labels == ['row_1', 'row_2']\n assert row_labels == cm.row_color_labels\n\n col_labels = [l.get_text() for l in\n cm.ax_col_colors.get_yticklabels()]\n assert cm.col_color_labels == ['col_1', 'col_2']\n assert col_labels == cm.col_color_labels\n\n def test_row_col_colors_df_shuffled(self):\n # Tests if colors are properly matched, even if given in wrong order\n\n m, n = self.df_norm.shape\n shuffled_inds = [self.df_norm.index[i] for i in\n list(range(0, m, 2)) + list(range(1, m, 2))]\n shuffled_cols = [self.df_norm.columns[i] for i in\n list(range(0, n, 2)) + list(range(1, n, 2))]\n\n kws = self.default_kws.copy()\n\n row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.loc[shuffled_inds]\n\n col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.loc[shuffled_cols]\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert list(cm.col_colors)[0] == list(self.col_colors)\n assert list(cm.row_colors)[0] == list(self.row_colors)\n\n def test_row_col_colors_df_missing(self):\n kws = self.default_kws.copy()\n row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.drop(self.df_norm.index[0])\n\n col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert list(cm.col_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])\n assert list(cm.row_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])\n\n def test_row_col_colors_df_one_axis(self):\n # Test case with only row annotation.\n kws1 = self.default_kws.copy()\n kws1['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),\n 'row_2': list(self.row_colors)},\n index=self.df_norm.index,\n columns=['row_1', 'row_2'])\n\n cm1 = mat.clustermap(self.df_norm, **kws1)\n\n row_labels = [l.get_text() for l in\n cm1.ax_row_colors.get_xticklabels()]\n assert cm1.row_color_labels == ['row_1', 'row_2']\n assert row_labels == cm1.row_color_labels\n\n # Test case with only col annotation.\n kws2 = self.default_kws.copy()\n kws2['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),\n 'col_2': list(self.col_colors)},\n index=self.df_norm.columns,\n columns=['col_1', 'col_2'])\n\n cm2 = mat.clustermap(self.df_norm, **kws2)\n\n col_labels = [l.get_text() for l in\n cm2.ax_col_colors.get_yticklabels()]\n assert cm2.col_color_labels == ['col_1', 'col_2']\n assert col_labels == cm2.col_color_labels\n\n def test_row_col_colors_series(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = pd.Series(list(self.row_colors), name='row_annot',\n index=self.df_norm.index)\n kws['col_colors'] = pd.Series(list(self.col_colors), name='col_annot',\n index=self.df_norm.columns)\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n row_labels = [l.get_text() for l in cm.ax_row_colors.get_xticklabels()]\n assert cm.row_color_labels == ['row_annot']\n assert row_labels == cm.row_color_labels\n\n col_labels = [l.get_text() for l in cm.ax_col_colors.get_yticklabels()]\n assert cm.col_color_labels == ['col_annot']\n assert col_labels == cm.col_color_labels\n\n def test_row_col_colors_series_shuffled(self):\n # Tests if colors are properly matched, even if given in wrong order\n\n m, n = self.df_norm.shape\n shuffled_inds = [self.df_norm.index[i] for i in\n list(range(0, m, 2)) + list(range(1, m, 2))]\n shuffled_cols = [self.df_norm.columns[i] for i in\n list(range(0, n, 2)) + list(range(1, n, 2))]\n\n kws = self.default_kws.copy()\n\n row_colors = pd.Series(list(self.row_colors), name='row_annot',\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.loc[shuffled_inds]\n\n col_colors = pd.Series(list(self.col_colors), name='col_annot',\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.loc[shuffled_cols]\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert list(cm.col_colors) == list(self.col_colors)\n assert list(cm.row_colors) == list(self.row_colors)\n\n def test_row_col_colors_series_missing(self):\n kws = self.default_kws.copy()\n row_colors = pd.Series(list(self.row_colors), name='row_annot',\n index=self.df_norm.index)\n kws['row_colors'] = row_colors.drop(self.df_norm.index[0])\n\n col_colors = pd.Series(list(self.col_colors), name='col_annot',\n index=self.df_norm.columns)\n kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert list(cm.col_colors) == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])\n assert list(cm.row_colors) == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])\n\n def test_row_col_colors_ignore_heatmap_kwargs(self):\n\n g = mat.clustermap(self.rs.uniform(0, 200, self.df_norm.shape),\n row_colors=self.row_colors,\n col_colors=self.col_colors,\n cmap=\"Spectral\",\n norm=mpl.colors.LogNorm(),\n vmax=100)\n\n assert np.array_equal(\n np.array(self.row_colors)[g.dendrogram_row.reordered_ind],\n g.ax_row_colors.collections[0].get_facecolors()[:, :3]\n )\n\n assert np.array_equal(\n np.array(self.col_colors)[g.dendrogram_col.reordered_ind],\n g.ax_col_colors.collections[0].get_facecolors()[:, :3]\n )\n\n def test_row_col_colors_raise_on_mixed_index_types(self):\n\n row_colors = pd.Series(\n list(self.row_colors), name=\"row_annot\", index=self.df_norm.index\n )\n\n col_colors = pd.Series(\n list(self.col_colors), name=\"col_annot\", index=self.df_norm.columns\n )\n\n with pytest.raises(TypeError):\n mat.clustermap(self.x_norm, row_colors=row_colors)\n\n with pytest.raises(TypeError):\n mat.clustermap(self.x_norm, col_colors=col_colors)\n\n def test_mask_reorganization(self):\n\n kws = self.default_kws.copy()\n kws[\"mask\"] = self.df_norm > 0\n\n g = mat.clustermap(self.df_norm, **kws)\n npt.assert_array_equal(g.data2d.index, g.mask.index)\n npt.assert_array_equal(g.data2d.columns, g.mask.columns)\n\n npt.assert_array_equal(g.mask.index,\n self.df_norm.index[\n g.dendrogram_row.reordered_ind])\n npt.assert_array_equal(g.mask.columns,\n self.df_norm.columns[\n g.dendrogram_col.reordered_ind])\n\n def test_ticklabel_reorganization(self):\n\n kws = self.default_kws.copy()\n xtl = np.arange(self.df_norm.shape[1])\n kws[\"xticklabels\"] = list(xtl)\n ytl = self.letters.loc[:self.df_norm.shape[0]]\n kws[\"yticklabels\"] = ytl\n\n g = mat.clustermap(self.df_norm, **kws)\n\n xtl_actual = [t.get_text() for t in g.ax_heatmap.get_xticklabels()]\n ytl_actual = [t.get_text() for t in g.ax_heatmap.get_yticklabels()]\n\n xtl_want = xtl[g.dendrogram_col.reordered_ind].astype(\" g1.ax_col_dendrogram.get_position().height)\n\n assert (g2.ax_col_colors.get_position().height\n > g1.ax_col_colors.get_position().height)\n\n assert (g2.ax_heatmap.get_position().height\n < g1.ax_heatmap.get_position().height)\n\n assert (g2.ax_row_dendrogram.get_position().width\n > g1.ax_row_dendrogram.get_position().width)\n\n assert (g2.ax_row_colors.get_position().width\n > g1.ax_row_colors.get_position().width)\n\n assert (g2.ax_heatmap.get_position().width\n < g1.ax_heatmap.get_position().width)\n\n kws1 = self.default_kws.copy()\n kws1.update(col_colors=self.col_colors)\n kws2 = kws1.copy()\n kws2.update(col_colors=[self.col_colors, self.col_colors])\n\n g1 = mat.clustermap(self.df_norm, **kws1)\n g2 = mat.clustermap(self.df_norm, **kws2)\n\n assert (g2.ax_col_colors.get_position().height\n > g1.ax_col_colors.get_position().height)\n\n kws1 = self.default_kws.copy()\n kws1.update(dendrogram_ratio=(.2, .2))\n\n kws2 = kws1.copy()\n kws2.update(dendrogram_ratio=(.2, .3))\n\n g1 = mat.clustermap(self.df_norm, **kws1)\n g2 = mat.clustermap(self.df_norm, **kws2)\n\n # Fails on pinned matplotlib?\n # assert (g2.ax_row_dendrogram.get_position().width\n # == g1.ax_row_dendrogram.get_position().width)\n assert g1.gs.get_width_ratios() == g2.gs.get_width_ratios()\n\n assert (g2.ax_col_dendrogram.get_position().height\n > g1.ax_col_dendrogram.get_position().height)\n\n def test_cbar_pos(self):\n\n kws = self.default_kws.copy()\n kws[\"cbar_pos\"] = (.2, .1, .4, .3)\n\n g = mat.clustermap(self.df_norm, **kws)\n pos = g.ax_cbar.get_position()\n assert pytest.approx(tuple(pos.p0)) == kws[\"cbar_pos\"][:2]\n assert pytest.approx(pos.width) == kws[\"cbar_pos\"][2]\n assert pytest.approx(pos.height) == kws[\"cbar_pos\"][3]\n\n kws[\"cbar_pos\"] = None\n g = mat.clustermap(self.df_norm, **kws)\n assert g.ax_cbar is None\n\n def test_square_warning(self):\n\n kws = self.default_kws.copy()\n g1 = mat.clustermap(self.df_norm, **kws)\n\n with pytest.warns(UserWarning):\n kws[\"square\"] = True\n g2 = mat.clustermap(self.df_norm, **kws)\n\n g1_shape = g1.ax_heatmap.get_position().get_points()\n g2_shape = g2.ax_heatmap.get_position().get_points()\n assert np.array_equal(g1_shape, g2_shape)\n\n def test_clustermap_annotation(self):\n\n g = mat.clustermap(self.df_norm, annot=True, fmt=\".1f\")\n for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):\n assert text.get_text() == f\"{val:.1f}\"\n\n g = mat.clustermap(self.df_norm, annot=self.df_norm, fmt=\".1f\")\n for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):\n assert text.get_text() == f\"{val:.1f}\"\n\n def test_tree_kws(self):\n\n rgb = (1, .5, .2)\n g = mat.clustermap(self.df_norm, tree_kws=dict(color=rgb))\n for ax in [g.ax_col_dendrogram, g.ax_row_dendrogram]:\n tree, = ax.collections\n assert tuple(tree.get_color().squeeze())[:3] == rgb"},{"attributeType":"null","col":4,"comment":"null","endLoc":520,"id":1834,"name":"_legend_attributes","nodeType":"Attribute","startLoc":520,"text":"_legend_attributes"},{"attributeType":"null","col":4,"comment":"null","endLoc":521,"id":1835,"name":"_legend_func","nodeType":"Attribute","startLoc":521,"text":"_legend_func"},{"attributeType":"null","col":8,"comment":"null","endLoc":534,"id":1836,"name":"legend","nodeType":"Attribute","startLoc":534,"text":"self.legend"},{"col":4,"comment":"null","endLoc":140,"header":"def test_distplot_with_nans(self)","id":1837,"name":"test_distplot_with_nans","nodeType":"Function","startLoc":125,"text":"def test_distplot_with_nans(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n x_null = np.append(self.x, [np.nan])\n\n with pytest.warns(UserWarning):\n distplot(self.x, ax=ax1)\n distplot(x_null, ax=ax2)\n\n line1 = ax1.lines[0]\n line2 = ax2.lines[0]\n assert np.array_equal(line1.get_xydata(), line2.get_xydata())\n\n for bar1, bar2 in zip(ax1.patches, ax2.patches):\n assert bar1.get_xy() == bar2.get_xy()\n assert bar1.get_height() == bar2.get_height()"},{"attributeType":"null","col":8,"comment":"null","endLoc":528,"id":1838,"name":"_default_size_range","nodeType":"Attribute","startLoc":528,"text":"self._default_size_range"},{"col":0,"comment":"null","endLoc":984,"header":"def relplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None, units=None,\n row=None, col=None, col_wrap=None, row_order=None, col_order=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=None, dashes=None, style_order=None,\n legend=\"auto\", kind=\"scatter\", height=5, aspect=1, facet_kws=None,\n **kwargs\n)","id":1839,"name":"relplot","nodeType":"Function","startLoc":819,"text":"def relplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None, units=None,\n row=None, col=None, col_wrap=None, row_order=None, col_order=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=None, dashes=None, style_order=None,\n legend=\"auto\", kind=\"scatter\", height=5, aspect=1, facet_kws=None,\n **kwargs\n):\n\n if kind == \"scatter\":\n\n plotter = _ScatterPlotter\n func = scatterplot\n markers = True if markers is None else markers\n\n elif kind == \"line\":\n\n plotter = _LinePlotter\n func = lineplot\n dashes = True if dashes is None else dashes\n\n else:\n err = f\"Plot kind {kind} not recognized\"\n raise ValueError(err)\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\n \"relplot is a figure-level function and does not accept \"\n \"the `ax` parameter. You may wish to try {}\".format(kind + \"plot\")\n )\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n # Use the full dataset to map the semantics\n p = plotter(\n data=data,\n variables=plotter.get_semantics(locals()),\n legend=legend,\n )\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, dashes=dashes, order=style_order)\n\n # Extract the semantic mappings\n if \"hue\" in p.variables:\n palette = p._hue_map.lookup_table\n hue_order = p._hue_map.levels\n hue_norm = p._hue_map.norm\n else:\n palette = hue_order = hue_norm = None\n\n if \"size\" in p.variables:\n sizes = p._size_map.lookup_table\n size_order = p._size_map.levels\n size_norm = p._size_map.norm\n\n if \"style\" in p.variables:\n style_order = p._style_map.levels\n if markers:\n markers = {k: p._style_map(k, \"marker\") for k in style_order}\n else:\n markers = None\n if dashes:\n dashes = {k: p._style_map(k, \"dashes\") for k in style_order}\n else:\n dashes = None\n else:\n markers = dashes = style_order = None\n\n # Now extract the data that would be used to draw a single plot\n variables = p.variables\n plot_data = p.plot_data\n plot_semantics = p.semantics\n\n # Define the common plotting parameters\n plot_kws = dict(\n palette=palette, hue_order=hue_order, hue_norm=hue_norm,\n sizes=sizes, size_order=size_order, size_norm=size_norm,\n markers=markers, dashes=dashes, style_order=style_order,\n legend=False,\n )\n plot_kws.update(kwargs)\n if kind == \"scatter\":\n plot_kws.pop(\"dashes\")\n\n # Add the grid semantics onto the plotter\n grid_semantics = \"row\", \"col\"\n p.semantics = plot_semantics + grid_semantics\n p.assign_variables(\n data=data,\n variables=dict(\n x=x, y=y,\n hue=hue, size=size, style=style, units=units,\n row=row, col=col,\n ),\n )\n\n # Define the named variables for plotting on each facet\n # Rename the variables with a leading underscore to avoid\n # collisions with faceting variable names\n plot_variables = {v: f\"_{v}\" for v in variables}\n plot_kws.update(plot_variables)\n\n # Pass the row/col variables to FacetGrid with their original\n # names so that the axes titles render correctly\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n grid_kws = {v: p.variables.get(v) for v in grid_semantics}\n\n # Rename the columns of the plot_data structure appropriately\n new_cols = plot_variables.copy()\n new_cols.update(grid_kws)\n full_data = p.plot_data.rename(columns=new_cols)\n\n # Set up the FacetGrid object\n facet_kws = {} if facet_kws is None else facet_kws.copy()\n g = FacetGrid(\n data=full_data.dropna(axis=1, how=\"all\"),\n **grid_kws,\n col_wrap=col_wrap, row_order=row_order, col_order=col_order,\n height=height, aspect=aspect, dropna=False,\n **facet_kws\n )\n\n # Draw the plot\n g.map_dataframe(func, **plot_kws)\n\n # Label the axes, using the original variables\n g.set(xlabel=variables.get(\"x\"), ylabel=variables.get(\"y\"))\n\n # Show the legend\n if legend:\n # Replace the original plot data so the legend uses\n # numeric data with the correct type\n p.plot_data = plot_data\n p.add_legend_data(g.axes.flat[0])\n if p.legend_data:\n g.add_legend(legend_data=p.legend_data,\n label_order=p.legend_order,\n title=p.legend_title,\n adjust_subtitles=True)\n\n # Rename the columns of the FacetGrid's `data` attribute\n # to match the original column names\n orig_cols = {\n f\"_{k}\": f\"_{k}_\" if v is None else v for k, v in variables.items()\n }\n grid_data = g.data.rename(columns=orig_cols)\n if data is not None and (x is not None or y is not None):\n if not isinstance(data, pd.DataFrame):\n data = pd.DataFrame(data)\n g.data = pd.merge(\n data,\n grid_data[grid_data.columns.difference(data.columns)],\n left_index=True,\n right_index=True,\n )\n else:\n g.data = grid_data\n\n return g"},{"col":4,"comment":"null","endLoc":763,"header":"def test_ndarray_input(self)","id":1840,"name":"test_ndarray_input","nodeType":"Function","startLoc":758,"text":"def test_ndarray_input(self):\n cg = mat.ClusterGrid(self.x_norm, **self.default_kws)\n pdt.assert_frame_equal(cg.data, pd.DataFrame(self.x_norm))\n assert len(cg.fig.axes) == 4\n assert cg.ax_row_colors is None\n assert cg.ax_col_colors is None"},{"col":4,"comment":"null","endLoc":767,"header":"def test_df_input(self)","id":1841,"name":"test_df_input","nodeType":"Function","startLoc":765,"text":"def test_df_input(self):\n cg = mat.ClusterGrid(self.df_norm, **self.default_kws)\n pdt.assert_frame_equal(cg.data, self.df_norm)"},{"col":0,"comment":"","endLoc":1,"header":"properties.py#","id":1842,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n from numpy.typing import ArrayLike\nexcept ImportError:\n # numpy<1.20.0 (Jan 2021)\n ArrayLike = Any\n\nRGBTuple = Tuple[float, float, float]\n\nRGBATuple = Tuple[float, float, float, float]\n\nColorSpec = Union[RGBTuple, RGBATuple, str]\n\nDashPattern = Tuple[float, ...]\n\nDashPatternWithOffset = Tuple[float, Optional[DashPattern]]\n\nMarkerPattern = Union[\n float,\n str,\n Tuple[int, int, float],\n List[Tuple[float, float]],\n Path,\n MarkerStyle,\n]\n\nPROPERTY_CLASSES = {\n \"x\": Coordinate,\n \"y\": Coordinate,\n \"color\": Color,\n \"alpha\": Alpha,\n \"fill\": Fill,\n \"marker\": Marker,\n \"pointsize\": PointSize,\n \"stroke\": Stroke,\n \"linewidth\": LineWidth,\n \"linestyle\": LineStyle,\n \"fillcolor\": Color,\n \"fillalpha\": Alpha,\n \"edgewidth\": EdgeWidth,\n \"edgestyle\": LineStyle,\n \"edgecolor\": Color,\n \"edgealpha\": Alpha,\n \"text\": Property,\n \"halign\": HorizontalAlignment,\n \"valign\": VerticalAlignment,\n \"offset\": Offset,\n \"fontsize\": FontSize,\n \"xmin\": Coordinate,\n \"xmax\": Coordinate,\n \"ymin\": Coordinate,\n \"ymax\": Coordinate,\n \"group\": Property,\n # TODO pattern?\n # TODO gradient?\n}\n\nPROPERTIES = {var: cls(var) for var, cls in PROPERTY_CLASSES.items()}"},{"col":4,"comment":"null","endLoc":774,"header":"def test_corr_df_input(self)","id":1843,"name":"test_corr_df_input","nodeType":"Function","startLoc":769,"text":"def test_corr_df_input(self):\n df = self.df_norm.corr()\n cg = mat.ClusterGrid(df, **self.default_kws)\n cg.plot(**self.default_plot_kws)\n diag = cg.data2d.values[np.diag_indices_from(cg.data2d)]\n npt.assert_array_almost_equal(diag, np.ones(cg.data2d.shape[0]))"},{"col":4,"comment":"null","endLoc":305,"header":"@pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim(self, dim)","id":1844,"name":"test_single_facet_dim","nodeType":"Function","startLoc":287,"text":"@pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim(self, dim):\n\n key = \"a\"\n order = list(\"abc\")\n spec = {\"variables\": {dim: key}, \"structure\": {dim: order}}\n s = Subplots({}, spec, {})\n s.init_figure(spec, {})\n\n assert len(s) == len(order)\n\n for i, e in enumerate(s):\n assert e[dim] == order[i]\n for axis in \"xy\":\n assert e[axis] == axis\n assert e[\"top\"] == (dim == \"col\" or i == 0)\n assert e[\"bottom\"] == (dim == \"col\" or i == len(order) - 1)\n assert e[\"left\"] == (dim == \"row\" or i == 0)\n assert e[\"right\"] == (dim == \"row\" or i == len(order) - 1)"},{"col":4,"comment":"\n Provide existing Matplotlib figure or axes for drawing the plot.\n\n When using this method, you will also need to explicitly call a method that\n triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you\n want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot`\n first to compile the plot without rendering it.\n\n Parameters\n ----------\n target : Axes, SubFigure, or Figure\n Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add\n artists without otherwise modifying the figure. Otherwise, subplots will be\n created within the space of the given :class:`matplotlib.figure.Figure` or\n :class:`matplotlib.figure.SubFigure`.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.on.rst\n\n ","endLoc":387,"header":"def on(self, target: Axes | SubFigure | Figure) -> Plot","id":1845,"name":"on","nodeType":"Function","startLoc":343,"text":"def on(self, target: Axes | SubFigure | Figure) -> Plot:\n \"\"\"\n Provide existing Matplotlib figure or axes for drawing the plot.\n\n When using this method, you will also need to explicitly call a method that\n triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you\n want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot`\n first to compile the plot without rendering it.\n\n Parameters\n ----------\n target : Axes, SubFigure, or Figure\n Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add\n artists without otherwise modifying the figure. Otherwise, subplots will be\n created within the space of the given :class:`matplotlib.figure.Figure` or\n :class:`matplotlib.figure.SubFigure`.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.on.rst\n\n \"\"\"\n accepted_types: tuple # Allow tuple of various length\n if hasattr(mpl.figure, \"SubFigure\"): # Added in mpl 3.4\n accepted_types = (\n mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure\n )\n accepted_types_str = (\n f\"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}\"\n )\n else:\n accepted_types = mpl.axes.Axes, mpl.figure.Figure\n accepted_types_str = f\"{mpl.axes.Axes} or {mpl.figure.Figure}\"\n\n if not isinstance(target, accepted_types):\n err = (\n f\"The `Plot.on` target must be an instance of {accepted_types_str}. \"\n f\"You passed an instance of {target.__class__} instead.\"\n )\n raise TypeError(err)\n\n new = self._clone()\n new._target = target\n\n return new"},{"attributeType":"list","col":4,"comment":"null","endLoc":348,"id":1846,"name":"_legend_attributes","nodeType":"Attribute","startLoc":348,"text":"_legend_attributes"},{"attributeType":"str","col":4,"comment":"null","endLoc":349,"id":1847,"name":"_legend_func","nodeType":"Attribute","startLoc":349,"text":"_legend_func"},{"attributeType":"null","col":8,"comment":"null","endLoc":367,"id":1848,"name":"estimator","nodeType":"Attribute","startLoc":367,"text":"self.estimator"},{"fileName":"miscplot.py","filePath":"seaborn","id":1849,"nodeType":"File","text":"import numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\n__all__ = [\"palplot\", \"dogplot\"]\n\n\ndef palplot(pal, size=1):\n \"\"\"Plot the values in a color palette as a horizontal array.\n\n Parameters\n ----------\n pal : sequence of matplotlib colors\n colors, i.e. as returned by seaborn.color_palette()\n size :\n scaling factor for size of plot\n\n \"\"\"\n n = len(pal)\n f, ax = plt.subplots(1, 1, figsize=(n * size, size))\n ax.imshow(np.arange(n).reshape(1, n),\n cmap=mpl.colors.ListedColormap(list(pal)),\n interpolation=\"nearest\", aspect=\"auto\")\n ax.set_xticks(np.arange(n) - .5)\n ax.set_yticks([-.5, .5])\n # Ensure nice border between colors\n ax.set_xticklabels([\"\" for _ in range(n)])\n # The proper way to set no ticks\n ax.yaxis.set_major_locator(ticker.NullLocator())\n\n\ndef dogplot(*_, **__):\n \"\"\"Who's a good boy?\"\"\"\n try:\n from urllib.request import urlopen\n except ImportError:\n from urllib2 import urlopen\n from io import BytesIO\n\n url = \"https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png\"\n pic = np.random.randint(2, 7)\n data = BytesIO(urlopen(url.format(pic)).read())\n img = plt.imread(data)\n f, ax = plt.subplots(figsize=(5, 5), dpi=100)\n f.subplots_adjust(0, 0, 1, 1)\n ax.imshow(img)\n ax.set_axis_off()\n"},{"attributeType":"null","col":4,"comment":"null","endLoc":66,"id":1850,"name":"rs","nodeType":"Attribute","startLoc":66,"text":"rs"},{"col":4,"comment":"null","endLoc":336,"header":"@pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim_wrapped(self, dim)","id":1851,"name":"test_single_facet_dim_wrapped","nodeType":"Function","startLoc":307,"text":"@pytest.mark.parametrize(\"dim\", [\"col\", \"row\"])\n def test_single_facet_dim_wrapped(self, dim):\n\n key = \"b\"\n order = list(\"abc\")\n wrap = len(order) - 1\n spec = {\"variables\": {dim: key}, \"structure\": {dim: order}, \"wrap\": wrap}\n s = Subplots({}, spec, {})\n s.init_figure(spec, {})\n\n assert len(s) == len(order)\n\n for i, e in enumerate(s):\n assert e[dim] == order[i]\n for axis in \"xy\":\n assert e[axis] == axis\n\n sides = {\n \"col\": [\"top\", \"bottom\", \"left\", \"right\"],\n \"row\": [\"left\", \"right\", \"top\", \"bottom\"],\n }\n tests = (\n i < wrap,\n i >= wrap or i >= len(s) % wrap,\n i % wrap == 0,\n i % wrap == wrap - 1 or i + 1 == len(s),\n )\n\n for side, expected in zip(sides[dim], tests):\n assert e[side] == expected"},{"col":0,"comment":"Plot the values in a color palette as a horizontal array.\n\n Parameters\n ----------\n pal : sequence of matplotlib colors\n colors, i.e. as returned by seaborn.color_palette()\n size :\n scaling factor for size of plot\n\n ","endLoc":30,"header":"def palplot(pal, size=1)","id":1852,"name":"palplot","nodeType":"Function","startLoc":9,"text":"def palplot(pal, size=1):\n \"\"\"Plot the values in a color palette as a horizontal array.\n\n Parameters\n ----------\n pal : sequence of matplotlib colors\n colors, i.e. as returned by seaborn.color_palette()\n size :\n scaling factor for size of plot\n\n \"\"\"\n n = len(pal)\n f, ax = plt.subplots(1, 1, figsize=(n * size, size))\n ax.imshow(np.arange(n).reshape(1, n),\n cmap=mpl.colors.ListedColormap(list(pal)),\n interpolation=\"nearest\", aspect=\"auto\")\n ax.set_xticks(np.arange(n) - .5)\n ax.set_yticks([-.5, .5])\n # Ensure nice border between colors\n ax.set_xticklabels([\"\" for _ in range(n)])\n # The proper way to set no ticks\n ax.yaxis.set_major_locator(ticker.NullLocator())"},{"col":0,"comment":"null","endLoc":92,"header":"def write_thumbnail(svg_path, page)","id":1853,"name":"write_thumbnail","nodeType":"Function","startLoc":79,"text":"def write_thumbnail(svg_path, page):\n\n with (\n sns.axes_style(\"dark\"),\n sns.plotting_context(\"notebook\"),\n sns.color_palette(\"deep\")\n ):\n fig = globals()[page]()\n for ax in fig.axes:\n ax.set(xticklabels=[], yticklabels=[], xlabel=\"\", ylabel=\"\", title=\"\")\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n fig.tight_layout()\n fig.savefig(svg_path, format=\"svg\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":67,"id":1854,"name":"x","nodeType":"Attribute","startLoc":67,"text":"x"},{"attributeType":"null","col":8,"comment":"null","endLoc":370,"id":1855,"name":"seed","nodeType":"Attribute","startLoc":370,"text":"self.seed"},{"col":4,"comment":"\n Specify a layer of the visualization in terms of mark and data transform(s).\n\n This is the main method for specifying how the data should be visualized.\n It can be called multiple times with different arguments to define\n a plot with multiple layers.\n\n Parameters\n ----------\n mark : :class:`Mark`\n The visual representation of the data to use in this layer.\n transforms : :class:`Stat` or :class:`Move`\n Objects representing transforms to be applied before plotting the data.\n Currently, at most one :class:`Stat` can be used, and it\n must be passed first. This constraint will be relaxed in the future.\n orient : \"x\", \"y\", \"v\", or \"h\"\n The orientation of the mark, which also affects how transforms are computed.\n Typically corresponds to the axis that defines groups for aggregation.\n The \"v\" (vertical) and \"h\" (horizontal) options are synonyms for \"x\" / \"y\",\n but may be more intuitive with some marks. When not provided, an\n orientation will be inferred from characteristics of the data and scales.\n legend : bool\n Option to suppress the mark/mappings for this layer from the legend.\n data : DataFrame or dict\n Data source to override the global source provided in the constructor.\n variables : data vectors or identifiers\n Additional layer-specific variables, including variables that will be\n passed directly to the transforms without scaling.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.add.rst\n\n ","endLoc":476,"header":"def add(\n self,\n mark: Mark,\n *transforms: Stat | Mark,\n orient: str | None = None,\n legend: bool = True,\n data: DataSource = None,\n **variables: VariableSpec,\n ) -> Plot","id":1856,"name":"add","nodeType":"Function","startLoc":389,"text":"def add(\n self,\n mark: Mark,\n *transforms: Stat | Mark,\n orient: str | None = None,\n legend: bool = True,\n data: DataSource = None,\n **variables: VariableSpec,\n ) -> Plot:\n \"\"\"\n Specify a layer of the visualization in terms of mark and data transform(s).\n\n This is the main method for specifying how the data should be visualized.\n It can be called multiple times with different arguments to define\n a plot with multiple layers.\n\n Parameters\n ----------\n mark : :class:`Mark`\n The visual representation of the data to use in this layer.\n transforms : :class:`Stat` or :class:`Move`\n Objects representing transforms to be applied before plotting the data.\n Currently, at most one :class:`Stat` can be used, and it\n must be passed first. This constraint will be relaxed in the future.\n orient : \"x\", \"y\", \"v\", or \"h\"\n The orientation of the mark, which also affects how transforms are computed.\n Typically corresponds to the axis that defines groups for aggregation.\n The \"v\" (vertical) and \"h\" (horizontal) options are synonyms for \"x\" / \"y\",\n but may be more intuitive with some marks. When not provided, an\n orientation will be inferred from characteristics of the data and scales.\n legend : bool\n Option to suppress the mark/mappings for this layer from the legend.\n data : DataFrame or dict\n Data source to override the global source provided in the constructor.\n variables : data vectors or identifiers\n Additional layer-specific variables, including variables that will be\n passed directly to the transforms without scaling.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.add.rst\n\n \"\"\"\n if not isinstance(mark, Mark):\n msg = f\"mark must be a Mark instance, not {type(mark)!r}.\"\n raise TypeError(msg)\n\n # TODO This API for transforms was a late decision, and previously Plot.add\n # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances.\n # It will take some work to refactor the internals so that Stat and Move are\n # treated identically, and until then well need to \"unpack\" the transforms\n # here and enforce limitations on the order / types.\n\n stat: Optional[Stat]\n move: Optional[List[Move]]\n error = False\n if not transforms:\n stat, move = None, None\n elif isinstance(transforms[0], Stat):\n stat = transforms[0]\n move = [m for m in transforms[1:] if isinstance(m, Move)]\n error = len(move) != len(transforms) - 1\n else:\n stat = None\n move = [m for m in transforms if isinstance(m, Move)]\n error = len(move) != len(transforms)\n\n if error:\n msg = \" \".join([\n \"Transforms must have at most one Stat type (in the first position),\",\n \"and all others must be a Move type. Given transform type(s):\",\n \", \".join(str(type(t).__name__) for t in transforms) + \".\"\n ])\n raise TypeError(msg)\n\n new = self._clone()\n new._layers.append({\n \"mark\": mark,\n \"stat\": stat,\n \"move\": move,\n # TODO it doesn't work to supply scalars to variables, but it should\n \"vars\": variables,\n \"source\": data,\n \"legend\": legend,\n \"orient\": {\"v\": \"x\", \"h\": \"y\"}.get(orient, orient), # type: ignore\n })\n\n return new"},{"className":"SharedAxesLevelTests","col":0,"comment":"null","endLoc":158,"id":1857,"nodeType":"Class","startLoc":143,"text":"class SharedAxesLevelTests:\n\n def test_color(self, long_df, **kwargs):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C0\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C1\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", color=\"C2\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C2\", check_alpha=False)"},{"col":4,"comment":"null","endLoc":158,"header":"def test_color(self, long_df, **kwargs)","id":1858,"name":"test_color","nodeType":"Function","startLoc":145,"text":"def test_color(self, long_df, **kwargs):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C0\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n self.func(data=long_df, x=\"y\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C1\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", color=\"C2\", ax=ax, **kwargs)\n assert_colors_equal(self.get_last_color(ax, **kwargs), \"C2\", check_alpha=False)"},{"attributeType":"str","col":8,"comment":"null","endLoc":372,"id":1859,"name":"orient","nodeType":"Attribute","startLoc":372,"text":"self.orient"},{"attributeType":"null","col":8,"comment":"null","endLoc":373,"id":1860,"name":"err_style","nodeType":"Attribute","startLoc":373,"text":"self.err_style"},{"attributeType":"null","col":8,"comment":"null","endLoc":376,"id":1861,"name":"legend","nodeType":"Attribute","startLoc":376,"text":"self.legend"},{"attributeType":"bool","col":8,"comment":"null","endLoc":371,"id":1862,"name":"sort","nodeType":"Attribute","startLoc":371,"text":"self.sort"},{"attributeType":"null","col":8,"comment":"null","endLoc":368,"id":1863,"name":"errorbar","nodeType":"Attribute","startLoc":368,"text":"self.errorbar"},{"className":"TestRugPlot","col":0,"comment":"null","endLoc":342,"id":1864,"nodeType":"Class","startLoc":161,"text":"class TestRugPlot(SharedAxesLevelTests):\n\n func = staticmethod(rugplot)\n\n def get_last_color(self, ax, **kwargs):\n\n return ax.collections[-1].get_color()\n\n def assert_rug_equal(self, a, b):\n\n assert_array_equal(a.get_segments(), b.get_segments())\n\n @pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_data(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, np.asarray(vector), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n rugplot(data=long_df, **{variable: vector})\n\n for a, b in itertools.product(ax.collections, ax.collections):\n self.assert_rug_equal(a, b)\n\n def test_bivariate_data(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n rugplot(data=long_df, x=\"x\", y=\"y\", ax=ax1)\n rugplot(data=long_df, x=\"x\", ax=ax2)\n rugplot(data=long_df, y=\"y\", ax=ax2)\n\n self.assert_rug_equal(ax1.collections[0], ax2.collections[0])\n self.assert_rug_equal(ax1.collections[1], ax2.collections[1])\n\n def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n rugplot(data=wide_df, ax=ax1)\n for col in wide_df:\n rugplot(data=wide_df, x=col, ax=ax2)\n\n wide_segments = np.sort(\n np.array(ax1.collections[0].get_segments())\n )\n long_segments = np.sort(\n np.concatenate([c.get_segments() for c in ax2.collections])\n )\n\n assert_array_equal(wide_segments, long_segments)\n\n def test_flat_vector(self, long_df):\n\n f, ax = plt.subplots()\n rugplot(data=long_df[\"x\"])\n rugplot(x=long_df[\"x\"])\n self.assert_rug_equal(*ax.collections)\n\n def test_datetime_data(self, long_df):\n\n ax = rugplot(data=long_df[\"t\"])\n vals = np.stack(ax.collections[0].get_segments())[:, 0, 0]\n assert_array_equal(vals, mpl.dates.date2num(long_df[\"t\"]))\n\n def test_empty_data(self):\n\n ax = rugplot(x=[])\n assert not ax.collections\n\n def test_a_deprecation(self, flat_series):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(a=flat_series)\n rugplot(x=flat_series)\n\n self.assert_rug_equal(*ax.collections)\n\n @pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_axis_deprecation(self, flat_series, variable):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(flat_series, axis=variable)\n rugplot(**{variable: flat_series})\n\n self.assert_rug_equal(*ax.collections)\n\n def test_vertical_deprecation(self, flat_series):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(flat_series, vertical=True)\n rugplot(y=flat_series)\n\n self.assert_rug_equal(*ax.collections)\n\n def test_rug_data(self, flat_array):\n\n height = .05\n ax = rugplot(x=flat_array, height=height)\n segments = np.stack(ax.collections[0].get_segments())\n\n n = flat_array.size\n assert_array_equal(segments[:, 0, 1], np.zeros(n))\n assert_array_equal(segments[:, 1, 1], np.full(n, height))\n assert_array_equal(segments[:, 1, 0], flat_array)\n\n def test_rug_colors(self, long_df):\n\n ax = rugplot(data=long_df, x=\"x\", hue=\"a\")\n\n order = categorical_order(long_df[\"a\"])\n palette = color_palette()\n\n expected_colors = np.ones((len(long_df), 4))\n for i, val in enumerate(long_df[\"a\"]):\n expected_colors[i, :3] = palette[order.index(val)]\n\n assert_array_equal(ax.collections[0].get_color(), expected_colors)\n\n def test_expand_margins(self, flat_array):\n\n f, ax = plt.subplots()\n x1, y1 = ax.margins()\n rugplot(x=flat_array, expand_margins=False)\n x2, y2 = ax.margins()\n assert x1 == x2\n assert y1 == y2\n\n f, ax = plt.subplots()\n x1, y1 = ax.margins()\n height = .05\n rugplot(x=flat_array, height=height)\n x2, y2 = ax.margins()\n assert x1 == x2\n assert y1 + height * 2 == pytest.approx(y2)\n\n def test_multiple_rugs(self):\n\n values = np.linspace(start=0, stop=1, num=5)\n ax = rugplot(x=values)\n ylim = ax.get_ylim()\n\n rugplot(x=values, ax=ax, expand_margins=False)\n\n assert ylim == ax.get_ylim()\n\n def test_matplotlib_kwargs(self, flat_series):\n\n lw = 2\n alpha = .2\n ax = rugplot(y=flat_series, linewidth=lw, alpha=alpha)\n rug = ax.collections[0]\n assert np.all(rug.get_alpha() == alpha)\n assert np.all(rug.get_linewidth() == lw)\n\n def test_axis_labels(self, flat_series):\n\n ax = rugplot(x=flat_series)\n assert ax.get_xlabel() == flat_series.name\n assert not ax.get_ylabel()\n\n def test_log_scale(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n\n ax2.set_xscale(\"log\")\n\n rugplot(data=long_df, x=\"z\", ax=ax1)\n rugplot(data=long_df, x=\"z\", ax=ax2)\n\n rug1 = np.stack(ax1.collections[0].get_segments())\n rug2 = np.stack(ax2.collections[0].get_segments())\n\n assert_array_almost_equal(rug1, rug2)"},{"col":4,"comment":"null","endLoc":167,"header":"def get_last_color(self, ax, **kwargs)","id":1865,"name":"get_last_color","nodeType":"Function","startLoc":165,"text":"def get_last_color(self, ax, **kwargs):\n\n return ax.collections[-1].get_color()"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":374,"id":1866,"name":"err_kws","nodeType":"Attribute","startLoc":374,"text":"self.err_kws"},{"attributeType":"null","col":8,"comment":"null","endLoc":369,"id":1867,"name":"n_boot","nodeType":"Attribute","startLoc":369,"text":"self.n_boot"},{"col":4,"comment":"null","endLoc":171,"header":"def assert_rug_equal(self, a, b)","id":1868,"name":"assert_rug_equal","nodeType":"Function","startLoc":169,"text":"def assert_rug_equal(self, a, b):\n\n assert_array_equal(a.get_segments(), b.get_segments())"},{"col":4,"comment":"null","endLoc":186,"header":"@pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_data(self, long_df, variable)","id":1869,"name":"test_long_data","nodeType":"Function","startLoc":173,"text":"@pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_data(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, np.asarray(vector), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n rugplot(data=long_df, **{variable: vector})\n\n for a, b in itertools.product(ax.collections, ax.collections):\n self.assert_rug_equal(a, b)"},{"attributeType":"null","col":8,"comment":"null","endLoc":361,"id":1870,"name":"_default_size_range","nodeType":"Attribute","startLoc":361,"text":"self._default_size_range"},{"col":0,"comment":"null","endLoc":757,"header":"def scatterplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=True, style_order=None, legend=\"auto\", ax=None,\n **kwargs\n)","id":1871,"name":"scatterplot","nodeType":"Function","startLoc":726,"text":"def scatterplot(\n data=None, *,\n x=None, y=None, hue=None, size=None, style=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=True, style_order=None, legend=\"auto\", ax=None,\n **kwargs\n):\n\n variables = _ScatterPlotter.get_semantics(locals())\n p = _ScatterPlotter(data=data, variables=variables, legend=legend)\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, order=style_order)\n\n if ax is None:\n ax = plt.gca()\n\n if not p.has_xy_data:\n return ax\n\n p._attach(ax)\n\n # Other functions have color as an explicit param,\n # and we should probably do that here too\n color = kwargs.pop(\"color\", None)\n kwargs[\"color\"] = _default_color(ax.scatter, hue, color, kwargs)\n\n p.plot(ax, kwargs)\n\n return ax"},{"col":4,"comment":"null","endLoc":786,"header":"def test_pivot_input(self)","id":1872,"name":"test_pivot_input","nodeType":"Function","startLoc":776,"text":"def test_pivot_input(self):\n df_norm = self.df_norm.copy()\n df_norm.index.name = 'numbers'\n df_long = pd.melt(df_norm.reset_index(), var_name='letters',\n id_vars='numbers')\n kws = self.default_kws.copy()\n kws['pivot_kws'] = dict(index='numbers', columns='letters',\n values='value')\n cg = mat.ClusterGrid(df_long, **kws)\n\n pdt.assert_frame_equal(cg.data2d, df_norm)"},{"col":4,"comment":"\n Produce subplots by pairing multiple `x` and/or `y` variables.\n\n Parameters\n ----------\n x, y : sequence(s) of data vectors or identifiers\n Variables that will define the grid of subplots.\n wrap : int\n When using only `x` or `y`, \"wrap\" subplots across a two-dimensional grid\n with this many columns (when using `x`) or rows (when using `y`).\n cross : bool\n When False, zip the `x` and `y` lists such that the first subplot gets the\n first pair, the second gets the second pair, etc. Otherwise, create a\n two-dimensional grid from the cartesian product of the lists.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.pair.rst\n\n ","endLoc":539,"header":"def pair(\n self,\n x: VariableSpecList = None,\n y: VariableSpecList = None,\n wrap: int | None = None,\n cross: bool = True,\n ) -> Plot","id":1873,"name":"pair","nodeType":"Function","startLoc":478,"text":"def pair(\n self,\n x: VariableSpecList = None,\n y: VariableSpecList = None,\n wrap: int | None = None,\n cross: bool = True,\n ) -> Plot:\n \"\"\"\n Produce subplots by pairing multiple `x` and/or `y` variables.\n\n Parameters\n ----------\n x, y : sequence(s) of data vectors or identifiers\n Variables that will define the grid of subplots.\n wrap : int\n When using only `x` or `y`, \"wrap\" subplots across a two-dimensional grid\n with this many columns (when using `x`) or rows (when using `y`).\n cross : bool\n When False, zip the `x` and `y` lists such that the first subplot gets the\n first pair, the second gets the second pair, etc. Otherwise, create a\n two-dimensional grid from the cartesian product of the lists.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.pair.rst\n\n \"\"\"\n # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows\n # This may also be possible by setting `wrap=1`, but is that too unobvious?\n # TODO PairGrid features not currently implemented: diagonals, corner\n\n pair_spec: PairSpec = {}\n\n axes = {\"x\": [] if x is None else x, \"y\": [] if y is None else y}\n for axis, arg in axes.items():\n if isinstance(arg, (str, int)):\n err = f\"You must pass a sequence of variable keys to `{axis}`\"\n raise TypeError(err)\n\n pair_spec[\"variables\"] = {}\n pair_spec[\"structure\"] = {}\n\n for axis in \"xy\":\n keys = []\n for i, col in enumerate(axes[axis]):\n key = f\"{axis}{i}\"\n keys.append(key)\n pair_spec[\"variables\"][key] = col\n\n if keys:\n pair_spec[\"structure\"][axis] = keys\n\n if not cross and len(axes[\"x\"]) != len(axes[\"y\"]):\n err = \"Lengths of the `x` and `y` lists must match with cross=False\"\n raise ValueError(err)\n\n pair_spec[\"cross\"] = cross\n pair_spec[\"wrap\"] = wrap\n\n new = self._clone()\n new._pair_spec.update(pair_spec)\n return new"},{"className":"Helpers","col":0,"comment":"null","endLoc":66,"id":1874,"nodeType":"Class","startLoc":48,"text":"class Helpers:\n\n # TODO Better place for these?\n\n def scatter_rgbs(self, collections):\n rgbs = []\n for col in collections:\n rgb = tuple(col.get_facecolor().squeeze()[:3])\n rgbs.append(rgb)\n return rgbs\n\n def paths_equal(self, *args):\n\n equal = all([len(a) == len(args[0]) for a in args])\n\n for p1, p2 in zip(*args):\n equal &= np.array_equal(p1.vertices, p2.vertices)\n equal &= np.array_equal(p1.codes, p2.codes)\n return equal"},{"col":4,"comment":"null","endLoc":57,"header":"def scatter_rgbs(self, collections)","id":1875,"name":"scatter_rgbs","nodeType":"Function","startLoc":52,"text":"def scatter_rgbs(self, collections):\n rgbs = []\n for col in collections:\n rgb = tuple(col.get_facecolor().squeeze()[:3])\n rgbs.append(rgb)\n return rgbs"},{"col":4,"comment":"null","endLoc":798,"header":"def test_colors_input(self)","id":1876,"name":"test_colors_input","nodeType":"Function","startLoc":788,"text":"def test_colors_input(self):\n kws = self.default_kws.copy()\n\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, self.row_colors)\n npt.assert_array_equal(cg.col_colors, self.col_colors)\n\n assert len(cg.fig.axes) == 6"},{"col":4,"comment":"null","endLoc":818,"header":"def test_categorical_colors_input(self)","id":1877,"name":"test_categorical_colors_input","nodeType":"Function","startLoc":800,"text":"def test_categorical_colors_input(self):\n kws = self.default_kws.copy()\n\n row_colors = pd.Series(self.row_colors, dtype=\"category\")\n col_colors = pd.Series(\n self.col_colors, dtype=\"category\", index=self.df_norm.columns\n )\n\n kws['row_colors'] = row_colors\n kws['col_colors'] = col_colors\n\n exp_row_colors = list(map(mpl.colors.to_rgb, row_colors))\n exp_col_colors = list(map(mpl.colors.to_rgb, col_colors))\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, exp_row_colors)\n npt.assert_array_equal(cg.col_colors, exp_col_colors)\n\n assert len(cg.fig.axes) == 6"},{"col":4,"comment":"null","endLoc":66,"header":"def paths_equal(self, *args)","id":1878,"name":"paths_equal","nodeType":"Function","startLoc":59,"text":"def paths_equal(self, *args):\n\n equal = all([len(a) == len(args[0]) for a in args])\n\n for p1, p2 in zip(*args):\n equal &= np.array_equal(p1.vertices, p2.vertices)\n equal &= np.array_equal(p1.codes, p2.codes)\n return equal"},{"attributeType":"list | dict","col":8,"comment":"null","endLoc":47,"id":1879,"name":"order","nodeType":"Attribute","startLoc":47,"text":"self.order"},{"col":4,"comment":"\n Produce subplots with conditional subsets of the data.\n\n Parameters\n ----------\n col, row : data vectors or identifiers\n Variables used to define subsets along the columns and/or rows of the grid.\n Can be references to the global data source passed in the constructor.\n order : list of strings, or dict with dimensional keys\n Define the order of the faceting variables.\n wrap : int\n When using only `col` or `row`, wrap subplots across a two-dimensional\n grid with this many subplots on the faceting dimension.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.facet.rst\n\n ","endLoc":600,"header":"def facet(\n self,\n col: VariableSpec = None,\n row: VariableSpec = None,\n order: OrderSpec | dict[str, OrderSpec] = None,\n wrap: int | None = None,\n ) -> Plot","id":1880,"name":"facet","nodeType":"Function","startLoc":541,"text":"def facet(\n self,\n col: VariableSpec = None,\n row: VariableSpec = None,\n order: OrderSpec | dict[str, OrderSpec] = None,\n wrap: int | None = None,\n ) -> Plot:\n \"\"\"\n Produce subplots with conditional subsets of the data.\n\n Parameters\n ----------\n col, row : data vectors or identifiers\n Variables used to define subsets along the columns and/or rows of the grid.\n Can be references to the global data source passed in the constructor.\n order : list of strings, or dict with dimensional keys\n Define the order of the faceting variables.\n wrap : int\n When using only `col` or `row`, wrap subplots across a two-dimensional\n grid with this many subplots on the faceting dimension.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.facet.rst\n\n \"\"\"\n variables: dict[str, VariableSpec] = {}\n if col is not None:\n variables[\"col\"] = col\n if row is not None:\n variables[\"row\"] = row\n\n structure = {}\n if isinstance(order, dict):\n for dim in [\"col\", \"row\"]:\n dim_order = order.get(dim)\n if dim_order is not None:\n structure[dim] = list(dim_order)\n elif order is not None:\n if col is not None and row is not None:\n err = \" \".join([\n \"When faceting on both col= and row=, passing `order` as a list\"\n \"is ambiguous. Use a dict with 'col' and/or 'row' keys instead.\"\n ])\n raise RuntimeError(err)\n elif col is not None:\n structure[\"col\"] = list(order)\n elif row is not None:\n structure[\"row\"] = list(order)\n\n spec: FacetSpec = {\n \"variables\": variables,\n \"structure\": structure,\n \"wrap\": wrap,\n }\n\n new = self._clone()\n new._facet_spec.update(spec)\n\n return new"},{"className":"PolyFit","col":0,"comment":"\n Fit a polynomial of the given order and resample data onto predicted curve.\n ","endLoc":44,"id":1881,"nodeType":"Class","startLoc":10,"text":"@dataclass\nclass PolyFit(Stat):\n \"\"\"\n Fit a polynomial of the given order and resample data onto predicted curve.\n \"\"\"\n # This is a provisional class that is useful for building out functionality.\n # It may or may not change substantially in form or dissappear as we think\n # through the organization of the stats subpackage.\n\n order: int = 2\n gridsize: int = 100\n\n def _fit_predict(self, data):\n\n x = data[\"x\"]\n y = data[\"y\"]\n if x.nunique() <= self.order:\n # TODO warn?\n xx = yy = []\n else:\n p = np.polyfit(x, y, self.order)\n xx = np.linspace(x.min(), x.max(), self.gridsize)\n yy = np.polyval(p, xx)\n\n return pd.DataFrame(dict(x=xx, y=yy))\n\n # TODO we should have a way of identifying the method that will be applied\n # and then only define __call__ on a base-class of stats with this pattern\n\n def __call__(self, data, groupby, orient, scales):\n\n return (\n groupby\n .apply(data.dropna(subset=[\"x\", \"y\"]), self._fit_predict)\n )"},{"col":4,"comment":"null","endLoc":197,"header":"def test_bivariate_data(self, long_df)","id":1882,"name":"test_bivariate_data","nodeType":"Function","startLoc":188,"text":"def test_bivariate_data(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n rugplot(data=long_df, x=\"x\", y=\"y\", ax=ax1)\n rugplot(data=long_df, x=\"x\", ax=ax2)\n rugplot(data=long_df, y=\"y\", ax=ax2)\n\n self.assert_rug_equal(ax1.collections[0], ax2.collections[0])\n self.assert_rug_equal(ax1.collections[1], ax2.collections[1])"},{"col":4,"comment":"null","endLoc":213,"header":"def test_wide_vs_long_data(self, wide_df)","id":1883,"name":"test_wide_vs_long_data","nodeType":"Function","startLoc":199,"text":"def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n rugplot(data=wide_df, ax=ax1)\n for col in wide_df:\n rugplot(data=wide_df, x=col, ax=ax2)\n\n wide_segments = np.sort(\n np.array(ax1.collections[0].get_segments())\n )\n long_segments = np.sort(\n np.concatenate([c.get_segments() for c in ax2.collections])\n )\n\n assert_array_equal(wide_segments, long_segments)"},{"className":"Stat","col":0,"comment":"Base class for objects that apply statistical transformations.","endLoc":52,"id":1884,"nodeType":"Class","startLoc":14,"text":"@dataclass\nclass Stat:\n \"\"\"Base class for objects that apply statistical transformations.\"\"\"\n\n # The class supports a partial-function application pattern. The object is\n # initialized with desired parameters and the result is a callable that\n # accepts and returns dataframes.\n\n # The statistical transformation logic should not add any state to the instance\n # beyond what is defined with the initialization parameters.\n\n # Subclasses can declare whether the orient dimension should be used in grouping\n # TODO consider whether this should be a parameter. Motivating example:\n # use the same KDE class violin plots and univariate density estimation.\n # In the former case, we would expect separate densities for each unique\n # value on the orient axis, but we would not in the latter case.\n group_by_orient: ClassVar[bool] = False\n\n def _check_param_one_of(self, param: Any, options: Iterable[Any]) -> None:\n \"\"\"Raise when parameter value is not one of a specified set.\"\"\"\n value = getattr(self, param)\n if value not in options:\n *most, last = options\n option_str = \", \".join(f\"{x!r}\" for x in most[:-1]) + f\" or {last!r}\"\n err = \" \".join([\n f\"The `{param}` parameter for `{self.__class__.__name__}` must be\",\n f\"one of {option_str}; not {value!r}.\",\n ])\n raise ValueError(err)\n\n def __call__(\n self,\n data: DataFrame,\n groupby: GroupBy,\n orient: str,\n scales: dict[str, Scale],\n ) -> DataFrame:\n \"\"\"Apply statistical transform to data subgroups and return combined result.\"\"\"\n return data"},{"col":4,"comment":"Raise when parameter value is not one of a specified set.","endLoc":42,"header":"def _check_param_one_of(self, param: Any, options: Iterable[Any]) -> None","id":1885,"name":"_check_param_one_of","nodeType":"Function","startLoc":32,"text":"def _check_param_one_of(self, param: Any, options: Iterable[Any]) -> None:\n \"\"\"Raise when parameter value is not one of a specified set.\"\"\"\n value = getattr(self, param)\n if value not in options:\n *most, last = options\n option_str = \", \".join(f\"{x!r}\" for x in most[:-1]) + f\" or {last!r}\"\n err = \" \".join([\n f\"The `{param}` parameter for `{self.__class__.__name__}` must be\",\n f\"one of {option_str}; not {value!r}.\",\n ])\n raise ValueError(err)"},{"col":4,"comment":"null","endLoc":220,"header":"def test_flat_vector(self, long_df)","id":1886,"name":"test_flat_vector","nodeType":"Function","startLoc":215,"text":"def test_flat_vector(self, long_df):\n\n f, ax = plt.subplots()\n rugplot(data=long_df[\"x\"])\n rugplot(x=long_df[\"x\"])\n self.assert_rug_equal(*ax.collections)"},{"col":4,"comment":"null","endLoc":226,"header":"def test_datetime_data(self, long_df)","id":1887,"name":"test_datetime_data","nodeType":"Function","startLoc":222,"text":"def test_datetime_data(self, long_df):\n\n ax = rugplot(data=long_df[\"t\"])\n vals = np.stack(ax.collections[0].get_segments())[:, 0, 0]\n assert_array_equal(vals, mpl.dates.date2num(long_df[\"t\"]))"},{"col":0,"comment":"Who's a good boy?","endLoc":48,"header":"def dogplot(*_, **__)","id":1888,"name":"dogplot","nodeType":"Function","startLoc":33,"text":"def dogplot(*_, **__):\n \"\"\"Who's a good boy?\"\"\"\n try:\n from urllib.request import urlopen\n except ImportError:\n from urllib2 import urlopen\n from io import BytesIO\n\n url = \"https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png\"\n pic = np.random.randint(2, 7)\n data = BytesIO(urlopen(url.format(pic)).read())\n img = plt.imread(data)\n f, ax = plt.subplots(figsize=(5, 5), dpi=100)\n f.subplots_adjust(0, 0, 1, 1)\n ax.imshow(img)\n ax.set_axis_off()"},{"col":4,"comment":"null","endLoc":231,"header":"def test_empty_data(self)","id":1889,"name":"test_empty_data","nodeType":"Function","startLoc":228,"text":"def test_empty_data(self):\n\n ax = rugplot(x=[])\n assert not ax.collections"},{"col":4,"comment":"null","endLoc":241,"header":"def test_a_deprecation(self, flat_series)","id":1890,"name":"test_a_deprecation","nodeType":"Function","startLoc":233,"text":"def test_a_deprecation(self, flat_series):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(a=flat_series)\n rugplot(x=flat_series)\n\n self.assert_rug_equal(*ax.collections)"},{"col":4,"comment":"null","endLoc":252,"header":"@pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_axis_deprecation(self, flat_series, variable)","id":1891,"name":"test_axis_deprecation","nodeType":"Function","startLoc":243,"text":"@pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_axis_deprecation(self, flat_series, variable):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(flat_series, axis=variable)\n rugplot(**{variable: flat_series})\n\n self.assert_rug_equal(*ax.collections)"},{"col":4,"comment":"null","endLoc":262,"header":"def test_vertical_deprecation(self, flat_series)","id":1892,"name":"test_vertical_deprecation","nodeType":"Function","startLoc":254,"text":"def test_vertical_deprecation(self, flat_series):\n\n f, ax = plt.subplots()\n\n with pytest.warns(UserWarning):\n rugplot(flat_series, vertical=True)\n rugplot(y=flat_series)\n\n self.assert_rug_equal(*ax.collections)"},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":1893,"name":"__all__","nodeType":"Attribute","startLoc":22,"text":"__all__"},{"attributeType":"DocstringComponents","col":0,"comment":"null","endLoc":25,"id":1894,"name":"_relational_narrative","nodeType":"Attribute","startLoc":25,"text":"_relational_narrative"},{"col":4,"comment":"null","endLoc":273,"header":"def test_rug_data(self, flat_array)","id":1895,"name":"test_rug_data","nodeType":"Function","startLoc":264,"text":"def test_rug_data(self, flat_array):\n\n height = .05\n ax = rugplot(x=flat_array, height=height)\n segments = np.stack(ax.collections[0].get_segments())\n\n n = flat_array.size\n assert_array_equal(segments[:, 0, 1], np.zeros(n))\n assert_array_equal(segments[:, 1, 1], np.full(n, height))\n assert_array_equal(segments[:, 1, 0], flat_array)"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":52,"id":1896,"name":"_relational_docs","nodeType":"Attribute","startLoc":52,"text":"_relational_docs"},{"col":4,"comment":"null","endLoc":286,"header":"def test_rug_colors(self, long_df)","id":1897,"name":"test_rug_colors","nodeType":"Function","startLoc":275,"text":"def test_rug_colors(self, long_df):\n\n ax = rugplot(data=long_df, x=\"x\", hue=\"a\")\n\n order = categorical_order(long_df[\"a\"])\n palette = color_palette()\n\n expected_colors = np.ones((len(long_df), 4))\n for i, val in enumerate(long_df[\"a\"]):\n expected_colors[i, :3] = palette[order.index(val)]\n\n assert_array_equal(ax.collections[0].get_color(), expected_colors)"},{"col":4,"comment":"null","endLoc":832,"header":"def test_nested_colors_input(self)","id":1898,"name":"test_nested_colors_input","nodeType":"Function","startLoc":820,"text":"def test_nested_colors_input(self):\n kws = self.default_kws.copy()\n\n row_colors = [self.row_colors, self.row_colors]\n col_colors = [self.col_colors, self.col_colors]\n kws['row_colors'] = row_colors\n kws['col_colors'] = col_colors\n\n cm = mat.ClusterGrid(self.df_norm, **kws)\n npt.assert_array_equal(cm.row_colors, row_colors)\n npt.assert_array_equal(cm.col_colors, col_colors)\n\n assert len(cm.fig.axes) == 6"},{"col":4,"comment":"Apply statistical transform to data subgroups and return combined result.","endLoc":52,"header":"def __call__(\n self,\n data: DataFrame,\n groupby: GroupBy,\n orient: str,\n scales: dict[str, Scale],\n ) -> DataFrame","id":1899,"name":"__call__","nodeType":"Function","startLoc":44,"text":"def __call__(\n self,\n data: DataFrame,\n groupby: GroupBy,\n orient: str,\n scales: dict[str, Scale],\n ) -> DataFrame:\n \"\"\"Apply statistical transform to data subgroups and return combined result.\"\"\"\n return data"},{"attributeType":"bool","col":4,"comment":"null","endLoc":30,"id":1900,"name":"group_by_orient","nodeType":"Attribute","startLoc":30,"text":"group_by_orient"},{"attributeType":"null","col":0,"comment":"null","endLoc":176,"id":1901,"name":"_param_docs","nodeType":"Attribute","startLoc":176,"text":"_param_docs"},{"col":4,"comment":"null","endLoc":845,"header":"def test_colors_input_custom_cmap(self)","id":1902,"name":"test_colors_input_custom_cmap","nodeType":"Function","startLoc":834,"text":"def test_colors_input_custom_cmap(self):\n kws = self.default_kws.copy()\n\n kws['cmap'] = mpl.cm.PRGn\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cg = mat.clustermap(self.df_norm, **kws)\n npt.assert_array_equal(cg.row_colors, self.row_colors)\n npt.assert_array_equal(cg.col_colors, self.col_colors)\n\n assert len(cg.fig.axes) == 6"},{"col":0,"comment":"","endLoc":1,"header":"relational.py#","id":1903,"name":"","nodeType":"Function","startLoc":1,"text":"__all__ = [\"relplot\", \"scatterplot\", \"lineplot\"]\n\n_relational_narrative = DocstringComponents(dict(\n\n # --- Introductory prose\n main_api=\"\"\"\nThe relationship between `x` and `y` can be shown for different subsets\nof the data using the `hue`, `size`, and `style` parameters. These\nparameters control what visual semantics are used to identify the different\nsubsets. It is possible to show up to three dimensions independently by\nusing all three semantic types, but this style of plot can be hard to\ninterpret and is often ineffective. Using redundant semantics (i.e. both\n`hue` and `style` for the same variable) can be helpful for making\ngraphics more accessible.\n\nSee the :ref:`tutorial ` for more information.\n \"\"\",\n\n relational_semantic=\"\"\"\nThe default treatment of the `hue` (and to a lesser extent, `size`)\nsemantic, if present, depends on whether the variable is inferred to\nrepresent \"numeric\" or \"categorical\" data. In particular, numeric variables\nare represented with a sequential colormap by default, and the legend\nentries show regular \"ticks\" with values that may or may not exist in the\ndata. This behavior can be controlled through various parameters, as\ndescribed and illustrated below.\n \"\"\",\n))\n\n_relational_docs = dict(\n\n # --- Shared function parameters\n data_vars=\"\"\"\nx, y : names of variables in `data` or vector data\n Input data variables; must be numeric. Can pass data directly or\n reference columns in `data`.\n \"\"\",\n data=\"\"\"\ndata : DataFrame, array, or list of arrays\n Input data structure. If `x` and `y` are specified as names, this\n should be a \"long-form\" DataFrame containing those columns. Otherwise\n it is treated as \"wide-form\" data and grouping variables are ignored.\n See the examples for the various ways this parameter can be specified\n and the different effects of each.\n \"\"\",\n palette=\"\"\"\npalette : string, list, dict, or matplotlib colormap\n An object that determines how colors are chosen when `hue` is used.\n It can be the name of a seaborn palette or matplotlib colormap, a list\n of colors (anything matplotlib understands), a dict mapping levels\n of the `hue` variable to colors, or a matplotlib colormap object.\n \"\"\",\n hue_order=\"\"\"\nhue_order : list\n Specified order for the appearance of the `hue` variable levels,\n otherwise they are determined from the data. Not relevant when the\n `hue` variable is numeric.\n \"\"\",\n hue_norm=\"\"\"\nhue_norm : tuple or :class:`matplotlib.colors.Normalize` object\n Normalization in data units for colormap applied to the `hue`\n variable when it is numeric. Not relevant if `hue` is categorical.\n \"\"\",\n sizes=\"\"\"\nsizes : list, dict, or tuple\n An object that determines how sizes are chosen when `size` is used.\n List or dict arguments should provide a size for each unique data value,\n which forces a categorical interpretation. The argument may also be a\n min, max tuple.\n \"\"\",\n size_order=\"\"\"\nsize_order : list\n Specified order for appearance of the `size` variable levels,\n otherwise they are determined from the data. Not relevant when the\n `size` variable is numeric.\n \"\"\",\n size_norm=\"\"\"\nsize_norm : tuple or Normalize object\n Normalization in data units for scaling plot objects when the\n `size` variable is numeric.\n \"\"\",\n dashes=\"\"\"\ndashes : boolean, list, or dictionary\n Object determining how to draw the lines for different levels of the\n `style` variable. Setting to `True` will use default dash codes, or\n you can pass a list of dash codes or a dictionary mapping levels of the\n `style` variable to dash codes. Setting to `False` will use solid\n lines for all subsets. Dashes are specified as in matplotlib: a tuple\n of `(segment, gap)` lengths, or an empty string to draw a solid line.\n \"\"\",\n markers=\"\"\"\nmarkers : boolean, list, or dictionary\n Object determining how to draw the markers for different levels of the\n `style` variable. Setting to `True` will use default markers, or\n you can pass a list of markers or a dictionary mapping levels of the\n `style` variable to markers. Setting to `False` will draw\n marker-less lines. Markers are specified as in matplotlib.\n \"\"\",\n style_order=\"\"\"\nstyle_order : list\n Specified order for appearance of the `style` variable levels\n otherwise they are determined from the data. Not relevant when the\n `style` variable is numeric.\n \"\"\",\n units=\"\"\"\nunits : vector or key in `data`\n Grouping variable identifying sampling units. When used, a separate\n line will be drawn for each unit with appropriate semantics, but no\n legend entry will be added. Useful for showing distribution of\n experimental replicates when exact identities are not needed.\n \"\"\",\n estimator=\"\"\"\nestimator : name of pandas method or callable or None\n Method for aggregating across multiple observations of the `y`\n variable at the same `x` level. If `None`, all observations will\n be drawn.\n \"\"\",\n ci=\"\"\"\nci : int or \"sd\" or None\n Size of the confidence interval to draw when aggregating.\n\n .. deprecated:: 0.12.0\n Use the new `errorbar` parameter for more flexibility.\n\n \"\"\",\n n_boot=\"\"\"\nn_boot : int\n Number of bootstraps to use for computing the confidence interval.\n \"\"\",\n seed=\"\"\"\nseed : int, numpy.random.Generator, or numpy.random.RandomState\n Seed or random number generator for reproducible bootstrapping.\n \"\"\",\n legend=\"\"\"\nlegend : \"auto\", \"brief\", \"full\", or False\n How to draw the legend. If \"brief\", numeric `hue` and `size`\n variables will be represented with a sample of evenly spaced values.\n If \"full\", every group will get an entry in the legend. If \"auto\",\n choose between brief or full representation based on number of levels.\n If `False`, no legend data is added and no legend is drawn.\n \"\"\",\n ax_in=\"\"\"\nax : matplotlib Axes\n Axes object to draw the plot onto, otherwise uses the current Axes.\n \"\"\",\n ax_out=\"\"\"\nax : matplotlib Axes\n Returns the Axes object with the plot drawn onto it.\n \"\"\",\n\n)\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n facets=DocstringComponents(_facet_docs),\n rel=DocstringComponents(_relational_docs),\n stat=DocstringComponents.from_function_params(EstimateAggregator.__init__),\n)\n\nlineplot.__doc__ = \"\"\"\\\nDraw a line plot with possibility of several semantic groupings.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nBy default, the plot aggregates over multiple `y` values at each value of\n`x` and shows an estimate of the central tendency and a confidence\ninterval for that estimate.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nhue : vector or key in `data`\n Grouping variable that will produce lines with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in `data`\n Grouping variable that will produce lines with different widths.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in `data`\n Grouping variable that will produce lines with different dashes\n and/or markers. Can have a numeric dtype but will always be treated\n as categorical.\n{params.rel.units}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.dashes}\n{params.rel.markers}\n{params.rel.style_order}\n{params.rel.estimator}\n{params.stat.errorbar}\n{params.rel.n_boot}\n{params.rel.seed}\norient : \"x\" or \"y\"\n Dimension along which the data are sorted / aggregated. Equivalently,\n the \"independent variable\" of the resulting function.\nsort : boolean\n If True, the data will be sorted by the x and y variables, otherwise\n lines will connect points in the order they appear in the dataset.\nerr_style : \"band\" or \"bars\"\n Whether to draw the confidence intervals with translucent error bands\n or discrete error bars.\nerr_kws : dict of keyword arguments\n Additional parameters to control the aesthetics of the error bars. The\n kwargs are passed either to :meth:`matplotlib.axes.Axes.fill_between`\n or :meth:`matplotlib.axes.Axes.errorbar`, depending on `err_style`.\n{params.rel.legend}\n{params.rel.ci}\n{params.core.ax}\nkwargs : key, value mappings\n Other keyword arguments are passed down to\n :meth:`matplotlib.axes.Axes.plot`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.scatterplot}\n{seealso.pointplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/lineplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\nscatterplot.__doc__ = \"\"\"\\\nDraw a scatter plot with possibility of several semantic groupings.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nhue : vector or key in `data`\n Grouping variable that will produce points with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in `data`\n Grouping variable that will produce points with different sizes.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in `data`\n Grouping variable that will produce points with different markers.\n Can have a numeric dtype but will always be treated as categorical.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.markers}\n{params.rel.style_order}\n{params.rel.legend}\n{params.core.ax}\nkwargs : key, value mappings\n Other keyword arguments are passed down to\n :meth:`matplotlib.axes.Axes.scatter`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.lineplot}\n{seealso.stripplot}\n{seealso.swarmplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/scatterplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\nrelplot.__doc__ = \"\"\"\\\nFigure-level interface for drawing relational plots onto a FacetGrid.\n\nThis function provides access to several different axes-level functions\nthat show the relationship between two variables with semantic mappings\nof subsets. The `kind` parameter selects the underlying axes-level\nfunction to use:\n\n- :func:`scatterplot` (with `kind=\"scatter\"`; the default)\n- :func:`lineplot` (with `kind=\"line\"`)\n\nExtra keyword arguments are passed to the underlying function, so you\nshould refer to the documentation for each to see kind-specific options.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nAfter plotting, the :class:`FacetGrid` with the plot is returned and can\nbe used directly to tweak supporting plot details or add other layers.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nhue : vector or key in `data`\n Grouping variable that will produce elements with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in `data`\n Grouping variable that will produce elements with different sizes.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in `data`\n Grouping variable that will produce elements with different styles.\n Can have a numeric dtype but will always be treated as categorical.\n{params.rel.units}\n{params.facets.rowcol}\n{params.facets.col_wrap}\nrow_order, col_order : lists of strings\n Order to organize the rows and/or columns of the grid in, otherwise the\n orders are inferred from the data objects.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.style_order}\n{params.rel.dashes}\n{params.rel.markers}\n{params.rel.legend}\nkind : string\n Kind of plot to draw, corresponding to a seaborn relational plot.\n Options are `\"scatter\"` or `\"line\"`.\n{params.facets.height}\n{params.facets.aspect}\nfacet_kws : dict\n Dictionary of other keyword arguments to pass to :class:`FacetGrid`.\nkwargs : key, value pairings\n Other keyword arguments are passed through to the underlying plotting\n function.\n\nReturns\n-------\n{returns.facetgrid}\n\nExamples\n--------\n\n.. include:: ../docstrings/relplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)"},{"col":4,"comment":"null","endLoc":854,"header":"def test_z_score(self)","id":1904,"name":"test_z_score","nodeType":"Function","startLoc":847,"text":"def test_z_score(self):\n df = self.df_norm.copy()\n df = (df - df.mean()) / df.std()\n kws = self.default_kws.copy()\n kws['z_score'] = 1\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)"},{"col":4,"comment":"\n Specify mappings from data units to visual properties.\n\n Keywords correspond to variables defined in the plot, including coordinate\n variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).\n\n A number of \"magic\" arguments are accepted, including:\n - The name of a transform (e.g., `\"log\"`, `\"sqrt\"`)\n - The name of a palette (e.g., `\"viridis\"`, `\"muted\"`)\n - A tuple of values, defining the output range (e.g. `(1, 5)`)\n - A dict, implying a :class:`Nominal` scale (e.g. `{\"a\": .2, \"b\": .5}`)\n - A list of values, implying a :class:`Nominal` scale (e.g. `[\"b\", \"r\"]`)\n\n For more explicit control, pass a scale spec object such as :class:`Continuous`\n or :class:`Nominal`. Or use `None` to use an \"identity\" scale, which treats data\n values as literally encoding visual properties.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.scale.rst\n\n ","endLoc":629,"header":"def scale(self, **scales: Scale) -> Plot","id":1905,"name":"scale","nodeType":"Function","startLoc":604,"text":"def scale(self, **scales: Scale) -> Plot:\n \"\"\"\n Specify mappings from data units to visual properties.\n\n Keywords correspond to variables defined in the plot, including coordinate\n variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).\n\n A number of \"magic\" arguments are accepted, including:\n - The name of a transform (e.g., `\"log\"`, `\"sqrt\"`)\n - The name of a palette (e.g., `\"viridis\"`, `\"muted\"`)\n - A tuple of values, defining the output range (e.g. `(1, 5)`)\n - A dict, implying a :class:`Nominal` scale (e.g. `{\"a\": .2, \"b\": .5}`)\n - A list of values, implying a :class:`Nominal` scale (e.g. `[\"b\", \"r\"]`)\n\n For more explicit control, pass a scale spec object such as :class:`Continuous`\n or :class:`Nominal`. Or use `None` to use an \"identity\" scale, which treats data\n values as literally encoding visual properties.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.scale.rst\n\n \"\"\"\n new = self._clone()\n new._scales.update(scales)\n return new"},{"col":4,"comment":"\n Control sharing of axis limits and ticks across subplots.\n\n Keywords correspond to variables defined in the plot, and values can be\n boolean (to share across all subplots), or one of \"row\" or \"col\" (to share\n more selectively across one dimension of a grid).\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.share.rst\n\n ","endLoc":648,"header":"def share(self, **shares: bool | str) -> Plot","id":1906,"name":"share","nodeType":"Function","startLoc":631,"text":"def share(self, **shares: bool | str) -> Plot:\n \"\"\"\n Control sharing of axis limits and ticks across subplots.\n\n Keywords correspond to variables defined in the plot, and values can be\n boolean (to share across all subplots), or one of \"row\" or \"col\" (to share\n more selectively across one dimension of a grid).\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.share.rst\n\n \"\"\"\n new = self._clone()\n new._shares.update(shares)\n return new"},{"col":4,"comment":"\n Control the range of visible data.\n\n Keywords correspond to variables defined in the plot, and values are a\n `(min, max)` tuple (where either can be `None` to leave unset).\n\n Limits apply only to the axis; data outside the visible range are\n still used for any stat transforms and added to the plot.\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.limit.rst\n\n ","endLoc":669,"header":"def limit(self, **limits: tuple[Any, Any]) -> Plot","id":1907,"name":"limit","nodeType":"Function","startLoc":650,"text":"def limit(self, **limits: tuple[Any, Any]) -> Plot:\n \"\"\"\n Control the range of visible data.\n\n Keywords correspond to variables defined in the plot, and values are a\n `(min, max)` tuple (where either can be `None` to leave unset).\n\n Limits apply only to the axis; data outside the visible range are\n still used for any stat transforms and added to the plot.\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.limit.rst\n\n \"\"\"\n new = self._clone()\n new._limits.update(limits)\n return new"},{"col":4,"comment":"\n Control the labels and titles for axes, legends, and subplots.\n\n Additional keywords correspond to variables defined in the plot.\n Values can be one of the following types:\n\n - string (used literally; pass \"\" to clear the default label)\n - function (called on the default label)\n\n For coordinate variables, the value sets the axis label.\n For semantic variables, the value sets the legend title.\n For faceting variables, `title=` modifies the subplot-specific label,\n while `col=` and/or `row=` add a label for the faceting variable.\n When using a single subplot, `title=` sets its title.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.label.rst\n\n\n ","endLoc":697,"header":"def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot","id":1908,"name":"label","nodeType":"Function","startLoc":671,"text":"def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot:\n \"\"\"\n Control the labels and titles for axes, legends, and subplots.\n\n Additional keywords correspond to variables defined in the plot.\n Values can be one of the following types:\n\n - string (used literally; pass \"\" to clear the default label)\n - function (called on the default label)\n\n For coordinate variables, the value sets the axis label.\n For semantic variables, the value sets the legend title.\n For faceting variables, `title=` modifies the subplot-specific label,\n while `col=` and/or `row=` add a label for the faceting variable.\n When using a single subplot, `title=` sets its title.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.label.rst\n\n\n \"\"\"\n new = self._clone()\n if title is not None:\n new._labels[\"title\"] = title\n new._labels.update(variables)\n return new"},{"col":4,"comment":"null","endLoc":865,"header":"def test_z_score_axis0(self)","id":1909,"name":"test_z_score_axis0","nodeType":"Function","startLoc":856,"text":"def test_z_score_axis0(self):\n df = self.df_norm.copy()\n df = df.T\n df = (df - df.mean()) / df.std()\n df = df.T\n kws = self.default_kws.copy()\n kws['z_score'] = 0\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)"},{"col":4,"comment":"\n Control the figure size and layout.\n\n .. note::\n\n Default figure sizes and the API for specifying the figure size are subject\n to change in future \"experimental\" releases of the objects API. The default\n layout engine may also change.\n\n Parameters\n ----------\n size : (width, height)\n Size of the resulting figure, in inches. Size is inclusive of legend when\n using pyplot, but not otherwise.\n engine : {{\"tight\", \"constrained\", None}}\n Name of method for automatically adjusting the layout to remove overlap.\n The default depends on whether :meth:`Plot.on` is used.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.layout.rst\n\n ","endLoc":740,"header":"def layout(\n self,\n *,\n size: tuple[float, float] | Default = default,\n engine: str | None | Default = default,\n ) -> Plot","id":1910,"name":"layout","nodeType":"Function","startLoc":699,"text":"def layout(\n self,\n *,\n size: tuple[float, float] | Default = default,\n engine: str | None | Default = default,\n ) -> Plot:\n \"\"\"\n Control the figure size and layout.\n\n .. note::\n\n Default figure sizes and the API for specifying the figure size are subject\n to change in future \"experimental\" releases of the objects API. The default\n layout engine may also change.\n\n Parameters\n ----------\n size : (width, height)\n Size of the resulting figure, in inches. Size is inclusive of legend when\n using pyplot, but not otherwise.\n engine : {{\"tight\", \"constrained\", None}}\n Name of method for automatically adjusting the layout to remove overlap.\n The default depends on whether :meth:`Plot.on` is used.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.layout.rst\n\n \"\"\"\n # TODO add an \"auto\" mode for figsize that roughly scales with the rcParams\n # figsize (so that works), but expands to prevent subplots from being squished\n # Also should we have height=, aspect=, exclusive with figsize? Or working\n # with figsize when only one is defined?\n\n new = self._clone()\n\n if size is not default:\n new._figure_spec[\"figsize\"] = size\n if engine is not default:\n new._layout_spec[\"engine\"] = engine\n\n return new"},{"col":4,"comment":"\n Control the default appearance of elements in the plot.\n\n .. note::\n\n The API for customizing plot appearance is not yet finalized.\n Currently, the only valid argument is a dict of matplotlib rc parameters.\n (This dict must be passed as a positional argument.)\n\n It is likely that this method will be enhanced in future releases.\n\n Matplotlib rc parameters are documented on the following page:\n https://matplotlib.org/stable/tutorials/introductory/customizing.html\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.theme.rst\n\n ","endLoc":775,"header":"def theme(self, *args: dict[str, Any]) -> Plot","id":1911,"name":"theme","nodeType":"Function","startLoc":744,"text":"def theme(self, *args: dict[str, Any]) -> Plot:\n \"\"\"\n Control the default appearance of elements in the plot.\n\n .. note::\n\n The API for customizing plot appearance is not yet finalized.\n Currently, the only valid argument is a dict of matplotlib rc parameters.\n (This dict must be passed as a positional argument.)\n\n It is likely that this method will be enhanced in future releases.\n\n Matplotlib rc parameters are documented on the following page:\n https://matplotlib.org/stable/tutorials/introductory/customizing.html\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.theme.rst\n\n \"\"\"\n new = self._clone()\n\n # We can skip this whole block on Python 3.8+ with positional-only syntax\n nargs = len(args)\n if nargs != 1:\n err = f\"theme() takes 1 positional argument, but {nargs} were given\"\n raise TypeError(err)\n\n rc = args[0]\n new._theme.update(rc)\n\n return new"},{"col":4,"comment":"null","endLoc":874,"header":"def test_standard_scale(self)","id":1912,"name":"test_standard_scale","nodeType":"Function","startLoc":867,"text":"def test_standard_scale(self):\n df = self.df_norm.copy()\n df = (df - df.min()) / (df.max() - df.min())\n kws = self.default_kws.copy()\n kws['standard_scale'] = 1\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)"},{"col":4,"comment":"\n Compile the plot and write it to a buffer or file on disk.\n\n Parameters\n ----------\n loc : str, path, or buffer\n Location on disk to save the figure, or a buffer to write into.\n kwargs\n Other keyword arguments are passed through to\n :meth:`matplotlib.figure.Figure.savefig`.\n\n ","endLoc":793,"header":"def save(self, loc, **kwargs) -> Plot","id":1913,"name":"save","nodeType":"Function","startLoc":777,"text":"def save(self, loc, **kwargs) -> Plot:\n \"\"\"\n Compile the plot and write it to a buffer or file on disk.\n\n Parameters\n ----------\n loc : str, path, or buffer\n Location on disk to save the figure, or a buffer to write into.\n kwargs\n Other keyword arguments are passed through to\n :meth:`matplotlib.figure.Figure.savefig`.\n\n \"\"\"\n # TODO expose important keyword arguments in our signature?\n with theme_context(self._theme_with_defaults()):\n self._plot().save(loc, **kwargs)\n return self"},{"col":4,"comment":"null","endLoc":303,"header":"def test_expand_margins(self, flat_array)","id":1914,"name":"test_expand_margins","nodeType":"Function","startLoc":288,"text":"def test_expand_margins(self, flat_array):\n\n f, ax = plt.subplots()\n x1, y1 = ax.margins()\n rugplot(x=flat_array, expand_margins=False)\n x2, y2 = ax.margins()\n assert x1 == x2\n assert y1 == y2\n\n f, ax = plt.subplots()\n x1, y1 = ax.margins()\n height = .05\n rugplot(x=flat_array, height=height)\n x2, y2 = ax.margins()\n assert x1 == x2\n assert y1 + height * 2 == pytest.approx(y2)"},{"col":4,"comment":"null","endLoc":885,"header":"def test_standard_scale_axis0(self)","id":1915,"name":"test_standard_scale_axis0","nodeType":"Function","startLoc":876,"text":"def test_standard_scale_axis0(self):\n df = self.df_norm.copy()\n df = df.T\n df = (df - df.min()) / (df.max() - df.min())\n df = df.T\n kws = self.default_kws.copy()\n kws['standard_scale'] = 0\n\n cg = mat.ClusterGrid(self.df_norm, **kws)\n pdt.assert_frame_equal(cg.data2d, df)"},{"col":4,"comment":"null","endLoc":34,"header":"def _fit_predict(self, data)","id":1916,"name":"_fit_predict","nodeType":"Function","startLoc":22,"text":"def _fit_predict(self, data):\n\n x = data[\"x\"]\n y = data[\"y\"]\n if x.nunique() <= self.order:\n # TODO warn?\n xx = yy = []\n else:\n p = np.polyfit(x, y, self.order)\n xx = np.linspace(x.min(), x.max(), self.gridsize)\n yy = np.polyval(p, xx)\n\n return pd.DataFrame(dict(x=xx, y=yy))"},{"col":4,"comment":"null","endLoc":891,"header":"def save(self, loc, **kwargs) -> Plotter","id":1917,"name":"save","nodeType":"Function","startLoc":883,"text":"def save(self, loc, **kwargs) -> Plotter: # TODO type args\n kwargs.setdefault(\"dpi\", 96)\n try:\n loc = os.path.expanduser(loc)\n except TypeError:\n # loc may be a buffer in which case that would not work\n pass\n self._figure.savefig(loc, **kwargs)\n return self"},{"fileName":"objects.py","filePath":"seaborn","id":1918,"nodeType":"File","text":"\"\"\"\nA declarative, object-oriented interface for creating statistical graphics.\n\nThe seaborn.objects namespace contains a number of classes that can be composed\ntogether to build a customized visualization.\n\nThe main object is :class:`Plot`, which is the starting point for all figures.\nPass :class:`Plot` a dataset and specify assignments from its variables to\nroles in the plot. Build up the visualization by calling its methods.\n\nThere are four other general types of objects in this interface:\n\n- :class:`Mark` subclasses, which create matplotlib artists for visualization\n- :class:`Stat` subclasses, which apply statistical transforms before plotting\n- :class:`Move` subclasses, which make further adjustments to reduce overplotting\n\nThese classes are passed to :meth:`Plot.add` to define a layer in the plot.\nEach layer has a :class:`Mark` and optional :class:`Stat` and/or :class:`Move`.\nPlots can have multiple layers.\n\nThe other general type of object is a :class:`Scale` subclass, which provide an\ninterface for controlling the mappings between data values and visual properties.\nPass :class:`Scale` objects to :meth:`Plot.scale`.\n\nSee the documentation for other :class:`Plot` methods to learn about the many\nways that a plot can be enhanced and customized.\n\n\"\"\"\nfrom seaborn._core.plot import Plot # noqa: F401\n\nfrom seaborn._marks.base import Mark # noqa: F401\nfrom seaborn._marks.area import Area, Band # noqa: F401\nfrom seaborn._marks.bar import Bar, Bars # noqa: F401\nfrom seaborn._marks.dot import Dot, Dots # noqa: F401\nfrom seaborn._marks.line import Line, Lines, Path, Paths, Range # noqa: F401\nfrom seaborn._marks.text import Text # noqa: F401\n\nfrom seaborn._stats.base import Stat # noqa: F401\nfrom seaborn._stats.aggregation import Agg, Est # noqa: F401\nfrom seaborn._stats.histogram import Hist # noqa: F401\nfrom seaborn._stats.order import Perc # noqa: F401\nfrom seaborn._stats.regression import PolyFit # noqa: F401\n\nfrom seaborn._core.moves import Dodge, Jitter, Norm, Shift, Stack, Move # noqa: F401\n\nfrom seaborn._core.scales import Nominal, Continuous, Temporal, Scale # noqa: F401\n"},{"col":4,"comment":"\n Compile the plot and display it by hooking into pyplot.\n\n Calling this method is not necessary to render a plot in notebook context,\n but it may be in other environments (e.g., in a terminal). After compiling the\n plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters).\n\n Unlike other :class:`Plot` methods, there is no return value. This should be\n the last method you call when specifying a plot.\n\n ","endLoc":813,"header":"def show(self, **kwargs) -> None","id":1919,"name":"show","nodeType":"Function","startLoc":795,"text":"def show(self, **kwargs) -> None:\n \"\"\"\n Compile the plot and display it by hooking into pyplot.\n\n Calling this method is not necessary to render a plot in notebook context,\n but it may be in other environments (e.g., in a terminal). After compiling the\n plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters).\n\n Unlike other :class:`Plot` methods, there is no return value. This should be\n the last method you call when specifying a plot.\n\n \"\"\"\n # TODO make pyplot configurable at the class level, and when not using,\n # import IPython.display and call on self to populate cell output?\n\n # Keep an eye on whether matplotlib implements \"attaching\" an existing\n # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024\n\n self.plot(pyplot=True).show(**kwargs)"},{"col":4,"comment":"null","endLoc":313,"header":"def test_multiple_rugs(self)","id":1920,"name":"test_multiple_rugs","nodeType":"Function","startLoc":305,"text":"def test_multiple_rugs(self):\n\n values = np.linspace(start=0, stop=1, num=5)\n ax = rugplot(x=values)\n ylim = ax.get_ylim()\n\n rugplot(x=values, ax=ax, expand_margins=False)\n\n assert ylim == ax.get_ylim()"},{"col":4,"comment":"\n Display the plot by hooking into pyplot.\n\n This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.\n\n ","endLoc":904,"header":"def show(self, **kwargs) -> None","id":1921,"name":"show","nodeType":"Function","startLoc":893,"text":"def show(self, **kwargs) -> None:\n \"\"\"\n Display the plot by hooking into pyplot.\n\n This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.\n\n \"\"\"\n # TODO if we did not create the Plotter with pyplot, is it possible to do this?\n # If not we should clearly raise.\n import matplotlib.pyplot as plt\n with theme_context(self._theme):\n plt.show(**kwargs)"},{"col":4,"comment":"null","endLoc":44,"header":"def __call__(self, data, groupby, orient, scales)","id":1922,"name":"__call__","nodeType":"Function","startLoc":39,"text":"def __call__(self, data, groupby, orient, scales):\n\n return (\n groupby\n .apply(data.dropna(subset=[\"x\", \"y\"]), self._fit_predict)\n )"},{"attributeType":"PlotData","col":4,"comment":"null","endLoc":183,"id":1923,"name":"_data","nodeType":"Attribute","startLoc":183,"text":"_data"},{"attributeType":"null","col":0,"comment":"null","endLoc":6,"id":1925,"name":"__all__","nodeType":"Attribute","startLoc":6,"text":"__all__"},{"col":0,"comment":"","endLoc":1,"header":"miscplot.py#","id":1926,"name":"","nodeType":"Function","startLoc":1,"text":"__all__ = [\"palplot\", \"dogplot\"]"},{"attributeType":"int","col":4,"comment":"null","endLoc":19,"id":1927,"name":"order","nodeType":"Attribute","startLoc":19,"text":"order"},{"col":4,"comment":"null","endLoc":892,"header":"def test_z_score_standard_scale(self)","id":1928,"name":"test_z_score_standard_scale","nodeType":"Function","startLoc":887,"text":"def test_z_score_standard_scale(self):\n kws = self.default_kws.copy()\n kws['z_score'] = True\n kws['standard_scale'] = True\n with pytest.raises(ValueError):\n mat.ClusterGrid(self.df_norm, **kws)"},{"attributeType":"int","col":4,"comment":"null","endLoc":20,"id":1929,"name":"gridsize","nodeType":"Attribute","startLoc":20,"text":"gridsize"},{"className":"TestPolyFit","col":0,"comment":"null","endLoc":61,"id":1930,"nodeType":"Class","startLoc":13,"text":"class TestPolyFit:\n\n @pytest.fixture\n def df(self, rng):\n\n n = 100\n return pd.DataFrame(dict(\n x=rng.normal(0, 1, n),\n y=rng.normal(0, 1, n),\n color=rng.choice([\"a\", \"b\", \"c\"], n),\n group=rng.choice([\"x\", \"y\"], n),\n ))\n\n def test_no_grouper(self, df):\n\n groupby = GroupBy([\"group\"])\n res = PolyFit(order=1, gridsize=100)(df[[\"x\", \"y\"]], groupby, \"x\", {})\n\n assert_array_equal(res.columns, [\"x\", \"y\"])\n\n grid = np.linspace(df[\"x\"].min(), df[\"x\"].max(), 100)\n assert_array_equal(res[\"x\"], grid)\n assert_array_almost_equal(\n res[\"y\"].diff().diff().dropna(), np.zeros(grid.size - 2)\n )\n\n def test_one_grouper(self, df):\n\n groupby = GroupBy([\"group\"])\n gridsize = 50\n res = PolyFit(gridsize=gridsize)(df, groupby, \"x\", {})\n\n assert res.columns.to_list() == [\"x\", \"y\", \"group\"]\n\n ngroups = df[\"group\"].nunique()\n assert_array_equal(res.index, np.arange(ngroups * gridsize))\n\n for _, part in res.groupby(\"group\"):\n grid = np.linspace(part[\"x\"].min(), part[\"x\"].max(), gridsize)\n assert_array_equal(part[\"x\"], grid)\n assert part[\"y\"].diff().diff().dropna().abs().gt(0).all()\n\n def test_missing_data(self, df):\n\n groupby = GroupBy([\"group\"])\n df.iloc[5:10] = np.nan\n res1 = PolyFit()(df[[\"x\", \"y\"]], groupby, \"x\", {})\n res2 = PolyFit()(df[[\"x\", \"y\"]].dropna(), groupby, \"x\", {})\n assert_frame_equal(res1, res2)"},{"col":4,"comment":"null","endLoc":901,"header":"def test_color_list_to_matrix_and_cmap(self)","id":1932,"name":"test_color_list_to_matrix_and_cmap","nodeType":"Function","startLoc":894,"text":"def test_color_list_to_matrix_and_cmap(self):\n # Note this uses the attribute named col_colors but tests row colors\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n self.col_colors, self.x_norm_leaves, axis=0)\n\n for i, leaf in enumerate(self.x_norm_leaves):\n color = self.col_colors[leaf]\n assert_colors_equal(cmap(matrix[i, 0]), color)"},{"id":1933,"name":"seaborn/_stats","nodeType":"Package"},{"fileName":"order.py","filePath":"seaborn/_stats","id":1934,"nodeType":"File","text":"\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import ClassVar, cast\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal # type: ignore\n\nimport numpy as np\nfrom pandas import DataFrame\n\nfrom seaborn._core.scales import Scale\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.base import Stat\nfrom seaborn.external.version import Version\n\n\n# From https://github.com/numpy/numpy/blob/main/numpy/lib/function_base.pyi\n_MethodKind = Literal[\n \"inverted_cdf\",\n \"averaged_inverted_cdf\",\n \"closest_observation\",\n \"interpolated_inverted_cdf\",\n \"hazen\",\n \"weibull\",\n \"linear\",\n \"median_unbiased\",\n \"normal_unbiased\",\n \"lower\",\n \"higher\",\n \"midpoint\",\n \"nearest\",\n]\n\n\n@dataclass\nclass Perc(Stat):\n \"\"\"\n Replace observations with percentile values.\n\n Parameters\n ----------\n k : list of numbers or int\n If a list of numbers, this gives the percentiles (in [0, 100]) to compute.\n If an integer, compute `k` evenly-spaced percentiles between 0 and 100.\n For example, `k=5` computes the 0, 25, 50, 75, and 100th percentiles.\n method : str\n Method for interpolating percentiles between observed datapoints.\n See :func:`numpy.percentile` for valid options and more information.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Perc.rst\n\n \"\"\"\n k: int | list[float] = 5\n method: str = \"linear\"\n\n group_by_orient: ClassVar[bool] = True\n\n def _percentile(self, data: DataFrame, var: str) -> DataFrame:\n\n k = list(np.linspace(0, 100, self.k)) if isinstance(self.k, int) else self.k\n method = cast(_MethodKind, self.method)\n values = data[var].dropna()\n if Version(np.__version__) < Version(\"1.22.0\"):\n res = np.percentile(values, k, interpolation=method) # type: ignore\n else:\n res = np.percentile(data[var].dropna(), k, method=method)\n return DataFrame({var: res, \"percentile\": k})\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n var = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.apply(data, self._percentile, var)\n"},{"attributeType":"_SpecialForm","col":0,"comment":"null","endLoc":213,"id":1935,"name":"Literal","nodeType":"Attribute","startLoc":213,"text":"Literal"},{"attributeType":"_SpecialForm","col":0,"comment":"null","endLoc":215,"id":1936,"name":"Literal","nodeType":"Attribute","startLoc":215,"text":"Literal"},{"col":4,"comment":"null","endLoc":322,"header":"def test_matplotlib_kwargs(self, flat_series)","id":1937,"name":"test_matplotlib_kwargs","nodeType":"Function","startLoc":315,"text":"def test_matplotlib_kwargs(self, flat_series):\n\n lw = 2\n alpha = .2\n ax = rugplot(y=flat_series, linewidth=lw, alpha=alpha)\n rug = ax.collections[0]\n assert np.all(rug.get_alpha() == alpha)\n assert np.all(rug.get_linewidth() == lw)"},{"col":4,"comment":"null","endLoc":328,"header":"def test_axis_labels(self, flat_series)","id":1938,"name":"test_axis_labels","nodeType":"Function","startLoc":324,"text":"def test_axis_labels(self, flat_series):\n\n ax = rugplot(x=flat_series)\n assert ax.get_xlabel() == flat_series.name\n assert not ax.get_ylabel()"},{"className":"Agg","col":0,"comment":"\n Aggregate data along the value axis using given method.\n\n Parameters\n ----------\n func : str or callable\n Name of a :class:`pandas.Series` method or a vector -> scalar function.\n\n ","endLoc":41,"id":1939,"nodeType":"Class","startLoc":15,"text":"@dataclass\nclass Agg(Stat):\n \"\"\"\n Aggregate data along the value axis using given method.\n\n Parameters\n ----------\n func : str or callable\n Name of a :class:`pandas.Series` method or a vector -> scalar function.\n\n \"\"\"\n func: str | Callable[[Vector], float] = \"mean\"\n\n group_by_orient: ClassVar[bool] = True\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n var = {\"x\": \"y\", \"y\": \"x\"}.get(orient)\n res = (\n groupby\n .agg(data, {var: self.func})\n .dropna()\n .reset_index(drop=True)\n )\n return res"},{"className":"Perc","col":0,"comment":"\n Replace observations with percentile values.\n\n Parameters\n ----------\n k : list of numbers or int\n If a list of numbers, this gives the percentiles (in [0, 100]) to compute.\n If an integer, compute `k` evenly-spaced percentiles between 0 and 100.\n For example, `k=5` computes the 0, 25, 50, 75, and 100th percentiles.\n method : str\n Method for interpolating percentiles between observed datapoints.\n See :func:`numpy.percentile` for valid options and more information.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Perc.rst\n\n ","endLoc":78,"id":1940,"nodeType":"Class","startLoc":37,"text":"@dataclass\nclass Perc(Stat):\n \"\"\"\n Replace observations with percentile values.\n\n Parameters\n ----------\n k : list of numbers or int\n If a list of numbers, this gives the percentiles (in [0, 100]) to compute.\n If an integer, compute `k` evenly-spaced percentiles between 0 and 100.\n For example, `k=5` computes the 0, 25, 50, 75, and 100th percentiles.\n method : str\n Method for interpolating percentiles between observed datapoints.\n See :func:`numpy.percentile` for valid options and more information.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Perc.rst\n\n \"\"\"\n k: int | list[float] = 5\n method: str = \"linear\"\n\n group_by_orient: ClassVar[bool] = True\n\n def _percentile(self, data: DataFrame, var: str) -> DataFrame:\n\n k = list(np.linspace(0, 100, self.k)) if isinstance(self.k, int) else self.k\n method = cast(_MethodKind, self.method)\n values = data[var].dropna()\n if Version(np.__version__) < Version(\"1.22.0\"):\n res = np.percentile(values, k, interpolation=method) # type: ignore\n else:\n res = np.percentile(data[var].dropna(), k, method=method)\n return DataFrame({var: res, \"percentile\": k})\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n var = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.apply(data, self._percentile, var)"},{"col":4,"comment":"null","endLoc":71,"header":"def _percentile(self, data: DataFrame, var: str) -> DataFrame","id":1941,"name":"_percentile","nodeType":"Function","startLoc":62,"text":"def _percentile(self, data: DataFrame, var: str) -> DataFrame:\n\n k = list(np.linspace(0, 100, self.k)) if isinstance(self.k, int) else self.k\n method = cast(_MethodKind, self.method)\n values = data[var].dropna()\n if Version(np.__version__) < Version(\"1.22.0\"):\n res = np.percentile(values, k, interpolation=method) # type: ignore\n else:\n res = np.percentile(data[var].dropna(), k, method=method)\n return DataFrame({var: res, \"percentile\": k})"},{"col":4,"comment":"null","endLoc":41,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":1942,"name":"__call__","nodeType":"Function","startLoc":30,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n var = {\"x\": \"y\", \"y\": \"x\"}.get(orient)\n res = (\n groupby\n .agg(data, {var: self.func})\n .dropna()\n .reset_index(drop=True)\n )\n return res"},{"col":4,"comment":"null","endLoc":342,"header":"def test_log_scale(self, long_df)","id":1943,"name":"test_log_scale","nodeType":"Function","startLoc":330,"text":"def test_log_scale(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n\n ax2.set_xscale(\"log\")\n\n rugplot(data=long_df, x=\"z\", ax=ax1)\n rugplot(data=long_df, x=\"z\", ax=ax2)\n\n rug1 = np.stack(ax1.collections[0].get_segments())\n rug2 = np.stack(ax2.collections[0].get_segments())\n\n assert_array_almost_equal(rug1, rug2)"},{"col":4,"comment":"null","endLoc":912,"header":"def test_nested_color_list_to_matrix_and_cmap(self)","id":1944,"name":"test_nested_color_list_to_matrix_and_cmap","nodeType":"Function","startLoc":903,"text":"def test_nested_color_list_to_matrix_and_cmap(self):\n # Note this uses the attribute named col_colors but tests row colors\n colors = [self.col_colors, self.col_colors[::-1]]\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n colors, self.x_norm_leaves, axis=0)\n\n for i, leaf in enumerate(self.x_norm_leaves):\n for j, color_row in enumerate(colors):\n color = color_row[leaf]\n assert_colors_equal(cmap(matrix[i, j]), color)"},{"attributeType":"str | (Any) -> float","col":4,"comment":"null","endLoc":26,"id":1945,"name":"func","nodeType":"Attribute","startLoc":26,"text":"func"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":163,"id":1946,"name":"func","nodeType":"Attribute","startLoc":163,"text":"func"},{"className":"TestKDEPlotUnivariate","col":0,"comment":"null","endLoc":918,"id":1947,"nodeType":"Class","startLoc":345,"text":"class TestKDEPlotUnivariate(SharedAxesLevelTests):\n\n func = staticmethod(kdeplot)\n\n def get_last_color(self, ax, fill=True):\n\n if fill:\n return ax.collections[-1].get_facecolor()\n else:\n return ax.lines[-1].get_color()\n\n @pytest.mark.parametrize(\"fill\", [True, False])\n def test_color(self, long_df, fill):\n\n super().test_color(long_df, fill=fill)\n\n if fill:\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", facecolor=\"C3\", fill=True, ax=ax)\n assert_colors_equal(self.get_last_color(ax), \"C3\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", fc=\"C4\", fill=True, ax=ax)\n assert_colors_equal(self.get_last_color(ax), \"C4\", check_alpha=False)\n\n @pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n kdeplot(data=long_df, **{variable: vector})\n\n xdata = [l.get_xdata() for l in ax.lines]\n for a, b in itertools.product(xdata, xdata):\n assert_array_equal(a, b)\n\n ydata = [l.get_ydata() for l in ax.lines]\n for a, b in itertools.product(ydata, ydata):\n assert_array_equal(a, b)\n\n def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(data=wide_df, ax=ax1, common_norm=False, common_grid=False)\n for col in wide_df:\n kdeplot(data=wide_df, x=col, ax=ax2)\n\n for l1, l2 in zip(ax1.lines[::-1], ax2.lines):\n assert_array_equal(l1.get_xydata(), l2.get_xydata())\n\n def test_flat_vector(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df[\"x\"])\n kdeplot(x=long_df[\"x\"])\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_empty_data(self):\n\n ax = kdeplot(x=[])\n assert not ax.lines\n\n def test_singular_data(self):\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=np.ones(10))\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=[5])\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n # https://github.com/mwaskom/seaborn/issues/2762\n ax = kdeplot(x=[1929245168.06679] * 18)\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\", UserWarning)\n ax = kdeplot(x=[5], warn_singular=False)\n assert not ax.lines\n\n def test_variable_assignment(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", fill=True)\n kdeplot(data=long_df, y=\"x\", fill=True)\n\n v0 = ax.collections[0].get_paths()[0].vertices\n v1 = ax.collections[1].get_paths()[0].vertices[:, [1, 0]]\n\n assert_array_equal(v0, v1)\n\n def test_vertical_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, y=\"x\")\n\n with pytest.warns(UserWarning):\n kdeplot(data=long_df, x=\"x\", vertical=True)\n\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_bw_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", bw_method=\"silverman\")\n\n with pytest.warns(UserWarning):\n kdeplot(data=long_df, x=\"x\", bw=\"silverman\")\n\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_kernel_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\")\n\n with pytest.warns(UserWarning):\n kdeplot(data=long_df, x=\"x\", kernel=\"epi\")\n\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())\n\n def test_shade_deprecation(self, long_df):\n\n f, ax = plt.subplots()\n with pytest.warns(FutureWarning):\n kdeplot(data=long_df, x=\"x\", shade=True)\n kdeplot(data=long_df, x=\"x\", fill=True)\n fill1, fill2 = ax.collections\n assert_array_equal(\n fill1.get_paths()[0].vertices, fill2.get_paths()[0].vertices\n )\n\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"stack\", \"fill\"])\n def test_hue_colors(self, long_df, multiple):\n\n ax = kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=multiple,\n fill=True, legend=False\n )\n\n # Note that hue order is reversed in the plot\n lines = ax.lines[::-1]\n fills = ax.collections[::-1]\n\n palette = color_palette()\n\n for line, fill, color in zip(lines, fills, palette):\n assert_colors_equal(line.get_color(), color)\n assert_colors_equal(fill.get_facecolor(), to_rgba(color, .25))\n\n def test_hue_stacking(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"layer\", common_grid=True,\n legend=False, ax=ax1,\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"stack\", fill=False,\n legend=False, ax=ax2,\n )\n\n layered_densities = np.stack([\n l.get_ydata() for l in ax1.lines\n ])\n stacked_densities = np.stack([\n l.get_ydata() for l in ax2.lines\n ])\n\n assert_array_equal(layered_densities.cumsum(axis=0), stacked_densities)\n\n def test_hue_filling(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"layer\", common_grid=True,\n legend=False, ax=ax1,\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=\"fill\", fill=False,\n legend=False, ax=ax2,\n )\n\n layered = np.stack([l.get_ydata() for l in ax1.lines])\n filled = np.stack([l.get_ydata() for l in ax2.lines])\n\n assert_array_almost_equal(\n (layered / layered.sum(axis=0)).cumsum(axis=0),\n filled,\n )\n\n @pytest.mark.parametrize(\"multiple\", [\"stack\", \"fill\"])\n def test_fill_default(self, long_df, multiple):\n\n ax = kdeplot(\n data=long_df, x=\"x\", hue=\"a\", multiple=multiple, fill=None\n )\n\n assert len(ax.collections) > 0\n\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"stack\", \"fill\"])\n def test_fill_nondefault(self, long_df, multiple):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\")\n kdeplot(**kws, multiple=multiple, fill=False, ax=ax1)\n kdeplot(**kws, multiple=multiple, fill=True, ax=ax2)\n\n assert len(ax1.collections) == 0\n assert len(ax2.collections) > 0\n\n def test_color_cycle_interaction(self, flat_series):\n\n color = (.2, 1, .6)\n\n f, ax = plt.subplots()\n kdeplot(flat_series)\n kdeplot(flat_series)\n assert_colors_equal(ax.lines[0].get_color(), \"C0\")\n assert_colors_equal(ax.lines[1].get_color(), \"C1\")\n plt.close(f)\n\n f, ax = plt.subplots()\n kdeplot(flat_series, color=color)\n kdeplot(flat_series)\n assert_colors_equal(ax.lines[0].get_color(), color)\n assert_colors_equal(ax.lines[1].get_color(), \"C0\")\n plt.close(f)\n\n f, ax = plt.subplots()\n kdeplot(flat_series, fill=True)\n kdeplot(flat_series, fill=True)\n assert_colors_equal(ax.collections[0].get_facecolor(), to_rgba(\"C0\", .25))\n assert_colors_equal(ax.collections[1].get_facecolor(), to_rgba(\"C1\", .25))\n plt.close(f)\n\n @pytest.mark.parametrize(\"fill\", [True, False])\n def test_artist_color(self, long_df, fill):\n\n color = (.2, 1, .6)\n alpha = .5\n\n f, ax = plt.subplots()\n\n kdeplot(long_df[\"x\"], fill=fill, color=color)\n if fill:\n artist_color = ax.collections[-1].get_facecolor().squeeze()\n else:\n artist_color = ax.lines[-1].get_color()\n default_alpha = .25 if fill else 1\n assert_colors_equal(artist_color, to_rgba(color, default_alpha))\n\n kdeplot(long_df[\"x\"], fill=fill, color=color, alpha=alpha)\n if fill:\n artist_color = ax.collections[-1].get_facecolor().squeeze()\n else:\n artist_color = ax.lines[-1].get_color()\n assert_colors_equal(artist_color, to_rgba(color, alpha))\n\n def test_datetime_scale(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n kdeplot(x=long_df[\"t\"], fill=True, ax=ax1)\n kdeplot(x=long_df[\"t\"], fill=False, ax=ax2)\n assert ax1.get_xlim() == ax2.get_xlim()\n\n def test_multiple_argument_check(self, long_df):\n\n with pytest.raises(ValueError, match=\"`multiple` must be\"):\n kdeplot(data=long_df, x=\"x\", hue=\"a\", multiple=\"bad_input\")\n\n def test_cut(self, rng):\n\n x = rng.normal(0, 3, 1000)\n\n f, ax = plt.subplots()\n kdeplot(x=x, cut=0, legend=False)\n\n xdata_0 = ax.lines[0].get_xdata()\n assert xdata_0.min() == x.min()\n assert xdata_0.max() == x.max()\n\n kdeplot(x=x, cut=2, legend=False)\n\n xdata_2 = ax.lines[1].get_xdata()\n assert xdata_2.min() < xdata_0.min()\n assert xdata_2.max() > xdata_0.max()\n\n assert len(xdata_0) == len(xdata_2)\n\n def test_clip(self, rng):\n\n x = rng.normal(0, 3, 1000)\n\n clip = -1, 1\n ax = kdeplot(x=x, clip=clip)\n\n xdata = ax.lines[0].get_xdata()\n\n assert xdata.min() >= clip[0]\n assert xdata.max() <= clip[1]\n\n def test_line_is_density(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", cut=5)\n x, y = ax.lines[0].get_xydata().T\n assert integrate(y, x) == pytest.approx(1)\n\n @pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n def test_cumulative(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", cut=5, cumulative=True)\n y = ax.lines[0].get_ydata()\n assert y[0] == pytest.approx(0)\n assert y[-1] == pytest.approx(1)\n\n @pytest.mark.skipif(not _no_scipy, reason=\"Test requires scipy's absence\")\n def test_cumulative_requires_scipy(self, long_df):\n\n with pytest.raises(RuntimeError):\n kdeplot(data=long_df, x=\"x\", cut=5, cumulative=True)\n\n def test_common_norm(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"c\", common_norm=True, cut=10, ax=ax1\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"c\", common_norm=False, cut=10, ax=ax2\n )\n\n total_area = 0\n for line in ax1.lines:\n xdata, ydata = line.get_xydata().T\n total_area += integrate(ydata, xdata)\n assert total_area == pytest.approx(1)\n\n for line in ax2.lines:\n xdata, ydata = line.get_xydata().T\n assert integrate(ydata, xdata) == pytest.approx(1)\n\n def test_common_grid(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n order = \"a\", \"b\", \"c\"\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\", hue_order=order,\n common_grid=False, cut=0, ax=ax1,\n )\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\", hue_order=order,\n common_grid=True, cut=0, ax=ax2,\n )\n\n for line, level in zip(ax1.lines[::-1], order):\n xdata = line.get_xdata()\n assert xdata.min() == long_df.loc[long_df[\"a\"] == level, \"x\"].min()\n assert xdata.max() == long_df.loc[long_df[\"a\"] == level, \"x\"].max()\n\n for line in ax2.lines:\n xdata = line.get_xdata().T\n assert xdata.min() == long_df[\"x\"].min()\n assert xdata.max() == long_df[\"x\"].max()\n\n def test_bw_method(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", bw_method=0.2, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_method=1.0, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_method=3.0, legend=False)\n\n l1, l2, l3 = ax.lines\n\n assert (\n np.abs(np.diff(l1.get_ydata())).mean()\n > np.abs(np.diff(l2.get_ydata())).mean()\n )\n\n assert (\n np.abs(np.diff(l2.get_ydata())).mean()\n > np.abs(np.diff(l3.get_ydata())).mean()\n )\n\n def test_bw_adjust(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", bw_adjust=0.2, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_adjust=1.0, legend=False)\n kdeplot(data=long_df, x=\"x\", bw_adjust=3.0, legend=False)\n\n l1, l2, l3 = ax.lines\n\n assert (\n np.abs(np.diff(l1.get_ydata())).mean()\n > np.abs(np.diff(l2.get_ydata())).mean()\n )\n\n assert (\n np.abs(np.diff(l2.get_ydata())).mean()\n > np.abs(np.diff(l3.get_ydata())).mean()\n )\n\n def test_log_scale_implicit(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n ax1.set_xscale(\"log\")\n\n kdeplot(x=x, ax=ax1)\n kdeplot(x=x, ax=ax1)\n\n xdata_log = ax1.lines[0].get_xdata()\n assert (xdata_log > 0).all()\n assert (np.diff(xdata_log, 2) > 0).all()\n assert np.allclose(np.diff(np.log(xdata_log), 2), 0)\n\n f, ax = plt.subplots()\n ax.set_yscale(\"log\")\n kdeplot(y=x, ax=ax)\n assert_array_equal(ax.lines[0].get_xdata(), ax1.lines[0].get_ydata())\n\n def test_log_scale_explicit(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n\n f, (ax1, ax2, ax3) = plt.subplots(ncols=3)\n\n ax1.set_xscale(\"log\")\n kdeplot(x=x, ax=ax1)\n kdeplot(x=x, log_scale=True, ax=ax2)\n kdeplot(x=x, log_scale=10, ax=ax3)\n\n for ax in f.axes:\n assert ax.get_xscale() == \"log\"\n\n supports = [ax.lines[0].get_xdata() for ax in f.axes]\n for a, b in itertools.product(supports, supports):\n assert_array_equal(a, b)\n\n densities = [ax.lines[0].get_ydata() for ax in f.axes]\n for a, b in itertools.product(densities, densities):\n assert_array_equal(a, b)\n\n f, ax = plt.subplots()\n kdeplot(y=x, log_scale=True, ax=ax)\n assert ax.get_yscale() == \"log\"\n\n def test_log_scale_with_hue(self, rng):\n\n data = rng.lognormal(0, 1, 50), rng.lognormal(0, 2, 100)\n ax = kdeplot(data=data, log_scale=True, common_grid=True)\n assert_array_equal(ax.lines[0].get_xdata(), ax.lines[1].get_xdata())\n\n def test_log_scale_normalization(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n ax = kdeplot(x=x, log_scale=True, cut=10)\n xdata, ydata = ax.lines[0].get_xydata().T\n integral = integrate(ydata, np.log10(xdata))\n assert integral == pytest.approx(1)\n\n def test_weights(self):\n\n x = [1, 2]\n weights = [2, 1]\n\n ax = kdeplot(x=x, weights=weights, bw_method=.1)\n\n xdata, ydata = ax.lines[0].get_xydata().T\n\n y1 = ydata[np.abs(xdata - 1).argmin()]\n y2 = ydata[np.abs(xdata - 2).argmin()]\n\n assert y1 == pytest.approx(2 * y2)\n\n def test_weight_norm(self, rng):\n\n vals = rng.normal(0, 1, 50)\n x = np.concatenate([vals, vals])\n w = np.repeat([1, 2], 50)\n ax = kdeplot(x=x, weights=w, hue=w, common_norm=True)\n\n # Recall that artists are added in reverse of hue order\n x1, y1 = ax.lines[0].get_xydata().T\n x2, y2 = ax.lines[1].get_xydata().T\n\n assert integrate(y1, x1) == pytest.approx(2 * integrate(y2, x2))\n\n def test_sticky_edges(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(data=long_df, x=\"x\", fill=True, ax=ax1)\n assert ax1.collections[0].sticky_edges.y[:] == [0, np.inf]\n\n kdeplot(\n data=long_df, x=\"x\", hue=\"a\", multiple=\"fill\", fill=True, ax=ax2\n )\n assert ax2.collections[0].sticky_edges.y[:] == [0, 1]\n\n def test_line_kws(self, flat_array):\n\n lw = 3\n color = (.2, .5, .8)\n ax = kdeplot(x=flat_array, linewidth=lw, color=color)\n line, = ax.lines\n assert line.get_linewidth() == lw\n assert_colors_equal(line.get_color(), color)\n\n def test_input_checking(self, long_df):\n\n err = \"The x variable is categorical,\"\n with pytest.raises(TypeError, match=err):\n kdeplot(data=long_df, x=\"a\")\n\n def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(data=long_df, x=\"x\", ax=ax1)\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"Density\"\n\n kdeplot(data=long_df, y=\"y\", ax=ax2)\n assert ax2.get_xlabel() == \"Density\"\n assert ax2.get_ylabel() == \"y\"\n\n def test_legend(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", hue=\"a\")\n\n assert ax.legend_.get_title().get_text() == \"a\"\n\n legend_labels = ax.legend_.get_texts()\n order = categorical_order(long_df[\"a\"])\n for label, level in zip(legend_labels, order):\n assert label.get_text() == level\n\n legend_artists = ax.legend_.findobj(mpl.lines.Line2D)\n if Version(mpl.__version__) < Version(\"3.5.0b0\"):\n # https://github.com/matplotlib/matplotlib/pull/20699\n legend_artists = legend_artists[::2]\n palette = color_palette()\n for artist, color in zip(legend_artists, palette):\n assert_colors_equal(artist.get_color(), color)\n\n ax.clear()\n\n kdeplot(data=long_df, x=\"x\", hue=\"a\", legend=False)\n\n assert ax.legend_ is None"},{"col":4,"comment":"null","endLoc":354,"header":"def get_last_color(self, ax, fill=True)","id":1948,"name":"get_last_color","nodeType":"Function","startLoc":349,"text":"def get_last_color(self, ax, fill=True):\n\n if fill:\n return ax.collections[-1].get_facecolor()\n else:\n return ax.lines[-1].get_color()"},{"col":4,"comment":"null","endLoc":920,"header":"def test_color_list_to_matrix_and_cmap_axis1(self)","id":1949,"name":"test_color_list_to_matrix_and_cmap_axis1","nodeType":"Function","startLoc":914,"text":"def test_color_list_to_matrix_and_cmap_axis1(self):\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n self.col_colors, self.x_norm_leaves, axis=1)\n\n for j, leaf in enumerate(self.x_norm_leaves):\n color = self.col_colors[leaf]\n assert_colors_equal(cmap(matrix[0, j]), color)"},{"attributeType":"bool","col":4,"comment":"null","endLoc":28,"id":1950,"name":"group_by_orient","nodeType":"Attribute","startLoc":28,"text":"group_by_orient"},{"col":4,"comment":"null","endLoc":369,"header":"@pytest.mark.parametrize(\"fill\", [True, False])\n def test_color(self, long_df, fill)","id":1951,"name":"test_color","nodeType":"Function","startLoc":356,"text":"@pytest.mark.parametrize(\"fill\", [True, False])\n def test_color(self, long_df, fill):\n\n super().test_color(long_df, fill=fill)\n\n if fill:\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", facecolor=\"C3\", fill=True, ax=ax)\n assert_colors_equal(self.get_last_color(ax), \"C3\", check_alpha=False)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"y\", fc=\"C4\", fill=True, ax=ax)\n assert_colors_equal(self.get_last_color(ax), \"C4\", check_alpha=False)"},{"className":"Est","col":0,"comment":"\n Calculate a point estimate and error bar interval.\n\n Parameters\n ----------\n func : str or callable\n Name of a :class:`numpy.ndarray` method or a vector -> scalar function.\n errorbar : str, (str, float) tuple, or callable\n Name of errorbar method (one of \"ci\", \"pi\", \"se\" or \"sd\"), or a tuple\n with a method name ane a level parameter, or a function that maps from a\n vector to a (min, max) interval.\n n_boot : int\n Number of bootstrap samples to draw for \"ci\" errorbars.\n seed : int\n Seed for the PRNG used to draw bootstrap samples.\n\n ","endLoc":95,"id":1952,"nodeType":"Class","startLoc":44,"text":"@dataclass\nclass Est(Stat):\n \"\"\"\n Calculate a point estimate and error bar interval.\n\n Parameters\n ----------\n func : str or callable\n Name of a :class:`numpy.ndarray` method or a vector -> scalar function.\n errorbar : str, (str, float) tuple, or callable\n Name of errorbar method (one of \"ci\", \"pi\", \"se\" or \"sd\"), or a tuple\n with a method name ane a level parameter, or a function that maps from a\n vector to a (min, max) interval.\n n_boot : int\n Number of bootstrap samples to draw for \"ci\" errorbars.\n seed : int\n Seed for the PRNG used to draw bootstrap samples.\n\n \"\"\"\n func: str | Callable[[Vector], float] = \"mean\"\n errorbar: str | tuple[str, float] = (\"ci\", 95)\n n_boot: int = 1000\n seed: int | None = None\n\n group_by_orient: ClassVar[bool] = True\n\n def _process(\n self, data: DataFrame, var: str, estimator: EstimateAggregator\n ) -> DataFrame:\n # Needed because GroupBy.apply assumes func is DataFrame -> DataFrame\n # which we could probably make more general to allow Series return\n res = estimator(data, var)\n return pd.DataFrame([res])\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n boot_kws = {\"n_boot\": self.n_boot, \"seed\": self.seed}\n engine = EstimateAggregator(self.func, self.errorbar, **boot_kws)\n\n var = {\"x\": \"y\", \"y\": \"x\"}[orient]\n res = (\n groupby\n .apply(data, self._process, var, engine)\n .dropna(subset=[\"x\", \"y\"])\n .reset_index(drop=True)\n )\n\n res = res.fillna({f\"{var}min\": res[var], f\"{var}max\": res[var]})\n\n return res"},{"col":4,"comment":"null","endLoc":76,"header":"def _process(\n self, data: DataFrame, var: str, estimator: EstimateAggregator\n ) -> DataFrame","id":1953,"name":"_process","nodeType":"Function","startLoc":70,"text":"def _process(\n self, data: DataFrame, var: str, estimator: EstimateAggregator\n ) -> DataFrame:\n # Needed because GroupBy.apply assumes func is DataFrame -> DataFrame\n # which we could probably make more general to allow Series return\n res = estimator(data, var)\n return pd.DataFrame([res])"},{"className":"SharedAxesLevelTests","col":0,"comment":"null","endLoc":88,"id":1954,"nodeType":"Class","startLoc":69,"text":"class SharedAxesLevelTests:\n\n def test_color(self, long_df):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C0\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C1\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", color=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", c=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")"},{"col":4,"comment":"null","endLoc":88,"header":"def test_color(self, long_df)","id":1955,"name":"test_color","nodeType":"Function","startLoc":71,"text":"def test_color(self, long_df):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C0\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n self.func(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C1\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", color=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", c=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")"},{"col":4,"comment":"null","endLoc":926,"header":"def test_color_list_to_matrix_and_cmap_different_sizes(self)","id":1956,"name":"test_color_list_to_matrix_and_cmap_different_sizes","nodeType":"Function","startLoc":922,"text":"def test_color_list_to_matrix_and_cmap_different_sizes(self):\n colors = [self.col_colors, self.col_colors * 2]\n with pytest.raises(ValueError):\n matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(\n colors, self.x_norm_leaves, axis=1)"},{"col":4,"comment":"null","endLoc":95,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":1957,"name":"__call__","nodeType":"Function","startLoc":78,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n boot_kws = {\"n_boot\": self.n_boot, \"seed\": self.seed}\n engine = EstimateAggregator(self.func, self.errorbar, **boot_kws)\n\n var = {\"x\": \"y\", \"y\": \"x\"}[orient]\n res = (\n groupby\n .apply(data, self._process, var, engine)\n .dropna(subset=[\"x\", \"y\"])\n .reset_index(drop=True)\n )\n\n res = res.fillna({f\"{var}min\": res[var], f\"{var}max\": res[var]})\n\n return res"},{"col":4,"comment":"null","endLoc":932,"header":"def test_savefig(self)","id":1958,"name":"test_savefig","nodeType":"Function","startLoc":928,"text":"def test_savefig(self):\n # Not sure if this is the right way to test....\n cg = mat.ClusterGrid(self.df_norm, **self.default_kws)\n cg.plot(**self.default_plot_kws)\n cg.savefig(tempfile.NamedTemporaryFile(), format='png')"},{"attributeType":"str | (Any) -> float","col":4,"comment":"null","endLoc":63,"id":1959,"name":"func","nodeType":"Attribute","startLoc":63,"text":"func"},{"col":4,"comment":"null","endLoc":78,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":1960,"name":"__call__","nodeType":"Function","startLoc":73,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n var = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.apply(data, self._percentile, var)"},{"className":"TestRelationalPlotter","col":0,"comment":"null","endLoc":659,"id":1962,"nodeType":"Class","startLoc":91,"text":"class TestRelationalPlotter(Helpers):\n\n def test_wide_df_variables(self, wide_df):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_df)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n assert len(p.plot_data) == np.product(wide_df.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(wide_df.index, wide_df.shape[1])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = wide_df.to_numpy().ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(wide_df.columns.to_numpy(), wide_df.shape[0])\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] == wide_df.index.name\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] == wide_df.columns.name\n assert p.variables[\"style\"] == wide_df.columns.name\n\n def test_wide_df_with_nonnumeric_variables(self, long_df):\n\n p = _RelationalPlotter()\n p.assign_variables(data=long_df)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n numeric_df = long_df.select_dtypes(\"number\")\n\n assert len(p.plot_data) == np.product(numeric_df.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(numeric_df.index, numeric_df.shape[1])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = numeric_df.to_numpy().ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(\n numeric_df.columns.to_numpy(), numeric_df.shape[0]\n )\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] == numeric_df.index.name\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] == numeric_df.columns.name\n assert p.variables[\"style\"] == numeric_df.columns.name\n\n def test_wide_array_variables(self, wide_array):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_array)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n assert len(p.plot_data) == np.product(wide_array.shape)\n\n nrow, ncol = wide_array.shape\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(nrow), ncol)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = wide_array.ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(ncol), nrow)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_flat_array_variables(self, flat_array):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_array)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == np.product(flat_array.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.arange(flat_array.shape[0])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_array\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n\n def test_flat_list_variables(self, flat_list):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_list)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_list)\n\n x = p.plot_data[\"x\"]\n expected_x = np.arange(len(flat_list))\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_list\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n\n def test_flat_series_variables(self, flat_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_series)\n\n x = p.plot_data[\"x\"]\n expected_x = flat_series.index\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_series\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is flat_series.index.name\n assert p.variables[\"y\"] is flat_series.name\n\n def test_wide_list_of_series_variables(self, wide_list_of_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_series)\n chunk_size = max(len(l) for l in wide_list_of_series)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n index_union = np.unique(\n np.concatenate([s.index for s in wide_list_of_series])\n )\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(index_union, chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = np.concatenate([\n s.reindex(index_union) for s in wide_list_of_series\n ])\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n series_names = [s.name for s in wide_list_of_series]\n expected_hue = np.repeat(series_names, chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_list_of_arrays_variables(self, wide_list_of_arrays):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_arrays)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_arrays)\n chunk_size = max(len(l) for l in wide_list_of_arrays)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(wide_list_of_arrays)\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(chunks), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_list_of_list_variables(self, wide_list_of_lists):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_lists)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_lists)\n chunk_size = max(len(l) for l in wide_list_of_lists)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(wide_list_of_lists)\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(chunks), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_dict_of_series_variables(self, wide_dict_of_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_series)\n chunk_size = max(len(l) for l in wide_dict_of_series.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_series.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_series), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_dict_of_arrays_variables(self, wide_dict_of_arrays):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_arrays)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_arrays)\n chunk_size = max(len(l) for l in wide_dict_of_arrays.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_arrays.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_arrays), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_wide_dict_of_lists_variables(self, wide_dict_of_lists):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_lists)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_lists)\n chunk_size = max(len(l) for l in wide_dict_of_lists.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_lists.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_lists), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None\n\n def test_relplot_simple(self, long_df):\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"scatter\")\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(x, long_df[\"x\"])\n assert_array_equal(y, long_df[\"y\"])\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"line\")\n x, y = g.ax.lines[0].get_xydata().T\n expected = long_df.groupby(\"x\").y.mean()\n assert_array_equal(x, expected.index)\n assert y == pytest.approx(expected.values)\n\n with pytest.raises(ValueError):\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"not_a_kind\")\n\n def test_relplot_complex(self, long_df):\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(data=long_df, x=\"x\", y=\"y\", **{sem: \"a\"})\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(x, long_df[\"x\"])\n assert_array_equal(y, long_df[\"y\"])\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(\n data=long_df, x=\"x\", y=\"y\", col=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n for sem in [\"size\", \"style\"]:\n g = relplot(\n data=long_df, x=\"x\", y=\"y\", hue=\"b\", col=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(\n data=long_df.sort_values([\"c\", \"b\"]),\n x=\"x\", y=\"y\", col=\"b\", row=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby([\"c\", \"b\"])\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n @pytest.mark.parametrize(\"vector_type\", [\"series\", \"numpy\", \"list\"])\n def test_relplot_vectors(self, long_df, vector_type):\n\n semantics = dict(x=\"x\", y=\"y\", hue=\"f\", col=\"c\")\n kws = {key: long_df[val] for key, val in semantics.items()}\n if vector_type == \"numpy\":\n kws = {k: v.to_numpy() for k, v in kws.items()}\n elif vector_type == \"list\":\n kws = {k: v.to_list() for k, v in kws.items()}\n g = relplot(data=long_df, **kws)\n grouped = long_df.groupby(\"c\")\n assert len(g.axes_dict) == len(grouped)\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n def test_relplot_wide(self, wide_df):\n\n g = relplot(data=wide_df)\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(y, wide_df.to_numpy().T.ravel())\n assert not g.ax.get_ylabel()\n\n def test_relplot_hues(self, long_df):\n\n palette = [\"r\", \"b\", \"g\"]\n g = relplot(\n x=\"x\", y=\"y\", hue=\"a\", style=\"b\", col=\"c\",\n palette=palette, data=long_df\n )\n\n palette = dict(zip(long_df[\"a\"].unique(), palette))\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n points = ax.collections[0]\n expected_hues = [palette[val] for val in grp_df[\"a\"]]\n assert same_color(points.get_facecolors(), expected_hues)\n\n def test_relplot_sizes(self, long_df):\n\n sizes = [5, 12, 7]\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", size=\"a\", hue=\"b\", col=\"c\",\n sizes=sizes,\n )\n\n sizes = dict(zip(long_df[\"a\"].unique(), sizes))\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n points = ax.collections[0]\n expected_sizes = [sizes[val] for val in grp_df[\"a\"]]\n assert_array_equal(points.get_sizes(), expected_sizes)\n\n def test_relplot_styles(self, long_df):\n\n markers = [\"o\", \"d\", \"s\"]\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", style=\"a\", hue=\"b\", col=\"c\",\n markers=markers,\n )\n\n paths = []\n for m in markers:\n m = mpl.markers.MarkerStyle(m)\n paths.append(m.get_path().transformed(m.get_transform()))\n paths = dict(zip(long_df[\"a\"].unique(), paths))\n\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n points = ax.collections[0]\n expected_paths = [paths[val] for val in grp_df[\"a\"]]\n assert self.paths_equal(points.get_paths(), expected_paths)\n\n def test_relplot_stringy_numerics(self, long_df):\n\n long_df[\"x_str\"] = long_df[\"x\"].astype(str)\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"x_str\")\n points = g.ax.collections[0]\n xys = points.get_offsets()\n mask = np.ma.getmask(xys)\n assert not mask.any()\n assert_array_equal(xys, long_df[[\"x\", \"y\"]])\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", size=\"x_str\")\n points = g.ax.collections[0]\n xys = points.get_offsets()\n mask = np.ma.getmask(xys)\n assert not mask.any()\n assert_array_equal(xys, long_df[[\"x\", \"y\"]])\n\n def test_relplot_legend(self, long_df):\n\n g = relplot(data=long_df, x=\"x\", y=\"y\")\n assert g._legend is None\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\")\n texts = [t.get_text() for t in g._legend.texts]\n expected_texts = long_df[\"a\"].unique()\n assert_array_equal(texts, expected_texts)\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"s\", size=\"s\")\n texts = [t.get_text() for t in g._legend.texts]\n assert_array_equal(texts, np.sort(texts))\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", legend=False)\n assert g._legend is None\n\n palette = color_palette(\"deep\", len(long_df[\"b\"].unique()))\n a_like_b = dict(zip(long_df[\"a\"].unique(), long_df[\"b\"].unique()))\n long_df[\"a_like_b\"] = long_df[\"a\"].map(a_like_b)\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", hue=\"b\", style=\"a_like_b\",\n palette=palette, kind=\"line\", estimator=None,\n )\n lines = g._legend.get_lines()[1:] # Chop off title dummy\n for line, color in zip(lines, palette):\n assert line.get_color() == color\n\n def test_relplot_data(self, long_df):\n\n g = relplot(\n data=long_df.to_dict(orient=\"list\"),\n x=\"x\",\n y=long_df[\"y\"].rename(\"y_var\"),\n hue=long_df[\"a\"].to_numpy(),\n col=\"c\",\n )\n expected_cols = set(long_df.columns.to_list() + [\"_hue_\", \"y_var\"])\n assert set(g.data.columns) == expected_cols\n assert_array_equal(g.data[\"y_var\"], long_df[\"y\"])\n assert_array_equal(g.data[\"_hue_\"], long_df[\"a\"])\n\n def test_facet_variable_collision(self, long_df):\n\n # https://github.com/mwaskom/seaborn/issues/2488\n col_data = long_df[\"c\"]\n long_df = long_df.assign(size=col_data)\n\n g = relplot(\n data=long_df,\n x=\"x\", y=\"y\", col=\"size\",\n )\n assert g.axes.shape == (1, len(col_data.unique()))\n\n def test_ax_kwarg_removal(self, long_df):\n\n f, ax = plt.subplots()\n with pytest.warns(UserWarning):\n g = relplot(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert len(ax.collections) == 0\n assert len(g.ax.collections) > 0"},{"col":4,"comment":"null","endLoc":120,"header":"def test_wide_df_variables(self, wide_df)","id":1963,"name":"test_wide_df_variables","nodeType":"Function","startLoc":93,"text":"def test_wide_df_variables(self, wide_df):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_df)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n assert len(p.plot_data) == np.product(wide_df.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(wide_df.index, wide_df.shape[1])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = wide_df.to_numpy().ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(wide_df.columns.to_numpy(), wide_df.shape[0])\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] == wide_df.index.name\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] == wide_df.columns.name\n assert p.variables[\"style\"] == wide_df.columns.name"},{"col":4,"comment":"null","endLoc":154,"header":"def test_wide_df_with_nonnumeric_variables(self, long_df)","id":1964,"name":"test_wide_df_with_nonnumeric_variables","nodeType":"Function","startLoc":122,"text":"def test_wide_df_with_nonnumeric_variables(self, long_df):\n\n p = _RelationalPlotter()\n p.assign_variables(data=long_df)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n numeric_df = long_df.select_dtypes(\"number\")\n\n assert len(p.plot_data) == np.product(numeric_df.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(numeric_df.index, numeric_df.shape[1])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = numeric_df.to_numpy().ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(\n numeric_df.columns.to_numpy(), numeric_df.shape[0]\n )\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] == numeric_df.index.name\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] == numeric_df.columns.name\n assert p.variables[\"style\"] == numeric_df.columns.name"},{"col":4,"comment":"null","endLoc":185,"header":"def test_wide_array_variables(self, wide_array)","id":1965,"name":"test_wide_array_variables","nodeType":"Function","startLoc":156,"text":"def test_wide_array_variables(self, wide_array):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_array)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n assert len(p.plot_data) == np.product(wide_array.shape)\n\n nrow, ncol = wide_array.shape\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(nrow), ncol)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = wide_array.ravel(order=\"f\")\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(ncol), nrow)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"attributeType":"str | (str, float)","col":4,"comment":"null","endLoc":64,"id":1966,"name":"errorbar","nodeType":"Attribute","startLoc":64,"text":"errorbar"},{"col":4,"comment":"null","endLoc":204,"header":"def test_flat_array_variables(self, flat_array)","id":1967,"name":"test_flat_array_variables","nodeType":"Function","startLoc":187,"text":"def test_flat_array_variables(self, flat_array):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_array)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == np.product(flat_array.shape)\n\n x = p.plot_data[\"x\"]\n expected_x = np.arange(flat_array.shape[0])\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_array\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None"},{"col":4,"comment":"null","endLoc":223,"header":"def test_flat_list_variables(self, flat_list)","id":1968,"name":"test_flat_list_variables","nodeType":"Function","startLoc":206,"text":"def test_flat_list_variables(self, flat_list):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_list)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_list)\n\n x = p.plot_data[\"x\"]\n expected_x = np.arange(len(flat_list))\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_list\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None"},{"col":4,"comment":"null","endLoc":242,"header":"def test_flat_series_variables(self, flat_series)","id":1969,"name":"test_flat_series_variables","nodeType":"Function","startLoc":225,"text":"def test_flat_series_variables(self, flat_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=flat_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_series)\n\n x = p.plot_data[\"x\"]\n expected_x = flat_series.index\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = flat_series\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] is flat_series.index.name\n assert p.variables[\"y\"] is flat_series.name"},{"col":4,"comment":"null","endLoc":282,"header":"def test_wide_list_of_series_variables(self, wide_list_of_series)","id":1970,"name":"test_wide_list_of_series_variables","nodeType":"Function","startLoc":244,"text":"def test_wide_list_of_series_variables(self, wide_list_of_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_series)\n chunk_size = max(len(l) for l in wide_list_of_series)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n index_union = np.unique(\n np.concatenate([s.index for s in wide_list_of_series])\n )\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(index_union, chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"]\n expected_y = np.concatenate([\n s.reindex(index_union) for s in wide_list_of_series\n ])\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n series_names = [s.name for s in wide_list_of_series]\n expected_hue = np.repeat(series_names, chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"col":4,"comment":"null","endLoc":315,"header":"def test_wide_list_of_arrays_variables(self, wide_list_of_arrays)","id":1971,"name":"test_wide_list_of_arrays_variables","nodeType":"Function","startLoc":284,"text":"def test_wide_list_of_arrays_variables(self, wide_list_of_arrays):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_arrays)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_arrays)\n chunk_size = max(len(l) for l in wide_list_of_arrays)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(wide_list_of_arrays)\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(chunks), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"col":4,"comment":"null","endLoc":348,"header":"def test_wide_list_of_list_variables(self, wide_list_of_lists)","id":1972,"name":"test_wide_list_of_list_variables","nodeType":"Function","startLoc":317,"text":"def test_wide_list_of_list_variables(self, wide_list_of_lists):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_list_of_lists)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_list_of_lists)\n chunk_size = max(len(l) for l in wide_list_of_lists)\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(wide_list_of_lists)\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(np.arange(chunks), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"col":4,"comment":"null","endLoc":381,"header":"def test_wide_dict_of_series_variables(self, wide_dict_of_series)","id":1973,"name":"test_wide_dict_of_series_variables","nodeType":"Function","startLoc":350,"text":"def test_wide_dict_of_series_variables(self, wide_dict_of_series):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_series)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_series)\n chunk_size = max(len(l) for l in wide_dict_of_series.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_series.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_series), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"col":4,"comment":"null","endLoc":414,"header":"def test_wide_dict_of_arrays_variables(self, wide_dict_of_arrays)","id":1974,"name":"test_wide_dict_of_arrays_variables","nodeType":"Function","startLoc":383,"text":"def test_wide_dict_of_arrays_variables(self, wide_dict_of_arrays):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_arrays)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_arrays)\n chunk_size = max(len(l) for l in wide_dict_of_arrays.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_arrays.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_arrays), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"col":4,"comment":"null","endLoc":447,"header":"def test_wide_dict_of_lists_variables(self, wide_dict_of_lists)","id":1975,"name":"test_wide_dict_of_lists_variables","nodeType":"Function","startLoc":416,"text":"def test_wide_dict_of_lists_variables(self, wide_dict_of_lists):\n\n p = _RelationalPlotter()\n p.assign_variables(data=wide_dict_of_lists)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\", \"hue\", \"style\"]\n\n chunks = len(wide_dict_of_lists)\n chunk_size = max(len(l) for l in wide_dict_of_lists.values())\n\n assert len(p.plot_data) == chunks * chunk_size\n\n x = p.plot_data[\"x\"]\n expected_x = np.tile(np.arange(chunk_size), chunks)\n assert_array_equal(x, expected_x)\n\n y = p.plot_data[\"y\"].dropna()\n expected_y = np.concatenate(list(wide_dict_of_lists.values()))\n assert_array_equal(y, expected_y)\n\n hue = p.plot_data[\"hue\"]\n expected_hue = np.repeat(list(wide_dict_of_lists), chunk_size)\n assert_array_equal(hue, expected_hue)\n\n style = p.plot_data[\"style\"]\n expected_style = expected_hue\n assert_array_equal(style, expected_style)\n\n assert p.variables[\"x\"] is None\n assert p.variables[\"y\"] is None\n assert p.variables[\"hue\"] is None\n assert p.variables[\"style\"] is None"},{"col":4,"comment":"null","endLoc":463,"header":"def test_relplot_simple(self, long_df)","id":1976,"name":"test_relplot_simple","nodeType":"Function","startLoc":449,"text":"def test_relplot_simple(self, long_df):\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"scatter\")\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(x, long_df[\"x\"])\n assert_array_equal(y, long_df[\"y\"])\n\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"line\")\n x, y = g.ax.lines[0].get_xydata().T\n expected = long_df.groupby(\"x\").y.mean()\n assert_array_equal(x, expected.index)\n assert y == pytest.approx(expected.values)\n\n with pytest.raises(ValueError):\n g = relplot(data=long_df, x=\"x\", y=\"y\", kind=\"not_a_kind\")"},{"attributeType":"int | list","col":4,"comment":"null","endLoc":57,"id":1977,"name":"k","nodeType":"Attribute","startLoc":57,"text":"k"},{"attributeType":"int","col":4,"comment":"null","endLoc":65,"id":1978,"name":"n_boot","nodeType":"Attribute","startLoc":65,"text":"n_boot"},{"col":4,"comment":"null","endLoc":945,"header":"def test_plot_dendrograms(self)","id":1981,"name":"test_plot_dendrograms","nodeType":"Function","startLoc":934,"text":"def test_plot_dendrograms(self):\n cm = mat.clustermap(self.df_norm, **self.default_kws)\n\n assert len(cm.ax_row_dendrogram.collections[0].get_paths()) == len(\n cm.dendrogram_row.independent_coord\n )\n assert len(cm.ax_col_dendrogram.collections[0].get_paths()) == len(\n cm.dendrogram_col.independent_coord\n )\n data2d = self.df_norm.iloc[cm.dendrogram_row.reordered_ind,\n cm.dendrogram_col.reordered_ind]\n pdt.assert_frame_equal(cm.data2d, data2d)"},{"attributeType":"str","col":4,"comment":"null","endLoc":58,"id":1982,"name":"method","nodeType":"Attribute","startLoc":58,"text":"method"},{"attributeType":"int | None","col":4,"comment":"null","endLoc":66,"id":1983,"name":"seed","nodeType":"Attribute","startLoc":66,"text":"seed"},{"attributeType":"bool","col":4,"comment":"null","endLoc":68,"id":1984,"name":"group_by_orient","nodeType":"Attribute","startLoc":68,"text":"group_by_orient"},{"attributeType":"bool","col":4,"comment":"null","endLoc":60,"id":1985,"name":"group_by_orient","nodeType":"Attribute","startLoc":60,"text":"group_by_orient"},{"attributeType":"null","col":16,"comment":"null","endLoc":10,"id":1986,"name":"np","nodeType":"Attribute","startLoc":10,"text":"np"},{"className":"Hist","col":0,"comment":"\n Bin observations, count them, and optionally normalize or cumulate.\n\n Parameters\n ----------\n stat : str\n Aggregate statistic to compute in each bin:\n\n - `count`: the number of observations\n - `density`: normalize so that the total area of the histogram equals 1\n - `percent`: normalize so that bar heights sum to 100\n - `probability` or `proportion`: normalize so that bar heights sum to 1\n - `frequency`: divide the number of observations by the bin width\n\n bins : str, int, or ArrayLike\n Generic parameter that can be the name of a reference rule, the number\n of bins, or the bin breaks. Passed to :func:`numpy.histogram_bin_edges`.\n binwidth : float\n Width of each bin; overrides `bins` but can be used with `binrange`.\n binrange : (min, max)\n Lowest and highest value for bin edges; can be used with either\n `bins` (when a number) or `binwidth`. Defaults to data extremes.\n common_norm : bool or list of variables\n When not `False`, the normalization is applied across groups. Use\n `True` to normalize across all groups, or pass variable name(s) that\n define normalization groups.\n common_bins : bool or list of variables\n When not `False`, the same bins are used for all groups. Use `True` to\n share bins across all groups, or pass variable name(s) to share within.\n cumulative : bool\n If True, cumulate the bin values.\n discrete : bool\n If True, set `binwidth` and `binrange` so that bins have unit width and\n are centered on integer values\n\n Notes\n -----\n\n The choice of bins for computing and plotting a histogram can exert\n substantial influence on the insights that one is able to draw from the\n visualization. If the bins are too large, they may erase important features.\n On the other hand, bins that are too small may be dominated by random\n variability, obscuring the shape of the true underlying distribution. The\n default bin size is determined using a reference rule that depends on the\n sample size and variance. This works well in many cases, (i.e., with\n \"well-behaved\" data) but it fails in others. It is always a good to try\n different bin sizes to be sure that you are not missing something important.\n This function allows you to specify bins in several different ways, such as\n by setting the total number of bins to use, the width of each bin, or the\n specific locations where the bins should break.\n\n\n Examples\n --------\n .. include:: ../docstrings/objects.Hist.rst\n\n ","endLoc":208,"id":1987,"nodeType":"Class","startLoc":16,"text":"@dataclass\nclass Hist(Stat):\n \"\"\"\n Bin observations, count them, and optionally normalize or cumulate.\n\n Parameters\n ----------\n stat : str\n Aggregate statistic to compute in each bin:\n\n - `count`: the number of observations\n - `density`: normalize so that the total area of the histogram equals 1\n - `percent`: normalize so that bar heights sum to 100\n - `probability` or `proportion`: normalize so that bar heights sum to 1\n - `frequency`: divide the number of observations by the bin width\n\n bins : str, int, or ArrayLike\n Generic parameter that can be the name of a reference rule, the number\n of bins, or the bin breaks. Passed to :func:`numpy.histogram_bin_edges`.\n binwidth : float\n Width of each bin; overrides `bins` but can be used with `binrange`.\n binrange : (min, max)\n Lowest and highest value for bin edges; can be used with either\n `bins` (when a number) or `binwidth`. Defaults to data extremes.\n common_norm : bool or list of variables\n When not `False`, the normalization is applied across groups. Use\n `True` to normalize across all groups, or pass variable name(s) that\n define normalization groups.\n common_bins : bool or list of variables\n When not `False`, the same bins are used for all groups. Use `True` to\n share bins across all groups, or pass variable name(s) to share within.\n cumulative : bool\n If True, cumulate the bin values.\n discrete : bool\n If True, set `binwidth` and `binrange` so that bins have unit width and\n are centered on integer values\n\n Notes\n -----\n\n The choice of bins for computing and plotting a histogram can exert\n substantial influence on the insights that one is able to draw from the\n visualization. If the bins are too large, they may erase important features.\n On the other hand, bins that are too small may be dominated by random\n variability, obscuring the shape of the true underlying distribution. The\n default bin size is determined using a reference rule that depends on the\n sample size and variance. This works well in many cases, (i.e., with\n \"well-behaved\" data) but it fails in others. It is always a good to try\n different bin sizes to be sure that you are not missing something important.\n This function allows you to specify bins in several different ways, such as\n by setting the total number of bins to use, the width of each bin, or the\n specific locations where the bins should break.\n\n\n Examples\n --------\n .. include:: ../docstrings/objects.Hist.rst\n\n \"\"\"\n stat: str = \"count\"\n bins: str | int | ArrayLike = \"auto\"\n binwidth: float | None = None\n binrange: tuple[float, float] | None = None\n common_norm: bool | list[str] = True\n common_bins: bool | list[str] = True\n cumulative: bool = False\n discrete: bool = False\n\n def __post_init__(self):\n\n stat_options = [\n \"count\", \"density\", \"percent\", \"probability\", \"proportion\", \"frequency\"\n ]\n self._check_param_one_of(\"stat\", stat_options)\n\n def _define_bin_edges(self, vals, weight, bins, binwidth, binrange, discrete):\n \"\"\"Inner function that takes bin parameters as arguments.\"\"\"\n vals = vals.dropna()\n\n if binrange is None:\n start, stop = vals.min(), vals.max()\n else:\n start, stop = binrange\n\n if discrete:\n bin_edges = np.arange(start - .5, stop + 1.5)\n elif binwidth is not None:\n step = binwidth\n bin_edges = np.arange(start, stop + step, step)\n else:\n bin_edges = np.histogram_bin_edges(vals, bins, binrange, weight)\n\n # TODO warning or cap on too many bins?\n\n return bin_edges\n\n def _define_bin_params(self, data, orient, scale_type):\n \"\"\"Given data, return numpy.histogram parameters to define bins.\"\"\"\n vals = data[orient]\n weights = data.get(\"weight\", None)\n\n # TODO We'll want this for ordinal / discrete scales too\n # (Do we need discrete as a parameter or just infer from scale?)\n discrete = self.discrete or scale_type == \"nominal\"\n\n bin_edges = self._define_bin_edges(\n vals, weights, self.bins, self.binwidth, self.binrange, discrete,\n )\n\n if isinstance(self.bins, (str, int)):\n n_bins = len(bin_edges) - 1\n bin_range = bin_edges.min(), bin_edges.max()\n bin_kws = dict(bins=n_bins, range=bin_range)\n else:\n bin_kws = dict(bins=bin_edges)\n\n return bin_kws\n\n def _get_bins_and_eval(self, data, orient, groupby, scale_type):\n\n bin_kws = self._define_bin_params(data, orient, scale_type)\n return groupby.apply(data, self._eval, orient, bin_kws)\n\n def _eval(self, data, orient, bin_kws):\n\n vals = data[orient]\n weights = data.get(\"weight\", None)\n\n density = self.stat == \"density\"\n hist, edges = np.histogram(vals, **bin_kws, weights=weights, density=density)\n\n width = np.diff(edges)\n center = edges[:-1] + width / 2\n\n return pd.DataFrame({orient: center, \"count\": hist, \"space\": width})\n\n def _normalize(self, data):\n\n hist = data[\"count\"]\n if self.stat == \"probability\" or self.stat == \"proportion\":\n hist = hist.astype(float) / hist.sum()\n elif self.stat == \"percent\":\n hist = hist.astype(float) / hist.sum() * 100\n elif self.stat == \"frequency\":\n hist = hist.astype(float) / data[\"space\"]\n\n if self.cumulative:\n if self.stat in [\"density\", \"frequency\"]:\n hist = (hist * data[\"space\"]).cumsum()\n else:\n hist = hist.cumsum()\n\n return data.assign(**{self.stat: hist})\n\n def __call__(self, data, groupby, orient, scales):\n\n scale_type = scales[orient].__class__.__name__.lower()\n grouping_vars = [v for v in data if v in groupby.order]\n if not grouping_vars or self.common_bins is True:\n bin_kws = self._define_bin_params(data, orient, scale_type)\n data = groupby.apply(data, self._eval, orient, bin_kws)\n else:\n if self.common_bins is False:\n bin_groupby = GroupBy(grouping_vars)\n else:\n bin_groupby = GroupBy(self.common_bins)\n undefined = set(self.common_bins) - set(grouping_vars)\n if undefined:\n param = f\"{self.__class__.__name__}.common_bins\"\n names = \", \".join(f\"{x!r}\" for x in undefined)\n msg = f\"Undefined variables(s) passed to `{param}`: {names}.\"\n warn(msg)\n data = bin_groupby.apply(\n data, self._get_bins_and_eval, orient, groupby, scale_type,\n )\n\n if not grouping_vars or self.common_norm is True:\n data = self._normalize(data)\n else:\n if self.common_norm is False:\n norm_grouper = grouping_vars\n else:\n norm_grouper = self.common_norm\n undefined = set(self.common_norm) - set(grouping_vars)\n if undefined:\n param = f\"{self.__class__.__name__}.common_norm\"\n names = \", \".join(f\"{x!r}\" for x in undefined)\n msg = f\"Undefined variables(s) passed to `{param}`: {names}.\"\n warn(msg)\n data = GroupBy(norm_grouper).apply(data, self._normalize)\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return data.assign(**{other: data[self.stat]})"},{"attributeType":"str","col":0,"comment":"null","endLoc":20,"id":1988,"name":"_MethodKind","nodeType":"Attribute","startLoc":20,"text":"_MethodKind"},{"col":4,"comment":"null","endLoc":961,"header":"def test_cluster_false(self)","id":1989,"name":"test_cluster_false","nodeType":"Function","startLoc":947,"text":"def test_cluster_false(self):\n kws = self.default_kws.copy()\n kws['row_cluster'] = False\n kws['col_cluster'] = False\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert len(cm.ax_row_dendrogram.lines) == 0\n assert len(cm.ax_col_dendrogram.lines) == 0\n\n assert len(cm.ax_row_dendrogram.get_xticks()) == 0\n assert len(cm.ax_row_dendrogram.get_yticks()) == 0\n assert len(cm.ax_col_dendrogram.get_xticks()) == 0\n assert len(cm.ax_col_dendrogram.get_yticks()) == 0\n\n pdt.assert_frame_equal(cm.data2d, self.df_norm)"},{"col":4,"comment":"null","endLoc":502,"header":"def test_relplot_complex(self, long_df)","id":1990,"name":"test_relplot_complex","nodeType":"Function","startLoc":465,"text":"def test_relplot_complex(self, long_df):\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(data=long_df, x=\"x\", y=\"y\", **{sem: \"a\"})\n x, y = g.ax.collections[0].get_offsets().T\n assert_array_equal(x, long_df[\"x\"])\n assert_array_equal(y, long_df[\"y\"])\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(\n data=long_df, x=\"x\", y=\"y\", col=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n for sem in [\"size\", \"style\"]:\n g = relplot(\n data=long_df, x=\"x\", y=\"y\", hue=\"b\", col=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby(\"c\")\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])\n\n for sem in [\"hue\", \"size\", \"style\"]:\n g = relplot(\n data=long_df.sort_values([\"c\", \"b\"]),\n x=\"x\", y=\"y\", col=\"b\", row=\"c\", **{sem: \"a\"}\n )\n grouped = long_df.groupby([\"c\", \"b\"])\n for (_, grp_df), ax in zip(grouped, g.axes.flat):\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, grp_df[\"x\"])\n assert_array_equal(y, grp_df[\"y\"])"},{"col":4,"comment":"null","endLoc":89,"header":"def __post_init__(self)","id":1992,"name":"__post_init__","nodeType":"Function","startLoc":84,"text":"def __post_init__(self):\n\n stat_options = [\n \"count\", \"density\", \"percent\", \"probability\", \"proportion\", \"frequency\"\n ]\n self._check_param_one_of(\"stat\", stat_options)"},{"col":0,"comment":"","endLoc":2,"header":"order.py#","id":1993,"name":"","nodeType":"Function","startLoc":2,"text":"try:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal # type: ignore\n\n_MethodKind = Literal[\n \"inverted_cdf\",\n \"averaged_inverted_cdf\",\n \"closest_observation\",\n \"interpolated_inverted_cdf\",\n \"hazen\",\n \"weibull\",\n \"linear\",\n \"median_unbiased\",\n \"normal_unbiased\",\n \"lower\",\n \"higher\",\n \"midpoint\",\n \"nearest\",\n]"},{"col":4,"comment":"Inner function that takes bin parameters as arguments.","endLoc":110,"header":"def _define_bin_edges(self, vals, weight, bins, binwidth, binrange, discrete)","id":1994,"name":"_define_bin_edges","nodeType":"Function","startLoc":91,"text":"def _define_bin_edges(self, vals, weight, bins, binwidth, binrange, discrete):\n \"\"\"Inner function that takes bin parameters as arguments.\"\"\"\n vals = vals.dropna()\n\n if binrange is None:\n start, stop = vals.min(), vals.max()\n else:\n start, stop = binrange\n\n if discrete:\n bin_edges = np.arange(start - .5, stop + 1.5)\n elif binwidth is not None:\n step = binwidth\n bin_edges = np.arange(start, stop + step, step)\n else:\n bin_edges = np.histogram_bin_edges(vals, bins, binrange, weight)\n\n # TODO warning or cap on too many bins?\n\n return bin_edges"},{"col":4,"comment":"null","endLoc":391,"header":"@pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable)","id":1995,"name":"test_long_vectors","nodeType":"Function","startLoc":371,"text":"@pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n kdeplot(data=long_df, **{variable: vector})\n\n xdata = [l.get_xdata() for l in ax.lines]\n for a, b in itertools.product(xdata, xdata):\n assert_array_equal(a, b)\n\n ydata = [l.get_ydata() for l in ax.lines]\n for a, b in itertools.product(ydata, ydata):\n assert_array_equal(a, b)"},{"col":4,"comment":"Given data, return numpy.histogram parameters to define bins.","endLoc":132,"header":"def _define_bin_params(self, data, orient, scale_type)","id":1996,"name":"_define_bin_params","nodeType":"Function","startLoc":112,"text":"def _define_bin_params(self, data, orient, scale_type):\n \"\"\"Given data, return numpy.histogram parameters to define bins.\"\"\"\n vals = data[orient]\n weights = data.get(\"weight\", None)\n\n # TODO We'll want this for ordinal / discrete scales too\n # (Do we need discrete as a parameter or just infer from scale?)\n discrete = self.discrete or scale_type == \"nominal\"\n\n bin_edges = self._define_bin_edges(\n vals, weights, self.bins, self.binwidth, self.binrange, discrete,\n )\n\n if isinstance(self.bins, (str, int)):\n n_bins = len(bin_edges) - 1\n bin_range = bin_edges.min(), bin_edges.max()\n bin_kws = dict(bins=n_bins, range=bin_range)\n else:\n bin_kws = dict(bins=bin_edges)\n\n return bin_kws"},{"id":1997,"name":"cubehelix_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"60aebc68-2c7c-4af5-a159-8421e1f94ba6\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"242b3d42-1f10-4da2-9ef9-af06f7fbd724\",\n \"metadata\": {},\n \"source\": [\n \"Return a discrete palette with default parameters:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6526accb-9930-4e39-9f58-1ca2941c1c9d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"887a40f0-d949-41fa-9a43-0ee246c9a077\",\n \"metadata\": {},\n \"source\": [\n \"Increase the number of colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"02833290-b1ee-46df-a2a0-8268fba94628\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a9eb86c7-f92e-4422-ae62-a2ef136e7e35\",\n \"metadata\": {},\n \"source\": [\n \"Return a continuous colormap rather than a discrete palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a460efc2-cf0a-46bf-a12f-12870afce8a5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5b84aa6c-ad79-45b1-a7d2-44b7ecba5f7d\",\n \"metadata\": {},\n \"source\": [\n \"Change the starting point of the helix:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"70ee079a-e760-4d43-8447-648fd236ab15\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(start=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5e21fa22-9ac3-4354-8694-967f2447b286\",\n \"metadata\": {},\n \"source\": [\n \"Change the amount of rotation in the helix:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ddb1b8c7-8933-4317-827f-4f10d2b4cecc\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(rot=.2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fa91aff7-54e7-4754-a13c-b629dfc33e8f\",\n \"metadata\": {},\n \"source\": [\n \"Rotate in the reverse direction:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"548a3942-48ae-40d2-abb7-acc2ffd71601\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(rot=-.2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e7188a1b-183f-4b04-93a0-975c27fe408e\",\n \"metadata\": {},\n \"source\": [\n \"Apply a nonlinearity to the luminance ramp:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9ced54ff-a396-451e-b17f-2366b56f920b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(gamma=.5)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"bc82ce48-2df3-464e-b70e-a1d73d0432c6\",\n \"metadata\": {},\n \"source\": [\n \"Increase the saturation of the colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a38b91a8-3fdc-4293-a3ea-71b4006cd2a1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(hue=1)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f8d23ba1-013a-489f-94c4-f2080bfdae87\",\n \"metadata\": {},\n \"source\": [\n \"Change the luminance at the start and end points:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a4f05a16-18f0-4c14-99a4-57a0734aad02\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(dark=.25, light=.75)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0bfcc5d9-05ba-4715-94ac-8d430d9416c2\",\n \"metadata\": {},\n \"source\": [\n \"Reverse the direction of the luminance ramp:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"74563491-5448-42c3-86c5-f5d55ce6924c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(reverse=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"94a83211-8b8e-4e60-8365-9600e71ddc5d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":971,"header":"def test_row_col_colors(self)","id":1998,"name":"test_row_col_colors","nodeType":"Function","startLoc":963,"text":"def test_row_col_colors(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n assert len(cm.ax_row_colors.collections) == 1\n assert len(cm.ax_col_colors.collections) == 1"},{"col":4,"comment":"null","endLoc":991,"header":"def test_cluster_false_row_col_colors(self)","id":1999,"name":"test_cluster_false_row_col_colors","nodeType":"Function","startLoc":973,"text":"def test_cluster_false_row_col_colors(self):\n kws = self.default_kws.copy()\n kws['row_cluster'] = False\n kws['col_cluster'] = False\n kws['row_colors'] = self.row_colors\n kws['col_colors'] = self.col_colors\n\n cm = mat.clustermap(self.df_norm, **kws)\n assert len(cm.ax_row_dendrogram.lines) == 0\n assert len(cm.ax_col_dendrogram.lines) == 0\n\n assert len(cm.ax_row_dendrogram.get_xticks()) == 0\n assert len(cm.ax_row_dendrogram.get_yticks()) == 0\n assert len(cm.ax_col_dendrogram.get_xticks()) == 0\n assert len(cm.ax_col_dendrogram.get_yticks()) == 0\n assert len(cm.ax_row_colors.collections) == 1\n assert len(cm.ax_col_colors.collections) == 1\n\n pdt.assert_frame_equal(cm.data2d, self.df_norm)"},{"fileName":"rules.py","filePath":"seaborn/_core","id":2000,"nodeType":"File","text":"from __future__ import annotations\n\nimport warnings\nfrom collections import UserString\nfrom numbers import Number\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Literal\n from pandas import Series\n\n\nclass VarType(UserString):\n \"\"\"\n Prevent comparisons elsewhere in the library from using the wrong name.\n\n Errors are simple assertions because users should not be able to trigger\n them. If that changes, they should be more verbose.\n\n \"\"\"\n # TODO VarType is an awfully overloaded name, but so is DataType ...\n # TODO adding unknown because we are using this in for scales, is that right?\n allowed = \"numeric\", \"datetime\", \"categorical\", \"unknown\"\n\n def __init__(self, data):\n assert data in self.allowed, data\n super().__init__(data)\n\n def __eq__(self, other):\n assert other in self.allowed, other\n return self.data == other\n\n\ndef variable_type(\n vector: Series,\n boolean_type: Literal[\"numeric\", \"categorical\"] = \"numeric\",\n) -> VarType:\n \"\"\"\n Determine whether a vector contains numeric, categorical, or datetime data.\n\n This function differs from the pandas typing API in two ways:\n\n - Python sequences or object-typed PyData objects are considered numeric if\n all of their entries are numeric.\n - String or mixed-type data are considered categorical even if not\n explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.\n\n Parameters\n ----------\n vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence\n Input data to test.\n boolean_type : 'numeric' or 'categorical'\n Type to use for vectors containing only 0s and 1s (and NAs).\n\n Returns\n -------\n var_type : 'numeric', 'categorical', or 'datetime'\n Name identifying the type of data in the vector.\n \"\"\"\n\n # If a categorical dtype is set, infer categorical\n if pd.api.types.is_categorical_dtype(vector):\n return VarType(\"categorical\")\n\n # Special-case all-na data, which is always \"numeric\"\n if pd.isna(vector).all():\n return VarType(\"numeric\")\n\n # Special-case binary/boolean data, allow caller to determine\n # This triggers a numpy warning when vector has strings/objects\n # https://github.com/numpy/numpy/issues/6784\n # Because we reduce with .all(), we are agnostic about whether the\n # comparison returns a scalar or vector, so we will ignore the warning.\n # It triggers a separate DeprecationWarning when the vector has datetimes:\n # https://github.com/numpy/numpy/issues/13548\n # This is considered a bug by numpy and will likely go away.\n with warnings.catch_warnings():\n warnings.simplefilter(\n action='ignore',\n category=(FutureWarning, DeprecationWarning) # type: ignore # mypy bug?\n )\n if np.isin(vector, [0, 1, np.nan]).all():\n return VarType(boolean_type)\n\n # Defer to positive pandas tests\n if pd.api.types.is_numeric_dtype(vector):\n return VarType(\"numeric\")\n\n if pd.api.types.is_datetime64_dtype(vector):\n return VarType(\"datetime\")\n\n # --- If we get to here, we need to check the entries\n\n # Check for a collection where everything is a number\n\n def all_numeric(x):\n for x_i in x:\n if not isinstance(x_i, Number):\n return False\n return True\n\n if all_numeric(vector):\n return VarType(\"numeric\")\n\n # Check for a collection where everything is a datetime\n\n def all_datetime(x):\n for x_i in x:\n if not isinstance(x_i, (datetime, np.datetime64)):\n return False\n return True\n\n if all_datetime(vector):\n return VarType(\"datetime\")\n\n # Otherwise, our final fallback is to consider things categorical\n\n return VarType(\"categorical\")\n\n\ndef categorical_order(vector: Series, order: list | None = None) -> list:\n \"\"\"\n Return a list of unique data values using seaborn's ordering rules.\n\n Parameters\n ----------\n vector : Series\n Vector of \"categorical\" values\n order : list\n Desired order of category levels to override the order determined\n from the `data` object.\n\n Returns\n -------\n order : list\n Ordered list of category levels not including null values.\n\n \"\"\"\n if order is not None:\n return order\n\n if vector.dtype.name == \"category\":\n order = list(vector.cat.categories)\n else:\n order = list(filter(pd.notnull, vector.unique()))\n if variable_type(pd.Series(order)) == \"numeric\":\n order.sort()\n\n return order\n"},{"className":"VarType","col":0,"comment":"\n Prevent comparisons elsewhere in the library from using the wrong name.\n\n Errors are simple assertions because users should not be able to trigger\n them. If that changes, they should be more verbose.\n\n ","endLoc":35,"id":2001,"nodeType":"Class","startLoc":17,"text":"class VarType(UserString):\n \"\"\"\n Prevent comparisons elsewhere in the library from using the wrong name.\n\n Errors are simple assertions because users should not be able to trigger\n them. If that changes, they should be more verbose.\n\n \"\"\"\n # TODO VarType is an awfully overloaded name, but so is DataType ...\n # TODO adding unknown because we are using this in for scales, is that right?\n allowed = \"numeric\", \"datetime\", \"categorical\", \"unknown\"\n\n def __init__(self, data):\n assert data in self.allowed, data\n super().__init__(data)\n\n def __eq__(self, other):\n assert other in self.allowed, other\n return self.data == other"},{"col":4,"comment":"null","endLoc":35,"header":"def __eq__(self, other)","id":2002,"name":"__eq__","nodeType":"Function","startLoc":33,"text":"def __eq__(self, other):\n assert other in self.allowed, other\n return self.data == other"},{"attributeType":"(str, str, str, str)","col":4,"comment":"null","endLoc":27,"id":2003,"name":"allowed","nodeType":"Attribute","startLoc":27,"text":"allowed"},{"col":0,"comment":"null","endLoc":127,"header":"def introduction()","id":2004,"name":"introduction","nodeType":"Function","startLoc":95,"text":"def introduction():\n\n tips = sns.load_dataset(\"tips\")\n fmri = sns.load_dataset(\"fmri\").query(\"region == 'parietal'\")\n penguins = sns.load_dataset(\"penguins\")\n\n f = mpl.figure.Figure(figsize=(5, 5))\n with sns.axes_style(\"whitegrid\"):\n f.subplots(2, 2)\n\n sns.scatterplot(\n tips, x=\"total_bill\", y=\"tip\", hue=\"sex\", size=\"size\",\n alpha=.75, palette=[\"C0\", \".5\"], legend=False, ax=f.axes[0],\n )\n sns.kdeplot(\n tips.query(\"size != 5\"), x=\"total_bill\", hue=\"size\",\n palette=\"blend:C0,.5\", fill=True, linewidth=.5,\n legend=False, common_norm=False, ax=f.axes[1],\n )\n sns.lineplot(\n fmri, x=\"timepoint\", y=\"signal\", hue=\"event\",\n errorbar=(\"se\", 2), legend=False, palette=[\"C0\", \".5\"], ax=f.axes[2],\n )\n sns.boxplot(\n penguins, x=\"bill_depth_mm\", y=\"species\", hue=\"sex\",\n whiskerprops=dict(linewidth=1.5), medianprops=dict(linewidth=1.5),\n boxprops=dict(linewidth=1.5), capprops=dict(linewidth=0),\n width=.5, palette=[\"C0\", \".8\"], whis=5, ax=f.axes[3],\n )\n f.axes[3].legend_ = None\n for ax in f.axes:\n ax.set(xticks=[], yticks=[])\n return f"},{"col":0,"comment":"","endLoc":1,"header":"rules.py#","id":2005,"name":"","nodeType":"Function","startLoc":1,"text":"if TYPE_CHECKING:\n from typing import Literal\n from pandas import Series"},{"col":4,"comment":"null","endLoc":1014,"header":"def test_row_col_colors_df(self)","id":2006,"name":"test_row_col_colors_df","nodeType":"Function","startLoc":993,"text":"def test_row_col_colors_df(self):\n kws = self.default_kws.copy()\n kws['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),\n 'row_2': list(self.row_colors)},\n index=self.df_norm.index,\n columns=['row_1', 'row_2'])\n kws['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),\n 'col_2': list(self.col_colors)},\n index=self.df_norm.columns,\n columns=['col_1', 'col_2'])\n\n cm = mat.clustermap(self.df_norm, **kws)\n\n row_labels = [l.get_text() for l in\n cm.ax_row_colors.get_xticklabels()]\n assert cm.row_color_labels == ['row_1', 'row_2']\n assert row_labels == cm.row_color_labels\n\n col_labels = [l.get_text() for l in\n cm.ax_col_colors.get_yticklabels()]\n assert cm.col_color_labels == ['col_1', 'col_2']\n assert col_labels == cm.col_color_labels"},{"col":4,"comment":"null","endLoc":401,"header":"def test_wide_vs_long_data(self, wide_df)","id":2008,"name":"test_wide_vs_long_data","nodeType":"Function","startLoc":393,"text":"def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(data=wide_df, ax=ax1, common_norm=False, common_grid=False)\n for col in wide_df:\n kdeplot(data=wide_df, x=col, ax=ax2)\n\n for l1, l2 in zip(ax1.lines[::-1], ax2.lines):\n assert_array_equal(l1.get_xydata(), l2.get_xydata())"},{"col":4,"comment":"null","endLoc":408,"header":"def test_flat_vector(self, long_df)","id":2009,"name":"test_flat_vector","nodeType":"Function","startLoc":403,"text":"def test_flat_vector(self, long_df):\n\n f, ax = plt.subplots()\n kdeplot(data=long_df[\"x\"])\n kdeplot(x=long_df[\"x\"])\n assert_array_equal(ax.lines[0].get_xydata(), ax.lines[1].get_xydata())"},{"col":4,"comment":"null","endLoc":413,"header":"def test_empty_data(self)","id":2010,"name":"test_empty_data","nodeType":"Function","startLoc":410,"text":"def test_empty_data(self):\n\n ax = kdeplot(x=[])\n assert not ax.lines"},{"col":4,"comment":"null","endLoc":137,"header":"def _get_bins_and_eval(self, data, orient, groupby, scale_type)","id":2013,"name":"_get_bins_and_eval","nodeType":"Function","startLoc":134,"text":"def _get_bins_and_eval(self, data, orient, groupby, scale_type):\n\n bin_kws = self._define_bin_params(data, orient, scale_type)\n return groupby.apply(data, self._eval, orient, bin_kws)"},{"id":2015,"name":"FacetGrid.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"ticks\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Calling the constructor requires a long-form data object. This initializes the grid, but doesn't plot anything on it:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.FacetGrid(tips)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assign column and/or row variables to add more subplots to the figure:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.FacetGrid(tips, col=\\\"time\\\", row=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To draw a plot on every facet, pass a function and the name of one or more columns in the dataframe to :meth:`FacetGrid.map`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\", row=\\\"sex\\\")\\n\",\n \"g.map(sns.scatterplot, \\\"total_bill\\\", \\\"tip\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The variable specification in :meth:`FacetGrid.map` requires a positional argument mapping, but if the function has a ``data`` parameter and accepts named variable assignments, you can also use :meth:`FacetGrid.map_dataframe`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\", row=\\\"sex\\\")\\n\",\n \"g.map_dataframe(sns.histplot, x=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Notice how the bins have different widths in each facet. A separate plot is drawn on each facet, so if the plotting function derives any parameters from the data, they may not be shared across facets. You can pass additional keyword arguments to synchronize them. But when possible, using a figure-level function like :func:`displot` will take care of this bookkeeping for you:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\", row=\\\"sex\\\")\\n\",\n \"g.map_dataframe(sns.histplot, x=\\\"total_bill\\\", binwidth=2, binrange=(0, 60))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The :class:`FacetGrid` constructor accepts a ``hue`` parameter. Setting this will condition the data on another variable and make multiple plots in different colors. Where possible, label information is tracked so that a single legend can be drawn:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\", hue=\\\"sex\\\")\\n\",\n \"g.map_dataframe(sns.scatterplot, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When ``hue`` is set on the :class:`FacetGrid`, however, a separate plot is drawn for each level of the variable. If the plotting function understands ``hue``, it is better to let it handle that logic. But it is important to ensure that each facet will use the same hue mapping. In the sample ``tips`` data, the ``sex`` column has a categorical datatype, which ensures this. Otherwise, you may want to use the `hue_order` or similar parameter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\")\\n\",\n \"g.map_dataframe(sns.scatterplot, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"sex\\\")\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The size and shape of the plot is specified at the level of each subplot using the ``height`` and ``aspect`` parameters:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"day\\\", height=3.5, aspect=.65)\\n\",\n \"g.map(sns.histplot, \\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If the variable assigned to ``col`` has many levels, it is possible to \\\"wrap\\\" it so that it spans multiple rows:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"size\\\", height=2.5, col_wrap=3)\\n\",\n \"g.map(sns.histplot, \\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To add horizontal or vertical reference lines on every facet, use :meth:`FacetGrid.refline`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"time\\\", margin_titles=True)\\n\",\n \"g.map_dataframe(sns.scatterplot, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \"g.refline(y=tips[\\\"tip\\\"].median())\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"You can pass custom functions to plot with, or to annotate each facet. Your custom function must use the matplotlib state-machine interface to plot on the \\\"current\\\" axes, and it should catch additional keyword arguments:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"import matplotlib.pyplot as plt\\n\",\n \"def annotate(data, **kws):\\n\",\n \" n = len(data)\\n\",\n \" ax = plt.gca()\\n\",\n \" ax.text(.1, .6, f\\\"N = {n}\\\", transform=ax.transAxes)\\n\",\n \"\\n\",\n \"g = sns.FacetGrid(tips, col=\\\"time\\\")\\n\",\n \"g.map_dataframe(sns.scatterplot, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \"g.map_dataframe(annotate)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The :class:`FacetGrid` object has some other useful parameters and methods for tweaking the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"sex\\\", row=\\\"time\\\", margin_titles=True)\\n\",\n \"g.map_dataframe(sns.scatterplot, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \"g.set_axis_labels(\\\"Total bill ($)\\\", \\\"Tip ($)\\\")\\n\",\n \"g.set_titles(col_template=\\\"{col_name} patrons\\\", row_template=\\\"{row_name}\\\")\\n\",\n \"g.set(xlim=(0, 60), ylim=(0, 12), xticks=[10, 30, 50], yticks=[2, 6, 10])\\n\",\n \"g.tight_layout()\\n\",\n \"g.savefig(\\\"facet_plot.png\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import os\\n\",\n \"if os.path.exists(\\\"facet_plot.png\\\"):\\n\",\n \" os.remove(\\\"facet_plot.png\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You also have access to the underlying matplotlib objects for additional tweaking:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.FacetGrid(tips, col=\\\"sex\\\", row=\\\"time\\\", margin_titles=True, despine=False)\\n\",\n \"g.map_dataframe(sns.scatterplot, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n \"g.figure.subplots_adjust(wspace=0, hspace=0)\\n\",\n \"for (row_val, col_val), ax in g.axes_dict.items():\\n\",\n \" if row_val == \\\"Lunch\\\" and col_val == \\\"Female\\\":\\n\",\n \" ax.set_facecolor(\\\".95\\\")\\n\",\n \" else:\\n\",\n \" ax.set_facecolor((0, 0, 0, 0))\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"fileName":"__init__.py","filePath":"tests/_stats","id":2016,"nodeType":"File","text":""},{"id":2017,"name":"objects.Plot.label.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"penguins = load_dataset(\\\"penguins\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fb32137a-e882-4222-9463-b8cf0ee1c8bd\",\n \"metadata\": {},\n \"source\": [\n \"Use strings to override default labels:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"65b4320e-6fb9-48ed-9132-53b0d21b85e6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = (\\n\",\n \" so.Plot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \" .add(so.Dot(), color=\\\"species\\\")\\n\",\n \")\\n\",\n \"p.label(x=\\\"Length\\\", y=\\\"Depth\\\", color=\\\"\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a39626d2-76f5-40a9-a3fd-6f44dd69bd30\",\n \"metadata\": {},\n \"source\": [\n \"Pass a function to *modify* the default label:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c3540c54-1c91-4d55-8f58-cd758abbe2fd\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.label(color=str.capitalize)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"68f3b321-0755-4ef1-a9e6-bcff61a9178d\",\n \"metadata\": {},\n \"source\": [\n \"Use this method to set the title for a single-axes plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"12d23c6e-781f-4b5c-a6b0-3ea0317ab7fb\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.label(title=\\\"Penguin species exhibit distinct bill shapes\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"8e0bcb80-0929-4ab9-b5c0-13bb3d8e4484\",\n \"metadata\": {},\n \"source\": [\n \"When faceting, the `title` parameter will modify default titles:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"da1516b7-b823-41c0-b251-01bdecb6a4e6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.facet(\\\"sex\\\").label(title=str.upper)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"bb439eae-6cc3-4a6c-bef2-b4b7746edbd1\",\n \"metadata\": {},\n \"source\": [\n \"And the `col`/`row` parameters will add labels to the title for each facet:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e0d49ba9-0507-4358-b477-2e0253f0df8f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.facet(\\\"sex\\\").label(col=\\\"Sex:\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"99471c06-1b1a-4ef5-844c-5f4aa8f322f5\",\n \"metadata\": {},\n \"source\": [\n \"If more customization is needed, a format string can work well:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"848be3a3-5a2c-4b98-918f-825257be85ae\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.facet(\\\"sex\\\").label(title=\\\"{} penguins\\\".format)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"94012def-dd7c-48f4-8830-f77a3bf7299b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2018,"name":"v0.3.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.3.0 (March 2014)\n-------------------\n\nThis is a major release from 0.2 with a number of enhancements to the plotting capabilities and styles. Highlights include :class:`FacetGrid`, ``factorplot``, :func:`jointplot`, and an overhaul to :ref:`style management `. There is also lots of new documentation, including an :ref:`example gallery ` and reorganized :ref:`tutorial `.\n\nNew plotting functions\n~~~~~~~~~~~~~~~~~~~~~~\n\n- The :class:`FacetGrid` class adds a new form of functionality to seaborn, providing a way to abstractly structure a grid of plots corresponding to subsets of a dataset. It can be used with a wide variety of plotting functions (including most of the matplotlib and seaborn APIs. See the :ref:`tutorial ` for more information.\n\n- Version 0.3 introduces the ``factorplot`` function, which is similar in spirit to :func:`lmplot` but intended for use when the main independent variable is categorical instead of quantitative. ``factorplot`` can draw a plot in either a point or bar representation using the corresponding Axes-level functions :func:`pointplot` and :func:`barplot` (which are also new). Additionally, the ``factorplot`` function can be used to draw box plots on a faceted grid. For examples of how to use these functions, you can refer to the tutorial.\n\n- Another new function is :func:`jointplot`, which is built using the new :class:`JointGrid` object. :func:`jointplot` generalizes the behavior of :func:`regplot` in previous versions of seaborn (:func:`regplot` has changed somewhat in 0.3; see below for details) by drawing a bivariate plot of the relationship between two variables with their marginal distributions drawn on the side of the plot. With :func:`jointplot`, you can draw a scatterplot or regression plot as before, but you can now also draw bivariate kernel densities or hexbin plots with appropriate univariate graphs for the marginal distributions. Additionally, it's easy to use :class:`JointGrid` directly to build up more complex plots when the default methods offered by :func:`jointplot` are not suitable for your visualization problem. The tutorial for :class:`JointGrid` has more examples of how this object can be useful.\n\n- The :func:`residplot` function complements :func:`regplot` and can be quickly used to diagnose problems with a linear model by calculating and plotting the residuals of a simple regression. There is also a ``\"resid\"`` kind for :func:`jointplot`.\n\nAPI changes\n~~~~~~~~~~~\n\n- The most noticeable change will be that :func:`regplot` no longer produces a multi-component plot with distributions in marginal axes. Instead. :func:`regplot` is now an \"Axes-level\" function that can be plotted into any existing figure on a specific set of axes. :func:`regplot` and :func:`lmplot` have also been unified (the latter uses the former behind the scenes), so all options for how to fit and represent the regression model can be used for both functions. To get the old behavior of :func:`regplot`, use :func:`jointplot` with ``kind=\"reg\"``.\n\n- As noted above, :func:`lmplot` has been rewritten to exploit the :class:`FacetGrid` machinery. This involves a few changes. The ``color`` keyword argument has been replaced with ``hue``, for better consistency across the package. The ``hue`` parameter will always take a variable *name*, while ``color`` will take a color name or (in some cases) a palette. The :func:`lmplot` function now returns the :class:`FacetGrid` used to draw the plot instance.\n\n- The functions that interact with matplotlib rc parameters have been updated and standardized. There are now three pairs of functions, :func:`axes_style` and :func:`set_style`, :func:`plotting_context` and :func:`set_context`, and :func:`color_palette` and :func:`set_palette`. In each case, the pairs take the exact same arguments. The first function defines and returns the parameters, and the second sets the matplotlib defaults. Additionally, the first function in each pair can be used in a ``with`` statement to temporarily change the defaults. Both the style and context functions also now accept a dictionary of matplotlib rc parameters to override the seaborn defaults, and :func:`set` now also takes a dictionary to update any of the matplotlib defaults. See the :ref:`tutorial ` for more information.\n\n- The ``nogrid`` style has been deprecated and changed to ``white`` for more uniformity (i.e. there are now ``darkgrid``, ``dark``, ``whitegrid``, and ``white`` styles).\n\n\nOther changes\n~~~~~~~~~~~~~\n\nUsing the package\n^^^^^^^^^^^^^^^^^\n\n- If you want to use plotting functions provided by the package without setting the matplotlib style to a seaborn theme, you can now do ``import seaborn.apionly as sns`` or ``from seaborn.apionly import lmplot``, etc. This is using the (also new) :func:`reset_orig` function, which returns the rc parameters to what they are at matplotlib import time — i.e. they will respect any custom `matplotlibrc` settings on top of the matplotlib defaults.\n\n- The dependency load of the package has been reduced. It can now be installed and used with only ``numpy``, ``scipy``, ``matplotlib``, and ``pandas``. Although ``statsmodels`` is still recommended for full functionality, it is not required.\n\nPlotting functions\n^^^^^^^^^^^^^^^^^^\n\n- :func:`lmplot` (and :func:`regplot`) have two new options for fitting regression models: ``lowess`` and ``robust``. The former fits a nonparametric smoother, while the latter fits a regression using methods that are less sensitive to outliers.\n\n- The regression uncertainty in :func:`lmplot` and :func:`regplot` is now estimated with fewer bootstrap iterations, so plotting should be faster.\n\n- The univariate :func:`kdeplot` can now be drawn as a *cumulative* density plot.\n\n- Changed :func:`interactplot` to use a robust calculation of the data range when finding default limits for the contour colormap to work better when there are outliers in the data.\n\nStyle\n^^^^^\n\n- There is a new style, ``dark``, which shares most features with ``darkgrid`` but does not draw a grid by default.\n\n- There is a new function, :func:`offset_spines`, and a corresponding option in :func:`despine` called ``trim``. Together, these can be used to make plots where the axis spines are offset from the main part of the figure and limited within the range of the ticks. This is recommended for use with the ``ticks`` style.\n\n- Other aspects of the seaborn styles have been tweaked for more attractive plots.\n"},{"fileName":"large_distributions.py","filePath":"examples","id":2019,"nodeType":"File","text":"\"\"\"\nPlotting large distributions\n============================\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\nclarity_ranking = [\"I1\", \"SI2\", \"SI1\", \"VS2\", \"VS1\", \"VVS2\", \"VVS1\", \"IF\"]\n\nsns.boxenplot(x=\"clarity\", y=\"carat\",\n color=\"b\", order=clarity_ranking,\n scale=\"linear\", data=diamonds)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":6,"id":2020,"name":"sns","nodeType":"Attribute","startLoc":6,"text":"sns"},{"fileName":"aggregation.py","filePath":"seaborn/_stats","id":2021,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Callable\n\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom seaborn._core.scales import Scale\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.base import Stat\nfrom seaborn._statistics import EstimateAggregator\nfrom seaborn._core.typing import Vector\n\n\n@dataclass\nclass Agg(Stat):\n \"\"\"\n Aggregate data along the value axis using given method.\n\n Parameters\n ----------\n func : str or callable\n Name of a :class:`pandas.Series` method or a vector -> scalar function.\n\n \"\"\"\n func: str | Callable[[Vector], float] = \"mean\"\n\n group_by_orient: ClassVar[bool] = True\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n var = {\"x\": \"y\", \"y\": \"x\"}.get(orient)\n res = (\n groupby\n .agg(data, {var: self.func})\n .dropna()\n .reset_index(drop=True)\n )\n return res\n\n\n@dataclass\nclass Est(Stat):\n \"\"\"\n Calculate a point estimate and error bar interval.\n\n Parameters\n ----------\n func : str or callable\n Name of a :class:`numpy.ndarray` method or a vector -> scalar function.\n errorbar : str, (str, float) tuple, or callable\n Name of errorbar method (one of \"ci\", \"pi\", \"se\" or \"sd\"), or a tuple\n with a method name ane a level parameter, or a function that maps from a\n vector to a (min, max) interval.\n n_boot : int\n Number of bootstrap samples to draw for \"ci\" errorbars.\n seed : int\n Seed for the PRNG used to draw bootstrap samples.\n\n \"\"\"\n func: str | Callable[[Vector], float] = \"mean\"\n errorbar: str | tuple[str, float] = (\"ci\", 95)\n n_boot: int = 1000\n seed: int | None = None\n\n group_by_orient: ClassVar[bool] = True\n\n def _process(\n self, data: DataFrame, var: str, estimator: EstimateAggregator\n ) -> DataFrame:\n # Needed because GroupBy.apply assumes func is DataFrame -> DataFrame\n # which we could probably make more general to allow Series return\n res = estimator(data, var)\n return pd.DataFrame([res])\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n boot_kws = {\"n_boot\": self.n_boot, \"seed\": self.seed}\n engine = EstimateAggregator(self.func, self.errorbar, **boot_kws)\n\n var = {\"x\": \"y\", \"y\": \"x\"}[orient]\n res = (\n groupby\n .apply(data, self._process, var, engine)\n .dropna(subset=[\"x\", \"y\"])\n .reset_index(drop=True)\n )\n\n res = res.fillna({f\"{var}min\": res[var], f\"{var}max\": res[var]})\n\n return res\n\n\n@dataclass\nclass Rolling(Stat):\n ...\n\n def __call__(self, data, groupby, orient, scales):\n ...\n"},{"id":2022,"name":"data_structure.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _data_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Data structures accepted by seaborn\\n\",\n \"===================================\\n\",\n \"\\n\",\n \"As a data visualization library, seaborn requires that you provide it with data. This chapter explains the various ways to accomplish that task. Seaborn supports several different dataset formats, and most functions accept data represented with objects from the `pandas `_ or `numpy `_ libraries as well as built-in Python types like lists and dictionaries. Understanding the usage patterns associated with these different options will help you quickly create useful visualizations for nearly any dataset.\\n\",\n \"\\n\",\n \".. note::\\n\",\n \" As of current writing (v0.11.0), the full breadth of options covered here are supported by only a subset of the modules in seaborn (namely, the :ref:`relational ` and :ref:`distribution ` modules). The other modules offer much of the same flexibility, but have some exceptions (e.g., :func:`catplot` and :func:`lmplot` are limited to long-form data with named variables). The data-ingest code will be standardized over the next few release cycles, but until that point, be mindful of the specific documentation for each function if it is not doing what you expect with your dataset.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import pandas as pd\\n\",\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Long-form vs. wide-form data\\n\",\n \"----------------------------\\n\",\n \"\\n\",\n \"Most plotting functions in seaborn are oriented towards *vectors* of data. When plotting ``x`` against ``y``, each variable should be a vector. Seaborn accepts data *sets* that have more than one vector organized in some tabular fashion. There is a fundamental distinction between \\\"long-form\\\" and \\\"wide-form\\\" data tables, and seaborn will treat each differently.\\n\",\n \"\\n\",\n \"Long-form data\\n\",\n \"~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"A long-form data table has the following characteristics:\\n\",\n \"\\n\",\n \"- Each variable is a column\\n\",\n \"- Each observation is a row\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As a simple example, consider the \\\"flights\\\" dataset, which records the number of airline passengers who flew in each month from 1949 to 1960. This dataset has three variables (*year*, *month*, and number of *passengers*):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights = sns.load_dataset(\\\"flights\\\")\\n\",\n \"flights.head()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"With long-form data, columns in the table are given roles in the plot by explicitly assigning them to one of the variables. For example, making a monthly plot of the number of passengers per year looks like this:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=flights, x=\\\"year\\\", y=\\\"passengers\\\", hue=\\\"month\\\", kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The advantage of long-form data is that it lends itself well to this explicit specification of the plot. It can accommodate datasets of arbitrary complexity, so long as the variables and observations can be clearly defined. But this format takes some getting used to, because it is often not the model of the data that one has in their head.\\n\",\n \"\\n\",\n \"Wide-form data\\n\",\n \"~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"For simple datasets, it is often more intuitive to think about data the way it might be viewed in a spreadsheet, where the columns and rows contain *levels* of different variables. For example, we can convert the flights dataset into a wide-form organization by \\\"pivoting\\\" it so that each column has each month's time series over years:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights_wide = flights.pivot(index=\\\"year\\\", columns=\\\"month\\\", values=\\\"passengers\\\")\\n\",\n \"flights_wide.head()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Here we have the same three variables, but they are organized differently. The variables in this dataset are linked to the *dimensions* of the table, rather than to named fields. Each observation is defined by both the value at a cell in the table and the coordinates of that cell with respect to the row and column indices.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"With long-form data, we can access variables in the dataset by their name. That is not the case with wide-form data. Nevertheless, because there is a clear association between the dimensions of the table and the variable in the dataset, seaborn is able to assign those variables roles in the plot.\\n\",\n \"\\n\",\n \".. note::\\n\",\n \" Seaborn treats the argument to ``data`` as wide form when neither ``x`` nor ``y`` are assigned.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=flights_wide, kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This plot looks very similar to the one before. Seaborn has assigned the index of the dataframe to ``x``, the values of the dataframe to ``y``, and it has drawn a separate line for each month. There is a notable difference between the two plots, however. When the dataset went through the \\\"pivot\\\" operation that converted it from long-form to wide-form, the information about what the values mean was lost. As a result, there is no y axis label. (The lines also have dashes here, because :func:`relplot` has mapped the column variable to both the ``hue`` and ``style`` semantic so that the plot is more accessible. We didn't do that in the long-form case, but we could have by setting ``style=\\\"month\\\"``).\\n\",\n \"\\n\",\n \"Thus far, we did much less typing while using wide-form data and made nearly the same plot. This seems easier! But a big advantage of long-form data is that, once you have the data in the correct format, you no longer need to think about its *structure*. You can design your plots by thinking only about the variables contained within it. For example, to draw lines that represent the monthly time series for each year, simply reassign the variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=flights, x=\\\"month\\\", y=\\\"passengers\\\", hue=\\\"year\\\", kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To achieve the same remapping with the wide-form dataset, we would need to transpose the table:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=flights_wide.transpose(), kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"(This example also illustrates another wrinkle, which is that seaborn currently considers the column variable in a wide-form dataset to be categorical regardless of its datatype, whereas, because the long-form variable is numeric, it is assigned a quantitative color palette and legend. This may change in the future).\\n\",\n \"\\n\",\n \"The absence of explicit variable assignments also means that each plot type needs to define a fixed mapping between the dimensions of the wide-form data and the roles in the plot. Because this natural mapping may vary across plot types, the results are less predictable when using wide-form data. For example, the :ref:`categorical ` plots assign the *column* dimension of the table to ``x`` and then aggregate across the rows (ignoring the index):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=flights_wide, kind=\\\"box\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When using pandas to represent wide-form data, you are limited to just a few variables (no more than three). This is because seaborn does not make use of multi-index information, which is how pandas represents additional variables in a tabular format. The `xarray `_ project offers labeled N-dimensional array objects, which can be considered a generalization of wide-form data to higher dimensions. At present, seaborn does not directly support objects from ``xarray``, but they can be transformed into a long-form :class:`pandas.DataFrame` using the ``to_pandas`` method and then plotted in seaborn like any other long-form data set.\\n\",\n \"\\n\",\n \"In summary, we can think of long-form and wide-form datasets as looking something like this:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import matplotlib.pyplot as plt\\n\",\n \"f = plt.figure(figsize=(7, 5))\\n\",\n \"\\n\",\n \"gs = plt.GridSpec(\\n\",\n \" ncols=6, nrows=2, figure=f,\\n\",\n \" left=0, right=.35, bottom=0, top=.9,\\n\",\n \" height_ratios=(1, 20),\\n\",\n \" wspace=.1, hspace=.01\\n\",\n \")\\n\",\n \"\\n\",\n \"colors = [c + (.5,) for c in sns.color_palette()]\\n\",\n \"\\n\",\n \"f.add_subplot(gs[0, :], facecolor=\\\".8\\\")\\n\",\n \"[\\n\",\n \" f.add_subplot(gs[1:, i], facecolor=colors[i])\\n\",\n \" for i in range(gs.ncols)\\n\",\n \"]\\n\",\n \"\\n\",\n \"gs = plt.GridSpec(\\n\",\n \" ncols=2, nrows=2, figure=f,\\n\",\n \" left=.4, right=1, bottom=.2, top=.8,\\n\",\n \" height_ratios=(1, 8), width_ratios=(1, 11),\\n\",\n \" wspace=.015, hspace=.02\\n\",\n \")\\n\",\n \"\\n\",\n \"f.add_subplot(gs[0, 1:], facecolor=colors[2])\\n\",\n \"f.add_subplot(gs[1:, 0], facecolor=colors[1])\\n\",\n \"f.add_subplot(gs[1, 1], facecolor=colors[0])\\n\",\n \"\\n\",\n \"for ax in f.axes:\\n\",\n \" ax.set(xticks=[], yticks=[])\\n\",\n \"\\n\",\n \"f.text(.35 / 2, .91, \\\"Long-form\\\", ha=\\\"center\\\", va=\\\"bottom\\\", size=15)\\n\",\n \"f.text(.7, .81, \\\"Wide-form\\\", ha=\\\"center\\\", va=\\\"bottom\\\", size=15)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Messy data\\n\",\n \"~~~~~~~~~~\\n\",\n \"\\n\",\n \"Many datasets cannot be clearly interpreted using either long-form or wide-form rules. If datasets that are clearly long-form or wide-form are `\\\"tidy\\\" `_, we might say that these more ambiguous datasets are \\\"messy\\\". In a messy dataset, the variables are neither uniquely defined by the keys nor by the dimensions of the table. This often occurs with *repeated-measures* data, where it is natural to organize a table such that each row corresponds to the *unit* of data collection. Consider this simple dataset from a psychology experiment in which twenty subjects performed a memory task where they studied anagrams while their attention was either divided or focused:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"anagrams = sns.load_dataset(\\\"anagrams\\\")\\n\",\n \"anagrams\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The attention variable is *between-subjects*, but there is also a *within-subjects* variable: the number of possible solutions to the anagrams, which varied from 1 to 3. The dependent measure is a score of memory performance. These two variables (number and score) are jointly encoded across several columns. As a result, the whole dataset is neither clearly long-form nor clearly wide-form.\\n\",\n \"\\n\",\n \"How might we tell seaborn to plot the average score as a function of attention and number of solutions? We'd first need to coerce the data into one of our two structures. Let's transform it to a tidy long-form table, such that each variable is a column and each row is an observation. We can use the method :meth:`pandas.DataFrame.melt` to accomplish this task:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"anagrams_long = anagrams.melt(id_vars=[\\\"subidr\\\", \\\"attnr\\\"], var_name=\\\"solutions\\\", value_name=\\\"score\\\")\\n\",\n \"anagrams_long.head()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Now we can make the plot that we want:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=anagrams_long, x=\\\"solutions\\\", y=\\\"score\\\", hue=\\\"attnr\\\", kind=\\\"point\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Further reading and take-home points\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"For a longer discussion about tabular data structures, you could read the `\\\"Tidy Data\\\" `_ paper by Hadley Whickham. Note that seaborn uses a slightly different set of concepts than are defined in the paper. While the paper associates tidyness with long-form structure, we have drawn a distinction between \\\"tidy wide-form\\\" data, where there is a clear mapping between variables in the dataset and the dimensions of the table, and \\\"messy data\\\", where no such mapping exists.\\n\",\n \"\\n\",\n \"The long-form structure has clear advantages. It allows you to create figures by explicitly assigning variables in the dataset to roles in plot, and you can do so with more than three variables. When possible, try to represent your data with a long-form structure when embarking on serious analysis. Most of the examples in the seaborn documentation will use long-form data. But in cases where it is more natural to keep the dataset wide, remember that seaborn can remain useful.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Options for visualizing long-form data\\n\",\n \"--------------------------------------\\n\",\n \"\\n\",\n \"While long-form data has a precise definition, seaborn is fairly flexible in terms of how it is actually organized across the data structures in memory. The examples in the rest of the documentation will typically use :class:`pandas.DataFrame` objects and reference variables in them by assigning names of their columns to the variables in the plot. But it is also possible to store vectors in a Python dictionary or a class that implements that interface:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights_dict = flights.to_dict()\\n\",\n \"sns.relplot(data=flights_dict, x=\\\"year\\\", y=\\\"passengers\\\", hue=\\\"month\\\", kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Many pandas operations, such as the split-apply-combine operations of a group-by, will produce a dataframe where information has moved from the columns of the input dataframe to the index of the output. So long as the name is retained, you can still reference the data as normal:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights_avg = flights.groupby(\\\"year\\\").mean()\\n\",\n \"sns.relplot(data=flights_avg, x=\\\"year\\\", y=\\\"passengers\\\", kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Additionally, it's possible to pass vectors of data directly as arguments to ``x``, ``y``, and other plotting variables. If these vectors are pandas objects, the ``name`` attribute will be used to label the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"year = flights_avg.index\\n\",\n \"passengers = flights_avg[\\\"passengers\\\"]\\n\",\n \"sns.relplot(x=year, y=passengers, kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Numpy arrays and other objects that implement the Python sequence interface work too, but if they don't have names, the plot will not be as informative without further tweaking:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(x=year.to_numpy(), y=passengers.to_list(), kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Options for visualizing wide-form data\\n\",\n \"--------------------------------------\\n\",\n \"\\n\",\n \"The options for passing wide-form data are even more flexible. As with long-form data, pandas objects are preferable because the name (and, in some cases, index) information can be used. But in essence, any format that can be viewed as a single vector or a collection of vectors can be passed to ``data``, and a valid plot can usually be constructed.\\n\",\n \"\\n\",\n \"The example we saw above used a rectangular :class:`pandas.DataFrame`, which can be thought of as a collection of its columns. A dict or list of pandas objects will also work, but we'll lose the axis labels:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights_wide_list = [col for _, col in flights_wide.items()]\\n\",\n \"sns.relplot(data=flights_wide_list, kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The vectors in a collection do not need to have the same length. If they have an ``index``, it will be used to align them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"two_series = [flights_wide.loc[:1955, \\\"Jan\\\"], flights_wide.loc[1952:, \\\"Aug\\\"]]\\n\",\n \"sns.relplot(data=two_series, kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Whereas an ordinal index will be used for numpy arrays or simple Python sequences:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"two_arrays = [s.to_numpy() for s in two_series]\\n\",\n \"sns.relplot(data=two_arrays, kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"But a dictionary of such vectors will at least use the keys:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"two_arrays_dict = {s.name: s.to_numpy() for s in two_series}\\n\",\n \"sns.relplot(data=two_arrays_dict, kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Rectangular numpy arrays are treated just like a dataframe without index information, so they are viewed as a collection of column vectors. Note that this is different from how numpy indexing operations work, where a single indexer will access a row. But it is consistent with how pandas would turn the array into a dataframe or how matplotlib would plot it:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights_array = flights_wide.to_numpy()\\n\",\n \"sns.relplot(data=flights_array, kind=\\\"line\\\")\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"fileName":"horizontal_boxplot.py","filePath":"examples","id":2023,"nodeType":"File","text":"\"\"\"\nHorizontal boxplot with observations\n====================================\n\n_thumb: .7, .37\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"ticks\")\n\n# Initialize the figure with a logarithmic x axis\nf, ax = plt.subplots(figsize=(7, 6))\nax.set_xscale(\"log\")\n\n# Load the example planets dataset\nplanets = sns.load_dataset(\"planets\")\n\n# Plot the orbital period with horizontal boxes\nsns.boxplot(x=\"distance\", y=\"method\", data=planets,\n whis=[0, 100], width=.6, palette=\"vlag\")\n\n# Add in points to show each observation\nsns.stripplot(x=\"distance\", y=\"method\", data=planets,\n size=4, color=\".3\", linewidth=0)\n\n# Tweak the visual presentation\nax.xaxis.grid(True)\nax.set(ylabel=\"\")\nsns.despine(trim=True, left=True)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2024,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":2025,"name":"Vector","nodeType":"Attribute","startLoc":15,"text":"Vector"},{"className":"Rolling","col":0,"comment":"null","endLoc":103,"id":2026,"nodeType":"Class","startLoc":98,"text":"@dataclass\nclass Rolling(Stat):\n ...\n\n def __call__(self, data, groupby, orient, scales):\n ..."},{"col":4,"comment":"null","endLoc":103,"header":"def __call__(self, data, groupby, orient, scales)","id":2027,"name":"__call__","nodeType":"Function","startLoc":102,"text":"def __call__(self, data, groupby, orient, scales):\n ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":9,"id":2028,"name":"diamonds","nodeType":"Attribute","startLoc":9,"text":"diamonds"},{"className":"Dodge","col":0,"comment":"\n Displacement and narrowing of overlapping marks along orientation axis.\n ","endLoc":137,"id":2029,"nodeType":"Class","startLoc":80,"text":"@dataclass\nclass Dodge(Move):\n \"\"\"\n Displacement and narrowing of overlapping marks along orientation axis.\n \"\"\"\n empty: str = \"keep\" # Options: keep, drop, fill\n gap: float = 0\n\n # TODO accept just a str here?\n # TODO should this always be present?\n # TODO should the default be an \"all\" singleton?\n by: Optional[list[str]] = None\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n grouping_vars = [v for v in groupby.order if v in data]\n groups = groupby.agg(data, {\"width\": \"max\"})\n if self.empty == \"fill\":\n groups = groups.dropna()\n\n def groupby_pos(s):\n grouper = [groups[v] for v in [orient, \"col\", \"row\"] if v in data]\n return s.groupby(grouper, sort=False, observed=True)\n\n def scale_widths(w):\n # TODO what value to fill missing widths??? Hard problem...\n # TODO short circuit this if outer widths has no variance?\n empty = 0 if self.empty == \"fill\" else w.mean()\n filled = w.fillna(empty)\n scale = filled.max()\n norm = filled.sum()\n if self.empty == \"keep\":\n w = filled\n return w / norm * scale\n\n def widths_to_offsets(w):\n return w.shift(1).fillna(0).cumsum() + (w - w.sum()) / 2\n\n new_widths = groupby_pos(groups[\"width\"]).transform(scale_widths)\n offsets = groupby_pos(new_widths).transform(widths_to_offsets)\n\n if self.gap:\n new_widths *= 1 - self.gap\n\n groups[\"_dodged\"] = groups[orient] + offsets\n groups[\"width\"] = new_widths\n\n out = (\n data\n .drop(\"width\", axis=1)\n .merge(groups, on=grouping_vars, how=\"left\")\n .drop(orient, axis=1)\n .rename(columns={\"_dodged\": orient})\n )\n\n return out"},{"attributeType":"list","col":0,"comment":"null","endLoc":10,"id":2030,"name":"clarity_ranking","nodeType":"Attribute","startLoc":10,"text":"clarity_ranking"},{"col":0,"comment":"","endLoc":5,"header":"large_distributions.py#","id":2031,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPlotting large distributions\n============================\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\n\nclarity_ranking = [\"I1\", \"SI2\", \"SI1\", \"VS2\", \"VS1\", \"VVS2\", \"VVS1\", \"IF\"]\n\nsns.boxenplot(x=\"clarity\", y=\"carat\",\n color=\"b\", order=clarity_ranking,\n scale=\"linear\", data=diamonds)"},{"col":0,"comment":"null","endLoc":2415,"header":"def boxenplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75,\n width=.8, dodge=True, k_depth='tukey', linewidth=None,\n scale='exponential', outlier_prop=0.007, trust_alpha=0.05,\n showfliers=True,\n ax=None, box_kws=None, flier_kws=None, line_kws=None,\n)","id":2032,"name":"boxenplot","nodeType":"Function","startLoc":2398,"text":"def boxenplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75,\n width=.8, dodge=True, k_depth='tukey', linewidth=None,\n scale='exponential', outlier_prop=0.007, trust_alpha=0.05,\n showfliers=True,\n ax=None, box_kws=None, flier_kws=None, line_kws=None,\n):\n plotter = _LVPlotter(x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale,\n outlier_prop, trust_alpha, showfliers)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, box_kws, flier_kws, line_kws)\n return ax"},{"className":"TestLinePlotter","col":0,"comment":"null","endLoc":1292,"id":2033,"nodeType":"Class","startLoc":662,"text":"class TestLinePlotter(SharedAxesLevelTests, Helpers):\n\n func = staticmethod(lineplot)\n\n def get_last_color(self, ax):\n\n return to_rgba(ax.lines[-1].get_color())\n\n def test_legend_data(self, long_df):\n\n f, ax = plt.subplots()\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert handles == []\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n assert labels == p._hue_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n markers = [h.get_marker() for h in handles]\n assert labels == p._hue_map.levels\n assert labels == p._style_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n assert markers == p._style_map(p._style_map.levels, \"marker\")\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n markers = [h.get_marker() for h in handles]\n expected_labels = (\n [\"a\"]\n + p._hue_map.levels\n + [\"b\"] + p._style_map.levels\n )\n expected_colors = (\n [\"w\"] + p._hue_map(p._hue_map.levels)\n + [\"w\"] + [\".2\" for _ in p._style_map.levels]\n )\n expected_markers = (\n [\"\"] + [\"None\" for _ in p._hue_map.levels]\n + [\"\"] + p._style_map(p._style_map.levels, \"marker\")\n )\n assert labels == expected_labels\n assert colors == expected_colors\n assert markers == expected_markers\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"a\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n widths = [h.get_linewidth() for h in handles]\n assert labels == p._hue_map.levels\n assert labels == p._size_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n assert widths == p._size_map(p._size_map.levels)\n\n # --\n\n x, y = np.random.randn(2, 40)\n z = np.tile(np.arange(20), 2)\n\n p = _LinePlotter(variables=dict(x=x, y=y, hue=z))\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._hue_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._hue_map.levels)\n\n p = _LinePlotter(variables=dict(x=x, y=y, size=z))\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._size_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"auto\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = True\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"bad_value\"\n with pytest.raises(ValueError):\n p.add_legend_data(ax)\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, hue=z + 1),\n legend=\"brief\"\n )\n p.map_hue(norm=mpl.colors.LogNorm()),\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert float(labels[1]) / float(labels[0]) == 10\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, hue=z % 2),\n legend=\"auto\"\n )\n p.map_hue(norm=mpl.colors.LogNorm()),\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [\"0\", \"1\"]\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, size=z + 1),\n legend=\"brief\"\n )\n p.map_size(norm=mpl.colors.LogNorm())\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert float(labels[1]) / float(labels[0]) == 10\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"f\"),\n legend=\"brief\",\n )\n p.add_legend_data(ax)\n expected_labels = ['0.20', '0.22', '0.24', '0.26', '0.28']\n handles, labels = ax.get_legend_handles_labels()\n assert labels == expected_labels\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"f\"),\n legend=\"brief\",\n )\n p.add_legend_data(ax)\n expected_levels = ['0.20', '0.22', '0.24', '0.26', '0.28']\n handles, labels = ax.get_legend_handles_labels()\n assert labels == expected_levels\n\n def test_plot(self, long_df, repeated_df):\n\n f, ax = plt.subplots()\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n sort=False,\n estimator=None\n )\n p.plot(ax, {})\n line, = ax.lines\n assert_array_equal(line.get_xdata(), long_df.x.to_numpy())\n assert_array_equal(line.get_ydata(), long_df.y.to_numpy())\n\n ax.clear()\n p.plot(ax, {\"color\": \"k\", \"label\": \"test\"})\n line, = ax.lines\n assert line.get_color() == \"k\"\n assert line.get_label() == \"test\"\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n sort=True, estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n sorted_data = long_df.sort_values([\"x\", \"y\"])\n assert_array_equal(line.get_xdata(), sorted_data.x.to_numpy())\n assert_array_equal(line.get_ydata(), sorted_data.y.to_numpy())\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._hue_map.levels)\n for line, level in zip(ax.lines, p._hue_map.levels):\n assert line.get_color() == p._hue_map(level)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._size_map.levels)\n for line, level in zip(ax.lines, p._size_map.levels):\n assert line.get_linewidth() == p._size_map(level)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._hue_map.levels)\n assert len(ax.lines) == len(p._style_map.levels)\n for line, level in zip(ax.lines, p._hue_map.levels):\n assert line.get_color() == p._hue_map(level)\n assert line.get_marker() == p._style_map(level, \"marker\")\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n levels = product(p._hue_map.levels, p._style_map.levels)\n expected_line_count = len(p._hue_map.levels) * len(p._style_map.levels)\n assert len(ax.lines) == expected_line_count\n for line, (hue, style) in zip(ax.lines, levels):\n assert line.get_color() == p._hue_map(hue)\n assert line.get_marker() == p._style_map(style, \"marker\")\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n estimator=\"mean\", err_style=\"band\", errorbar=\"sd\", sort=True\n )\n\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n expected_data = long_df.groupby(\"x\").y.mean()\n assert_array_equal(line.get_xdata(), expected_data.index.to_numpy())\n assert np.allclose(line.get_ydata(), expected_data.to_numpy())\n assert len(ax.collections) == 1\n\n # Test that nans do not propagate to means or CIs\n\n p = _LinePlotter(\n variables=dict(\n x=[1, 1, 1, 2, 2, 2, 3, 3, 3],\n y=[1, 2, 3, 3, np.nan, 5, 4, 5, 6],\n ),\n estimator=\"mean\", err_style=\"band\", errorbar=\"ci\", n_boot=100, sort=True,\n )\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n assert line.get_xdata().tolist() == [1, 2, 3]\n err_band = ax.collections[0].get_paths()\n assert len(err_band) == 1\n assert len(err_band[0].vertices) == 9\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n estimator=\"mean\", err_style=\"band\", errorbar=\"sd\"\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(ax.collections) == len(p._hue_map.levels)\n for c in ax.collections:\n assert isinstance(c, mpl.collections.PolyCollection)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n estimator=\"mean\", err_style=\"bars\", errorbar=\"sd\"\n )\n\n ax.clear()\n p.plot(ax, {})\n n_lines = len(ax.lines)\n assert n_lines / 2 == len(ax.collections) == len(p._hue_map.levels)\n assert len(ax.collections) == len(p._hue_map.levels)\n for c in ax.collections:\n assert isinstance(c, mpl.collections.LineCollection)\n\n p = _LinePlotter(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", units=\"u\"),\n estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n n_units = len(repeated_df[\"u\"].unique())\n assert len(ax.lines) == n_units\n\n p = _LinePlotter(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", units=\"u\"),\n estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n n_units *= len(repeated_df[\"a\"].unique())\n assert len(ax.lines) == n_units\n\n p.estimator = \"mean\"\n with pytest.raises(ValueError):\n p.plot(ax, {})\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n err_style=\"band\", err_kws={\"alpha\": .5},\n )\n\n ax.clear()\n p.plot(ax, {})\n for band in ax.collections:\n assert band.get_alpha() == .5\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n err_style=\"bars\", err_kws={\"elinewidth\": 2},\n )\n\n ax.clear()\n p.plot(ax, {})\n for lines in ax.collections:\n assert lines.get_linestyles() == 2\n\n p.err_style = \"invalid\"\n with pytest.raises(ValueError):\n p.plot(ax, {})\n\n x_str = long_df[\"x\"].astype(str)\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n def test_orient(self, long_df):\n\n long_df = long_df.drop(\"x\", axis=1).rename(columns={\"s\": \"y\", \"y\": \"x\"})\n\n ax1 = plt.figure().subplots()\n lineplot(data=long_df, x=\"x\", y=\"y\", orient=\"y\", errorbar=\"sd\")\n assert len(ax1.lines) == len(ax1.collections)\n line, = ax1.lines\n expected = long_df.groupby(\"y\").agg({\"x\": \"mean\"}).reset_index()\n assert_array_almost_equal(line.get_xdata(), expected[\"x\"])\n assert_array_almost_equal(line.get_ydata(), expected[\"y\"])\n ribbon_y = ax1.collections[0].get_paths()[0].vertices[:, 1]\n assert_array_equal(np.unique(ribbon_y), long_df[\"y\"].sort_values().unique())\n\n ax2 = plt.figure().subplots()\n lineplot(\n data=long_df, x=\"x\", y=\"y\", orient=\"y\", errorbar=\"sd\", err_style=\"bars\"\n )\n segments = ax2.collections[0].get_segments()\n for i, val in enumerate(sorted(long_df[\"y\"].unique())):\n assert (segments[i][:, 1] == val).all()\n\n with pytest.raises(ValueError, match=\"`orient` must be either 'x' or 'y'\"):\n lineplot(long_df, x=\"y\", y=\"x\", orient=\"bad\")\n\n def test_log_scale(self):\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n\n x = [1, 10, 100]\n y = [1, 2, 3]\n\n lineplot(x=x, y=y)\n line = ax.lines[0]\n assert_array_equal(line.get_xdata(), x)\n assert_array_equal(line.get_ydata(), y)\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n\n x = [1, 1, 2, 2]\n y = [1, 10, 1, 100]\n\n lineplot(x=x, y=y, err_style=\"bars\", errorbar=(\"pi\", 100))\n line = ax.lines[0]\n assert line.get_ydata()[1] == 10\n\n ebars = ax.collections[0].get_segments()\n assert_array_equal(ebars[0][:, 1], y[:2])\n assert_array_equal(ebars[1][:, 1], y[2:])\n\n def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n\n p.plot(ax1, {})\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n\n p.plot(ax2, {})\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()\n\n def test_matplotlib_kwargs(self, long_df):\n\n kws = {\n \"linestyle\": \"--\",\n \"linewidth\": 3,\n \"color\": (1, .5, .2),\n \"markeredgecolor\": (.2, .5, .2),\n \"markeredgewidth\": 1,\n }\n ax = lineplot(data=long_df, x=\"x\", y=\"y\", **kws)\n\n line, *_ = ax.lines\n for key, val in kws.items():\n plot_val = getattr(line, f\"get_{key}\")()\n assert plot_val == val\n\n def test_nonmapped_dashes(self):\n\n ax = lineplot(x=[1, 2], y=[1, 2], dashes=(2, 1))\n line = ax.lines[0]\n # Not a great test, but lines don't expose the dash style publicly\n assert line.get_linestyle() == \"--\"\n\n def test_lineplot_axes(self, wide_df):\n\n f1, ax1 = plt.subplots()\n f2, ax2 = plt.subplots()\n\n ax = lineplot(data=wide_df)\n assert ax is ax2\n\n ax = lineplot(data=wide_df, ax=ax1)\n assert ax is ax1\n\n def test_lineplot_vs_relplot(self, long_df, long_semantics):\n\n ax = lineplot(data=long_df, **long_semantics)\n g = relplot(data=long_df, kind=\"line\", **long_semantics)\n\n lin_lines = ax.lines\n rel_lines = g.ax.lines\n\n for l1, l2 in zip(lin_lines, rel_lines):\n assert_array_equal(l1.get_xydata(), l2.get_xydata())\n assert same_color(l1.get_color(), l2.get_color())\n assert l1.get_linewidth() == l2.get_linewidth()\n assert l1.get_linestyle() == l2.get_linestyle()\n\n def test_lineplot_smoke(\n self,\n wide_df, wide_array,\n wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n flat_array, flat_series, flat_list,\n long_df, missing_df, object_df\n ):\n\n f, ax = plt.subplots()\n\n lineplot(x=[], y=[])\n ax.clear()\n\n lineplot(data=wide_df)\n ax.clear()\n\n lineplot(data=wide_array)\n ax.clear()\n\n lineplot(data=wide_list_of_series)\n ax.clear()\n\n lineplot(data=wide_list_of_arrays)\n ax.clear()\n\n lineplot(data=wide_list_of_lists)\n ax.clear()\n\n lineplot(data=flat_series)\n ax.clear()\n\n lineplot(data=flat_array)\n ax.clear()\n\n lineplot(data=flat_list)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", data=long_df)\n ax.clear()\n\n lineplot(x=long_df.x, y=long_df.y)\n ax.clear()\n\n lineplot(x=long_df.x, y=\"y\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=long_df.y.to_numpy(), data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"t\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"f\", data=object_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"c\", size=\"f\", data=object_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"f\", size=\"s\", data=object_df)\n ax.clear()\n\n def test_ci_deprecation(self, long_df):\n\n axs = plt.figure().subplots(2)\n lineplot(data=long_df, x=\"x\", y=\"y\", errorbar=(\"ci\", 95), seed=0, ax=axs[0])\n with pytest.warns(FutureWarning, match=\"\\n\\nThe `ci` parameter is deprecated\"):\n lineplot(data=long_df, x=\"x\", y=\"y\", ci=95, seed=0, ax=axs[1])\n assert_plots_equal(*axs)\n\n axs = plt.figure().subplots(2)\n lineplot(data=long_df, x=\"x\", y=\"y\", errorbar=\"sd\", ax=axs[0])\n with pytest.warns(FutureWarning, match=\"\\n\\nThe `ci` parameter is deprecated\"):\n lineplot(data=long_df, x=\"x\", y=\"y\", ci=\"sd\", ax=axs[1])\n assert_plots_equal(*axs)"},{"col":4,"comment":"null","endLoc":668,"header":"def get_last_color(self, ax)","id":2034,"name":"get_last_color","nodeType":"Function","startLoc":666,"text":"def get_last_color(self, ax):\n\n return to_rgba(ax.lines[-1].get_color())"},{"col":4,"comment":"null","endLoc":1785,"header":"def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale, outlier_prop,\n trust_alpha, showfliers=True)","id":2035,"name":"__init__","nodeType":"Function","startLoc":1746,"text":"def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale, outlier_prop,\n trust_alpha, showfliers=True):\n\n self.width = width\n self.dodge = dodge\n self.saturation = saturation\n\n k_depth_methods = ['proportion', 'tukey', 'trustworthy', 'full']\n if not (k_depth in k_depth_methods or isinstance(k_depth, Number)):\n msg = (f'k_depth must be one of {k_depth_methods} or a number, '\n f'but {k_depth} was passed.')\n raise ValueError(msg)\n self.k_depth = k_depth\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n scales = ['linear', 'exponential', 'area']\n if scale not in scales:\n msg = f'scale must be one of {scales}, but {scale} was passed.'\n raise ValueError(msg)\n self.scale = scale\n\n if ((outlier_prop > 1) or (outlier_prop <= 0)):\n msg = f'outlier_prop {outlier_prop} not in range (0, 1]'\n raise ValueError(msg)\n self.outlier_prop = outlier_prop\n\n if not 0 < trust_alpha < 1:\n msg = f'trust_alpha {trust_alpha} not in range (0, 1)'\n raise ValueError(msg)\n self.trust_alpha = trust_alpha\n\n self.showfliers = showfliers\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)"},{"col":4,"comment":"null","endLoc":862,"header":"def test_legend_data(self, long_df)","id":2036,"name":"test_legend_data","nodeType":"Function","startLoc":670,"text":"def test_legend_data(self, long_df):\n\n f, ax = plt.subplots()\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert handles == []\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n assert labels == p._hue_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n markers = [h.get_marker() for h in handles]\n assert labels == p._hue_map.levels\n assert labels == p._style_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n assert markers == p._style_map(p._style_map.levels, \"marker\")\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n markers = [h.get_marker() for h in handles]\n expected_labels = (\n [\"a\"]\n + p._hue_map.levels\n + [\"b\"] + p._style_map.levels\n )\n expected_colors = (\n [\"w\"] + p._hue_map(p._hue_map.levels)\n + [\"w\"] + [\".2\" for _ in p._style_map.levels]\n )\n expected_markers = (\n [\"\"] + [\"None\" for _ in p._hue_map.levels]\n + [\"\"] + p._style_map(p._style_map.levels, \"marker\")\n )\n assert labels == expected_labels\n assert colors == expected_colors\n assert markers == expected_markers\n\n # --\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"a\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_color() for h in handles]\n widths = [h.get_linewidth() for h in handles]\n assert labels == p._hue_map.levels\n assert labels == p._size_map.levels\n assert colors == p._hue_map(p._hue_map.levels)\n assert widths == p._size_map(p._size_map.levels)\n\n # --\n\n x, y = np.random.randn(2, 40)\n z = np.tile(np.arange(20), 2)\n\n p = _LinePlotter(variables=dict(x=x, y=y, hue=z))\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._hue_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._hue_map.levels)\n\n p = _LinePlotter(variables=dict(x=x, y=y, size=z))\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._size_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"auto\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = True\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"bad_value\"\n with pytest.raises(ValueError):\n p.add_legend_data(ax)\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, hue=z + 1),\n legend=\"brief\"\n )\n p.map_hue(norm=mpl.colors.LogNorm()),\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert float(labels[1]) / float(labels[0]) == 10\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, hue=z % 2),\n legend=\"auto\"\n )\n p.map_hue(norm=mpl.colors.LogNorm()),\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [\"0\", \"1\"]\n\n ax.clear()\n p = _LinePlotter(\n variables=dict(x=x, y=y, size=z + 1),\n legend=\"brief\"\n )\n p.map_size(norm=mpl.colors.LogNorm())\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert float(labels[1]) / float(labels[0]) == 10\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"f\"),\n legend=\"brief\",\n )\n p.add_legend_data(ax)\n expected_labels = ['0.20', '0.22', '0.24', '0.26', '0.28']\n handles, labels = ax.get_legend_handles_labels()\n assert labels == expected_labels\n\n ax.clear()\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"f\"),\n legend=\"brief\",\n )\n p.add_legend_data(ax)\n expected_levels = ['0.20', '0.22', '0.24', '0.26', '0.28']\n handles, labels = ax.get_legend_handles_labels()\n assert labels == expected_levels"},{"col":0,"comment":"null","endLoc":179,"header":"def function_overview()","id":2037,"name":"function_overview","nodeType":"Function","startLoc":130,"text":"def function_overview():\n\n from matplotlib.patches import FancyBboxPatch\n\n f = mpl.figure.Figure(figsize=(7, 5))\n with sns.axes_style(\"white\"):\n ax = f.subplots()\n f.subplots_adjust(0, 0, 1, 1)\n ax.set_axis_off()\n ax.set(xlim=(0, 1), ylim=(0, 1))\n\n deep = sns.color_palette(\"deep\")\n colors = dict(relational=deep[0], distributions=deep[1], categorical=deep[2])\n dark = sns.color_palette(\"dark\")\n text_colors = dict(relational=dark[0], distributions=dark[1], categorical=dark[2])\n\n functions = dict(\n relational=[\"scatterplot\", \"lineplot\"],\n distributions=[\"histplot\", \"kdeplot\", \"ecdfplot\", \"rugplot\"],\n categorical=[\n \"stripplot\", \"swarmplot\", \"boxplot\", \"violinplot\", \"pointplot\", \"barplot\"\n ],\n )\n pad, w, h = .06, .2, .15\n xs, y = np.arange(0, 1, 1 / 3) + pad * 1.05, .7\n for x, mod in zip(xs, functions):\n color = colors[mod] + (.2,)\n text_color = text_colors[mod]\n ax.add_artist(FancyBboxPatch((x, y), w, h, f\"round,pad={pad}\", color=\"white\"))\n ax.add_artist(FancyBboxPatch(\n (x, y), w, h, f\"round,pad={pad}\",\n linewidth=1, edgecolor=text_color, facecolor=color,\n ))\n ax.text(\n x + w / 2, y + h / 2, f\"{mod[:3]}plot\\n({mod})\",\n ha=\"center\", va=\"center\", size=20, color=text_color\n )\n for i, func in enumerate(functions[mod]):\n x_i, y_i = x + w / 2, y - i * .1 - h / 2 - pad\n xy = x_i - w / 2, y_i - pad / 3\n ax.add_artist(\n FancyBboxPatch(xy, w, h / 4, f\"round,pad={pad / 3}\", color=\"white\")\n )\n ax.add_artist(FancyBboxPatch(\n xy, w, h / 4, f\"round,pad={pad / 3}\",\n linewidth=1, edgecolor=text_color, facecolor=color\n ))\n ax.text(x_i, y_i, func, ha=\"center\", va=\"center\", size=16, color=text_color)\n ax.plot([x_i, x_i], [y, y_i], zorder=-100, color=text_color, lw=1)\n return f"},{"className":"Move","col":0,"comment":"Base class for objects that apply simple positional transforms.","endLoc":24,"id":2038,"nodeType":"Class","startLoc":15,"text":"@dataclass\nclass Move:\n \"\"\"Base class for objects that apply simple positional transforms.\"\"\"\n\n group_by_orient: ClassVar[bool] = True\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n raise NotImplementedError"},{"col":4,"comment":"null","endLoc":24,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":2039,"name":"__call__","nodeType":"Function","startLoc":21,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n raise NotImplementedError"},{"attributeType":"bool","col":4,"comment":"null","endLoc":19,"id":2040,"name":"group_by_orient","nodeType":"Attribute","startLoc":19,"text":"group_by_orient"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":2041,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":2042,"name":"f","nodeType":"Attribute","startLoc":13,"text":"f"},{"attributeType":"null","col":3,"comment":"null","endLoc":13,"id":2043,"name":"ax","nodeType":"Attribute","startLoc":13,"text":"ax"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":2044,"name":"planets","nodeType":"Attribute","startLoc":17,"text":"planets"},{"id":2045,"name":"objects.Dot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"tips = load_dataset(\\\"tips\\\")\\n\",\n \"glue = load_dataset(\\\"glue\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f8e7b343-0301-49b3-8d42-862266d322bb\",\n \"metadata\": {},\n \"source\": [\n \"This mark draws relatively large, filled dots by default:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f92e97d0-b6a5-41ec-8507-dc64e60cb6e0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p1 = so.Plot(tips, \\\"total_bill\\\", \\\"tip\\\")\\n\",\n \"p1.add(so.Dot())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"625abe2a-7b0b-42a7-bfbc-dc2bfaf14897\",\n \"metadata\": {},\n \"source\": [\n \"While :class:`Dots` is a better choice for dense scatter plots, adding a thin edge can help to resolve individual points:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a3c7c22d-c7ce-40a9-941b-a8bc30db1e54\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p1.add(so.Dot(edgecolor=\\\"w\\\"))\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"398a43e1-4d45-42ea-bc87-41a8602540a4\",\n \"metadata\": {},\n \"source\": [\n \"Dodging and jittering can also help to reduce overplotting, when appropriate:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1b15e393-35cf-457f-8180-d92d05e2675a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, \\\"total_bill\\\", \\\"day\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Dot(), so.Dodge(), so.Jitter(.2))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"12453ada-40e6-4aad-9f32-ba41fd7b27ca\",\n \"metadata\": {},\n \"source\": [\n \"The larger dot size makes this mark well suited to representing values along a nominal scale:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"bd2edac0-ee6b-4cc9-8201-641b589630b8\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p2 = so.Plot(glue, \\\"Score\\\", \\\"Model\\\").facet(\\\"Task\\\", wrap=4).limit(x=(-5, 105))\\n\",\n \"p2.add(so.Dot())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"ddd86209-d5cd-4f7a-9274-c578bc6a9f07\",\n \"metadata\": {},\n \"source\": [\n \"A number of properties can be set or mapped:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d00cdc35-4b9c-4f32-a047-8e036e565c4f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" p2\\n\",\n \" .add(so.Dot(pointsize=6), color=\\\"Year\\\", marker=\\\"Encoder\\\")\\n\",\n \" .scale(marker=[\\\"o\\\", \\\"s\\\"], color=\\\"flare\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"061e22f4-8505-425d-8c80-8ac82c6a3125\",\n \"metadata\": {},\n \"source\": [\n \"Note that the edge properties are parameterized differently for filled and unfilled markers; use `stroke` and `color` rather than `edgewidth` and `edgecolor` if the marker is unfilled:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"964b00be-1c29-4664-838d-0daeead9154a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p2.add(so.Dot(stroke=1.5), fill=\\\"Encoder\\\", color=\\\"Encoder\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fb5e1383-1460-4389-a67b-09ec7965af90\",\n \"metadata\": {},\n \"source\": [\n \"Combine with :class:`Range` to show error bars:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b2618c22-bc7f-4ddd-9824-346e8d9b2b51\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(tips, x=\\\"total_bill\\\", y=\\\"day\\\")\\n\",\n \" .add(so.Dot(pointsize=3), so.Shift(y=.2), so.Jitter(.2))\\n\",\n \" .add(so.Dot(), so.Agg())\\n\",\n \" .add(so.Range(), so.Est(errorbar=(\\\"se\\\", 2)))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e5dc04fd-dba4-4b86-99a1-31ba00c7650d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":137,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":2046,"name":"__call__","nodeType":"Function","startLoc":93,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n grouping_vars = [v for v in groupby.order if v in data]\n groups = groupby.agg(data, {\"width\": \"max\"})\n if self.empty == \"fill\":\n groups = groups.dropna()\n\n def groupby_pos(s):\n grouper = [groups[v] for v in [orient, \"col\", \"row\"] if v in data]\n return s.groupby(grouper, sort=False, observed=True)\n\n def scale_widths(w):\n # TODO what value to fill missing widths??? Hard problem...\n # TODO short circuit this if outer widths has no variance?\n empty = 0 if self.empty == \"fill\" else w.mean()\n filled = w.fillna(empty)\n scale = filled.max()\n norm = filled.sum()\n if self.empty == \"keep\":\n w = filled\n return w / norm * scale\n\n def widths_to_offsets(w):\n return w.shift(1).fillna(0).cumsum() + (w - w.sum()) / 2\n\n new_widths = groupby_pos(groups[\"width\"]).transform(scale_widths)\n offsets = groupby_pos(new_widths).transform(widths_to_offsets)\n\n if self.gap:\n new_widths *= 1 - self.gap\n\n groups[\"_dodged\"] = groups[orient] + offsets\n groups[\"width\"] = new_widths\n\n out = (\n data\n .drop(\"width\", axis=1)\n .merge(groups, on=grouping_vars, how=\"left\")\n .drop(orient, axis=1)\n .rename(columns={\"_dodged\": orient})\n )\n\n return out"},{"col":0,"comment":"","endLoc":6,"header":"horizontal_boxplot.py#","id":2047,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nHorizontal boxplot with observations\n====================================\n\n_thumb: .7, .37\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\nf, ax = plt.subplots(figsize=(7, 6))\n\nax.set_xscale(\"log\")\n\nplanets = sns.load_dataset(\"planets\")\n\nsns.boxplot(x=\"distance\", y=\"method\", data=planets,\n whis=[0, 100], width=.6, palette=\"vlag\")\n\nsns.stripplot(x=\"distance\", y=\"method\", data=planets,\n size=4, color=\".3\", linewidth=0)\n\nax.xaxis.grid(True)\n\nax.set(ylabel=\"\")\n\nsns.despine(trim=True, left=True)"},{"col":0,"comment":"null","endLoc":14,"header":"def test_objects_namespace()","id":2048,"name":"test_objects_namespace","nodeType":"Function","startLoc":9,"text":"def test_objects_namespace():\n\n for name in dir(seaborn.objects):\n if not name.startswith(\"__\"):\n obj = getattr(seaborn.objects, name)\n assert issubclass(obj, (Plot, Mark, Stat, Move, Scale))"},{"attributeType":"null","col":16,"comment":"null","endLoc":3,"id":2049,"name":"np","nodeType":"Attribute","startLoc":3,"text":"np"},{"col":4,"comment":"null","endLoc":1343,"header":"def test_required_scipy_errors()","id":2050,"name":"test_required_scipy_errors","nodeType":"Function","startLoc":1332,"text":"def test_required_scipy_errors():\n\n x = np.random.normal(0, 1, (10, 10))\n\n with pytest.raises(RuntimeError):\n mat.clustermap(x)\n\n with pytest.raises(RuntimeError):\n mat.ClusterGrid(x)\n\n with pytest.raises(RuntimeError):\n mat.dendrogram(x)"},{"col":0,"comment":"null","endLoc":2550,"header":"def stripplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n jitter=True, dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0,\n hue_norm=None, native_scale=False, formatter=None, legend=\"auto\",\n ax=None, **kwargs\n)","id":2051,"name":"stripplot","nodeType":"Function","startLoc":2494,"text":"def stripplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n jitter=True, dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0,\n hue_norm=None, native_scale=False, formatter=None, legend=\"auto\",\n ax=None, **kwargs\n):\n\n p = _CategoricalPlotterNew(\n data=data,\n variables=_CategoricalPlotterNew.get_semantics(locals()),\n order=order,\n orient=orient,\n require_numeric=False,\n legend=legend,\n )\n\n if ax is None:\n ax = plt.gca()\n\n if p.var_types.get(p.cat_axis) == \"categorical\" or not native_scale:\n p.scale_categorical(p.cat_axis, order=order, formatter=formatter)\n\n p._attach(ax)\n\n hue_order = p._palette_without_hue_backcompat(palette, hue_order)\n palette, hue_order = p._hue_backcompat(color, palette, hue_order)\n\n color = _default_color(ax.scatter, hue, color, kwargs)\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # XXX Copying possibly bad default decisions from original code for now\n kwargs.setdefault(\"zorder\", 3)\n size = kwargs.get(\"s\", size)\n\n kwargs.update(dict(\n s=size ** 2,\n edgecolor=edgecolor,\n linewidth=linewidth)\n )\n\n p.plot_strips(\n jitter=jitter,\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n plot_kws=kwargs,\n )\n\n # XXX this happens inside a plotting method in the distribution plots\n # but maybe it's better out here? Alternatively, we have an open issue\n # suggesting that _attach could add default axes labels, which seems smart.\n p._add_axis_labels(ax)\n p._adjust_cat_axis(ax, axis=p.cat_axis)\n\n return ax"},{"attributeType":"null","col":16,"comment":"null","endLoc":4,"id":2053,"name":"np","nodeType":"Attribute","startLoc":4,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":2054,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":6,"id":2055,"name":"plt","nodeType":"Attribute","startLoc":6,"text":"plt"},{"attributeType":"null","col":17,"comment":"null","endLoc":7,"id":2056,"name":"pd","nodeType":"Attribute","startLoc":7,"text":"pd"},{"attributeType":"bool","col":4,"comment":"null","endLoc":12,"id":2057,"name":"_no_scipy","nodeType":"Attribute","startLoc":12,"text":"_no_scipy"},{"attributeType":"bool","col":4,"comment":"null","endLoc":14,"id":2058,"name":"_no_scipy","nodeType":"Attribute","startLoc":14,"text":"_no_scipy"},{"attributeType":"bool","col":4,"comment":"null","endLoc":19,"id":2059,"name":"_no_fastcluster","nodeType":"Attribute","startLoc":19,"text":"_no_fastcluster"},{"attributeType":"bool","col":4,"comment":"null","endLoc":21,"id":2060,"name":"_no_fastcluster","nodeType":"Attribute","startLoc":21,"text":"_no_fastcluster"},{"attributeType":"null","col":24,"comment":"null","endLoc":23,"id":2061,"name":"npt","nodeType":"Attribute","startLoc":23,"text":"npt"},{"attributeType":"null","col":29,"comment":"null","endLoc":25,"id":2062,"name":"pdt","nodeType":"Attribute","startLoc":25,"text":"pdt"},{"attributeType":"null","col":34,"comment":"null","endLoc":27,"id":2063,"name":"pdt","nodeType":"Attribute","startLoc":27,"text":"pdt"},{"attributeType":"null","col":30,"comment":"null","endLoc":30,"id":2064,"name":"mat","nodeType":"Attribute","startLoc":30,"text":"mat"},{"col":0,"comment":"","endLoc":1,"header":"test_matrix.py#","id":2065,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n from scipy.spatial import distance\n from scipy.cluster import hierarchy\n _no_scipy = False\nexcept ImportError:\n _no_scipy = True\n\ntry:\n import fastcluster\n assert fastcluster\n _no_fastcluster = False\nexcept ImportError:\n _no_fastcluster = True\n\ntry:\n import pandas.testing as pdt\nexcept ImportError:\n import pandas.util.testing as pdt\n\nif _no_scipy:\n\n def test_required_scipy_errors():\n\n x = np.random.normal(0, 1, (10, 10))\n\n with pytest.raises(RuntimeError):\n mat.clustermap(x)\n\n with pytest.raises(RuntimeError):\n mat.ClusterGrid(x)\n\n with pytest.raises(RuntimeError):\n mat.dendrogram(x)"},{"col":0,"comment":"null","endLoc":38,"header":"@pytest.fixture\ndef wide_array(wide_df)","id":2066,"name":"wide_array","nodeType":"Function","startLoc":35,"text":"@pytest.fixture\ndef wide_array(wide_df):\n\n return wide_df.to_numpy()"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":2068,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":2069,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"id":2070,"name":"boxenplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"882d215b-88d8-4b5e-ae7a-0e3f6bb53bad\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6809326c-14a9-4314-994d-b4e8e7414172\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"df = sns.load_dataset(\\\"diamonds\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"9ccbc2d5-5a44-4e80-8b07-e12629729f4a\",\n \"metadata\": {},\n \"source\": [\n \"Draw a single horizontal plot, assigning the data directly to the coordinate variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"391e1162-b438-4486-9a08-60686ee8e96a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxenplot(x=df[\\\"price\\\"])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"a3b0e9b8-1673-494c-a27a-aa9c60457ba1\",\n \"metadata\": {},\n \"source\": [\n \"Group by a categorical variable, referencing columns in a datafame\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e30fec18-f127-40a3-bfaf-f71324dd60ec\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxenplot(data=df, x=\\\"price\\\", y=\\\"clarity\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"4f01a821-74d1-452d-a1f7-cf5b806169e8\",\n \"metadata\": {},\n \"source\": [\n \"Use a different scaling rule to control the width of each box:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d0c1aa43-5e8a-486c-bd6d-3c29d6d23138\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxenplot(data=df, x=\\\"carat\\\", y=\\\"cut\\\", scale=\\\"linear\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"fd5d197c-8cbb-4be3-a14d-76447f06d3f1\",\n \"metadata\": {},\n \"source\": [\n \"Use a different method to determine the number of boxes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1aead6a3-6f12-47d3-b472-a39c61867963\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.boxenplot(data=df, x=\\\"carat\\\", y=\\\"cut\\\", k_depth=\\\"trustworthy\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"719fd61f-9795-47d6-96bd-4929d8647038\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"attributeType":"str","col":4,"comment":"null","endLoc":85,"id":2071,"name":"empty","nodeType":"Attribute","startLoc":85,"text":"empty"},{"id":2072,"name":"licences","nodeType":"Package"},{"id":2073,"name":"NUMPYDOC_LICENSE","nodeType":"TextFile","path":"licences","text":"Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen \n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the\n distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n"},{"id":2074,"name":"properties.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"id\": \"6cb222bb-4781-48b6-9675-c0ba195b5efb\",\n \"metadata\": {},\n \"source\": [\n \".. _properties_tutorial:\\n\",\n \"\\n\",\n \"Properties of Mark objects\\n\",\n \"===========================\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ae9d52dc-55ad-4804-a533-f2b724d0b85b\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import pandas as pd\\n\",\n \"import matplotlib as mpl\\n\",\n \"import seaborn.objects as so\\n\",\n \"from seaborn import axes_style, color_palette\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dd828c60-3895-46e4-a2f4-782a6e6cd9a6\",\n \"metadata\": {},\n \"source\": [\n \"Coordinate properties\\n\",\n \"---------------------\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fa97cc40-f02f-477b-90ec-a764b7253b68\",\n \"metadata\": {},\n \"source\": [\n \".. _coordinate_property:\\n\",\n \"\\n\",\n \"x, y, xmin, xmax, ymin, ymax\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Coordinate properties determine where a mark is drawn on a plot. Canonically, the `x` coordinate is the horizontal positon and the `y` coordinate is the vertical position. Some marks accept a span (i.e., `min`, `max`) parameterization for one or both variables. Others may accept `x` and `y` but also use a `baseline` parameter to show a span. The layer's `orient` parameter determines how this works.\\n\",\n \"\\n\",\n \"If a variable does not contain numeric data, its scale will apply a conversion so that data can be drawn on a screen. For instance, :class:`Nominal` scales assign an integer index to each distinct category, and :class:`Temporal` scales represent dates as the number of days from a reference \\\"epoch\\\":\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"7b418365-b99c-45d6-bf1e-e347e2b9012a\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(y=[0, 0, 0])\\n\",\n \" .pair(x=[\\n\",\n \" [1, 2, 3],\\n\",\n \" [\\\"A\\\", \\\"B\\\", \\\"C\\\"],\\n\",\n \" np.array([\\\"2020-01-01\\\", \\\"2020-02-01\\\", \\\"2020-03-01\\\"], dtype=\\\"datetime64\\\"),\\n\",\n \" ])\\n\",\n \" .limit(\\n\",\n \" x0=(0, 10),\\n\",\n \" x1=(-.5, 2.5),\\n\",\n \" x2=(pd.Timestamp(\\\"2020-01-01\\\"), pd.Timestamp(\\\"2020-03-01\\\"))\\n\",\n \" )\\n\",\n \" .scale(y=so.Continuous().tick(count=0), x2=so.Temporal().label(concise=True))\\n\",\n \" .layout(size=(7, 1), engine=\\\"tight\\\")\\n\",\n \" .label(x0=\\\"Continuous\\\", x1=\\\"Nominal\\\", x2=\\\"Temporal\\\")\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" })\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0ae06665-2ce5-470d-b90a-02d990221fc5\",\n \"metadata\": {},\n \"source\": [\n \"A :class:`Continuous` scale can also apply a nonlinear transform between data values and spatial positions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b731a3bb-a52e-4b12-afbb-b036753adcbe\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(y=[0, 0, 0])\\n\",\n \" .pair(x=[[1, 10, 100], [-100, 0, 100], [0, 10, 40]])\\n\",\n \" .limit(\\n\",\n \" )\\n\",\n \" .add(so.Dot(marker=\\\"\\\"))\\n\",\n \" .scale(\\n\",\n \" y=so.Continuous().tick(count=0),\\n\",\n \" x0=so.Continuous(trans=\\\"log\\\"),\\n\",\n \" x1=so.Continuous(trans=\\\"symlog\\\").tick(at=[-100, -10, 0, 10, 100]),\\n\",\n \" x2=so.Continuous(trans=\\\"sqrt\\\").tick(every=10),\\n\",\n \" )\\n\",\n \" .layout(size=(7, 1), engine=\\\"tight\\\")\\n\",\n \" .label(x0=\\\"trans='log'\\\", x1=\\\"trans='symlog'\\\", x2=\\\"trans='sqrt'\\\")\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"axes.labelpad\\\": 8,\\n\",\n \" })\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e384941a-da38-4e12-997d-d750b19b1fa6\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\",\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"# Hiding from the page but keeping around for now\\n\",\n \"(\\n\",\n \" so.Plot()\\n\",\n \" .add(\\n\",\n \" so.Dot(edgewidth=3, stroke=3),\\n\",\n \" so.Dodge(by=[\\\"group\\\"]),\\n\",\n \" x=[\\\"A\\\", \\\"A\\\", \\\"A\\\", \\\"A\\\", \\\"A\\\"],\\n\",\n \" y=[1.75, 2.25, 2.75, 2.0, 2.5],\\n\",\n \" color=[1, 2, 3, 1, 3],\\n\",\n \" marker=[mpl.markers.MarkerStyle(x) for x in \\\"os^+o\\\"],\\n\",\n \" pointsize=(9, 9, 9, 13, 10),\\n\",\n \" fill=[True, False, True, True, False],\\n\",\n \" group=[1, 2, 3, 4, 5], width=.5, legend=False,\\n\",\n \" )\\n\",\n \" .add(\\n\",\n \" so.Bar(edgewidth=2.5, alpha=.2, width=.9),\\n\",\n \" so.Dodge(gap=.05),\\n\",\n \" x=[\\\"B\\\", \\\"B\\\", \\\"B\\\",], y=[2, 2.5, 1.75], color=[1, 2, 3],\\n\",\n \" legend=False,\\n\",\n \" )\\n\",\n \" .add(\\n\",\n \" so.Range({\\\"capstyle\\\": \\\"round\\\"}, linewidth=3),\\n\",\n \" so.Dodge(by=[\\\"group\\\"]),\\n\",\n \" x=[\\\"C\\\", \\\"C\\\", \\\"C\\\"], ymin=[1.5, 1.75, 1.25], ymax=[2.5, 2.75, 2.25],\\n\",\n \" color=[1, 2, 2], linestyle=[\\\"-\\\", \\\"-\\\", \\\":\\\"],\\n\",\n \" group=[1, 2, 3], width=.5, legend=False,\\n\",\n \" )\\n\",\n \" .layout(size=(4, 4), engine=None)\\n\",\n \" .limit(x=(-.5, 2.5), y=(0, 3))\\n\",\n \" .label(x=\\\"X Axis (nominal)\\\", y=\\\"Y Axis (continuous)\\\")\\n\",\n \" .scale(\\n\",\n \" color=\\\"dark:C0_r\\\", #None,\\n\",\n \" fill=None, marker=None,\\n\",\n \" pointsize=None, linestyle=None,\\n\",\n \" y=so.Continuous().tick(every=1, minor=1)\\n\",\n \" )\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" \\\"axes.spines.top\\\": False, \\\"axes.spines.right\\\": False,\\n\",\n \" \\\"axes.labelsize\\\": 14,\\n\",\n \" })\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"8279d74f-0cd0-4ba8-80ed-c6051541d956\",\n \"metadata\": {},\n \"source\": [\n \"Color properties\\n\",\n \"----------------\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fca25527-6bbe-42d6-beea-a996a46d9761\",\n \"metadata\": {},\n \"source\": [\n \".. _color_property:\\n\",\n \"\\n\",\n \"color, fillcolor, edgecolor\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"All marks can be given a `color`, and many distinguish between the color of the mark's \\\"edge\\\" and \\\"fill\\\". Often, simply using `color` will set both, while the more-specific properties allow further control:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ff7a1e64-7b02-45b8-b1e7-d7ec2bf1e7f7\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"no_spines = {\\n\",\n \" f\\\"axes.spines.{side}\\\": False\\n\",\n \" for side in [\\\"left\\\", \\\"right\\\", \\\"bottom\\\", \\\"top\\\"]\\n\",\n \"}\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1dda4c42-31f4-4316-baad-f30a465d3fd9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"color_mark = so.Dot(marker=\\\"s\\\", pointsize=20, edgewidth=2.5, alpha=.7, edgealpha=1)\\n\",\n \"color_plot = (\\n\",\n \" so.Plot()\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"white\\\"),\\n\",\n \" **no_spines,\\n\",\n \" \\\"axes.titlesize\\\": 15,\\n\",\n \" \\\"figure.subplot.wspace\\\": .1,\\n\",\n \" \\\"axes.xmargin\\\": .1,\\n\",\n \" })\\n\",\n \" .scale(\\n\",\n \" x=so.Continuous().tick(count=0),\\n\",\n \" y=so.Continuous().tick(count=0),\\n\",\n \" color=None, edgecolor=None,\\n\",\n \" )\\n\",\n \" .layout(size=(9, .5), engine=None)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"54fc98b4-dc4c-45e1-a2a7-840a724fc746\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"n = 6\\n\",\n \"rgb = [f\\\"C{i}\\\" for i in range(n)]\\n\",\n \"(\\n\",\n \" color_plot\\n\",\n \" .facet([\\\"color\\\"] * n + [\\\"edgecolor\\\"] * n + [\\\"fillcolor\\\"] * n)\\n\",\n \" .add(\\n\",\n \" color_mark,\\n\",\n \" x=np.tile(np.arange(n), 3),\\n\",\n \" y=np.zeros(n * 3),\\n\",\n \" color=rgb + [\\\".8\\\"] * n + rgb,\\n\",\n \" edgecolor=rgb + rgb + [\\\".3\\\"] * n,\\n\",\n \" legend=False,\\n\",\n \" )\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0dc26a01-6290-44f4-9815-5cea531207e2\",\n \"metadata\": {},\n \"source\": [\n \"When the color property is mapped, the default palette depends on the type of scale. Nominal scales use discrete, unordered hues, while continuous scales (including temporal ones) use a sequential gradient:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6927a0d3-687b-4ca0-a425-0376b39f1b1f\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"n = 9\\n\",\n \"rgb = color_palette(\\\"deep\\\", n) + color_palette(\\\"ch:\\\", n)\\n\",\n \"(\\n\",\n \" color_plot\\n\",\n \" .facet([\\\"nominal\\\"] * n + [\\\"continuous\\\"] * n)\\n\",\n \" .add(\\n\",\n \" color_mark,\\n\",\n \" x=list(range(n)) * 2,\\n\",\n \" y=[0] * n * 2,\\n\",\n \" color=rgb,\\n\",\n \" legend=False,\\n\",\n \" )\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e79d0da7-a53e-468c-9952-726eeae810d1\",\n \"metadata\": {},\n \"source\": [\n \".. note::\\n\",\n \" The default continuous scale is subject to change in future releases to improve discriminability.\\n\",\n \"\\n\",\n \"Color scales are parameterized by the name of a palette, such as `'viridis'`, `'rocket'`, or `'deep'`. Some palette names can include parameters, including simple gradients (e.g. `'dark:blue'`) or the cubehelix system (e.g. `'ch:start=.2,rot=-.4``). See the :doc:`color palette tutorial ` for guidance on making an appropriate selection.\\n\",\n \"\\n\",\n \"Continuous scales can also be parameterized by a tuple of colors that the scale should interpolate between. When using a nominal scale, it is possible to provide either the name of the palette (which will be discretely-sampled, if necessary), a list of individual color values, or a dictionary directly mapping data values to colors.\\n\",\n \"\\n\",\n \"Individual colors may be specified `in a wide range of formats `_. These include indexed references to the current color cycle (`'C0'`), single-letter shorthands (`'b'`), grayscale values (`'.4'`), RGB hex codes (`'#4c72b0'`), X11 color names (`'seagreen'`), and XKCD color survey names (`'purpleish'`):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ce7300dc-0ed2-4eb3-bd6f-2e42280f5e54\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"color_dict = {\\n\",\n \" \\\"cycle\\\": [\\\"C0\\\", \\\"C1\\\", \\\"C2\\\"],\\n\",\n \" \\\"short\\\": [\\\"r\\\", \\\"y\\\", \\\"b\\\"],\\n\",\n \" \\\"gray\\\": [\\\".3\\\", \\\".7\\\", \\\".5\\\"],\\n\",\n \" \\\"hex\\\": [\\\"#825f87\\\", \\\"#05696b\\\", \\\"#de7e5d\\\"],\\n\",\n \" \\\"X11\\\": [\\\"seagreen\\\", \\\"sienna\\\", \\\"darkblue\\\"],\\n\",\n \" \\\"XKCD\\\": [\\\"xkcd:gold\\\", \\\"xkcd:steel\\\", \\\"xkcd:plum\\\"],\\n\",\n \"}\\n\",\n \"groups = [k for k in color_dict for _ in range(3)]\\n\",\n \"colors = [c for pal in color_dict.values() for c in pal]\\n\",\n \"(\\n\",\n \" so.Plot(\\n\",\n \" x=[0] * len(colors),\\n\",\n \" y=[f\\\"'{c}'\\\" for c in colors],\\n\",\n \" color=colors,\\n\",\n \" )\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **no_spines,\\n\",\n \" \\\"axes.ymargin\\\": .2,\\n\",\n \" \\\"axes.titlesize\\\": 14,\\n\",\n \" \\n\",\n \" })\\n\",\n \" .facet(groups)\\n\",\n \" .layout(size=(8, 1.15), engine=\\\"constrained\\\")\\n\",\n \" .scale(x=so.Continuous().tick(count=0))\\n\",\n \" .add(color_mark)\\n\",\n \" .limit(x=(-.2, .5))\\n\",\n \" # .label(title=\\\"{} \\\".format)\\n\",\n \" .label(title=\\\"\\\")\\n\",\n \" .scale(color=None)\\n\",\n \" .share(y=False)\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4ea6ac35-2a73-4dec-8b9b-bf15ba67f01b\",\n \"metadata\": {},\n \"source\": [\n \".. _alpha_property:\\n\",\n \"\\n\",\n \"alpha, fillalpha, edgealpha\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The `alpha` property determines the mark's opacity. Lowering the alpha can be helpful for representing density in the case of overplotting:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e73839d2-27c4-42b8-8587-9f6e99c8a464\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"rng = np.random.default_rng(3)\\n\",\n \"n_samp = 300\\n\",\n \"x = 1 - rng.exponential(size=n_samp)\\n\",\n \"y = rng.uniform(-1, 1, size=n_samp)\\n\",\n \"keep = np.sqrt(x ** 2 + y ** 2) < 1\\n\",\n \"x, y = x[keep], y[keep]\\n\",\n \"n = keep.sum()\\n\",\n \"alpha_vals = np.linspace(.1, .9, 9).round(1)\\n\",\n \"xs = np.concatenate([x for _ in alpha_vals])\\n\",\n \"ys = np.concatenate([y for _ in alpha_vals])\\n\",\n \"alphas = np.repeat(alpha_vals, n)\\n\",\n \"(\\n\",\n \" so.Plot(x=xs, y=ys, alpha=alphas)\\n\",\n \" .facet(alphas)\\n\",\n \" .add(so.Dot(color=\\\".2\\\", pointsize=3))\\n\",\n \" .scale(\\n\",\n \" alpha=None,\\n\",\n \" x=so.Continuous().tick(count=0),\\n\",\n \" y=so.Continuous().tick(count=0)\\n\",\n \" )\\n\",\n \" .layout(size=(9, 1), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"white\\\"),\\n\",\n \" **no_spines,\\n\",\n \" })\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a551732e-e8f5-45f0-9345-7ef45248d9d7\",\n \"metadata\": {},\n \"source\": [\n \"Mapping the `alpha` property can also be useful even when marks do not overlap because it conveys a sense of importance and can be combined with a `color` scale to represent two variables. Moreover, colors with lower alpha appear less saturated, which can improve the appearance of larger filled marks (such as bars).\\n\",\n \"\\n\",\n \"As with `color`, some marks define separate `edgealpha` and `fillalpha` properties for additional control.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"77d168e4-0539-409f-8542-750d3981e22b\",\n \"metadata\": {},\n \"source\": [\n \"Style properties\\n\",\n \"----------------\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"95e342fa-1086-4e63-81ae-dce1c628df9b\",\n \"metadata\": {},\n \"source\": [\n \".. _fill_property:\\n\",\n \"\\n\",\n \"fill\\n\",\n \"~~~~\\n\",\n \"\\n\",\n \"The `fill` property is relevant to marks with a distinction between the edge and interior and determines whether the interior is visible. It is a boolean state: `fill` can be set only to `True` or `False`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5fb3b839-8bae-4392-b5f0-70dfc5a33c7a\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"nan = float(\\\"nan\\\")\\n\",\n \"x_bar = [0, 1]\\n\",\n \"y_bar = [2, 1]\\n\",\n \"f_bar = [True, False]\\n\",\n \"\\n\",\n \"x_dot = [2.2, 2.5, 2.8, 3.2, 3.5, 3.8]\\n\",\n \"y_dot = [1.2, 1.7, 1.4, 0.7, 1.2, 0.9]\\n\",\n \"f_dot = [True, True, True, False, False, False]\\n\",\n \"\\n\",\n \"xx = np.linspace(0, .8, 100)\\n\",\n \"yy = xx ** 2 * np.exp(-xx * 10)\\n\",\n \"x_area = list(4.5 + xx) + list(5.5 + xx)\\n\",\n \"y_area = list(yy / yy.max() * 2) + list(yy / yy.max())\\n\",\n \"f_area = [True] * 100 + [False] * 100\\n\",\n \"\\n\",\n \"(\\n\",\n \" so.Plot()\\n\",\n \" .add(\\n\",\n \" so.Bar(color=\\\".3\\\", edgecolor=\\\".2\\\", edgewidth=2.5),\\n\",\n \" x=x_bar + [nan for _ in x_dot + x_area],\\n\",\n \" y=y_bar + [nan for _ in y_dot + y_area],\\n\",\n \" fill=f_bar + [nan for _ in f_dot + f_area]\\n\",\n \" )\\n\",\n \" .add(\\n\",\n \" so.Dot(color=\\\".2\\\", pointsize=13, stroke=2.5),\\n\",\n \" x=[nan for _ in x_bar] + x_dot + [nan for _ in x_area],\\n\",\n \" y=[nan for _ in y_bar] + y_dot + [nan for _ in y_area],\\n\",\n \" fill=[nan for _ in f_bar] + f_dot + [nan for _ in f_area],\\n\",\n \" )\\n\",\n \" .add(\\n\",\n \" so.Area(color=\\\".2\\\", edgewidth=2.5),\\n\",\n \" x=[nan for _ in x_bar + x_dot] + x_area,\\n\",\n \" y=[nan for _ in y_bar + y_dot] + y_area,\\n\",\n \" fill=[nan for _ in f_bar + f_dot] + f_area,\\n\",\n \" )\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" \\\"axes.spines.left\\\": False,\\n\",\n \" \\\"axes.spines.top\\\": False,\\n\",\n \" \\\"axes.spines.right\\\": False,\\n\",\n \" \\\"xtick.labelsize\\\": 14,\\n\",\n \" })\\n\",\n \" .layout(size=(9, 1.25), engine=None)\\n\",\n \" .scale(\\n\",\n \" fill=None,\\n\",\n \" x=so.Continuous().tick(at=[0, 1, 2.5, 3.5, 4.8, 5.8]).label(\\n\",\n \" like={\\n\",\n \" 0: True, 1: False, 2.5: True, 3.5: False, 4.8: True, 5.8: False\\n\",\n \" }.get,\\n\",\n \" ),\\n\",\n \" y=so.Continuous().tick(count=0),\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"119741b0-9eca-45a1-983e-35effc49c7fa\",\n \"metadata\": {},\n \"source\": [\n \".. _marker_property:\\n\",\n \"\\n\",\n \"marker\\n\",\n \"~~~~~~\\n\",\n \"\\n\",\n \"The `marker` property is relevant for dot marks and some line marks. The API for specifying markers is very flexible, as detailed in the matplotlib API docs: :mod:`matplotlib.markers`.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"0ba9c5aa-3d9c-47c7-8aee-5851e1f3c4dd\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"marker_plot = (\\n\",\n \" so.Plot()\\n\",\n \" .scale(marker=None, y=so.Continuous().tick(count=0))\\n\",\n \" .layout(size=(10, .5), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" \\\"axes.spines.left\\\": False,\\n\",\n \" \\\"axes.spines.top\\\": False,\\n\",\n \" \\\"axes.spines.right\\\": False,\\n\",\n \" \\\"xtick.labelsize\\\":12,\\n\",\n \" \\\"axes.xmargin\\\": .02,\\n\",\n \" })\\n\",\n \"\\n\",\n \")\\n\",\n \"marker_mark = so.Dot(pointsize=15, color=\\\".2\\\", stroke=1.5)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3c07a874-18a1-485a-8d65-70ea3f246340\",\n \"metadata\": {},\n \"source\": [\n \"Markers can be specified using a number of simple string codes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6a764efd-df55-412b-8a01-8eba6f897893\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"marker_codes = [\\n\",\n \" \\\"o\\\", \\\"^\\\", \\\"v\\\", \\\"<\\\", \\\">\\\",\\\"s\\\", \\\"D\\\", \\\"d\\\", \\\"p\\\", \\\"h\\\", \\\"H\\\", \\\"8\\\",\\n\",\n \" \\\"X\\\", \\\"*\\\", \\\".\\\", \\\"P\\\", \\\"x\\\", \\\"+\\\", \\\"1\\\", \\\"2\\\", \\\"3\\\", \\\"4\\\", \\\"|\\\", \\\"_\\\",\\n\",\n \"]\\n\",\n \"x, y = [f\\\"'{m}'\\\" for m in marker_codes], [0] * len(marker_codes)\\n\",\n \"marker_objs = [mpl.markers.MarkerStyle(m) for m in marker_codes]\\n\",\n \"marker_plot.add(marker_mark, marker=marker_objs, x=x, y=y).plot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1c614f08-3aa4-450d-bfe2-3295c29155d5\",\n \"metadata\": {},\n \"source\": [\n \"They can also be programatically generated using a `(num_sides, fill_style, angle)` tuple:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c9c1efe7-33e1-4add-9c4e-567d8dfbb821\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"marker_codes = [\\n\",\n \" (4, 0, 0), (4, 0, 45), (8, 0, 0),\\n\",\n \" (4, 1, 0), (4, 1, 45), (8, 1, 0),\\n\",\n \" (4, 2, 0), (4, 2, 45), (8, 2, 0),\\n\",\n \"]\\n\",\n \"x, y = [f\\\"{m}\\\" for m in marker_codes], [0] * len(marker_codes)\\n\",\n \"marker_objs = [mpl.markers.MarkerStyle(m) for m in marker_codes]\\n\",\n \"marker_plot.add(marker_mark, marker=marker_objs, x=x, y=y).plot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dc518508-cb08-4508-a7f3-5762841da6fc\",\n \"metadata\": {},\n \"source\": [\n \"See the matplotlib docs for additional formats, including mathtex character codes (`'$...$'`) and arrays of vertices.\\n\",\n \"\\n\",\n \"A marker property is always mapped with a nominal scale; there is no inherent ordering to the different shapes. If no scale is provided, the plot will programmatically generate a suitably large set of unique markers:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"3466dc10-07a5-470f-adac-c3c05326945d\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"from seaborn._core.properties import Marker\\n\",\n \"n = 14\\n\",\n \"marker_objs = Marker()._default_values(n)\\n\",\n \"x, y = list(map(str, range(n))), [0] * n\\n\",\n \"marker_plot.add(marker_mark, marker=marker_objs, x=x, y=y).plot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"30916c65-6d4c-4294-a5e2-58af8b9392f3\",\n \"metadata\": {},\n \"source\": [\n \"While this ensures that the shapes are technically distinct, bear in mind that — in most cases — it will be difficult to tell the markers apart if more than a handful are used in a single plot.\\n\",\n \"\\n\",\n \".. note::\\n\",\n \" The default marker scale is subject to change in future releases to improve discriminability.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3b1d0630-808a-4099-8bd0-768718f86f72\",\n \"metadata\": {},\n \"source\": [\n \".. _linestyle_property:\\n\",\n \"\\n\",\n \"linestyle, edgestyle\\n\",\n \"~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The `linestyle` property is relevant to line marks, and the `edgestyle` propety is relevant to a number of marks with \\\"edges. Both properties determine the \\\"dashing\\\" of a line in terms of on-off segments.\\n\",\n \"\\n\",\n \"Dashes can be specified with a small number of shorthand codes (`'-'`, `'--'`, `'-.'`, and `':'`) or programatically using `(on, off, ...)` tuples. In the tuple specification, the unit is equal to the linewidth:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"33a729db-84e4-4619-bd1a-1f60c77f7073\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"xx = np.linspace(0, 1, 100)\\n\",\n \"dashes = [\\\"-\\\", \\\"--\\\", \\\"-.\\\", \\\":\\\", (6, 2), (2, 1), (.5, .5), (4, 1, 2, 1)] \\n\",\n \"dash_data = (\\n\",\n \" pd.DataFrame({i: xx for i in range(len(dashes))})\\n\",\n \" .stack()\\n\",\n \" .reset_index(1)\\n\",\n \" .set_axis([\\\"y\\\", \\\"x\\\"], axis=1)\\n\",\n \" .reset_index(drop=True)\\n\",\n \")\\n\",\n \"(\\n\",\n \" so.Plot(dash_data, \\\"x\\\", \\\"y\\\", linestyle=\\\"y\\\")\\n\",\n \" .add(so.Line(linewidth=1.7, color=\\\".2\\\"), legend=None)\\n\",\n \" .scale(\\n\",\n \" linestyle=dashes,\\n\",\n \" x=so.Continuous().tick(count=0),\\n\",\n \" y=so.Continuous().tick(every=1).label(like={\\n\",\n \" i: f\\\"'$\\\\mathtt{{{pat}}}$'\\\" if isinstance(pat, str) else pat\\n\",\n \" for i, pat in enumerate(dashes)\\n\",\n \" }.get)\\n\",\n \" )\\n\",\n \" .label(x=\\\"\\\", y=\\\"\\\")\\n\",\n \" .limit(x=(0, 1), y=(7.5, -0.5))\\n\",\n \" .layout(size=(9, 2.5), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"white\\\"),\\n\",\n \" **no_spines,\\n\",\n \" \\\"ytick.labelsize\\\": 12,\\n\",\n \" })\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"41063f3b-a207-4f03-a606-78e2826be522\",\n \"metadata\": {},\n \"source\": [\n \"Size properties\\n\",\n \"---------------\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"7a909d91-9d60-4e95-a855-18b2779f19ce\",\n \"metadata\": {},\n \"source\": [\n \".. _pointsize_property:\\n\",\n \"\\n\",\n \"pointsize\\n\",\n \"~~~~~~~~~\\n\",\n \"\\n\",\n \"The `pointsize` property is relevant to dot marks and to line marks that can show markers at individual data points. The units correspond to the diameter of the mark in points.\\n\",\n \"\\n\",\n \"The `pointsize` scales with the square root of the data by default so that magnitude is represented by diameter rather than area:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b55b106d-ba14-43ec-ab9b-5d7a04fb813c\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"x = np.arange(1, 21)\\n\",\n \"y = [0 for _ in x]\\n\",\n \"(\\n\",\n \" so.Plot(x, y)\\n\",\n \" .add(so.Dots(color=\\\".2\\\", stroke=1), pointsize=x)\\n\",\n \" .layout(size=(9, .5), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"xtick.labelsize\\\": 12,\\n\",\n \" \\\"axes.xmargin\\\": .025,\\n\",\n \" })\\n\",\n \" .scale(\\n\",\n \" pointsize=None,\\n\",\n \" x=so.Continuous().tick(every=1),\\n\",\n \" y=so.Continuous().tick(count=0),\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"66660d74-0252-4cb1-960a-c2c4823bb0e6\",\n \"metadata\": {},\n \"source\": [\n \".. _linewidth_property:\\n\",\n \"\\n\",\n \"linewidth\\n\",\n \"~~~~~~~~~\\n\",\n \"\\n\",\n \"The `linewidth` property is relevant to line marks and determines their thickness. The value should be non-negative and has point units:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a77c60d5-0d21-43a5-ab8c-f3f4abbc70ad\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"lw = np.arange(0.5, 5, .5)\\n\",\n \"x = [i for i in [0, 1] for _ in lw]\\n\",\n \"y = [*lw, *lw]\\n\",\n \"(\\n\",\n \" so.Plot(x=x, y=y, linewidth=y)\\n\",\n \" .add(so.Line(color=\\\".2\\\"))\\n\",\n \" .limit(y=(4.9, .1))\\n\",\n \" .layout(size=(9, 1.4), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"bottom\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"xtick.labelsize\\\": 12,\\n\",\n \" \\\"axes.xmargin\\\": .015,\\n\",\n \" \\\"ytick.labelsize\\\": 12,\\n\",\n \" })\\n\",\n \" .scale(\\n\",\n \" linewidth=None,\\n\",\n \" x=so.Continuous().tick(count=0),\\n\",\n \" y=so.Continuous().tick(every=1, between=(.5, 4.5), minor=1),\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dcbdfcb9-d55e-467a-8514-bdb4cc2bec90\",\n \"metadata\": {},\n \"source\": [\n \".. _edgewidth_property:\\n\",\n \"\\n\",\n \"edgewidth\\n\",\n \"~~~~~~~~~\\n\",\n \"\\n\",\n \"The `edgewidth` property is akin to `linewidth` but applies to marks with an edge/fill rather than to lines. It also has a different default range when used in a scale. The units are the same:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"7a1f1d5a-a2d5-4b8e-a172-73104f5ec715\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"x = np.arange(0, 21) / 5\\n\",\n \"y = [0 for _ in x]\\n\",\n \"edge_plot = (\\n\",\n \" so.Plot(x, y)\\n\",\n \" .layout(size=(9, .5), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"xtick.labelsize\\\": 12,\\n\",\n \" \\\"axes.xmargin\\\": .02,\\n\",\n \" })\\n\",\n \" .scale(\\n\",\n \" x=so.Continuous().tick(every=1, minor=4),\\n\",\n \" y=so.Continuous().tick(count=0),\\n\",\n \" )\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ba70ed6c-d902-41b0-a043-d8f27bf65e9b\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" edge_plot\\n\",\n \" .add(so.Dot(color=\\\".75\\\", edgecolor=\\\".2\\\", marker=\\\"o\\\", pointsize=14), edgewidth=x)\\n\",\n \" .scale(edgewidth=None)\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"98a25a16-67fa-4467-a425-6a78a17c63ab\",\n \"metadata\": {},\n \"source\": [\n \".. _stroke_property:\\n\",\n \"\\n\",\n \"stroke\\n\",\n \"~~~~~~\\n\",\n \"\\n\",\n \"The `stroke` property is akin to `edgewidth` but applies when a dot mark is defined by its stroke rather than its fill. It also has a slightly different default scale range, but otherwise behaves similarly:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f73a0428-a787-4f21-8098-848eb1c816fb\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" edge_plot\\n\",\n \" .add(so.Dot(color=\\\".2\\\", marker=\\\"x\\\", pointsize=11), stroke=x)\\n\",\n \" .scale(stroke=None)\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"c2ca33db-df52-4958-889a-320b4833a0d7\",\n \"metadata\": {},\n \"source\": [\n \"Text properties\\n\",\n \"---------------\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b75af2fe-4d81-407c-9858-23362710f25f\",\n \"metadata\": {},\n \"source\": [\n \".. _horizontalalignment_property:\\n\",\n \"\\n\",\n \".. _verticalalignment_property:\\n\",\n \"\\n\",\n \"halign, valign\\n\",\n \"~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The `halign` and `valign` properties control the *horizontal* and *vertical* alignment of text marks. The options for horizontal alignment are `'left'`, `'right'`, and `'center'`, while the options for vertical alignment are `'top'`, `'bottom'`, `'center'`, `'baseline'`, and `'center_baseline'`.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e9588309-bee4-4b97-b428-eb91ea582105\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"x = [\\\"left\\\", \\\"right\\\", \\\"top\\\", \\\"bottom\\\", \\\"baseline\\\", \\\"center\\\"]\\n\",\n \"ha = x[:2] + [\\\"center\\\"] * 4\\n\",\n \"va = [\\\"center_baseline\\\"] * 2 + x[2:]\\n\",\n \"y = np.zeros(len(x))\\n\",\n \"(\\n\",\n \" so.Plot(x=[f\\\"'{_x_}'\\\" for _x_ in x], y=y, halign=ha, valign=va)\\n\",\n \" .add(so.Dot(marker=\\\"+\\\", color=\\\"r\\\", alpha=.5, stroke=1, pointsize=24))\\n\",\n \" .add(so.Text(text=\\\"XyZ\\\", fontsize=14, offset=0))\\n\",\n \" .scale(y=so.Continuous().tick(at=[]), halign=None, valign=None)\\n\",\n \" .limit(x=(-.25, len(x) - .75))\\n\",\n \" .layout(size=(9, .6), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"xtick.labelsize\\\": 12,\\n\",\n \" \\\"axes.xmargin\\\": .015,\\n\",\n \" \\\"ytick.labelsize\\\": 12,\\n\",\n \" })\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"ea74c7e5-798b-47bc-bc18-9086902fb5c6\",\n \"metadata\": {},\n \"source\": [\n \".. _fontsize_property:\\n\",\n \"\\n\",\n \"fontsize\\n\",\n \"~~~~~~~~\\n\",\n \"\\n\",\n \"The `fontsize` property controls the size of textual marks. The value has point units:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c515b790-385d-4521-b14a-0769c1902928\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"from string import ascii_uppercase\\n\",\n \"n = 26\\n\",\n \"s = np.arange(n) + 1\\n\",\n \"y = np.zeros(n)\\n\",\n \"t = list(ascii_uppercase[:n])\\n\",\n \"(\\n\",\n \" so.Plot(x=s, y=y, text=t, fontsize=s)\\n\",\n \" .add(so.Text())\\n\",\n \" .scale(x=so.Nominal(), y=so.Continuous().tick(at=[]))\\n\",\n \" .layout(size=(9, .5), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"xtick.labelsize\\\": 12,\\n\",\n \" \\\"axes.xmargin\\\": .015,\\n\",\n \" \\\"ytick.labelsize\\\": 12,\\n\",\n \" })\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4b367f36-fb96-44fa-83a3-1cc66c7a3279\",\n \"metadata\": {},\n \"source\": [\n \".. _offset_property:\\n\",\n \"\\n\",\n \"offset\\n\",\n \"~~~~~~\\n\",\n \"\\n\",\n \"The `offset` property controls the spacing between a text mark and its anchor position. It applies when *not* using `center` alignment (i.e., when using left/right or top/bottom). The value has point units. \"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"25a49331-9580-4578-8bdb-d0d1829dde71\",\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"n = 17\\n\",\n \"x = np.linspace(0, 8, n)\\n\",\n \"y = np.full(n, .5)\\n\",\n \"(\\n\",\n \" so.Plot(x=x, y=y, offset=x)\\n\",\n \" .add(so.Bar(color=\\\".6\\\", edgecolor=\\\"k\\\"))\\n\",\n \" .add(so.Text(text=\\\"abc\\\", valign=\\\"bottom\\\"))\\n\",\n \" .scale(\\n\",\n \" x=so.Continuous().tick(every=1, minor=1),\\n\",\n \" y=so.Continuous().tick(at=[]),\\n\",\n \" offset=None,\\n\",\n \" )\\n\",\n \" .limit(y=(0, 1.5))\\n\",\n \" .layout(size=(9, .5), engine=None)\\n\",\n \" .theme({\\n\",\n \" **axes_style(\\\"ticks\\\"),\\n\",\n \" **{f\\\"axes.spines.{side}\\\": False for side in [\\\"left\\\", \\\"right\\\", \\\"top\\\"]},\\n\",\n \" \\\"axes.xmargin\\\": .015,\\n\",\n \" \\\"xtick.labelsize\\\": 12,\\n\",\n \" \\\"ytick.labelsize\\\": 12,\\n\",\n \" })\\n\",\n \" .plot()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"77723ffd-2da3-4ece-a97a-3c00e864c743\",\n \"metadata\": {},\n \"source\": [\n \"Other properties\\n\",\n \"----------------\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"287bb259-0194-4c8c-8836-5e3eb6d88e79\",\n \"metadata\": {},\n \"source\": [\n \".. _property_property:\\n\",\n \"\\n\",\n \"text\\n\",\n \"~~~~\\n\",\n \"\\n\",\n \"The `text` property is used to set the content of a textual mark. It is always used literally (not mapped), and cast to string when necessary.\\n\",\n \"\\n\",\n \"group\\n\",\n \"~~~~~\\n\",\n \"\\n\",\n \"The `group` property is special in that it does not change anything about the mark's appearance but defines additional data subsets that transforms should operate on independently.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f23c9251-1685-4150-b5c2-ab5b0589d8e6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"marginal_ticks.py","filePath":"examples","id":2075,"nodeType":"File","text":"\"\"\"\nScatterplot with marginal ticks\n===============================\n\n_thumb: .66, .34\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"white\", color_codes=True)\nmpg = sns.load_dataset(\"mpg\")\n\n# Use JointGrid directly to draw a custom plot\ng = sns.JointGrid(data=mpg, x=\"mpg\", y=\"acceleration\", space=0, ratio=17)\ng.plot_joint(sns.scatterplot, size=mpg[\"horsepower\"], sizes=(30, 120),\n color=\"g\", alpha=.6, legend=False)\ng.plot_marginals(sns.rugplot, height=1, color=\"g\", alpha=.6)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2076,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"className":"TestKDEPlotBivariate","col":0,"comment":"null","endLoc":1130,"id":2077,"nodeType":"Class","startLoc":921,"text":"class TestKDEPlotBivariate:\n\n def test_long_vectors(self, long_df):\n\n ax1 = kdeplot(data=long_df, x=\"x\", y=\"y\")\n\n x = long_df[\"x\"]\n x_values = [x, x.to_numpy(), x.to_list()]\n\n y = long_df[\"y\"]\n y_values = [y, y.to_numpy(), y.to_list()]\n\n for x, y in zip(x_values, y_values):\n f, ax2 = plt.subplots()\n kdeplot(x=x, y=y, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(c1.get_offsets(), c2.get_offsets())\n\n def test_singular_data(self):\n\n with pytest.warns(UserWarning):\n ax = dist.kdeplot(x=np.ones(10), y=np.arange(10))\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = dist.kdeplot(x=[5], y=[6])\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=[1929245168.06679] * 18, y=np.arange(18))\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\", UserWarning)\n ax = kdeplot(x=[5], y=[7], warn_singular=False)\n assert not ax.lines\n\n def test_fill_artists(self, long_df):\n\n for fill in [True, False]:\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"c\", fill=fill)\n for c in ax.collections:\n if fill or Version(mpl.__version__) >= Version(\"3.5.0b0\"):\n assert isinstance(c, mpl.collections.PathCollection)\n else:\n assert isinstance(c, mpl.collections.LineCollection)\n\n def test_common_norm(self, rng):\n\n hue = np.repeat([\"a\", \"a\", \"a\", \"b\"], 40)\n x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], len(hue)).T\n x[hue == \"a\"] -= 2\n x[hue == \"b\"] += 2\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, hue=hue, common_norm=True, ax=ax1)\n kdeplot(x=x, y=y, hue=hue, common_norm=False, ax=ax2)\n\n n_seg_1 = sum(len(get_contour_coords(c)) > 0 for c in ax1.collections)\n n_seg_2 = sum(len(get_contour_coords(c)) > 0 for c in ax2.collections)\n assert n_seg_2 > n_seg_1\n\n def test_log_scale(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n y = rng.uniform(0, 1, 100)\n\n levels = .2, .5, 1\n\n f, ax = plt.subplots()\n kdeplot(x=x, y=y, log_scale=True, levels=levels, ax=ax)\n assert ax.get_xscale() == \"log\"\n assert ax.get_yscale() == \"log\"\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, log_scale=(10, False), levels=levels, ax=ax1)\n assert ax1.get_xscale() == \"log\"\n assert ax1.get_yscale() == \"linear\"\n\n p = _DistributionPlotter()\n kde = KDE()\n density, (xx, yy) = kde(np.log10(x), y)\n levels = p._quantile_to_level(density, levels)\n ax2.contour(10 ** xx, yy, density, levels=levels)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n\n def test_bandwidth(self, rng):\n\n n = 100\n x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], n).T\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(x=x, y=y, ax=ax1)\n kdeplot(x=x, y=y, bw_adjust=2, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n seg1, seg2 = get_contour_coords(c1), get_contour_coords(c2)\n if seg1 + seg2:\n x1 = seg1[0][:, 0]\n x2 = seg2[0][:, 0]\n assert np.abs(x2).max() > np.abs(x1).max()\n\n def test_weights(self, rng):\n\n import warnings\n warnings.simplefilter(\"error\", np.VisibleDeprecationWarning)\n\n n = 100\n x, y = rng.multivariate_normal([1, 3], [(.2, .5), (.5, 2)], n).T\n hue = np.repeat([0, 1], n // 2)\n weights = rng.uniform(0, 1, n)\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, hue=hue, ax=ax1)\n kdeplot(x=x, y=y, hue=hue, weights=weights, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n if get_contour_coords(c1) and get_contour_coords(c2):\n seg1 = np.concatenate(get_contour_coords(c1), axis=0)\n seg2 = np.concatenate(get_contour_coords(c2), axis=0)\n assert not np.array_equal(seg1, seg2)\n\n def test_hue_ignores_cmap(self, long_df):\n\n with pytest.warns(UserWarning, match=\"cmap parameter ignored\"):\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"c\", cmap=\"viridis\")\n\n assert_colors_equal(get_contour_color(ax.collections[0]), \"C0\")\n\n def test_contour_line_colors(self, long_df):\n\n color = (.2, .9, .8, 1)\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", color=color)\n\n for c in ax.collections:\n assert_colors_equal(get_contour_color(c), color)\n\n def test_contour_line_cmap(self, long_df):\n\n color_list = color_palette(\"Blues\", 12)\n cmap = mpl.colors.ListedColormap(color_list)\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", cmap=cmap)\n for c in ax.collections:\n color = to_rgb(get_contour_color(c).squeeze())\n assert color in color_list\n\n def test_contour_fill_colors(self, long_df):\n\n n = 6\n color = (.2, .9, .8, 1)\n ax = kdeplot(\n data=long_df, x=\"x\", y=\"y\", fill=True, color=color, levels=n,\n )\n\n cmap = light_palette(color, reverse=True, as_cmap=True)\n lut = cmap(np.linspace(0, 1, 256))\n for c in ax.collections:\n color = c.get_facecolor().squeeze()\n assert color in lut\n\n def test_colorbar(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", fill=True, cbar=True)\n assert len(ax.figure.axes) == 2\n\n def test_levels_and_thresh(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n n = 8\n thresh = .1\n plot_kws = dict(data=long_df, x=\"x\", y=\"y\")\n kdeplot(**plot_kws, levels=n, thresh=thresh, ax=ax1)\n kdeplot(**plot_kws, levels=np.linspace(thresh, 1, n), ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n\n with pytest.raises(ValueError):\n kdeplot(**plot_kws, levels=[0, 1, 2])\n\n ax1.clear()\n ax2.clear()\n\n kdeplot(**plot_kws, levels=n, thresh=None, ax=ax1)\n kdeplot(**plot_kws, levels=n, thresh=0, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(c1.get_facecolors(), c2.get_facecolors())\n\n def test_quantile_to_level(self, rng):\n\n x = rng.uniform(0, 1, 100000)\n isoprop = np.linspace(.1, 1, 6)\n\n levels = _DistributionPlotter()._quantile_to_level(x, isoprop)\n for h, p in zip(levels, isoprop):\n assert (x[x <= h].sum() / x.sum()) == pytest.approx(p, abs=1e-4)\n\n def test_input_checking(self, long_df):\n\n with pytest.raises(TypeError, match=\"The x variable is categorical,\"):\n kdeplot(data=long_df, x=\"a\", y=\"y\")"},{"col":4,"comment":"null","endLoc":938,"header":"def test_long_vectors(self, long_df)","id":2078,"name":"test_long_vectors","nodeType":"Function","startLoc":923,"text":"def test_long_vectors(self, long_df):\n\n ax1 = kdeplot(data=long_df, x=\"x\", y=\"y\")\n\n x = long_df[\"x\"]\n x_values = [x, x.to_numpy(), x.to_list()]\n\n y = long_df[\"y\"]\n y_values = [y, y.to_numpy(), y.to_list()]\n\n for x, y in zip(x_values, y_values):\n f, ax2 = plt.subplots()\n kdeplot(x=x, y=y, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(c1.get_offsets(), c2.get_offsets())"},{"attributeType":"null","col":0,"comment":"null","endLoc":9,"id":2079,"name":"mpg","nodeType":"Attribute","startLoc":9,"text":"mpg"},{"attributeType":"float","col":4,"comment":"null","endLoc":86,"id":2080,"name":"gap","nodeType":"Attribute","startLoc":86,"text":"gap"},{"attributeType":"list | None","col":4,"comment":"null","endLoc":91,"id":2081,"name":"by","nodeType":"Attribute","startLoc":91,"text":"by"},{"id":2083,"name":"logo-tall-lightbg.svg","nodeType":"TextFile","path":"doc/_static","text":"\n\n\n\n \n \n \n \n 2020-09-07T14:13:59.334522\n image/svg+xml\n \n \n Matplotlib v3.3.1, https://matplotlib.org/\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"className":"Jitter","col":0,"comment":"\n Random displacement along one or both axes to reduce overplotting.\n\n Parameters\n ----------\n width : float\n Magnitude of jitter, relative to mark width, along the orientation axis.\n If not provided, the default value will be 0 when `x` or `y` are set, otherwise\n there will be a small amount of jitter applied by default.\n x : float\n Magnitude of jitter, in data units, along the x axis.\n y : float\n Magnitude of jitter, in data units, along the y axis.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Jitter.rst\n\n ","endLoc":77,"id":2084,"nodeType":"Class","startLoc":27,"text":"@dataclass\nclass Jitter(Move):\n \"\"\"\n Random displacement along one or both axes to reduce overplotting.\n\n Parameters\n ----------\n width : float\n Magnitude of jitter, relative to mark width, along the orientation axis.\n If not provided, the default value will be 0 when `x` or `y` are set, otherwise\n there will be a small amount of jitter applied by default.\n x : float\n Magnitude of jitter, in data units, along the x axis.\n y : float\n Magnitude of jitter, in data units, along the y axis.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Jitter.rst\n\n \"\"\"\n width: float | Default = default\n x: float = 0\n y: float = 0\n seed: int | None = None\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n data = data.copy()\n rng = np.random.default_rng(self.seed)\n\n def jitter(data, col, scale):\n noise = rng.uniform(-.5, +.5, len(data))\n offsets = noise * scale\n return data[col] + offsets\n\n if self.width is default:\n width = 0.0 if self.x or self.y else 0.2\n else:\n width = cast(float, self.width)\n\n if self.width:\n data[orient] = jitter(data, orient, width * data[\"width\"])\n if self.x:\n data[\"x\"] = jitter(data, \"x\", self.x)\n if self.y:\n data[\"y\"] = jitter(data, \"y\", self.y)\n\n return data"},{"col":4,"comment":"null","endLoc":77,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":2085,"name":"__call__","nodeType":"Function","startLoc":53,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n data = data.copy()\n rng = np.random.default_rng(self.seed)\n\n def jitter(data, col, scale):\n noise = rng.uniform(-.5, +.5, len(data))\n offsets = noise * scale\n return data[col] + offsets\n\n if self.width is default:\n width = 0.0 if self.x or self.y else 0.2\n else:\n width = cast(float, self.width)\n\n if self.width:\n data[orient] = jitter(data, orient, width * data[\"width\"])\n if self.x:\n data[\"x\"] = jitter(data, \"x\", self.x)\n if self.y:\n data[\"y\"] = jitter(data, \"y\", self.y)\n\n return data"},{"attributeType":"JointGrid","col":0,"comment":"null","endLoc":12,"id":2086,"name":"g","nodeType":"Attribute","startLoc":12,"text":"g"},{"id":2087,"name":"APPDIRS_LICENSE","nodeType":"TextFile","path":"licences","text":"Copyright (c) 2005-2010 ActiveState Software Inc.\nCopyright (c) 2013 Eddy Petrișor\n\nThis file is directly from\nhttps://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py\n\nThe license of https://github.com/ActiveState/appdirs copied below:\n\n\n# This is the MIT license\n\nCopyright (c) 2010 ActiveState Software Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"},{"col":0,"comment":"","endLoc":6,"header":"marginal_ticks.py#","id":2088,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot with marginal ticks\n===============================\n\n_thumb: .66, .34\n\"\"\"\n\nsns.set_theme(style=\"white\", color_codes=True)\n\nmpg = sns.load_dataset(\"mpg\")\n\ng = sns.JointGrid(data=mpg, x=\"mpg\", y=\"acceleration\", space=0, ratio=17)\n\ng.plot_joint(sns.scatterplot, size=mpg[\"horsepower\"], sizes=(30, 120),\n color=\"g\", alpha=.6, legend=False)\n\ng.plot_marginals(sns.rugplot, height=1, color=\"g\", alpha=.6)"},{"id":2089,"name":"swarmplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a single numeric variable shows its univariate distribution with points adjusted along on the other axis such that they don't overlap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a second variable splits the groups of points to compare categorical levels of that variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Show vertically-oriented swarms by swapping the assignment of the categorical and numerical variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Prior to version 0.12, the levels of the categorical variable had different colors by default. To get the same effect, assign the `hue` variable explicitly:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"day\\\", legend=False)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Or you can assign a distinct variable to `hue` to show a multidimensional relationship:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If the `hue` variable is numeric, it will be mapped with a quantitative palette by default (note that this was not the case prior to version 0.12):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Use `palette` to control the color mapping, including forcing a categorical mapping by passing the name of a qualitative palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"size\\\", palette=\\\"deep\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, the different levels of the `hue` variable are intermingled in each swarm, but setting `dodge=True` will split them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\", dodge=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The \\\"orientation\\\" of the plot (defined as the direction along which quantitative relationships are preserved) is usually inferred automatically. But in ambiguous cases, such as when both axis variables are numeric, it can be specified:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When the local density of points is too high, they will be forced to overlap in the \\\"gutters\\\" of each swarm and a warning will be issued. Decreasing the size of the points can help to avoid this problem:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(data=tips, x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\", size=3)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, the categorical variable will be mapped to discrete indices with a fixed scale (0, 1, ...), even when it is numeric:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(\\n\",\n \" data=tips.query(\\\"size in [2, 3, 5]\\\"),\\n\",\n \" x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To disable this behavior and use the original scale of the variable, set `native_scale=True` (notice how this also changes the order of the variables on the y axis):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(\\n\",\n \" data=tips.query(\\\"size in [2, 3, 5]\\\"),\\n\",\n \" x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\",\\n\",\n \" native_scale=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Further visual customization can be achieved by passing keyword arguments for :func:`matplotlib.axes.Axes.scatter`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.swarmplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"day\\\",\\n\",\n \" marker=\\\"x\\\", linewidth=1, \\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To make a plot with multiple facets, it is safer to use :func:`catplot` with `kind=\\\"swarm\\\"` than to work with :class:`FacetGrid` directly, because :func:`catplot` will ensure that the categorical and hue variables are properly synchronized in each facet:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=tips, kind=\\\"swarm\\\",\\n\",\n \" x=\\\"time\\\", y=\\\"total_bill\\\", hue=\\\"sex\\\", col=\\\"day\\\",\\n\",\n \" aspect=.5\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"attributeType":"float | Default","col":4,"comment":"null","endLoc":48,"id":2091,"name":"width","nodeType":"Attribute","startLoc":48,"text":"width"},{"fileName":"layered_bivariate_plot.py","filePath":"examples","id":2092,"nodeType":"File","text":"\"\"\"\nBivariate plot with multiple elements\n=====================================\n\n\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_theme(style=\"dark\")\n\n# Simulate data from a bivariate Gaussian\nn = 10000\nmean = [0, 0]\ncov = [(2, .4), (.4, .2)]\nrng = np.random.RandomState(0)\nx, y = rng.multivariate_normal(mean, cov, n).T\n\n# Draw a combo histogram and scatterplot with density contours\nf, ax = plt.subplots(figsize=(6, 6))\nsns.scatterplot(x=x, y=y, s=5, color=\".15\")\nsns.histplot(x=x, y=y, bins=50, pthresh=.1, cmap=\"mako\")\nsns.kdeplot(x=x, y=y, levels=5, color=\"w\", linewidths=1)\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":7,"id":2093,"name":"np","nodeType":"Attribute","startLoc":7,"text":"np"},{"attributeType":"float","col":4,"comment":"null","endLoc":49,"id":2094,"name":"x","nodeType":"Attribute","startLoc":49,"text":"x"},{"attributeType":"float","col":4,"comment":"null","endLoc":50,"id":2095,"name":"y","nodeType":"Attribute","startLoc":50,"text":"y"},{"attributeType":"int | None","col":4,"comment":"null","endLoc":51,"id":2096,"name":"seed","nodeType":"Attribute","startLoc":51,"text":"seed"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":2097,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"className":"Norm","col":0,"comment":"\n Divisive scaling on the value axis after aggregating within groups.\n ","endLoc":224,"id":2098,"nodeType":"Class","startLoc":193,"text":"@dataclass\nclass Norm(Move):\n \"\"\"\n Divisive scaling on the value axis after aggregating within groups.\n \"\"\"\n\n func: Union[Callable, str] = \"max\"\n where: Optional[str] = None\n by: Optional[list[str]] = None\n percent: bool = False\n\n group_by_orient: ClassVar[bool] = False\n\n def _norm(self, df, var):\n\n if self.where is None:\n denom_data = df[var]\n else:\n denom_data = df.query(self.where)[var]\n df[var] = df[var] / denom_data.agg(self.func)\n\n if self.percent:\n df[var] = df[var] * 100\n\n return df\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.apply(data, self._norm, other)"},{"attributeType":"null","col":28,"comment":"null","endLoc":9,"id":2099,"name":"plt","nodeType":"Attribute","startLoc":9,"text":"plt"},{"attributeType":"int","col":0,"comment":"null","endLoc":13,"id":2100,"name":"n","nodeType":"Attribute","startLoc":13,"text":"n"},{"col":4,"comment":"null","endLoc":217,"header":"def _norm(self, df, var)","id":2101,"name":"_norm","nodeType":"Function","startLoc":206,"text":"def _norm(self, df, var):\n\n if self.where is None:\n denom_data = df[var]\n else:\n denom_data = df.query(self.where)[var]\n df[var] = df[var] / denom_data.agg(self.func)\n\n if self.percent:\n df[var] = df[var] * 100\n\n return df"},{"attributeType":"list","col":0,"comment":"null","endLoc":14,"id":2102,"name":"mean","nodeType":"Attribute","startLoc":14,"text":"mean"},{"attributeType":"list","col":0,"comment":"null","endLoc":15,"id":2103,"name":"cov","nodeType":"Attribute","startLoc":15,"text":"cov"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":2104,"name":"rng","nodeType":"Attribute","startLoc":16,"text":"rng"},{"col":4,"comment":"null","endLoc":224,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":2105,"name":"__call__","nodeType":"Function","startLoc":219,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.apply(data, self._norm, other)"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":2106,"name":"x","nodeType":"Attribute","startLoc":17,"text":"x"},{"attributeType":"null","col":3,"comment":"null","endLoc":17,"id":2107,"name":"y","nodeType":"Attribute","startLoc":17,"text":"y"},{"attributeType":"null","col":0,"comment":"null","endLoc":20,"id":2108,"name":"f","nodeType":"Attribute","startLoc":20,"text":"f"},{"attributeType":"null","col":3,"comment":"null","endLoc":20,"id":2109,"name":"ax","nodeType":"Attribute","startLoc":20,"text":"ax"},{"col":0,"comment":"","endLoc":6,"header":"layered_bivariate_plot.py#","id":2110,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nBivariate plot with multiple elements\n=====================================\n\n\n\"\"\"\n\nsns.set_theme(style=\"dark\")\n\nn = 10000\n\nmean = [0, 0]\n\ncov = [(2, .4), (.4, .2)]\n\nrng = np.random.RandomState(0)\n\nx, y = rng.multivariate_normal(mean, cov, n).T\n\nf, ax = plt.subplots(figsize=(6, 6))\n\nsns.scatterplot(x=x, y=y, s=5, color=\".15\")\n\nsns.histplot(x=x, y=y, bins=50, pthresh=.1, cmap=\"mako\")\n\nsns.kdeplot(x=x, y=y, levels=5, color=\"w\", linewidths=1)"},{"attributeType":"(...) -> Any | str","col":4,"comment":"null","endLoc":199,"id":2111,"name":"func","nodeType":"Attribute","startLoc":199,"text":"func"},{"id":2112,"name":"HUSL_LICENSE","nodeType":"TextFile","path":"licences","text":"Copyright (C) 2012 Alexei Boronine\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"},{"id":2113,"name":"jointplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"white\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In the simplest invocation, assign ``x`` and ``y`` to create a scatterplot (using :func:`scatterplot`) with marginal histograms (using :func:`histplot`):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a ``hue`` variable will add conditional colors to the scatterplot and draw separate density curves (using :func:`kdeplot`) on the marginal axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Several different approaches to plotting are available through the ``kind`` parameter. Setting ``kind=\\\"kde\\\"`` will draw both bivariate and univariate KDEs:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\", kind=\\\"kde\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Set ``kind=\\\"reg\\\"`` to add a linear regression fit (using :func:`regplot`) and univariate KDE curves:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", kind=\\\"reg\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"There are also two options for bin-based visualization of the joint distribution. The first, with ``kind=\\\"hist\\\"``, uses :func:`histplot` on all of the axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", kind=\\\"hist\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Alternatively, setting ``kind=\\\"hex\\\"`` will use :meth:`matplotlib.axes.Axes.hexbin` to compute a bivariate histogram using hexagonal bins:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", kind=\\\"hex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Additional keyword arguments can be passed down to the underlying plots:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(\\n\",\n \" data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n \" marker=\\\"+\\\", s=100, marginal_kws=dict(bins=25, fill=False),\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Use :class:`JointGrid` parameters to control the size and layout of the figure:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", height=5, ratio=2, marginal_ticks=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To add more layers onto the plot, use the methods on the :class:`JointGrid` object that :func:`jointplot` returns:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.jointplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \"g.plot_joint(sns.kdeplot, color=\\\"r\\\", zorder=0, levels=6)\\n\",\n \"g.plot_marginals(sns.rugplot, color=\\\"r\\\", height=-.15, clip_on=False)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":2114,"name":"objects.Plot.share.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"penguins = load_dataset(\\\"penguins\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3a874676-6b0d-45b1-a227-857a536c5ed2\",\n \"metadata\": {},\n \"source\": [\n \"By default, faceted plots will share all axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"615d0765-98c7-4694-8115-a6d1b3557fe7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = (\\n\",\n \" so.Plot(penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\\n\",\n \" .facet(col=\\\"species\\\", row=\\\"sex\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \")\\n\",\n \"p\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"8b75feb1-491e-4031-9fcb-619037bd1bfb\",\n \"metadata\": {},\n \"source\": [\n \"Set a coordinate variable to `False` to let each subplot adapt independently:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4c23c570-ca9b-49cc-9aab-7d167218454b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.share(x=False, y=False)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"cc46d8d0-7ab9-44c2-8a28-c656fe86c085\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to share only across rows or columns:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"7cb8136b-9aa3-4c48-bd41-fc0e19fa997c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.share(x=\\\"col\\\", y=\\\"row\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"91533aba-45ae-4011-b72c-10f5f79e01d0\",\n \"metadata\": {},\n \"source\": [\n \"This method is also relevant for paired plots, which have different defaults. In this case, you would need to opt *in* to full sharing (although it may not always make sense):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e2b71770-e520-45b9-b41c-a66431f21e1f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, y=\\\"flipper_length_mm\\\")\\n\",\n \" .pair(x=[\\\"bill_length_mm\\\", \\\"bill_depth_mm\\\"])\\n\",\n \" .add(so.Dots())\\n\",\n \" .share(x=True)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"92c29080-8561-4c90-8581-4d435a5f96b9\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"wide_form_violinplot.py","filePath":"examples","id":2115,"nodeType":"File","text":"\"\"\"\nViolinplot from a wide-form dataset\n===================================\n\n_thumb: .6, .45\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_theme(style=\"whitegrid\")\n\n# Load the example dataset of brain network correlations\ndf = sns.load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n\n# Pull out a specific subset of networks\nused_networks = [1, 3, 4, 5, 6, 7, 8, 11, 12, 13, 16, 17]\nused_columns = (df.columns.get_level_values(\"network\")\n .astype(int)\n .isin(used_networks))\ndf = df.loc[:, used_columns]\n\n# Compute the correlation matrix and average over networks\ncorr_df = df.corr().groupby(level=\"network\").mean()\ncorr_df.index = corr_df.index.astype(int)\ncorr_df = corr_df.sort_index().T\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(11, 6))\n\n# Draw a violinplot with a narrower bandwidth than the default\nsns.violinplot(data=corr_df, palette=\"Set3\", bw=.2, cut=1, linewidth=1)\n\n# Finalize the figure\nax.set(ylim=(-.7, 1.05))\nsns.despine(left=True, bottom=True)\n"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":200,"id":2116,"name":"where","nodeType":"Attribute","startLoc":200,"text":"where"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2117,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"fileName":"scatterplot_categorical.py","filePath":"examples","id":2118,"nodeType":"File","text":"\"\"\"\nScatterplot with categorical variables\n======================================\n\n_thumb: .45, .45\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\", palette=\"muted\")\n\n# Load the penguins dataset\ndf = sns.load_dataset(\"penguins\")\n\n# Draw a categorical scatterplot to show each observation\nax = sns.swarmplot(data=df, x=\"body_mass_g\", y=\"sex\", hue=\"species\")\nax.set(ylabel=\"\")\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":2119,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"list | None","col":4,"comment":"null","endLoc":201,"id":2120,"name":"by","nodeType":"Attribute","startLoc":201,"text":"by"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":2121,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":2122,"name":"df","nodeType":"Attribute","startLoc":12,"text":"df"},{"attributeType":"bool","col":4,"comment":"null","endLoc":202,"id":2123,"name":"percent","nodeType":"Attribute","startLoc":202,"text":"percent"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":2124,"name":"df","nodeType":"Attribute","startLoc":12,"text":"df"},{"attributeType":"bool","col":4,"comment":"null","endLoc":204,"id":2125,"name":"group_by_orient","nodeType":"Attribute","startLoc":204,"text":"group_by_orient"},{"fileName":"typing.py","filePath":"seaborn/_core","id":2126,"nodeType":"File","text":"from __future__ import annotations\n\nfrom datetime import date, datetime, timedelta\nfrom typing import Any, Optional, Union, Mapping, Tuple, List, Dict\nfrom collections.abc import Hashable, Iterable\n\nfrom numpy import ndarray # TODO use ArrayLike?\nfrom pandas import DataFrame, Series, Index, Timestamp, Timedelta\nfrom matplotlib.colors import Colormap, Normalize\n\n\nColumnName = Union[\n str, bytes, date, datetime, timedelta, bool, complex, Timestamp, Timedelta\n]\nVector = Union[Series, Index, ndarray]\n\nVariableSpec = Union[ColumnName, Vector, None]\nVariableSpecList = Union[List[VariableSpec], Index, None]\n\nDataSource = Union[DataFrame, Mapping[Hashable, Vector], None]\n\nOrderSpec = Union[Iterable, None] # TODO technically str is iterable\nNormSpec = Union[Tuple[Optional[float], Optional[float]], Normalize, None]\n\n# TODO for discrete mappings, it would be ideal to use a parameterized type\n# as the dict values / list entries should be of specific type(s) for each method\nPaletteSpec = Union[str, list, dict, Colormap, None]\nDiscreteValueSpec = Union[dict, list, None]\nContinuousValueSpec = Union[\n Tuple[float, float], List[float], Dict[Any, float], None,\n]\n\n\nclass Default:\n def __repr__(self):\n return \"\"\n\n\ndefault = Default()\n"},{"className":"timedelta","col":0,"comment":"null","endLoc":227,"id":2127,"nodeType":"Class","startLoc":181,"text":"class timedelta:\n min: ClassVar[timedelta]\n max: ClassVar[timedelta]\n resolution: ClassVar[timedelta]\n def __new__(\n cls,\n days: float = ...,\n seconds: float = ...,\n microseconds: float = ...,\n milliseconds: float = ...,\n minutes: float = ...,\n hours: float = ...,\n weeks: float = ...,\n ) -> Self: ...\n @property\n def days(self) -> int: ...\n @property\n def seconds(self) -> int: ...\n @property\n def microseconds(self) -> int: ...\n def total_seconds(self) -> float: ...\n def __add__(self, value: timedelta, /) -> timedelta: ...\n def __radd__(self, value: timedelta, /) -> timedelta: ...\n def __sub__(self, value: timedelta, /) -> timedelta: ...\n def __rsub__(self, value: timedelta, /) -> timedelta: ...\n def __neg__(self) -> timedelta: ...\n def __pos__(self) -> timedelta: ...\n def __abs__(self) -> timedelta: ...\n def __mul__(self, value: float, /) -> timedelta: ...\n def __rmul__(self, value: float, /) -> timedelta: ...\n @overload\n def __floordiv__(self, value: timedelta, /) -> int: ...\n @overload\n def __floordiv__(self, value: int, /) -> timedelta: ...\n @overload\n def __truediv__(self, value: timedelta, /) -> float: ...\n @overload\n def __truediv__(self, value: float, /) -> timedelta: ...\n def __mod__(self, value: timedelta, /) -> timedelta: ...\n def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ...\n def __le__(self, value: timedelta, /) -> bool: ...\n def __lt__(self, value: timedelta, /) -> bool: ...\n def __ge__(self, value: timedelta, /) -> bool: ...\n def __gt__(self, value: timedelta, /) -> bool: ...\n def __eq__(self, value: object, /) -> bool: ...\n def __bool__(self) -> bool: ...\n def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":194,"header":"def __new__(\n cls,\n days: float = ...,\n seconds: float = ...,\n microseconds: float = ...,\n milliseconds: float = ...,\n minutes: float = ...,\n hours: float = ...,\n weeks: float = ...,\n ) -> Self","id":2128,"name":"__new__","nodeType":"Function","startLoc":185,"text":"def __new__(\n cls,\n days: float = ...,\n seconds: float = ...,\n microseconds: float = ...,\n milliseconds: float = ...,\n minutes: float = ...,\n hours: float = ...,\n weeks: float = ...,\n ) -> Self: ..."},{"col":4,"comment":"null","endLoc":196,"header":"@property\n def days(self) -> int","id":2129,"name":"days","nodeType":"Function","startLoc":195,"text":"@property\n def days(self) -> int: ..."},{"col":4,"comment":"null","endLoc":198,"header":"@property\n def seconds(self) -> int","id":2130,"name":"seconds","nodeType":"Function","startLoc":197,"text":"@property\n def seconds(self) -> int: ..."},{"col":4,"comment":"null","endLoc":200,"header":"@property\n def microseconds(self) -> int","id":2131,"name":"microseconds","nodeType":"Function","startLoc":199,"text":"@property\n def microseconds(self) -> int: ..."},{"col":4,"comment":"null","endLoc":201,"header":"def total_seconds(self) -> float","id":2132,"name":"total_seconds","nodeType":"Function","startLoc":201,"text":"def total_seconds(self) -> float: ..."},{"col":4,"comment":"null","endLoc":202,"header":"def __add__(self, value: timedelta, /) -> timedelta","id":2133,"name":"__add__","nodeType":"Function","startLoc":202,"text":"def __add__(self, value: timedelta, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":203,"header":"def __radd__(self, value: timedelta, /) -> timedelta","id":2134,"name":"__radd__","nodeType":"Function","startLoc":203,"text":"def __radd__(self, value: timedelta, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":204,"header":"def __sub__(self, value: timedelta, /) -> timedelta","id":2135,"name":"__sub__","nodeType":"Function","startLoc":204,"text":"def __sub__(self, value: timedelta, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":205,"header":"def __rsub__(self, value: timedelta, /) -> timedelta","id":2136,"name":"__rsub__","nodeType":"Function","startLoc":205,"text":"def __rsub__(self, value: timedelta, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":206,"header":"def __neg__(self) -> timedelta","id":2137,"name":"__neg__","nodeType":"Function","startLoc":206,"text":"def __neg__(self) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":207,"header":"def __pos__(self) -> timedelta","id":2138,"name":"__pos__","nodeType":"Function","startLoc":207,"text":"def __pos__(self) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":208,"header":"def __abs__(self) -> timedelta","id":2139,"name":"__abs__","nodeType":"Function","startLoc":208,"text":"def __abs__(self) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":209,"header":"def __mul__(self, value: float, /) -> timedelta","id":2140,"name":"__mul__","nodeType":"Function","startLoc":209,"text":"def __mul__(self, value: float, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":210,"header":"def __rmul__(self, value: float, /) -> timedelta","id":2141,"name":"__rmul__","nodeType":"Function","startLoc":210,"text":"def __rmul__(self, value: float, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":212,"header":"@overload\n def __floordiv__(self, value: timedelta, /) -> int","id":2142,"name":"__floordiv__","nodeType":"Function","startLoc":211,"text":"@overload\n def __floordiv__(self, value: timedelta, /) -> int: ..."},{"col":4,"comment":"null","endLoc":214,"header":"@overload\n def __floordiv__(self, value: int, /) -> timedelta","id":2143,"name":"__floordiv__","nodeType":"Function","startLoc":213,"text":"@overload\n def __floordiv__(self, value: int, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":216,"header":"@overload\n def __truediv__(self, value: timedelta, /) -> float","id":2144,"name":"__truediv__","nodeType":"Function","startLoc":215,"text":"@overload\n def __truediv__(self, value: timedelta, /) -> float: ..."},{"col":4,"comment":"null","endLoc":218,"header":"@overload\n def __truediv__(self, value: float, /) -> timedelta","id":2145,"name":"__truediv__","nodeType":"Function","startLoc":217,"text":"@overload\n def __truediv__(self, value: float, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":219,"header":"def __mod__(self, value: timedelta, /) -> timedelta","id":2146,"name":"__mod__","nodeType":"Function","startLoc":219,"text":"def __mod__(self, value: timedelta, /) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":220,"header":"def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]","id":2147,"name":"__divmod__","nodeType":"Function","startLoc":220,"text":"def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ..."},{"col":4,"comment":"null","endLoc":221,"header":"def __le__(self, value: timedelta, /) -> bool","id":2148,"name":"__le__","nodeType":"Function","startLoc":221,"text":"def __le__(self, value: timedelta, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":222,"header":"def __lt__(self, value: timedelta, /) -> bool","id":2149,"name":"__lt__","nodeType":"Function","startLoc":222,"text":"def __lt__(self, value: timedelta, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":223,"header":"def __ge__(self, value: timedelta, /) -> bool","id":2150,"name":"__ge__","nodeType":"Function","startLoc":223,"text":"def __ge__(self, value: timedelta, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":224,"header":"def __gt__(self, value: timedelta, /) -> bool","id":2151,"name":"__gt__","nodeType":"Function","startLoc":224,"text":"def __gt__(self, value: timedelta, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":225,"header":"def __eq__(self, value: object, /) -> bool","id":2152,"name":"__eq__","nodeType":"Function","startLoc":225,"text":"def __eq__(self, value: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":226,"header":"def __bool__(self) -> bool","id":2153,"name":"__bool__","nodeType":"Function","startLoc":226,"text":"def __bool__(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":227,"header":"def __hash__(self) -> int","id":2154,"name":"__hash__","nodeType":"Function","startLoc":227,"text":"def __hash__(self) -> int: ..."},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":182,"id":2155,"name":"min","nodeType":"Attribute","startLoc":182,"text":"min"},{"attributeType":"list","col":0,"comment":"null","endLoc":15,"id":2156,"name":"used_networks","nodeType":"Attribute","startLoc":15,"text":"used_networks"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":2157,"name":"used_columns","nodeType":"Attribute","startLoc":16,"text":"used_columns"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":2158,"name":"df","nodeType":"Attribute","startLoc":19,"text":"df"},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":2159,"name":"corr_df","nodeType":"Attribute","startLoc":22,"text":"corr_df"},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":183,"id":2160,"name":"max","nodeType":"Attribute","startLoc":183,"text":"max"},{"attributeType":"null","col":0,"comment":"null","endLoc":23,"id":2161,"name":"index","nodeType":"Attribute","startLoc":23,"text":"corr_df.index"},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":184,"id":2162,"name":"resolution","nodeType":"Attribute","startLoc":184,"text":"resolution"},{"attributeType":"null","col":0,"comment":"null","endLoc":24,"id":2163,"name":"corr_df","nodeType":"Attribute","startLoc":24,"text":"corr_df"},{"attributeType":"dict","col":0,"comment":"null","endLoc":345,"id":2164,"name":"Dict","nodeType":"Attribute","startLoc":345,"text":"Dict"},{"className":"Hashable","col":0,"comment":"null","endLoc":418,"id":2165,"nodeType":"Class","startLoc":412,"text":"@runtime_checkable\nclass Hashable(Protocol, metaclass=ABCMeta):\n # TODO: This is special, in that a subclass of a hashable class may not be hashable\n # (for example, list vs. object). It's not obvious how to represent this. This class\n # is currently mostly useless for static checking.\n @abstractmethod\n def __hash__(self) -> int: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":2166,"name":"f","nodeType":"Attribute","startLoc":27,"text":"f"},{"col":4,"comment":"null","endLoc":418,"header":"@abstractmethod\n def __hash__(self) -> int","id":2167,"name":"__hash__","nodeType":"Function","startLoc":417,"text":"@abstractmethod\n def __hash__(self) -> int: ..."},{"className":"Default","col":0,"comment":"null","endLoc":36,"id":2168,"nodeType":"Class","startLoc":34,"text":"class Default:\n def __repr__(self):\n return \"\""},{"col":4,"comment":"null","endLoc":36,"header":"def __repr__(self)","id":2169,"name":"__repr__","nodeType":"Function","startLoc":35,"text":"def __repr__(self):\n return \"\""},{"attributeType":"null","col":0,"comment":"null","endLoc":18,"id":2170,"name":"VariableSpecList","nodeType":"Attribute","startLoc":18,"text":"VariableSpecList"},{"attributeType":"null","col":3,"comment":"null","endLoc":27,"id":2171,"name":"ax","nodeType":"Attribute","startLoc":27,"text":"ax"},{"col":0,"comment":"","endLoc":6,"header":"wide_form_violinplot.py#","id":2172,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nViolinplot from a wide-form dataset\n===================================\n\n_thumb: .6, .45\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ndf = sns.load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n\nused_networks = [1, 3, 4, 5, 6, 7, 8, 11, 12, 13, 16, 17]\n\nused_columns = (df.columns.get_level_values(\"network\")\n .astype(int)\n .isin(used_networks))\n\ndf = df.loc[:, used_columns]\n\ncorr_df = df.corr().groupby(level=\"network\").mean()\n\ncorr_df.index = corr_df.index.astype(int)\n\ncorr_df = corr_df.sort_index().T\n\nf, ax = plt.subplots(figsize=(11, 6))\n\nsns.violinplot(data=corr_df, palette=\"Set3\", bw=.2, cut=1, linewidth=1)\n\nax.set(ylim=(-.7, 1.05))\n\nsns.despine(left=True, bottom=True)"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":2173,"name":"ax","nodeType":"Attribute","startLoc":15,"text":"ax"},{"className":"Shift","col":0,"comment":"\n Displacement of all marks with the same magnitude / direction.\n ","endLoc":190,"id":2174,"nodeType":"Class","startLoc":175,"text":"@dataclass\nclass Shift(Move):\n \"\"\"\n Displacement of all marks with the same magnitude / direction.\n \"\"\"\n x: float = 0\n y: float = 0\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n data = data.copy(deep=False)\n data[\"x\"] = data[\"x\"] + self.x\n data[\"y\"] = data[\"y\"] + self.y\n return data"},{"col":4,"comment":"null","endLoc":957,"header":"def test_singular_data(self)","id":2175,"name":"test_singular_data","nodeType":"Function","startLoc":940,"text":"def test_singular_data(self):\n\n with pytest.warns(UserWarning):\n ax = dist.kdeplot(x=np.ones(10), y=np.arange(10))\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = dist.kdeplot(x=[5], y=[6])\n assert not ax.lines\n\n with pytest.warns(UserWarning):\n ax = kdeplot(x=[1929245168.06679] * 18, y=np.arange(18))\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\", UserWarning)\n ax = kdeplot(x=[5], y=[7], warn_singular=False)\n assert not ax.lines"},{"col":0,"comment":"","endLoc":7,"header":"scatterplot_categorical.py#","id":2176,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot with categorical variables\n======================================\n\n_thumb: .45, .45\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\", palette=\"muted\")\n\ndf = sns.load_dataset(\"penguins\")\n\nax = sns.swarmplot(data=df, x=\"body_mass_g\", y=\"sex\", hue=\"species\")\n\nax.set(ylabel=\"\")"},{"col":4,"comment":"null","endLoc":190,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":2177,"name":"__call__","nodeType":"Function","startLoc":183,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n data = data.copy(deep=False)\n data[\"x\"] = data[\"x\"] + self.x\n data[\"y\"] = data[\"y\"] + self.y\n return data"},{"col":0,"comment":"null","endLoc":2673,"header":"def swarmplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0, hue_norm=None,\n native_scale=False, formatter=None, legend=\"auto\", warn_thresh=.05,\n ax=None, **kwargs\n)","id":2178,"name":"swarmplot","nodeType":"Function","startLoc":2615,"text":"def swarmplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0, hue_norm=None,\n native_scale=False, formatter=None, legend=\"auto\", warn_thresh=.05,\n ax=None, **kwargs\n):\n\n p = _CategoricalPlotterNew(\n data=data,\n variables=_CategoricalPlotterNew.get_semantics(locals()),\n order=order,\n orient=orient,\n require_numeric=False,\n legend=legend,\n )\n\n if ax is None:\n ax = plt.gca()\n\n if p.var_types.get(p.cat_axis) == \"categorical\" or not native_scale:\n p.scale_categorical(p.cat_axis, order=order, formatter=formatter)\n\n p._attach(ax)\n\n if not p.has_xy_data:\n return ax\n\n hue_order = p._palette_without_hue_backcompat(palette, hue_order)\n palette, hue_order = p._hue_backcompat(color, palette, hue_order)\n\n color = _default_color(ax.scatter, hue, color, kwargs)\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # XXX Copying possibly bad default decisions from original code for now\n kwargs.setdefault(\"zorder\", 3)\n size = kwargs.get(\"s\", size)\n\n if linewidth is None:\n linewidth = size / 10\n\n kwargs.update(dict(\n s=size ** 2,\n linewidth=linewidth,\n ))\n\n p.plot_swarms(\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n warn_thresh=warn_thresh,\n plot_kws=kwargs,\n )\n\n p._add_axis_labels(ax)\n p._adjust_cat_axis(ax, axis=p.cat_axis)\n\n return ax"},{"id":2179,"name":"objects.Plot.theme.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"anscombe = load_dataset(\\\"anscombe\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"406f6608-daf2-4d3e-9f2c-1a9e93ecb840\",\n \"metadata\": {},\n \"source\": [\n \"The default theme uses the same parameters as :func:`seaborn.set_theme` with no additional arguments:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5e3d639c-1167-48d2-b9b5-c26b7fa12c66\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = (\\n\",\n \" so.Plot(anscombe, \\\"x\\\", \\\"y\\\")\\n\",\n \" .facet(\\\"dataset\\\", wrap=2)\\n\",\n \" .add(so.Line(), so.PolyFit(order=1))\\n\",\n \" .add(so.Dot())\\n\",\n \")\\n\",\n \"p\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e2823a91-47f1-40a8-a150-32f00bcb59ea\",\n \"metadata\": {},\n \"source\": [\n \"Pass a dictionary of rc parameters to change the appearance of the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"368c8cdb-2e6f-4520-8412-cd1864a6c09b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.theme({\\\"axes.facecolor\\\": \\\"w\\\", \\\"axes.edgecolor\\\": \\\"C0\\\"})\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"637cf0ba-e9b7-4f0f-a628-854e300c4122\",\n \"metadata\": {},\n \"source\": [\n \"Many (though not all) mark properties will reflect theme parameters by default:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9eb330b3-f424-405b-9653-5df9948792d9\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.theme({\\\"lines.linewidth\\\": 4})\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"2c8fa27e-d1ea-4376-a717-c3059ba1d272\",\n \"metadata\": {},\n \"source\": [\n \"Apply seaborn styles by passing in the output of the style functions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"48cafbb1-37da-42c7-a20e-b63c0fef4d41\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"from seaborn import axes_style\\n\",\n \"p.theme({**axes_style(\\\"ticks\\\")})\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"bbdecb4b-382a-49f3-8928-16f5f72c39b5\",\n \"metadata\": {},\n \"source\": [\n \"Or apply styles that ship with matplotlib:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"84a7ac28-798d-4560-bbc8-d214fd6fcada\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"from matplotlib import style\\n\",\n \"p.theme({**style.library[\\\"fivethirtyeight\\\"]})\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"dec4db5b-1b2b-4b9d-97e1-9cf0f20d6b83\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2180,"name":"v0.7.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.7.1 (June 2016)\n-------------------\n\n- Added the ability to put \"caps\" on the error bars that are drawn by :func:`barplot` or :func:`pointplot` (and, by extension, ``factorplot``). Additionally, the line width of the error bars can now be controlled. These changes involve the new parameters ``capsize`` and ``errwidth``. See the `github pull request (#898) `_ for examples of usage.\n\n- Improved the row and column colors display in :func:`clustermap`. It is now possible to pass Pandas objects for these elements and, when possible, the semantic information in the Pandas objects will be used to add labels to the plot. When Pandas objects are used, the color data is matched against the main heatmap based on the index, not on position. This is more accurate, but it may lead to different results if current code assumed positional matching.\n\n- Improved the luminance calculation that determines the annotation color in :func:`heatmap`.\n\n- The ``annot`` parameter of :func:`heatmap` now accepts a rectangular dataset in addition to a boolean value. If a dataset is passed, its values will be used for the annotations, while the main dataset will be used for the heatmap cell colors.\n\n- Fixed a bug in :class:`FacetGrid` that appeared when using ``col_wrap`` with missing ``col`` levels.\n\n- Made it possible to pass a tick locator object to the :func:`heatmap` colorbar.\n\n- Made it possible to use different styles (e.g., step) for :class:`PairGrid` histograms when there are multiple hue levels.\n\n- Fixed a bug in scipy-based univariate kernel density bandwidth calculation.\n\n- The :func:`reset_orig` function (and, by extension, importing ``seaborn.apionly``) resets matplotlib rcParams to their values at the time seaborn itself was imported, which should work better with rcParams changed by the jupyter notebook backend.\n\n- Removed some objects from the top-level ``seaborn`` namespace.\n\n- Improved unicode compatibility in :class:`FacetGrid`.\n"},{"id":2181,"name":"v0.9.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.9.1 (January 2020)\n---------------------\n\nThis is a minor release with a number of bug fixes and adaptations to changes in seaborn's dependencies. There are also several new features.\n\nThis is the final version of seaborn that will support Python 2.7 or 3.5.\n\nNew features\n~~~~~~~~~~~~\n\n- Added more control over the arrangement of the elements drawn by :func:`clustermap` with the ``{dendrogram,colors}_ratio`` and ``cbar_pos`` parameters. Additionally, the default organization and scaling with different figure sizes has been improved.\n\n- Added the ``corner`` option to :class:`PairGrid` and :func:`pairplot` to make a grid without the upper triangle of bivariate axes.\n\n- Added the ability to seed the random number generator for the bootstrap used to define error bars in several plots. Relevant functions now have a ``seed`` parameter, which can take either fixed seed (typically an ``int``) or a numpy random number generator object (either the newer :class:`numpy.random.Generator` or the older :class:`numpy.random.mtrand.RandomState`).\n\n- Generalized the idea of \"diagonal\" axes in :class:`PairGrid` to any axes that share an x and y variable.\n\n- In :class:`PairGrid`, the ``hue`` variable is now excluded from the default list of variables that make up the rows and columns of the grid.\n\n- Exposed the ``layout_pad`` parameter in :class:`PairGrid` and set a smaller default than what matptlotlib sets for more efficient use of space in dense grids.\n\n- It is now possible to force a categorical interpretation of the ``hue`` variable in a relational plot by passing the name of a categorical palette (e.g. ``\"deep\"``, or ``\"Set2\"``). This complements the (previously supported) option of passing a list/dict of colors.\n\n- Added the ``tree_kws`` parameter to :func:`clustermap` to control the properties of the lines in the dendrogram.\n\n- Added the ability to pass hierarchical label names to the :class:`FacetGrid` legend, which also fixes a bug in :func:`relplot` when the same label appeared in different semantics.\n\n- Improved support for grouping observations based on pandas index information in categorical plots.\n\nBug fixes and adaptations\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n- Avoided an error when singular data is passed to :func:`kdeplot`, issuing a warning instead. This makes :func:`pairplot` more robust.\n\n- Fixed the behavior of ``dropna`` in :class:`PairGrid` to properly exclude null datapoints from each plot when set to ``True``.\n\n- Fixed an issue where :func:`regplot` could interfere with other axes in a multi-plot matplotlib figure.\n\n- Semantic variables with a ``category`` data type will always be treated as categorical in relational plots.\n\n- Avoided a warning about color specifications that arose from :func:`boxenplot` on newer matplotlibs.\n\n- Adapted to a change in how matplotlib scales axis margins, which caused multiple calls to :func:`regplot` with ``truncate=False`` to progressively expand the x axis limits. Because there are currently limitations on how autoscaling works in matplotlib, the default value for ``truncate`` in seaborn has also been changed to ``True``.\n\n- Relational plots no longer error when hue/size data are inferred to be numeric but stored with a string datatype.\n\n- Relational plots now consider semantics with only a single value that can be interpreted as boolean (0 or 1) to be categorical, not numeric.\n\n- Relational plots now handle list or dict specifications for ``sizes`` correctly.\n\n- Fixed an issue in :func:`pointplot` where missing levels of a hue variable would cause an exception after a recent update in matplotlib.\n\n- Fixed a bug when setting the rotation of x tick labels on a :class:`FacetGrid`.\n\n- Fixed a bug where values would be excluded from categorical plots when only one variable was a pandas ``Series`` with a non-default index.\n\n- Fixed a bug when using ``Series`` objects as arguments for ``x_partial`` or ``y_partial`` in :func:`regplot`.\n\n- Fixed a bug when passing a ``norm`` object and using color annotations in :func:`clustermap`.\n\n- Fixed a bug where annotations were not rearranged to match the clustering in :func:`clustermap`.\n\n- Fixed a bug when trying to call :func:`set` while specifying a list of colors for the palette.\n\n- Fixed a bug when resetting the color code short-hands to the matplotlib default.\n\n- Avoided errors from stricter type checking in upcoming ``numpy`` changes.\n\n- Avoided error/warning in :func:`lineplot` when plotting categoricals with empty levels.\n\n- Allowed ``colors`` to be passed through to a bivariate :func:`kdeplot`.\n\n- Standardized the output format of custom color palette functions.\n\n- Fixed a bug where legends for numerical variables in a relational plot could show a surprisingly large number of decimal places.\n\n- Improved robustness to missing values in distribution plots.\n\n- Made it possible to specify the location of the :class:`FacetGrid` legend using matplotlib keyword arguments.\n"},{"id":2182,"name":"v0.9.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.9.0 (July 2018)\n------------------\n\nThis is a major release with several substantial and long-desired new features. There are also updates/modifications to the themes and color palettes that give better consistency with matplotlib 2.0 and some notable API changes.\n\nNew relational plots\n~~~~~~~~~~~~~~~~~~~~\n\nThree completely new plotting functions have been added: :func:`relplot`, :func:`scatterplot`, and :func:`lineplot`. The first is a figure-level interface to the latter two that combines them with a :class:`FacetGrid`. The functions bring the high-level, dataset-oriented API of the seaborn categorical plotting functions to more general plots (scatter plots and line plots).\n\nThese functions can visualize a relationship between two numeric variables while mapping up to three additional variables by modifying ``hue``, ``size``, and/or ``style`` semantics. The common high-level API is implemented differently in the two functions. For example, the size semantic in :func:`scatterplot` scales the area of scatter plot points, but in :func:`lineplot` it scales width of the line plot lines. The API is dataset-oriented, meaning that in both cases you pass the variable in your dataset rather than directly specifying the matplotlib parameters to use for point area or line width.\n\nAnother way the relational functions differ from existing seaborn functionality is that they have better support for using numeric variables for ``hue`` and ``size`` semantics. This functionality may be propagated to other functions that can add a ``hue`` semantic in future versions; it has not been in this release.\n\nThe :func:`lineplot` function also has support for statistical estimation and is replacing the older ``tsplot`` function, which still exists but is marked for removal in a future release. :func:`lineplot` is better aligned with the API of the rest of the library and more flexible in showing relationships across additional variables by modifying the size and style semantics independently. It also has substantially improved support for date and time data, a major pain factor in ``tsplot``. The cost is that some of the more esoteric options in ``tsplot`` for representing uncertainty (e.g. a colormapped KDE of the bootstrap distribution) have not been implemented in the new function.\n\nThere is quite a bit of new documentation that explains these new functions in more detail, including detailed examples of the various options in the :ref:`API reference ` and a more verbose :ref:`tutorial `.\n\nThese functions should be considered in a \"stable beta\" state. They have been thoroughly tested, but some unknown corner cases may remain to be found. The main features are in place, but not all planned functionality has been implemented. There are planned improvements to some elements, particularly the default legend, that are a little rough around the edges in this release. Finally, some of the default behavior (e.g. the default range of point/line sizes) may change somewhat in future releases.\n\nUpdates to themes and palettes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSeveral changes have been made to the seaborn style themes, context scaling, and color palettes. In general the aim of these changes was to make the seaborn styles more consistent with the `style updates in matplotlib 2.0 `_ and to leverage some of the new style parameters for better implementation of some aspects of the seaborn styles. Here is a list of the changes:\n\n- Reorganized and updated some :func:`axes_style`/:func:`plotting_context` parameters to take advantage of improvements in the matplotlib 2.0 update. The biggest change involves using several new parameters in the \"style\" spec while moving parameters that used to implement the corresponding aesthetics to the \"context\" spec. For example, axes spines and ticks are now off instead of having their width/length zeroed out for the darkgrid style. That means the width/length of these elements can now be scaled in different contexts. The effect is a more cohesive appearance of the plots, especially in larger contexts. These changes include only minimal support for the 1.x matplotlib series. Users who are stuck on matplotlib 1.5 but wish to use seaborn styling may want to use the seaborn parameters that can be accessed through the `matplotlib stylesheet interface `_.\n\n- Updated the seaborn palettes (\"deep\", \"muted\", \"colorblind\", etc.) to correspond with the new 10-color matplotlib default. The legacy palettes are now available at \"deep6\", \"muted6\", \"colorblind6\", etc. Additionally, a few individual colors were tweaked for better consistency, aesthetics, and accessibility.\n\n- Calling :func:`color_palette` (or :func:`set_palette`) with a named qualitative palettes (i.e. one of the seaborn palettes, the colorbrewer qualitative palettes, or the matplotlib matplotlib tableau-derived palettes) and no specified number of colors will return all of the colors in the palette. This means that for some palettes, the returned list will have a different length than it did in previous versions.\n\n- Enhanced :func:`color_palette` to accept a parameterized specification of a cubehelix palette in in a string, prefixed with ``\"ch:\"`` (e.g. ``\"ch:-.1,.2,l=.7\"``). Note that keyword arguments can be spelled out or referenced using only their first letter. Reversing the palette is accomplished by appending ``\"_r\"``, as with other matplotlib colormaps. This specification will be accepted by any seaborn function with a ``palette=`` parameter.\n\n- Slightly increased the base font sizes in :func:`plotting_context` and increased the scaling factors for ``\"talk\"`` and ``\"poster\"`` contexts.\n\n- Calling :func:`set` will now call :func:`set_color_codes` to re-assign the single letter color codes by default\n\nAPI changes\n~~~~~~~~~~~\n\nA few functions have been renamed or have had changes to their default parameters.\n\n- The ``factorplot`` function has been renamed to :func:`catplot`. The new name ditches the original R-inflected terminology to use a name that is more consistent with terminology in pandas and in seaborn itself. This change should hopefully make :func:`catplot` easier to discover, and it should make more clear what its role is. ``factorplot`` still exists and will pass its arguments through to :func:`catplot` with a warning. It may be removed eventually, but the transition will be as gradual as possible.\n\n- The other reason that the ``factorplot`` name was changed was to ease another alteration which is that the default ``kind`` in :func:`catplot` is now ``\"strip\"`` (corresponding to :func:`stripplot`). This plots a categorical scatter plot which is usually a much better place to start and is more consistent with the default in :func:`relplot`. The old default style in ``factorplot`` (``\"point\"``, corresponding to :func:`pointplot`) remains available if you want to show a statistical estimation.\n\n- The ``lvplot`` function has been renamed to :func:`boxenplot`. The \"letter-value\" terminology that was used to name the original kind of plot is obscure, and the abbreviation to ``lv`` did not help anything. The new name should make the plot more discoverable by describing its format (it plots multiple boxes, also known as \"boxen\"). As with ``factorplot``, the ``lvplot`` function still exists to provide a relatively smooth transition.\n\n- Renamed the ``size`` parameter to ``height`` in multi-plot grid objects (:class:`FacetGrid`, :class:`PairGrid`, and :class:`JointGrid`) along with functions that use them (``factorplot``, :func:`lmplot`, :func:`pairplot`, and :func:`jointplot`) to avoid conflicts with the ``size`` parameter that is used in ``scatterplot`` and ``lineplot`` (necessary to make :func:`relplot` work) and also makes the meaning of the parameter a bit more clear.\n\n- Changed the default diagonal plots in :func:`pairplot` to use func:`kdeplot` when a ``\"hue\"`` dimension is used.\n\n- Deprecated the statistical annotation component of :class:`JointGrid`. The method is still available but will be removed in a future version.\n\n- Two older functions that were deprecated in earlier versions, ``coefplot`` and ``interactplot``, have undergone final removal from the code base.\n\nDocumentation improvements\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere has been some effort put into improving the documentation. The biggest change is that the :ref:`introduction to the library ` has been completely rewritten to provide much more information and, critically, examples. In addition to the high-level motivation, the introduction also covers some important topics that are often sources of confusion, like the distinction between figure-level and axes-level functions, how datasets should be formatted for use in seaborn, and how to customize the appearance of the plots.\n\nOther improvements have been made throughout, most notably a thorough re-write of the :ref:`categorical tutorial `.\n\nOther small enhancements and bug fixes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n- Changed :func:`rugplot` to plot a matplotlib ``LineCollection`` instead of many ``Line2D`` objects, providing a big speedup for large arrays.\n\n- Changed the default off-diagonal plots to use :func:`scatterplot`. (Note that the ``\"hue\"`` currently draws three separate scatterplots instead of using the hue semantic of the scatterplot function).\n\n- Changed color handling when using :func:`kdeplot` with two variables. The default colormap for the 2D density now follows the color cycle, and the function can use ``color`` and ``label`` kwargs, adding more flexibility and avoiding a warning when using with multi-plot grids.\n\n- Added the ``subplot_kws`` parameter to :class:`PairGrid` for more flexibility.\n\n- Removed a special case in :class:`PairGrid` that defaulted to drawing stacked histograms on the diagonal axes.\n\n- Fixed :func:`jointplot`/:class:`JointGrid` and :func:`regplot` so that they now accept list inputs.\n\n- Fixed a bug in :class:`FacetGrid` when using a single row/column level or using ``col_wrap=1``.\n\n- Fixed functions that set axis limits so that they preserve auto-scaling state on matplotlib 2.0.\n\n- Avoided an error when using matplotlib backends that cannot render a canvas (e.g. PDF).\n\n- Changed the install infrastructure to explicitly declare dependencies in a way that ``pip`` is aware of. This means that ``pip install seaborn`` will now work in an empty environment. Additionally, the dependencies are specified with strict minimal versions.\n\n- Updated the testing infrastructure to execute tests with `pytest `_ (although many individual tests still use nose assertion).\n"},{"attributeType":"float","col":4,"comment":"null","endLoc":180,"id":2183,"name":"x","nodeType":"Attribute","startLoc":180,"text":"x"},{"id":2184,"name":"v0.4.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.4.0 (September 2014)\n-----------------------\n\nThis is a major release from 0.3. Highlights include new approaches for :ref:`quick, high-level dataset exploration ` (along with a more :ref:`flexible interface `) and easy creation of :ref:`perceptually-appropriate color palettes ` using the cubehelix system. Along with these additions, there are a number of smaller changes that make visualizing data with seaborn easier and more powerful.\n\nPlotting functions\n~~~~~~~~~~~~~~~~~~\n\n- A new object, :class:`PairGrid`, and a corresponding function :func:`pairplot`, for drawing grids of pairwise relationships in a dataset. This style of plot is sometimes called a \"scatterplot matrix\", but the representation of the data in :class:`PairGrid` is flexible and many styles other than scatterplots can be used. See the :ref:`docs ` for more information. **Note:** due to a bug in older versions of matplotlib, you will have best results if you use these functions with matplotlib 1.4 or later.\n\n- The rules for choosing default color palettes when variables are mapped to different colors have been unified (and thus changed in some cases). Now when no specific palette is requested, the current global color palette will be used, unless the number of variables to be mapped exceeds the number of unique colors in the palette, in which case the ``\"husl\"`` palette will be used to avoid cycling.\n\n- Added a keyword argument ``hist_norm`` to :func:`distplot`. When a :func:`distplot` is now drawn without a KDE or parametric density, the histogram is drawn as counts instead of a density. This can be overridden by by setting ``hist_norm`` to ``True``.\n\n- When using :class:`FacetGrid` with a ``hue`` variable, the legend is no longer drawn by default when you call :meth:`FacetGrid.map`. Instead, you have to call :meth:`FacetGrid.add_legend` manually. This should make it easier to layer multiple plots onto the grid without having duplicated legends.\n\n- Made some changes to ``factorplot`` so that it behaves better when not all levels of the ``x`` variable are represented in each facet.\n\n- Added the ``logx`` option to :func:`regplot` for fitting the regression in log space.\n\n- When :func:`violinplot` encounters a bin with only a single observation, it will now plot a horizontal line at that value instead of erroring out.\n\nStyle and color palettes\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n- Added the :func:`cubehelix_palette` function for generating sequential palettes from the cubehelix system. See the :ref:`palette docs ` for more information on how these palettes can be used. There is also the :func:`choose_cubehelix` which will launch an interactive app to select cubehelix parameters in the notebook.\n\n- Added the :func:`xkcd_palette` and the ``xkcd_rgb`` dictionary so that colors can be specified with names from the `xkcd color survey `_.\n\n- Added the ``font_scale`` option to :func:`plotting_context`, :func:`set_context`, and :func:`set`. ``font_scale`` can independently increase or decrease the size of the font elements in the plot.\n\n- Font-handling should work better on systems without Arial installed. This is accomplished by adding the ``font.sans-serif`` field to the ``axes_style`` definition with Arial and Liberation Sans prepended to matplotlib defaults. The font family can also be set through the ``font`` keyword argument in :func:`set`. Due to matplotlib bugs, this might not work as expected on matplotlib 1.3.\n\n- The :func:`despine` function gets a new keyword argument ``offset``, which replaces the deprecated :func:`offset_spines` function. You no longer need to offset the spines before plotting data.\n\n- Added a default value for ``pdf.fonttype`` so that text in PDFs is editable in Adobe Illustrator.\n\n\nOther API Changes\n~~~~~~~~~~~~~~~~~\n\n- Removed the deprecated ``set_color_palette`` and ``palette_context`` functions. These were replaced in version 0.3 by the :func:`set_palette` function and ability to use :func:`color_palette` directly in a ``with`` statement.\n\n- Removed the ability to specify a ``nogrid`` style, which was renamed to ``white`` in 0.3.\n"},{"attributeType":"float","col":4,"comment":"null","endLoc":181,"id":2185,"name":"y","nodeType":"Attribute","startLoc":181,"text":"y"},{"className":"Stack","col":0,"comment":"\n Displacement of overlapping bar or area marks along the value axis.\n ","endLoc":172,"id":2186,"nodeType":"Class","startLoc":140,"text":"@dataclass\nclass Stack(Move):\n \"\"\"\n Displacement of overlapping bar or area marks along the value axis.\n \"\"\"\n # TODO center? (or should this be a different move, eg. Stream())\n\n def _stack(self, df, orient):\n\n # TODO should stack do something with ymin/ymax style marks?\n # Should there be an upstream conversion to baseline/height parameterization?\n\n if df[\"baseline\"].nunique() > 1:\n err = \"Stack move cannot be used when baselines are already heterogeneous\"\n raise RuntimeError(err)\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n stacked_lengths = (df[other] - df[\"baseline\"]).dropna().cumsum()\n offsets = stacked_lengths.shift(1).fillna(0)\n\n df[other] = stacked_lengths\n df[\"baseline\"] = df[\"baseline\"] + offsets\n\n return df\n\n def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n # TODO where to ensure that other semantic variables are sorted properly?\n # TODO why are we not using the passed in groupby here?\n groupers = [\"col\", \"row\", orient]\n return GroupBy(groupers).apply(data, self._stack, orient)"},{"col":4,"comment":"null","endLoc":163,"header":"def _stack(self, df, orient)","id":2187,"name":"_stack","nodeType":"Function","startLoc":147,"text":"def _stack(self, df, orient):\n\n # TODO should stack do something with ymin/ymax style marks?\n # Should there be an upstream conversion to baseline/height parameterization?\n\n if df[\"baseline\"].nunique() > 1:\n err = \"Stack move cannot be used when baselines are already heterogeneous\"\n raise RuntimeError(err)\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n stacked_lengths = (df[other] - df[\"baseline\"]).dropna().cumsum()\n offsets = stacked_lengths.shift(1).fillna(0)\n\n df[other] = stacked_lengths\n df[\"baseline\"] = df[\"baseline\"] + offsets\n\n return df"},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":2188,"name":"OrderSpec","nodeType":"Attribute","startLoc":22,"text":"OrderSpec"},{"attributeType":"null","col":0,"comment":"null","endLoc":23,"id":2189,"name":"NormSpec","nodeType":"Attribute","startLoc":23,"text":"NormSpec"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":2190,"name":"PaletteSpec","nodeType":"Attribute","startLoc":27,"text":"PaletteSpec"},{"attributeType":"null","col":0,"comment":"null","endLoc":28,"id":2191,"name":"DiscreteValueSpec","nodeType":"Attribute","startLoc":28,"text":"DiscreteValueSpec"},{"attributeType":"null","col":0,"comment":"null","endLoc":29,"id":2192,"name":"ContinuousValueSpec","nodeType":"Attribute","startLoc":29,"text":"ContinuousValueSpec"},{"attributeType":"Default","col":0,"comment":"null","endLoc":39,"id":2193,"name":"default","nodeType":"Attribute","startLoc":39,"text":"default"},{"col":4,"comment":"null","endLoc":172,"header":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame","id":2194,"name":"__call__","nodeType":"Function","startLoc":165,"text":"def __call__(\n self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n ) -> DataFrame:\n\n # TODO where to ensure that other semantic variables are sorted properly?\n # TODO why are we not using the passed in groupby here?\n groupers = [\"col\", \"row\", orient]\n return GroupBy(groupers).apply(data, self._stack, orient)"},{"col":0,"comment":"","endLoc":1,"header":"typing.py#","id":2195,"name":"","nodeType":"Function","startLoc":1,"text":"ColumnName = Union[\n str, bytes, date, datetime, timedelta, bool, complex, Timestamp, Timedelta\n]\n\nVector = Union[Series, Index, ndarray]\n\nVariableSpec = Union[ColumnName, Vector, None]\n\nVariableSpecList = Union[List[VariableSpec], Index, None]\n\nDataSource = Union[DataFrame, Mapping[Hashable, Vector], None]\n\nOrderSpec = Union[Iterable, None] # TODO technically str is iterable\n\nNormSpec = Union[Tuple[Optional[float], Optional[float]], Normalize, None]\n\nPaletteSpec = Union[str, list, dict, Colormap, None]\n\nDiscreteValueSpec = Union[dict, list, None]\n\nContinuousValueSpec = Union[\n Tuple[float, float], List[float], Dict[Any, float], None,\n]\n\ndefault = Default()"},{"id":2196,"name":"ci","nodeType":"Package"},{"id":2197,"name":"deps_pinned.txt","nodeType":"TextFile","path":"ci","text":"numpy~=1.17.0\npandas~=0.25.0\nmatplotlib~=3.1.0\nscipy~=1.3.0\nstatsmodels~=0.10.0\n# Pillow added in install_requires for later matplotlibs\npillow>=6.2.0\ntyping_extensions\n"},{"id":2198,"name":".github/workflows","nodeType":"Package"},{"id":2199,"name":"ci.yaml","nodeType":"TextFile","path":".github/workflows","text":"name: CI\n\non:\n push:\n branches: [master, v0.*]\n pull_request:\n branches: master\n schedule:\n - cron: '0 6 * * 1,4' # Each Monday and Thursday at 06:00 UTC\n workflow_dispatch:\n\nenv:\n NB_KERNEL: python\n MPLBACKEND: Agg\n SEABORN_DATA: ${{ github.workspace }}/seaborn-data\n\njobs:\n build-docs:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n\n - name: Setup Python 3.10\n uses: actions/setup-python@v3\n with:\n python-version: \"3.10\"\n\n - name: Install seaborn\n run: |\n pip install --upgrade pip\n pip install .[stats,docs]\n\n - name: Install pandoc\n run: |\n sudo apt-get install pandoc\n\n - name: Cache datasets\n run: |\n git clone https://github.com/mwaskom/seaborn-data.git\n ls $SEABORN_DATA\n\n - name: Build docs\n env:\n SPHINXOPTS: -j `nproc`\n run: |\n cd doc\n make -j `nproc` notebooks\n make html\n\n\n run-tests:\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n python: [\"3.7\", \"3.8\", \"3.9\", \"3.10\"]\n install: [full]\n deps: [latest]\n\n include:\n - python: \"3.7\"\n install: full\n deps: pinned\n - python: \"3.10\"\n install: light\n deps: latest\n\n steps:\n - uses: actions/checkout@v3\n\n - name: Setup Python ${{ matrix.python }}\n uses: actions/setup-python@v3\n with:\n python-version: ${{ matrix.python }}\n\n - name: Install seaborn\n run: |\n pip install --upgrade pip wheel\n if [[ ${{matrix.install}} == 'full' ]]; then EXTRAS=',stats'; fi\n if [[ ${{matrix.deps }} == 'pinned' ]]; then DEPS='-r ci/deps_pinned.txt'; fi\n pip install .[dev$EXTRAS] $DEPS\n\n - name: Run tests\n run: make test\n\n - name: Upload coverage\n uses: codecov/codecov-action@v2\n if: ${{ success() }}\n\n lint:\n runs-on: ubuntu-latest\n strategy:\n fail-fast: false\n steps:\n\n - name: Checkout\n uses: actions/checkout@v2\n\n - name: Setup Python\n uses: actions/setup-python@v2\n\n - name: Install tools\n run: pip install mypy flake8\n\n - name: Flake8\n run: make lint\n\n - name: Type checking\n run: make typecheck\n"},{"col":0,"comment":"","endLoc":28,"header":"objects.py#","id":2200,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nA declarative, object-oriented interface for creating statistical graphics.\n\nThe seaborn.objects namespace contains a number of classes that can be composed\ntogether to build a customized visualization.\n\nThe main object is :class:`Plot`, which is the starting point for all figures.\nPass :class:`Plot` a dataset and specify assignments from its variables to\nroles in the plot. Build up the visualization by calling its methods.\n\nThere are four other general types of objects in this interface:\n\n- :class:`Mark` subclasses, which create matplotlib artists for visualization\n- :class:`Stat` subclasses, which apply statistical transforms before plotting\n- :class:`Move` subclasses, which make further adjustments to reduce overplotting\n\nThese classes are passed to :meth:`Plot.add` to define a layer in the plot.\nEach layer has a :class:`Mark` and optional :class:`Stat` and/or :class:`Move`.\nPlots can have multiple layers.\n\nThe other general type of object is a :class:`Scale` subclass, which provide an\ninterface for controlling the mappings between data values and visual properties.\nPass :class:`Scale` objects to :meth:`Plot.scale`.\n\nSee the documentation for other :class:`Plot` methods to learn about the many\nways that a plot can be enhanced and customized.\n\n\"\"\""},{"fileName":"axisgrid.py","filePath":"seaborn","id":2201,"nodeType":"File","text":"from __future__ import annotations\nfrom itertools import product\nfrom inspect import signature\nimport warnings\nfrom textwrap import dedent\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom ._oldcore import VectorPlotter, variable_type, categorical_order\nfrom ._compat import share_axis\nfrom . import utils\nfrom .utils import (\n adjust_legend_subtitles, _check_argument, _draw_figure, _disable_autolayout\n)\nfrom .palettes import color_palette, blend_palette\nfrom ._docstrings import (\n DocstringComponents,\n _core_docs,\n)\n\n__all__ = [\"FacetGrid\", \"PairGrid\", \"JointGrid\", \"pairplot\", \"jointplot\"]\n\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n)\n\n\nclass _BaseGrid:\n \"\"\"Base class for grids of subplots.\"\"\"\n\n def set(self, **kwargs):\n \"\"\"Set attributes on each subplot Axes.\"\"\"\n for ax in self.axes.flat:\n if ax is not None: # Handle removed axes\n ax.set(**kwargs)\n return self\n\n @property\n def fig(self):\n \"\"\"DEPRECATED: prefer the `figure` property.\"\"\"\n # Grid.figure is preferred because it matches the Axes attribute name.\n # But as the maintanace burden on having this property is minimal,\n # let's be slow about formally deprecating it. For now just note its deprecation\n # in the docstring; add a warning in version 0.13, and eventually remove it.\n return self._figure\n\n @property\n def figure(self):\n \"\"\"Access the :class:`matplotlib.figure.Figure` object underlying the grid.\"\"\"\n return self._figure\n\n def apply(self, func, *args, **kwargs):\n \"\"\"\n Pass the grid to a user-supplied function and return self.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` is ignored; this method returns self.\n See the `pipe` method if you want the return value.\n\n Added in v0.12.0.\n\n \"\"\"\n func(self, *args, **kwargs)\n return self\n\n def pipe(self, func, *args, **kwargs):\n \"\"\"\n Pass the grid to a user-supplied function and return its value.\n\n The `func` must accept an object of this type for its first\n positional argument. Additional arguments are passed through.\n The return value of `func` becomes the return value of this method.\n See the `apply` method if you want to return self instead.\n\n Added in v0.12.0.\n\n \"\"\"\n return func(self, *args, **kwargs)\n\n def savefig(self, *args, **kwargs):\n \"\"\"\n Save an image of the plot.\n\n This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches=\"tight\"\n by default. Parameters are passed through to the matplotlib function.\n\n \"\"\"\n kwargs = kwargs.copy()\n kwargs.setdefault(\"bbox_inches\", \"tight\")\n self.figure.savefig(*args, **kwargs)\n\n\nclass Grid(_BaseGrid):\n \"\"\"A grid that can have multiple subplots and an external legend.\"\"\"\n _margin_titles = False\n _legend_out = True\n\n def __init__(self):\n\n self._tight_layout_rect = [0, 0, 1, 1]\n self._tight_layout_pad = None\n\n # This attribute is set externally and is a hack to handle newer functions that\n # don't add proxy artists onto the Axes. We need an overall cleaner approach.\n self._extract_legend_handles = False\n\n def tight_layout(self, *args, **kwargs):\n \"\"\"Call fig.tight_layout within rect that exclude the legend.\"\"\"\n kwargs = kwargs.copy()\n kwargs.setdefault(\"rect\", self._tight_layout_rect)\n if self._tight_layout_pad is not None:\n kwargs.setdefault(\"pad\", self._tight_layout_pad)\n self._figure.tight_layout(*args, **kwargs)\n return self\n\n def add_legend(self, legend_data=None, title=None, label_order=None,\n adjust_subtitles=False, **kwargs):\n \"\"\"Draw a legend, maybe placing it outside axes and resizing the figure.\n\n Parameters\n ----------\n legend_data : dict\n Dictionary mapping label names (or two-element tuples where the\n second element is a label name) to matplotlib artist handles. The\n default reads from ``self._legend_data``.\n title : string\n Title for the legend. The default reads from ``self._hue_var``.\n label_order : list of labels\n The order that the legend entries should appear in. The default\n reads from ``self.hue_names``.\n adjust_subtitles : bool\n If True, modify entries with invisible artists to left-align\n the labels and set the font size to that of a title.\n kwargs : key, value pairings\n Other keyword arguments are passed to the underlying legend methods\n on the Figure or Axes object.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n \"\"\"\n # Find the data for the legend\n if legend_data is None:\n legend_data = self._legend_data\n if label_order is None:\n if self.hue_names is None:\n label_order = list(legend_data.keys())\n else:\n label_order = list(map(utils.to_utf8, self.hue_names))\n\n blank_handle = mpl.patches.Patch(alpha=0, linewidth=0)\n handles = [legend_data.get(l, blank_handle) for l in label_order]\n title = self._hue_var if title is None else title\n title_size = mpl.rcParams[\"legend.title_fontsize\"]\n\n # Unpack nested labels from a hierarchical legend\n labels = []\n for entry in label_order:\n if isinstance(entry, tuple):\n _, label = entry\n else:\n label = entry\n labels.append(label)\n\n # Set default legend kwargs\n kwargs.setdefault(\"scatterpoints\", 1)\n\n if self._legend_out:\n\n kwargs.setdefault(\"frameon\", False)\n kwargs.setdefault(\"loc\", \"center right\")\n\n # Draw a full-figure legend outside the grid\n figlegend = self._figure.legend(handles, labels, **kwargs)\n\n self._legend = figlegend\n figlegend.set_title(title, prop={\"size\": title_size})\n\n if adjust_subtitles:\n adjust_legend_subtitles(figlegend)\n\n # Draw the plot to set the bounding boxes correctly\n _draw_figure(self._figure)\n\n # Calculate and set the new width of the figure so the legend fits\n legend_width = figlegend.get_window_extent().width / self._figure.dpi\n fig_width, fig_height = self._figure.get_size_inches()\n self._figure.set_size_inches(fig_width + legend_width, fig_height)\n\n # Draw the plot again to get the new transformations\n _draw_figure(self._figure)\n\n # Now calculate how much space we need on the right side\n legend_width = figlegend.get_window_extent().width / self._figure.dpi\n space_needed = legend_width / (fig_width + legend_width)\n margin = .04 if self._margin_titles else .01\n self._space_needed = margin + space_needed\n right = 1 - self._space_needed\n\n # Place the subplot axes to give space for the legend\n self._figure.subplots_adjust(right=right)\n self._tight_layout_rect[2] = right\n\n else:\n # Draw a legend in the first axis\n ax = self.axes.flat[0]\n kwargs.setdefault(\"loc\", \"best\")\n\n leg = ax.legend(handles, labels, **kwargs)\n leg.set_title(title, prop={\"size\": title_size})\n self._legend = leg\n\n if adjust_subtitles:\n adjust_legend_subtitles(leg)\n\n return self\n\n def _update_legend_data(self, ax):\n \"\"\"Extract the legend data from an axes object and save it.\"\"\"\n data = {}\n\n # Get data directly from the legend, which is necessary\n # for newer functions that don't add labeled proxy artists\n if ax.legend_ is not None and self._extract_legend_handles:\n handles = ax.legend_.legendHandles\n labels = [t.get_text() for t in ax.legend_.texts]\n data.update({l: h for h, l in zip(handles, labels)})\n\n handles, labels = ax.get_legend_handles_labels()\n data.update({l: h for h, l in zip(handles, labels)})\n\n self._legend_data.update(data)\n\n # Now clear the legend\n ax.legend_ = None\n\n def _get_palette(self, data, hue, hue_order, palette):\n \"\"\"Get a list of colors for the hue variable.\"\"\"\n if hue is None:\n palette = color_palette(n_colors=1)\n\n else:\n hue_names = categorical_order(data[hue], hue_order)\n n_colors = len(hue_names)\n\n # By default use either the current color palette or HUSL\n if palette is None:\n current_palette = utils.get_color_cycle()\n if n_colors > len(current_palette):\n colors = color_palette(\"husl\", n_colors)\n else:\n colors = color_palette(n_colors=n_colors)\n\n # Allow for palette to map from hue variable names\n elif isinstance(palette, dict):\n color_names = [palette[h] for h in hue_names]\n colors = color_palette(color_names, n_colors)\n\n # Otherwise act as if we just got a list of colors\n else:\n colors = color_palette(palette, n_colors)\n\n palette = color_palette(colors, n_colors)\n\n return palette\n\n @property\n def legend(self):\n \"\"\"The :class:`matplotlib.legend.Legend` object, if present.\"\"\"\n try:\n return self._legend\n except AttributeError:\n return None\n\n def tick_params(self, axis='both', **kwargs):\n \"\"\"Modify the ticks, tick labels, and gridlines.\n\n Parameters\n ----------\n axis : {'x', 'y', 'both'}\n The axis on which to apply the formatting.\n kwargs : keyword arguments\n Additional keyword arguments to pass to\n :meth:`matplotlib.axes.Axes.tick_params`.\n\n Returns\n -------\n self : Grid instance\n Returns self for easy chaining.\n\n \"\"\"\n for ax in self.figure.axes:\n ax.tick_params(axis=axis, **kwargs)\n return self\n\n\n_facet_docs = dict(\n\n data=dedent(\"\"\"\\\n data : DataFrame\n Tidy (\"long-form\") dataframe where each column is a variable and each\n row is an observation.\\\n \"\"\"),\n rowcol=dedent(\"\"\"\\\n row, col : vectors or keys in ``data``\n Variables that define subsets to plot on different facets.\\\n \"\"\"),\n rowcol_order=dedent(\"\"\"\\\n {row,col}_order : vector of strings\n Specify the order in which levels of the ``row`` and/or ``col`` variables\n appear in the grid of subplots.\\\n \"\"\"),\n col_wrap=dedent(\"\"\"\\\n col_wrap : int\n \"Wrap\" the column variable at this width, so that the column facets\n span multiple rows. Incompatible with a ``row`` facet.\\\n \"\"\"),\n share_xy=dedent(\"\"\"\\\n share{x,y} : bool, 'col', or 'row' optional\n If true, the facets will share y axes across columns and/or x axes\n across rows.\\\n \"\"\"),\n height=dedent(\"\"\"\\\n height : scalar\n Height (in inches) of each facet. See also: ``aspect``.\\\n \"\"\"),\n aspect=dedent(\"\"\"\\\n aspect : scalar\n Aspect ratio of each facet, so that ``aspect * height`` gives the width\n of each facet in inches.\\\n \"\"\"),\n palette=dedent(\"\"\"\\\n palette : palette name, list, or dict\n Colors to use for the different levels of the ``hue`` variable. Should\n be something that can be interpreted by :func:`color_palette`, or a\n dictionary mapping hue levels to matplotlib colors.\\\n \"\"\"),\n legend_out=dedent(\"\"\"\\\n legend_out : bool\n If ``True``, the figure size will be extended, and the legend will be\n drawn outside the plot on the center right.\\\n \"\"\"),\n margin_titles=dedent(\"\"\"\\\n margin_titles : bool\n If ``True``, the titles for the row variable are drawn to the right of\n the last column. This option is experimental and may not work in all\n cases.\\\n \"\"\"),\n facet_kws=dedent(\"\"\"\\\n facet_kws : dict\n Additional parameters passed to :class:`FacetGrid`.\n \"\"\"),\n)\n\n\nclass FacetGrid(Grid):\n \"\"\"Multi-plot grid for plotting conditional relationships.\"\"\"\n\n def __init__(\n self, data, *,\n row=None, col=None, hue=None, col_wrap=None,\n sharex=True, sharey=True, height=3, aspect=1, palette=None,\n row_order=None, col_order=None, hue_order=None, hue_kws=None,\n dropna=False, legend_out=True, despine=True,\n margin_titles=False, xlim=None, ylim=None, subplot_kws=None,\n gridspec_kws=None,\n ):\n\n super().__init__()\n\n # Determine the hue facet layer information\n hue_var = hue\n if hue is None:\n hue_names = None\n else:\n hue_names = categorical_order(data[hue], hue_order)\n\n colors = self._get_palette(data, hue, hue_order, palette)\n\n # Set up the lists of names for the row and column facet variables\n if row is None:\n row_names = []\n else:\n row_names = categorical_order(data[row], row_order)\n\n if col is None:\n col_names = []\n else:\n col_names = categorical_order(data[col], col_order)\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n hue_kws = hue_kws if hue_kws is not None else {}\n\n # Make a boolean mask that is True anywhere there is an NA\n # value in one of the faceting variables, but only if dropna is True\n none_na = np.zeros(len(data), bool)\n if dropna:\n row_na = none_na if row is None else data[row].isnull()\n col_na = none_na if col is None else data[col].isnull()\n hue_na = none_na if hue is None else data[hue].isnull()\n not_na = ~(row_na | col_na | hue_na)\n else:\n not_na = ~none_na\n\n # Compute the grid shape\n ncol = 1 if col is None else len(col_names)\n nrow = 1 if row is None else len(row_names)\n self._n_facets = ncol * nrow\n\n self._col_wrap = col_wrap\n if col_wrap is not None:\n if row is not None:\n err = \"Cannot use `row` and `col_wrap` together.\"\n raise ValueError(err)\n ncol = col_wrap\n nrow = int(np.ceil(len(col_names) / col_wrap))\n self._ncol = ncol\n self._nrow = nrow\n\n # Calculate the base figure size\n # This can get stretched later by a legend\n # TODO this doesn't account for axis labels\n figsize = (ncol * height * aspect, nrow * height)\n\n # Validate some inputs\n if col_wrap is not None:\n margin_titles = False\n\n # Build the subplot keyword dictionary\n subplot_kws = {} if subplot_kws is None else subplot_kws.copy()\n gridspec_kws = {} if gridspec_kws is None else gridspec_kws.copy()\n if xlim is not None:\n subplot_kws[\"xlim\"] = xlim\n if ylim is not None:\n subplot_kws[\"ylim\"] = ylim\n\n # --- Initialize the subplot grid\n\n with _disable_autolayout():\n fig = plt.figure(figsize=figsize)\n\n if col_wrap is None:\n\n kwargs = dict(squeeze=False,\n sharex=sharex, sharey=sharey,\n subplot_kw=subplot_kws,\n gridspec_kw=gridspec_kws)\n\n axes = fig.subplots(nrow, ncol, **kwargs)\n\n if col is None and row is None:\n axes_dict = {}\n elif col is None:\n axes_dict = dict(zip(row_names, axes.flat))\n elif row is None:\n axes_dict = dict(zip(col_names, axes.flat))\n else:\n facet_product = product(row_names, col_names)\n axes_dict = dict(zip(facet_product, axes.flat))\n\n else:\n\n # If wrapping the col variable we need to make the grid ourselves\n if gridspec_kws:\n warnings.warn(\"`gridspec_kws` ignored when using `col_wrap`\")\n\n n_axes = len(col_names)\n axes = np.empty(n_axes, object)\n axes[0] = fig.add_subplot(nrow, ncol, 1, **subplot_kws)\n if sharex:\n subplot_kws[\"sharex\"] = axes[0]\n if sharey:\n subplot_kws[\"sharey\"] = axes[0]\n for i in range(1, n_axes):\n axes[i] = fig.add_subplot(nrow, ncol, i + 1, **subplot_kws)\n\n axes_dict = dict(zip(col_names, axes))\n\n # --- Set up the class attributes\n\n # Attributes that are part of the public API but accessed through\n # a property so that Sphinx adds them to the auto class doc\n self._figure = fig\n self._axes = axes\n self._axes_dict = axes_dict\n self._legend = None\n\n # Public attributes that aren't explicitly documented\n # (It's not obvious that having them be public was a good idea)\n self.data = data\n self.row_names = row_names\n self.col_names = col_names\n self.hue_names = hue_names\n self.hue_kws = hue_kws\n\n # Next the private variables\n self._nrow = nrow\n self._row_var = row\n self._ncol = ncol\n self._col_var = col\n\n self._margin_titles = margin_titles\n self._margin_titles_texts = []\n self._col_wrap = col_wrap\n self._hue_var = hue_var\n self._colors = colors\n self._legend_out = legend_out\n self._legend_data = {}\n self._x_var = None\n self._y_var = None\n self._sharex = sharex\n self._sharey = sharey\n self._dropna = dropna\n self._not_na = not_na\n\n # --- Make the axes look good\n\n self.set_titles()\n self.tight_layout()\n\n if despine:\n self.despine()\n\n if sharex in [True, 'col']:\n for ax in self._not_bottom_axes:\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n ax.xaxis.label.set_visible(False)\n\n if sharey in [True, 'row']:\n for ax in self._not_left_axes:\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n ax.yaxis.label.set_visible(False)\n\n __init__.__doc__ = dedent(\"\"\"\\\n Initialize the matplotlib figure and FacetGrid object.\n\n This class maps a dataset onto multiple axes arrayed in a grid of rows\n and columns that correspond to *levels* of variables in the dataset.\n The plots it produces are often called \"lattice\", \"trellis\", or\n \"small-multiple\" graphics.\n\n It can also represent levels of a third variable with the ``hue``\n parameter, which plots different subsets of data in different colors.\n This uses color to resolve elements on a third dimension, but only\n draws subsets on top of each other and will not tailor the ``hue``\n parameter for the specific visualization the way that axes-level\n functions that accept ``hue`` will.\n\n The basic workflow is to initialize the :class:`FacetGrid` object with\n the dataset and the variables that are used to structure the grid. Then\n one or more plotting functions can be applied to each subset by calling\n :meth:`FacetGrid.map` or :meth:`FacetGrid.map_dataframe`. Finally, the\n plot can be tweaked with other methods to do things like change the\n axis labels, use different ticks, or add a legend. See the detailed\n code examples below for more information.\n\n .. warning::\n\n When using seaborn functions that infer semantic mappings from a\n dataset, care must be taken to synchronize those mappings across\n facets (e.g., by defining the ``hue`` mapping with a palette dict or\n setting the data type of the variables to ``category``). In most cases,\n it will be better to use a figure-level function (e.g. :func:`relplot`\n or :func:`catplot`) than to use :class:`FacetGrid` directly.\n\n See the :ref:`tutorial ` for more information.\n\n Parameters\n ----------\n {data}\n row, col, hue : strings\n Variables that define subsets of the data, which will be drawn on\n separate facets in the grid. See the ``{{var}}_order`` parameters to\n control the order of levels of this variable.\n {col_wrap}\n {share_xy}\n {height}\n {aspect}\n {palette}\n {{row,col,hue}}_order : lists\n Order for the levels of the faceting variables. By default, this\n will be the order that the levels appear in ``data`` or, if the\n variables are pandas categoricals, the category order.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n {legend_out}\n despine : boolean\n Remove the top and right spines from the plots.\n {margin_titles}\n {{x, y}}lim: tuples\n Limits for each of the axes on each facet (only relevant when\n share{{x, y}} is True).\n subplot_kws : dict\n Dictionary of keyword arguments passed to matplotlib subplot(s)\n methods.\n gridspec_kws : dict\n Dictionary of keyword arguments passed to\n :class:`matplotlib.gridspec.GridSpec`\n (via :meth:`matplotlib.figure.Figure.subplots`).\n Ignored if ``col_wrap`` is not ``None``.\n\n See Also\n --------\n PairGrid : Subplot grid for plotting pairwise relationships\n relplot : Combine a relational plot and a :class:`FacetGrid`\n displot : Combine a distribution plot and a :class:`FacetGrid`\n catplot : Combine a categorical plot and a :class:`FacetGrid`\n lmplot : Combine a regression plot and a :class:`FacetGrid`\n\n Examples\n --------\n\n .. note::\n\n These examples use seaborn functions to demonstrate some of the\n advanced features of the class, but in most cases you will want\n to use figue-level functions (e.g. :func:`displot`, :func:`relplot`)\n to make the plots shown here.\n\n .. include:: ../docstrings/FacetGrid.rst\n\n \"\"\").format(**_facet_docs)\n\n def facet_data(self):\n \"\"\"Generator for name indices and data subsets for each facet.\n\n Yields\n ------\n (i, j, k), data_ijk : tuple of ints, DataFrame\n The ints provide an index into the {row, col, hue}_names attribute,\n and the dataframe contains a subset of the full data corresponding\n to each facet. The generator yields subsets that correspond with\n the self.axes.flat iterator, or self.axes[i, j] when `col_wrap`\n is None.\n\n \"\"\"\n data = self.data\n\n # Construct masks for the row variable\n if self.row_names:\n row_masks = [data[self._row_var] == n for n in self.row_names]\n else:\n row_masks = [np.repeat(True, len(self.data))]\n\n # Construct masks for the column variable\n if self.col_names:\n col_masks = [data[self._col_var] == n for n in self.col_names]\n else:\n col_masks = [np.repeat(True, len(self.data))]\n\n # Construct masks for the hue variable\n if self.hue_names:\n hue_masks = [data[self._hue_var] == n for n in self.hue_names]\n else:\n hue_masks = [np.repeat(True, len(self.data))]\n\n # Here is the main generator loop\n for (i, row), (j, col), (k, hue) in product(enumerate(row_masks),\n enumerate(col_masks),\n enumerate(hue_masks)):\n data_ijk = data[row & col & hue & self._not_na]\n yield (i, j, k), data_ijk\n\n def map(self, func, *args, **kwargs):\n \"\"\"Apply a plotting function to each facet's subset of the data.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. It\n must plot to the currently active matplotlib Axes and take a\n `color` keyword argument. If faceting on the `hue` dimension,\n it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # How we use the function depends on where it comes from\n func_module = str(getattr(func, \"__module__\", \"\"))\n\n # Check for categorical plots without order information\n if func_module == \"seaborn.categorical\":\n if \"order\" not in kwargs:\n warning = (\"Using the {} function without specifying \"\n \"`order` is likely to produce an incorrect \"\n \"plot.\".format(func.__name__))\n warnings.warn(warning)\n if len(args) == 3 and \"hue_order\" not in kwargs:\n warning = (\"Using the {} function without specifying \"\n \"`hue_order` is likely to produce an incorrect \"\n \"plot.\".format(func.__name__))\n warnings.warn(warning)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.size:\n continue\n\n # Get the current axis\n modify_state = not func_module.startswith(\"seaborn\")\n ax = self.facet_axis(row_i, col_j, modify_state)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = utils.to_utf8(self.hue_names[hue_k])\n\n # Get the actual data we are going to plot with\n plot_data = data_ijk[list(args)]\n if self._dropna:\n plot_data = plot_data.dropna()\n plot_args = [v for k, v in plot_data.items()]\n\n # Some matplotlib functions don't handle pandas objects correctly\n if func_module.startswith(\"matplotlib\"):\n plot_args = [v.values for v in plot_args]\n\n # Draw the plot\n self._facet_plot(func, ax, plot_args, kwargs)\n\n # Finalize the annotations and layout\n self._finalize_grid(args[:2])\n\n return self\n\n def map_dataframe(self, func, *args, **kwargs):\n \"\"\"Like ``.map`` but passes args as strings and inserts data in kwargs.\n\n This method is suitable for plotting with functions that accept a\n long-form DataFrame as a `data` keyword argument and access the\n data in that DataFrame using string variable names.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. Unlike\n the `map` method, a function used here must \"understand\" Pandas\n objects. It also must plot to the currently active matplotlib Axes\n and take a `color` keyword argument. If faceting on the `hue`\n dimension, it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.size:\n continue\n\n # Get the current axis\n modify_state = not str(func.__module__).startswith(\"seaborn\")\n ax = self.facet_axis(row_i, col_j, modify_state)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = self.hue_names[hue_k]\n\n # Stick the facet dataframe into the kwargs\n if self._dropna:\n data_ijk = data_ijk.dropna()\n kwargs[\"data\"] = data_ijk\n\n # Draw the plot\n self._facet_plot(func, ax, args, kwargs)\n\n # For axis labels, prefer to use positional args for backcompat\n # but also extract the x/y kwargs and use if no corresponding arg\n axis_labels = [kwargs.get(\"x\", None), kwargs.get(\"y\", None)]\n for i, val in enumerate(args[:2]):\n axis_labels[i] = val\n self._finalize_grid(axis_labels)\n\n return self\n\n def _facet_color(self, hue_index, kw_color):\n\n color = self._colors[hue_index]\n if kw_color is not None:\n return kw_color\n elif color is not None:\n return color\n\n def _facet_plot(self, func, ax, plot_args, plot_kwargs):\n\n # Draw the plot\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs = plot_kwargs.copy()\n semantics = [\"x\", \"y\", \"hue\", \"size\", \"style\"]\n for key, val in zip(semantics, plot_args):\n plot_kwargs[key] = val\n plot_args = []\n plot_kwargs[\"ax\"] = ax\n func(*plot_args, **plot_kwargs)\n\n # Sort out the supporting information\n self._update_legend_data(ax)\n\n def _finalize_grid(self, axlabels):\n \"\"\"Finalize the annotations and layout.\"\"\"\n self.set_axis_labels(*axlabels)\n self.tight_layout()\n\n def facet_axis(self, row_i, col_j, modify_state=True):\n \"\"\"Make the axis identified by these indices active and return it.\"\"\"\n\n # Calculate the actual indices of the axes to plot on\n if self._col_wrap is not None:\n ax = self.axes.flat[col_j]\n else:\n ax = self.axes[row_i, col_j]\n\n # Get a reference to the axes object we want, and make it active\n if modify_state:\n plt.sca(ax)\n return ax\n\n def despine(self, **kwargs):\n \"\"\"Remove axis spines from the facets.\"\"\"\n utils.despine(self._figure, **kwargs)\n return self\n\n def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs):\n \"\"\"Set axis labels on the left column and bottom row of the grid.\"\"\"\n if x_var is not None:\n self._x_var = x_var\n self.set_xlabels(x_var, clear_inner=clear_inner, **kwargs)\n if y_var is not None:\n self._y_var = y_var\n self.set_ylabels(y_var, clear_inner=clear_inner, **kwargs)\n\n return self\n\n def set_xlabels(self, label=None, clear_inner=True, **kwargs):\n \"\"\"Label the x axis on the bottom row of the grid.\"\"\"\n if label is None:\n label = self._x_var\n for ax in self._bottom_axes:\n ax.set_xlabel(label, **kwargs)\n if clear_inner:\n for ax in self._not_bottom_axes:\n ax.set_xlabel(\"\")\n return self\n\n def set_ylabels(self, label=None, clear_inner=True, **kwargs):\n \"\"\"Label the y axis on the left column of the grid.\"\"\"\n if label is None:\n label = self._y_var\n for ax in self._left_axes:\n ax.set_ylabel(label, **kwargs)\n if clear_inner:\n for ax in self._not_left_axes:\n ax.set_ylabel(\"\")\n return self\n\n def set_xticklabels(self, labels=None, step=None, **kwargs):\n \"\"\"Set x axis tick labels of the grid.\"\"\"\n for ax in self.axes.flat:\n curr_ticks = ax.get_xticks()\n ax.set_xticks(curr_ticks)\n if labels is None:\n curr_labels = [l.get_text() for l in ax.get_xticklabels()]\n if step is not None:\n xticks = ax.get_xticks()[::step]\n curr_labels = curr_labels[::step]\n ax.set_xticks(xticks)\n ax.set_xticklabels(curr_labels, **kwargs)\n else:\n ax.set_xticklabels(labels, **kwargs)\n return self\n\n def set_yticklabels(self, labels=None, **kwargs):\n \"\"\"Set y axis tick labels on the left column of the grid.\"\"\"\n for ax in self.axes.flat:\n curr_ticks = ax.get_yticks()\n ax.set_yticks(curr_ticks)\n if labels is None:\n curr_labels = [l.get_text() for l in ax.get_yticklabels()]\n ax.set_yticklabels(curr_labels, **kwargs)\n else:\n ax.set_yticklabels(labels, **kwargs)\n return self\n\n def set_titles(self, template=None, row_template=None, col_template=None,\n **kwargs):\n \"\"\"Draw titles either above each facet or on the grid margins.\n\n Parameters\n ----------\n template : string\n Template for all titles with the formatting keys {col_var} and\n {col_name} (if using a `col` faceting variable) and/or {row_var}\n and {row_name} (if using a `row` faceting variable).\n row_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {row_var} and {row_name} formatting keys.\n col_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {col_var} and {col_name} formatting keys.\n\n Returns\n -------\n self: object\n Returns self.\n\n \"\"\"\n args = dict(row_var=self._row_var, col_var=self._col_var)\n kwargs[\"size\"] = kwargs.pop(\"size\", mpl.rcParams[\"axes.labelsize\"])\n\n # Establish default templates\n if row_template is None:\n row_template = \"{row_var} = {row_name}\"\n if col_template is None:\n col_template = \"{col_var} = {col_name}\"\n if template is None:\n if self._row_var is None:\n template = col_template\n elif self._col_var is None:\n template = row_template\n else:\n template = \" | \".join([row_template, col_template])\n\n row_template = utils.to_utf8(row_template)\n col_template = utils.to_utf8(col_template)\n template = utils.to_utf8(template)\n\n if self._margin_titles:\n\n # Remove any existing title texts\n for text in self._margin_titles_texts:\n text.remove()\n self._margin_titles_texts = []\n\n if self.row_names is not None:\n # Draw the row titles on the right edge of the grid\n for i, row_name in enumerate(self.row_names):\n ax = self.axes[i, -1]\n args.update(dict(row_name=row_name))\n title = row_template.format(**args)\n text = ax.annotate(\n title, xy=(1.02, .5), xycoords=\"axes fraction\",\n rotation=270, ha=\"left\", va=\"center\",\n **kwargs\n )\n self._margin_titles_texts.append(text)\n\n if self.col_names is not None:\n # Draw the column titles as normal titles\n for j, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = col_template.format(**args)\n self.axes[0, j].set_title(title, **kwargs)\n\n return self\n\n # Otherwise title each facet with all the necessary information\n if (self._row_var is not None) and (self._col_var is not None):\n for i, row_name in enumerate(self.row_names):\n for j, col_name in enumerate(self.col_names):\n args.update(dict(row_name=row_name, col_name=col_name))\n title = template.format(**args)\n self.axes[i, j].set_title(title, **kwargs)\n elif self.row_names is not None and len(self.row_names):\n for i, row_name in enumerate(self.row_names):\n args.update(dict(row_name=row_name))\n title = template.format(**args)\n self.axes[i, 0].set_title(title, **kwargs)\n elif self.col_names is not None and len(self.col_names):\n for i, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = template.format(**args)\n # Index the flat array so col_wrap works\n self.axes.flat[i].set_title(title, **kwargs)\n return self\n\n def refline(self, *, x=None, y=None, color='.5', linestyle='--', **line_kws):\n \"\"\"Add a reference line(s) to each facet.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s). Pass ``color=None`` to\n use ``hue`` mapping.\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`FacetGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n line_kws['color'] = color\n line_kws['linestyle'] = linestyle\n\n if x is not None:\n self.map(plt.axvline, x=x, **line_kws)\n\n if y is not None:\n self.map(plt.axhline, y=y, **line_kws)\n\n return self\n\n # ------ Properties that are part of the public API and documented by Sphinx\n\n @property\n def axes(self):\n \"\"\"An array of the :class:`matplotlib.axes.Axes` objects in the grid.\"\"\"\n return self._axes\n\n @property\n def ax(self):\n \"\"\"The :class:`matplotlib.axes.Axes` when no faceting variables are assigned.\"\"\"\n if self.axes.shape == (1, 1):\n return self.axes[0, 0]\n else:\n err = (\n \"Use the `.axes` attribute when facet variables are assigned.\"\n )\n raise AttributeError(err)\n\n @property\n def axes_dict(self):\n \"\"\"A mapping of facet names to corresponding :class:`matplotlib.axes.Axes`.\n\n If only one of ``row`` or ``col`` is assigned, each key is a string\n representing a level of that variable. If both facet dimensions are\n assigned, each key is a ``({row_level}, {col_level})`` tuple.\n\n \"\"\"\n return self._axes_dict\n\n # ------ Private properties, that require some computation to get\n\n @property\n def _inner_axes(self):\n \"\"\"Return a flat array of the inner axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, 1:].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i % self._ncol\n and i < (self._ncol * (self._nrow - 1))\n and i < (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _left_axes(self):\n \"\"\"Return a flat array of the left column of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 0].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if not i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _not_left_axes(self):\n \"\"\"Return a flat array of axes that aren't on the left column.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 1:].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _bottom_axes(self):\n \"\"\"Return a flat array of the bottom row of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i >= (self._ncol * (self._nrow - 1))\n or i >= (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _not_bottom_axes(self):\n \"\"\"Return a flat array of axes that aren't on the bottom row.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (\n i < (self._ncol * (self._nrow - 1))\n and i < (self._ncol * (self._nrow - 1) - n_empty)\n )\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n\nclass PairGrid(Grid):\n \"\"\"Subplot grid for plotting pairwise relationships in a dataset.\n\n This object maps each variable in a dataset onto a column and row in a\n grid of multiple axes. Different axes-level plotting functions can be\n used to draw bivariate plots in the upper and lower triangles, and the\n marginal distribution of each variable can be shown on the diagonal.\n\n Several different common plots can be generated in a single line using\n :func:`pairplot`. Use :class:`PairGrid` when you need more flexibility.\n\n See the :ref:`tutorial ` for more information.\n\n \"\"\"\n def __init__(\n self, data, *, hue=None, vars=None, x_vars=None, y_vars=None,\n hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True,\n height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False,\n ):\n \"\"\"Initialize the plot figure and PairGrid object.\n\n Parameters\n ----------\n data : DataFrame\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : string (variable name)\n Variable in ``data`` to map plot aspects to different colors. This\n variable will be excluded from the default x and y variables.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n layout_pad : scalar\n Padding between axes; passed to ``fig.tight_layout``.\n despine : boolean\n Remove the top and right spines from the plots.\n dropna : boolean\n Drop missing values from the data before plotting.\n\n See Also\n --------\n pairplot : Easily drawing common uses of :class:`PairGrid`.\n FacetGrid : Subplot grid for plotting conditional relationships.\n\n Examples\n --------\n\n .. include:: ../docstrings/PairGrid.rst\n\n \"\"\"\n\n super().__init__()\n\n # Sort out the variables that define the grid\n numeric_cols = self._find_numeric_cols(data)\n if hue in numeric_cols:\n numeric_cols.remove(hue)\n if vars is not None:\n x_vars = list(vars)\n y_vars = list(vars)\n if x_vars is None:\n x_vars = numeric_cols\n if y_vars is None:\n y_vars = numeric_cols\n\n if np.isscalar(x_vars):\n x_vars = [x_vars]\n if np.isscalar(y_vars):\n y_vars = [y_vars]\n\n self.x_vars = x_vars = list(x_vars)\n self.y_vars = y_vars = list(y_vars)\n self.square_grid = self.x_vars == self.y_vars\n\n if not x_vars:\n raise ValueError(\"No variables found for grid columns.\")\n if not y_vars:\n raise ValueError(\"No variables found for grid rows.\")\n\n # Create the figure and the array of subplots\n figsize = len(x_vars) * height * aspect, len(y_vars) * height\n\n with _disable_autolayout():\n fig = plt.figure(figsize=figsize)\n\n axes = fig.subplots(len(y_vars), len(x_vars),\n sharex=\"col\", sharey=\"row\",\n squeeze=False)\n\n # Possibly remove upper axes to make a corner grid\n # Note: setting up the axes is usually the most time-intensive part\n # of using the PairGrid. We are foregoing the speed improvement that\n # we would get by just not setting up the hidden axes so that we can\n # avoid implementing fig.subplots ourselves. But worth thinking about.\n self._corner = corner\n if corner:\n hide_indices = np.triu_indices_from(axes, 1)\n for i, j in zip(*hide_indices):\n axes[i, j].remove()\n axes[i, j] = None\n\n self._figure = fig\n self.axes = axes\n self.data = data\n\n # Save what we are going to do with the diagonal\n self.diag_sharey = diag_sharey\n self.diag_vars = None\n self.diag_axes = None\n\n self._dropna = dropna\n\n # Label the axes\n self._add_axis_labels()\n\n # Sort out the hue variable\n self._hue_var = hue\n if hue is None:\n self.hue_names = hue_order = [\"_nolegend_\"]\n self.hue_vals = pd.Series([\"_nolegend_\"] * len(data),\n index=data.index)\n else:\n # We need hue_order and hue_names because the former is used to control\n # the order of drawing and the latter is used to control the order of\n # the legend. hue_names can become string-typed while hue_order must\n # retain the type of the input data. This is messy but results from\n # the fact that PairGrid can implement the hue-mapping logic itself\n # (and was originally written exclusively that way) but now can delegate\n # to the axes-level functions, while always handling legend creation.\n # See GH2307\n hue_names = hue_order = categorical_order(data[hue], hue_order)\n if dropna:\n # Filter NA from the list of unique hue names\n hue_names = list(filter(pd.notnull, hue_names))\n self.hue_names = hue_names\n self.hue_vals = data[hue]\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n self.hue_kws = hue_kws if hue_kws is not None else {}\n\n self._orig_palette = palette\n self._hue_order = hue_order\n self.palette = self._get_palette(data, hue, hue_order, palette)\n self._legend_data = {}\n\n # Make the plot look nice\n for ax in axes[:-1, :].flat:\n if ax is None:\n continue\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n ax.xaxis.label.set_visible(False)\n\n for ax in axes[:, 1:].flat:\n if ax is None:\n continue\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n ax.yaxis.label.set_visible(False)\n\n self._tight_layout_rect = [.01, .01, .99, .99]\n self._tight_layout_pad = layout_pad\n self._despine = despine\n if despine:\n utils.despine(fig=fig)\n self.tight_layout(pad=layout_pad)\n\n def map(self, func, **kwargs):\n \"\"\"Plot with the same function in every subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n row_indices, col_indices = np.indices(self.axes.shape)\n indices = zip(row_indices.flat, col_indices.flat)\n self._map_bivariate(func, indices, **kwargs)\n\n return self\n\n def map_lower(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the lower diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n indices = zip(*np.tril_indices_from(self.axes, -1))\n self._map_bivariate(func, indices, **kwargs)\n return self\n\n def map_upper(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the upper diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n indices = zip(*np.triu_indices_from(self.axes, 1))\n self._map_bivariate(func, indices, **kwargs)\n return self\n\n def map_offdiag(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the off-diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n if self.square_grid:\n self.map_lower(func, **kwargs)\n if not self._corner:\n self.map_upper(func, **kwargs)\n else:\n indices = []\n for i, (y_var) in enumerate(self.y_vars):\n for j, (x_var) in enumerate(self.x_vars):\n if x_var != y_var:\n indices.append((i, j))\n self._map_bivariate(func, indices, **kwargs)\n return self\n\n def map_diag(self, func, **kwargs):\n \"\"\"Plot with a univariate function on each diagonal subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take an x array as a positional argument and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n # Add special diagonal axes for the univariate plot\n if self.diag_axes is None:\n diag_vars = []\n diag_axes = []\n for i, y_var in enumerate(self.y_vars):\n for j, x_var in enumerate(self.x_vars):\n if x_var == y_var:\n\n # Make the density axes\n diag_vars.append(x_var)\n ax = self.axes[i, j]\n diag_ax = ax.twinx()\n diag_ax.set_axis_off()\n diag_axes.append(diag_ax)\n\n # Work around matplotlib bug\n # https://github.com/matplotlib/matplotlib/issues/15188\n if not plt.rcParams.get(\"ytick.left\", True):\n for tick in ax.yaxis.majorTicks:\n tick.tick1line.set_visible(False)\n\n # Remove main y axis from density axes in a corner plot\n if self._corner:\n ax.yaxis.set_visible(False)\n if self._despine:\n utils.despine(ax=ax, left=True)\n # TODO add optional density ticks (on the right)\n # when drawing a corner plot?\n\n if self.diag_sharey and diag_axes:\n for ax in diag_axes[1:]:\n share_axis(diag_axes[0], ax, \"y\")\n\n self.diag_vars = np.array(diag_vars, np.object_)\n self.diag_axes = np.array(diag_axes, np.object_)\n\n if \"hue\" not in signature(func).parameters:\n return self._map_diag_iter_hue(func, **kwargs)\n\n # Loop over diagonal variables and axes, making one plot in each\n for var, ax in zip(self.diag_vars, self.diag_axes):\n\n plot_kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n vector = self.data[var]\n if self._hue_var is not None:\n hue = self.data[self._hue_var]\n else:\n hue = None\n\n if self._dropna:\n not_na = vector.notna()\n if hue is not None:\n not_na &= hue.notna()\n vector = vector[not_na]\n if hue is not None:\n hue = hue[not_na]\n\n plot_kwargs.setdefault(\"hue\", hue)\n plot_kwargs.setdefault(\"hue_order\", self._hue_order)\n plot_kwargs.setdefault(\"palette\", self._orig_palette)\n func(x=vector, **plot_kwargs)\n ax.legend_ = None\n\n self._add_axis_labels()\n return self\n\n def _map_diag_iter_hue(self, func, **kwargs):\n \"\"\"Put marginal plot on each diagonal axes, iterating over hue.\"\"\"\n # Plot on each of the diagonal axes\n fixed_color = kwargs.pop(\"color\", None)\n\n for var, ax in zip(self.diag_vars, self.diag_axes):\n hue_grouped = self.data[var].groupby(self.hue_vals)\n\n plot_kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n for k, label_k in enumerate(self._hue_order):\n\n # Attempt to get data for this level, allowing for empty\n try:\n data_k = hue_grouped.get_group(label_k)\n except KeyError:\n data_k = pd.Series([], dtype=float)\n\n if fixed_color is None:\n color = self.palette[k]\n else:\n color = fixed_color\n\n if self._dropna:\n data_k = utils.remove_na(data_k)\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=data_k, label=label_k, color=color, **plot_kwargs)\n else:\n func(data_k, label=label_k, color=color, **plot_kwargs)\n\n self._add_axis_labels()\n\n return self\n\n def _map_bivariate(self, func, indices, **kwargs):\n \"\"\"Draw a bivariate plot on the indicated axes.\"\"\"\n # This is a hack to handle the fact that new distribution plots don't add\n # their artists onto the axes. This is probably superior in general, but\n # we'll need a better way to handle it in the axisgrid functions.\n from .distributions import histplot, kdeplot\n if func is histplot or func is kdeplot:\n self._extract_legend_handles = True\n\n kws = kwargs.copy() # Use copy as we insert other kwargs\n for i, j in indices:\n x_var = self.x_vars[j]\n y_var = self.y_vars[i]\n ax = self.axes[i, j]\n if ax is None: # i.e. we are in corner mode\n continue\n self._plot_bivariate(x_var, y_var, ax, func, **kws)\n self._add_axis_labels()\n\n if \"hue\" in signature(func).parameters:\n self.hue_names = list(self._legend_data)\n\n def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):\n \"\"\"Draw a bivariate plot on the specified axes.\"\"\"\n if \"hue\" not in signature(func).parameters:\n self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)\n return\n\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n if x_var == y_var:\n axes_vars = [x_var]\n else:\n axes_vars = [x_var, y_var]\n\n if self._hue_var is not None and self._hue_var not in axes_vars:\n axes_vars.append(self._hue_var)\n\n data = self.data[axes_vars]\n if self._dropna:\n data = data.dropna()\n\n x = data[x_var]\n y = data[y_var]\n if self._hue_var is None:\n hue = None\n else:\n hue = data.get(self._hue_var)\n\n if \"hue\" not in kwargs:\n kwargs.update({\n \"hue\": hue, \"hue_order\": self._hue_order, \"palette\": self._orig_palette,\n })\n func(x=x, y=y, **kwargs)\n\n self._update_legend_data(ax)\n\n def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs):\n \"\"\"Draw a bivariate plot while iterating over hue subsets.\"\"\"\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n if x_var == y_var:\n axes_vars = [x_var]\n else:\n axes_vars = [x_var, y_var]\n\n hue_grouped = self.data.groupby(self.hue_vals)\n for k, label_k in enumerate(self._hue_order):\n\n kws = kwargs.copy()\n\n # Attempt to get data for this level, allowing for empty\n try:\n data_k = hue_grouped.get_group(label_k)\n except KeyError:\n data_k = pd.DataFrame(columns=axes_vars,\n dtype=float)\n\n if self._dropna:\n data_k = data_k[axes_vars].dropna()\n\n x = data_k[x_var]\n y = data_k[y_var]\n\n for kw, val_list in self.hue_kws.items():\n kws[kw] = val_list[k]\n kws.setdefault(\"color\", self.palette[k])\n if self._hue_var is not None:\n kws[\"label\"] = label_k\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=x, y=y, **kws)\n else:\n func(x, y, **kws)\n\n self._update_legend_data(ax)\n\n def _add_axis_labels(self):\n \"\"\"Add labels to the left and bottom Axes.\"\"\"\n for ax, label in zip(self.axes[-1, :], self.x_vars):\n ax.set_xlabel(label)\n for ax, label in zip(self.axes[:, 0], self.y_vars):\n ax.set_ylabel(label)\n\n def _find_numeric_cols(self, data):\n \"\"\"Find which variables in a DataFrame are numeric.\"\"\"\n numeric_cols = []\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n numeric_cols.append(col)\n return numeric_cols\n\n\nclass JointGrid(_BaseGrid):\n \"\"\"Grid for drawing a bivariate plot with marginal univariate plots.\n\n Many plots can be drawn by using the figure-level interface :func:`jointplot`.\n Use this class directly when you need more flexibility.\n\n \"\"\"\n\n def __init__(\n self, data=None, *,\n x=None, y=None, hue=None,\n height=6, ratio=5, space=.2,\n palette=None, hue_order=None, hue_norm=None,\n dropna=False, xlim=None, ylim=None, marginal_ticks=False,\n ):\n\n # Set up the subplot grid\n f = plt.figure(figsize=(height, height))\n gs = plt.GridSpec(ratio + 1, ratio + 1)\n\n ax_joint = f.add_subplot(gs[1:, :-1])\n ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint)\n ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint)\n\n self._figure = f\n self.ax_joint = ax_joint\n self.ax_marg_x = ax_marg_x\n self.ax_marg_y = ax_marg_y\n\n # Turn off tick visibility for the measure axis on the marginal plots\n plt.setp(ax_marg_x.get_xticklabels(), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(), visible=False)\n plt.setp(ax_marg_x.get_xticklabels(minor=True), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(minor=True), visible=False)\n\n # Turn off the ticks on the density axis for the marginal plots\n if not marginal_ticks:\n plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(minor=True), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(minor=True), visible=False)\n ax_marg_x.yaxis.grid(False)\n ax_marg_y.xaxis.grid(False)\n\n # Process the input variables\n p = VectorPlotter(data=data, variables=dict(x=x, y=y, hue=hue))\n plot_data = p.plot_data.loc[:, p.plot_data.notna().any()]\n\n # Possibly drop NA\n if dropna:\n plot_data = plot_data.dropna()\n\n def get_var(var):\n vector = plot_data.get(var, None)\n if vector is not None:\n vector = vector.rename(p.variables.get(var, None))\n return vector\n\n self.x = get_var(\"x\")\n self.y = get_var(\"y\")\n self.hue = get_var(\"hue\")\n\n for axis in \"xy\":\n name = p.variables.get(axis, None)\n if name is not None:\n getattr(ax_joint, f\"set_{axis}label\")(name)\n\n if xlim is not None:\n ax_joint.set_xlim(xlim)\n if ylim is not None:\n ax_joint.set_ylim(ylim)\n\n # Store the semantic mapping parameters for axes-level functions\n self._hue_params = dict(palette=palette, hue_order=hue_order, hue_norm=hue_norm)\n\n # Make the grid look nice\n utils.despine(f)\n if not marginal_ticks:\n utils.despine(ax=ax_marg_x, left=True)\n utils.despine(ax=ax_marg_y, bottom=True)\n for axes in [ax_marg_x, ax_marg_y]:\n for axis in [axes.xaxis, axes.yaxis]:\n axis.label.set_visible(False)\n f.tight_layout()\n f.subplots_adjust(hspace=space, wspace=space)\n\n def _inject_kwargs(self, func, kws, params):\n \"\"\"Add params to kws if they are accepted by func.\"\"\"\n func_params = signature(func).parameters\n for key, val in params.items():\n if key in func_params:\n kws.setdefault(key, val)\n\n def plot(self, joint_func, marginal_func, **kwargs):\n \"\"\"Draw the plot by passing functions for joint and marginal axes.\n\n This method passes the ``kwargs`` dictionary to both functions. If you\n need more control, call :meth:`JointGrid.plot_joint` and\n :meth:`JointGrid.plot_marginals` directly with specific parameters.\n\n Parameters\n ----------\n joint_func, marginal_func : callables\n Functions to draw the bivariate and univariate plots. See methods\n referenced above for information about the required characteristics\n of these functions.\n kwargs\n Additional keyword arguments are passed to both functions.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n self.plot_marginals(marginal_func, **kwargs)\n self.plot_joint(joint_func, **kwargs)\n return self\n\n def plot_joint(self, func, **kwargs):\n \"\"\"Draw a bivariate plot on the joint axes of the grid.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y``. Otherwise,\n it must accept ``x`` and ``y`` vectors of data as the first two\n positional arguments, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, the function must\n accept ``hue`` as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = self.ax_joint\n else:\n plt.sca(self.ax_joint)\n if self.hue is not None:\n kwargs[\"hue\"] = self.hue\n self._inject_kwargs(func, kwargs, self._hue_params)\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=self.x, y=self.y, **kwargs)\n else:\n func(self.x, self.y, **kwargs)\n\n return self\n\n def plot_marginals(self, func, **kwargs):\n \"\"\"Draw univariate plots on each marginal axes.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y`` and plot\n when only one of them is defined. Otherwise, it must accept a vector\n of data as the first positional argument and determine its orientation\n using the ``vertical`` parameter, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, it must accept ``hue``\n as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n seaborn_func = (\n str(func.__module__).startswith(\"seaborn\")\n # deprecated distplot has a legacy API, special case it\n and not func.__name__ == \"distplot\"\n )\n func_params = signature(func).parameters\n kwargs = kwargs.copy()\n if self.hue is not None:\n kwargs[\"hue\"] = self.hue\n self._inject_kwargs(func, kwargs, self._hue_params)\n\n if \"legend\" in func_params:\n kwargs.setdefault(\"legend\", False)\n\n if \"orientation\" in func_params:\n # e.g. plt.hist\n orient_kw_x = {\"orientation\": \"vertical\"}\n orient_kw_y = {\"orientation\": \"horizontal\"}\n elif \"vertical\" in func_params:\n # e.g. sns.distplot (also how did this get backwards?)\n orient_kw_x = {\"vertical\": False}\n orient_kw_y = {\"vertical\": True}\n\n if seaborn_func:\n func(x=self.x, ax=self.ax_marg_x, **kwargs)\n else:\n plt.sca(self.ax_marg_x)\n func(self.x, **orient_kw_x, **kwargs)\n\n if seaborn_func:\n func(y=self.y, ax=self.ax_marg_y, **kwargs)\n else:\n plt.sca(self.ax_marg_y)\n func(self.y, **orient_kw_y, **kwargs)\n\n self.ax_marg_x.yaxis.get_label().set_visible(False)\n self.ax_marg_y.xaxis.get_label().set_visible(False)\n\n return self\n\n def refline(\n self, *, x=None, y=None, joint=True, marginal=True,\n color='.5', linestyle='--', **line_kws\n ):\n \"\"\"Add a reference line(s) to joint and/or marginal axes.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n joint, marginal : bools\n Whether to add the reference line(s) to the joint/marginal axes.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s).\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n line_kws['color'] = color\n line_kws['linestyle'] = linestyle\n\n if x is not None:\n if joint:\n self.ax_joint.axvline(x, **line_kws)\n if marginal:\n self.ax_marg_x.axvline(x, **line_kws)\n\n if y is not None:\n if joint:\n self.ax_joint.axhline(y, **line_kws)\n if marginal:\n self.ax_marg_y.axhline(y, **line_kws)\n\n return self\n\n def set_axis_labels(self, xlabel=\"\", ylabel=\"\", **kwargs):\n \"\"\"Set axis labels on the bivariate axes.\n\n Parameters\n ----------\n xlabel, ylabel : strings\n Label names for the x and y variables.\n kwargs : key, value mappings\n Other keyword arguments are passed to the following functions:\n\n - :meth:`matplotlib.axes.Axes.set_xlabel`\n - :meth:`matplotlib.axes.Axes.set_ylabel`\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n self.ax_joint.set_xlabel(xlabel, **kwargs)\n self.ax_joint.set_ylabel(ylabel, **kwargs)\n return self\n\n\nJointGrid.__init__.__doc__ = \"\"\"\\\nSet up the grid of subplots and store data internally for easy plotting.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nheight : number\n Size of each side of the figure in inches (it will be square).\nratio : number\n Ratio of joint axes height to marginal axes height.\nspace : number\n Space between the joint and marginal axes\ndropna : bool\n If True, remove missing observations before plotting.\n{{x, y}}lim : pairs of numbers\n Set axis limits to these values before plotting.\nmarginal_ticks : bool\n If False, suppress ticks on the count/density axis of the marginal plots.\n{params.core.hue}\n Note: unlike in :class:`FacetGrid` or :class:`PairGrid`, the axes-level\n functions must support ``hue`` to use it in :class:`JointGrid`.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n\nSee Also\n--------\n{seealso.jointplot}\n{seealso.pairgrid}\n{seealso.pairplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/JointGrid.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef pairplot(\n data, *,\n hue=None, hue_order=None, palette=None,\n vars=None, x_vars=None, y_vars=None,\n kind=\"scatter\", diag_kind=\"auto\", markers=None,\n height=2.5, aspect=1, corner=False, dropna=False,\n plot_kws=None, diag_kws=None, grid_kws=None, size=None,\n):\n \"\"\"Plot pairwise relationships in a dataset.\n\n By default, this function will create a grid of Axes such that each numeric\n variable in ``data`` will by shared across the y-axes across a single row and\n the x-axes across a single column. The diagonal plots are treated\n differently: a univariate distribution plot is drawn to show the marginal\n distribution of the data in each column.\n\n It is also possible to show a subset of variables or plot different\n variables on the rows and columns.\n\n This is a high-level interface for :class:`PairGrid` that is intended to\n make it easy to draw a few common styles. You should use :class:`PairGrid`\n directly if you need more flexibility.\n\n Parameters\n ----------\n data : `pandas.DataFrame`\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : name of variable in ``data``\n Variable in ``data`` to map plot aspects to different colors.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n kind : {'scatter', 'kde', 'hist', 'reg'}\n Kind of plot to make.\n diag_kind : {'auto', 'hist', 'kde', None}\n Kind of plot for the diagonal subplots. If 'auto', choose based on\n whether or not ``hue`` is used.\n markers : single matplotlib marker code or list\n Either the marker to use for all scatterplot points or a list of markers\n with a length the same as the number of levels in the hue variable so that\n differently colored points will also have different scatterplot\n markers.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n dropna : boolean\n Drop missing values from the data before plotting.\n {plot, diag, grid}_kws : dicts\n Dictionaries of keyword arguments. ``plot_kws`` are passed to the\n bivariate plotting function, ``diag_kws`` are passed to the univariate\n plotting function, and ``grid_kws`` are passed to the :class:`PairGrid`\n constructor.\n\n Returns\n -------\n grid : :class:`PairGrid`\n Returns the underlying :class:`PairGrid` instance for further tweaking.\n\n See Also\n --------\n PairGrid : Subplot grid for more flexible plotting of pairwise relationships.\n JointGrid : Grid for plotting joint and marginal distributions of two variables.\n\n Examples\n --------\n\n .. include:: ../docstrings/pairplot.rst\n\n \"\"\"\n # Avoid circular import\n from .distributions import histplot, kdeplot\n\n # Handle deprecations\n if size is not None:\n height = size\n msg = (\"The `size` parameter has been renamed to `height`; \"\n \"please update your code.\")\n warnings.warn(msg, UserWarning)\n\n if not isinstance(data, pd.DataFrame):\n raise TypeError(\n f\"'data' must be pandas DataFrame object, not: {type(data)}\")\n\n plot_kws = {} if plot_kws is None else plot_kws.copy()\n diag_kws = {} if diag_kws is None else diag_kws.copy()\n grid_kws = {} if grid_kws is None else grid_kws.copy()\n\n # Resolve \"auto\" diag kind\n if diag_kind == \"auto\":\n if hue is None:\n diag_kind = \"kde\" if kind == \"kde\" else \"hist\"\n else:\n diag_kind = \"hist\" if kind == \"hist\" else \"kde\"\n\n # Set up the PairGrid\n grid_kws.setdefault(\"diag_sharey\", diag_kind == \"hist\")\n grid = PairGrid(data, vars=vars, x_vars=x_vars, y_vars=y_vars, hue=hue,\n hue_order=hue_order, palette=palette, corner=corner,\n height=height, aspect=aspect, dropna=dropna, **grid_kws)\n\n # Add the markers here as PairGrid has figured out how many levels of the\n # hue variable are needed and we don't want to duplicate that process\n if markers is not None:\n if kind == \"reg\":\n # Needed until regplot supports style\n if grid.hue_names is None:\n n_markers = 1\n else:\n n_markers = len(grid.hue_names)\n if not isinstance(markers, list):\n markers = [markers] * n_markers\n if len(markers) != n_markers:\n raise ValueError(\"markers must be a singleton or a list of \"\n \"markers for each level of the hue variable\")\n grid.hue_kws = {\"marker\": markers}\n elif kind == \"scatter\":\n if isinstance(markers, str):\n plot_kws[\"marker\"] = markers\n elif hue is not None:\n plot_kws[\"style\"] = data[hue]\n plot_kws[\"markers\"] = markers\n\n # Draw the marginal plots on the diagonal\n diag_kws = diag_kws.copy()\n diag_kws.setdefault(\"legend\", False)\n if diag_kind == \"hist\":\n grid.map_diag(histplot, **diag_kws)\n elif diag_kind == \"kde\":\n diag_kws.setdefault(\"fill\", True)\n diag_kws.setdefault(\"warn_singular\", False)\n grid.map_diag(kdeplot, **diag_kws)\n\n # Maybe plot on the off-diagonals\n if diag_kind is not None:\n plotter = grid.map_offdiag\n else:\n plotter = grid.map\n\n if kind == \"scatter\":\n from .relational import scatterplot # Avoid circular import\n plotter(scatterplot, **plot_kws)\n elif kind == \"reg\":\n from .regression import regplot # Avoid circular import\n plotter(regplot, **plot_kws)\n elif kind == \"kde\":\n from .distributions import kdeplot # Avoid circular import\n plot_kws.setdefault(\"warn_singular\", False)\n plotter(kdeplot, **plot_kws)\n elif kind == \"hist\":\n from .distributions import histplot # Avoid circular import\n plotter(histplot, **plot_kws)\n\n # Add a legend\n if hue is not None:\n grid.add_legend()\n\n grid.tight_layout()\n\n return grid\n\n\ndef jointplot(\n data=None, *, x=None, y=None, hue=None, kind=\"scatter\",\n height=6, ratio=5, space=.2, dropna=False, xlim=None, ylim=None,\n color=None, palette=None, hue_order=None, hue_norm=None, marginal_ticks=False,\n joint_kws=None, marginal_kws=None,\n **kwargs\n):\n # Avoid circular imports\n from .relational import scatterplot\n from .regression import regplot, residplot\n from .distributions import histplot, kdeplot, _freedman_diaconis_bins\n\n if kwargs.pop(\"ax\", None) is not None:\n msg = \"Ignoring `ax`; jointplot is a figure-level function.\"\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Set up empty default kwarg dicts\n joint_kws = {} if joint_kws is None else joint_kws.copy()\n joint_kws.update(kwargs)\n marginal_kws = {} if marginal_kws is None else marginal_kws.copy()\n\n # Handle deprecations of distplot-specific kwargs\n distplot_keys = [\n \"rug\", \"fit\", \"hist_kws\", \"norm_hist\" \"hist_kws\", \"rug_kws\",\n ]\n unused_keys = []\n for key in distplot_keys:\n if key in marginal_kws:\n unused_keys.append(key)\n marginal_kws.pop(key)\n if unused_keys and kind != \"kde\":\n msg = (\n \"The marginal plotting function has changed to `histplot`,\"\n \" which does not accept the following argument(s): {}.\"\n ).format(\", \".join(unused_keys))\n warnings.warn(msg, UserWarning)\n\n # Validate the plot kind\n plot_kinds = [\"scatter\", \"hist\", \"hex\", \"kde\", \"reg\", \"resid\"]\n _check_argument(\"kind\", plot_kinds, kind)\n\n # Raise early if using `hue` with a kind that does not support it\n if hue is not None and kind in [\"hex\", \"reg\", \"resid\"]:\n msg = (\n f\"Use of `hue` with `kind='{kind}'` is not currently supported.\"\n )\n raise ValueError(msg)\n\n # Make a colormap based off the plot color\n # (Currently used only for kind=\"hex\")\n if color is None:\n color = \"C0\"\n color_rgb = mpl.colors.colorConverter.to_rgb(color)\n colors = [utils.set_hls_values(color_rgb, l=l) # noqa\n for l in np.linspace(1, 0, 12)]\n cmap = blend_palette(colors, as_cmap=True)\n\n # Matplotlib's hexbin plot is not na-robust\n if kind == \"hex\":\n dropna = True\n\n # Initialize the JointGrid object\n grid = JointGrid(\n data=data, x=x, y=y, hue=hue,\n palette=palette, hue_order=hue_order, hue_norm=hue_norm,\n dropna=dropna, height=height, ratio=ratio, space=space,\n xlim=xlim, ylim=ylim, marginal_ticks=marginal_ticks,\n )\n\n if grid.hue is not None:\n marginal_kws.setdefault(\"legend\", False)\n\n # Plot the data using the grid\n if kind.startswith(\"scatter\"):\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(scatterplot, **joint_kws)\n\n if grid.hue is None:\n marg_func = histplot\n else:\n marg_func = kdeplot\n marginal_kws.setdefault(\"warn_singular\", False)\n marginal_kws.setdefault(\"fill\", True)\n\n marginal_kws.setdefault(\"color\", color)\n grid.plot_marginals(marg_func, **marginal_kws)\n\n elif kind.startswith(\"hist\"):\n\n # TODO process pair parameters for bins, etc. and pass\n # to both joint and marginal plots\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(histplot, **joint_kws)\n\n marginal_kws.setdefault(\"kde\", False)\n marginal_kws.setdefault(\"color\", color)\n\n marg_x_kws = marginal_kws.copy()\n marg_y_kws = marginal_kws.copy()\n\n pair_keys = \"bins\", \"binwidth\", \"binrange\"\n for key in pair_keys:\n if isinstance(joint_kws.get(key), tuple):\n x_val, y_val = joint_kws[key]\n marg_x_kws.setdefault(key, x_val)\n marg_y_kws.setdefault(key, y_val)\n\n histplot(data=data, x=x, hue=hue, **marg_x_kws, ax=grid.ax_marg_x)\n histplot(data=data, y=y, hue=hue, **marg_y_kws, ax=grid.ax_marg_y)\n\n elif kind.startswith(\"kde\"):\n\n joint_kws.setdefault(\"color\", color)\n joint_kws.setdefault(\"warn_singular\", False)\n grid.plot_joint(kdeplot, **joint_kws)\n\n marginal_kws.setdefault(\"color\", color)\n if \"fill\" in joint_kws:\n marginal_kws.setdefault(\"fill\", joint_kws[\"fill\"])\n\n grid.plot_marginals(kdeplot, **marginal_kws)\n\n elif kind.startswith(\"hex\"):\n\n x_bins = min(_freedman_diaconis_bins(grid.x), 50)\n y_bins = min(_freedman_diaconis_bins(grid.y), 50)\n gridsize = int(np.mean([x_bins, y_bins]))\n\n joint_kws.setdefault(\"gridsize\", gridsize)\n joint_kws.setdefault(\"cmap\", cmap)\n grid.plot_joint(plt.hexbin, **joint_kws)\n\n marginal_kws.setdefault(\"kde\", False)\n marginal_kws.setdefault(\"color\", color)\n grid.plot_marginals(histplot, **marginal_kws)\n\n elif kind.startswith(\"reg\"):\n\n marginal_kws.setdefault(\"color\", color)\n marginal_kws.setdefault(\"kde\", True)\n grid.plot_marginals(histplot, **marginal_kws)\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(regplot, **joint_kws)\n\n elif kind.startswith(\"resid\"):\n\n joint_kws.setdefault(\"color\", color)\n grid.plot_joint(residplot, **joint_kws)\n\n x, y = grid.ax_joint.collections[0].get_offsets().T\n marginal_kws.setdefault(\"color\", color)\n histplot(x=x, hue=hue, ax=grid.ax_marg_x, **marginal_kws)\n histplot(y=y, hue=hue, ax=grid.ax_marg_y, **marginal_kws)\n\n # Make the main axes active in the matplotlib state machine\n plt.sca(grid.ax_joint)\n\n return grid\n\n\njointplot.__doc__ = \"\"\"\\\nDraw a plot of two variables with bivariate and univariate graphs.\n\nThis function provides a convenient interface to the :class:`JointGrid`\nclass, with several canned plot kinds. This is intended to be a fairly\nlightweight wrapper; if you need more flexibility, you should use\n:class:`JointGrid` directly.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\n Semantic variable that is mapped to determine the color of plot elements.\nkind : {{ \"scatter\" | \"kde\" | \"hist\" | \"hex\" | \"reg\" | \"resid\" }}\n Kind of plot to draw. See the examples for references to the underlying functions.\nheight : numeric\n Size of the figure (it will be square).\nratio : numeric\n Ratio of joint axes height to marginal axes height.\nspace : numeric\n Space between the joint and marginal axes\ndropna : bool\n If True, remove observations that are missing from ``x`` and ``y``.\n{{x, y}}lim : pairs of numbers\n Axis limits to set before plotting.\n{params.core.color}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\nmarginal_ticks : bool\n If False, suppress ticks on the count/density axis of the marginal plots.\n{{joint, marginal}}_kws : dicts\n Additional keyword arguments for the plot components.\nkwargs\n Additional keyword arguments are passed to the function used to\n draw the plot on the joint Axes, superseding items in the\n ``joint_kws`` dictionary.\n\nReturns\n-------\n{returns.jointgrid}\n\nSee Also\n--------\n{seealso.jointgrid}\n{seealso.pairgrid}\n{seealso.pairplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/jointplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n"},{"col":0,"comment":"null","endLoc":201,"header":"def data_structure()","id":2202,"name":"data_structure","nodeType":"Function","startLoc":182,"text":"def data_structure():\n\n f = mpl.figure.Figure(figsize=(7, 5))\n gs = mpl.gridspec.GridSpec(\n figure=f, ncols=6, nrows=2, height_ratios=(1, 20),\n left=0, right=.35, bottom=0, top=.9, wspace=.1, hspace=.01\n )\n colors = [c + (.5,) for c in sns.color_palette(\"deep\")]\n f.add_subplot(gs[0, :], facecolor=\".8\")\n for i in range(gs.ncols):\n f.add_subplot(gs[1:, i], facecolor=colors[i])\n\n gs = mpl.gridspec.GridSpec(\n figure=f, ncols=2, nrows=2, height_ratios=(1, 8), width_ratios=(1, 11),\n left=.4, right=1, bottom=.2, top=.8, wspace=.015, hspace=.02\n )\n f.add_subplot(gs[0, 1:], facecolor=colors[2])\n f.add_subplot(gs[1:, 0], facecolor=colors[1])\n f.add_subplot(gs[1, 1], facecolor=colors[0])\n return f"},{"col":0,"comment":"Context manager for preventing rc-controlled auto-layout behavior.","endLoc":868,"header":"@contextmanager\ndef _disable_autolayout()","id":2203,"name":"_disable_autolayout","nodeType":"Function","startLoc":852,"text":"@contextmanager\ndef _disable_autolayout():\n \"\"\"Context manager for preventing rc-controlled auto-layout behavior.\"\"\"\n # This is a workaround for an issue in matplotlib, for details see\n # https://github.com/mwaskom/seaborn/issues/2914\n # The only affect of this rcParam is to set the default value for\n # layout= in plt.figure, so we could just do that instead.\n # But then we would need to own the complexity of the transition\n # from tight_layout=True -> layout=\"tight\". This seems easier,\n # but can be removed when (if) that is simpler on the matplotlib side,\n # or if the layout algorithms are improved to handle figure legends.\n orig_val = mpl.rcParams[\"figure.autolayout\"]\n try:\n mpl.rcParams[\"figure.autolayout\"] = False\n yield\n finally:\n mpl.rcParams[\"figure.autolayout\"] = orig_val"},{"className":"PairGrid","col":0,"comment":"Subplot grid for plotting pairwise relationships in a dataset.\n\n This object maps each variable in a dataset onto a column and row in a\n grid of multiple axes. Different axes-level plotting functions can be\n used to draw bivariate plots in the upper and lower triangles, and the\n marginal distribution of each variable can be shown on the diagonal.\n\n Several different common plots can be generated in a single line using\n :func:`pairplot`. Use :class:`PairGrid` when you need more flexibility.\n\n See the :ref:`tutorial ` for more information.\n\n ","endLoc":1670,"id":2204,"nodeType":"Class","startLoc":1172,"text":"class PairGrid(Grid):\n \"\"\"Subplot grid for plotting pairwise relationships in a dataset.\n\n This object maps each variable in a dataset onto a column and row in a\n grid of multiple axes. Different axes-level plotting functions can be\n used to draw bivariate plots in the upper and lower triangles, and the\n marginal distribution of each variable can be shown on the diagonal.\n\n Several different common plots can be generated in a single line using\n :func:`pairplot`. Use :class:`PairGrid` when you need more flexibility.\n\n See the :ref:`tutorial ` for more information.\n\n \"\"\"\n def __init__(\n self, data, *, hue=None, vars=None, x_vars=None, y_vars=None,\n hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True,\n height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False,\n ):\n \"\"\"Initialize the plot figure and PairGrid object.\n\n Parameters\n ----------\n data : DataFrame\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : string (variable name)\n Variable in ``data`` to map plot aspects to different colors. This\n variable will be excluded from the default x and y variables.\n vars : list of variable names\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n corner : bool\n If True, don't add axes to the upper (off-diagonal) triangle of the\n grid, making this a \"corner\" plot.\n height : scalar\n Height (in inches) of each facet.\n aspect : scalar\n Aspect * height gives the width (in inches) of each facet.\n layout_pad : scalar\n Padding between axes; passed to ``fig.tight_layout``.\n despine : boolean\n Remove the top and right spines from the plots.\n dropna : boolean\n Drop missing values from the data before plotting.\n\n See Also\n --------\n pairplot : Easily drawing common uses of :class:`PairGrid`.\n FacetGrid : Subplot grid for plotting conditional relationships.\n\n Examples\n --------\n\n .. include:: ../docstrings/PairGrid.rst\n\n \"\"\"\n\n super().__init__()\n\n # Sort out the variables that define the grid\n numeric_cols = self._find_numeric_cols(data)\n if hue in numeric_cols:\n numeric_cols.remove(hue)\n if vars is not None:\n x_vars = list(vars)\n y_vars = list(vars)\n if x_vars is None:\n x_vars = numeric_cols\n if y_vars is None:\n y_vars = numeric_cols\n\n if np.isscalar(x_vars):\n x_vars = [x_vars]\n if np.isscalar(y_vars):\n y_vars = [y_vars]\n\n self.x_vars = x_vars = list(x_vars)\n self.y_vars = y_vars = list(y_vars)\n self.square_grid = self.x_vars == self.y_vars\n\n if not x_vars:\n raise ValueError(\"No variables found for grid columns.\")\n if not y_vars:\n raise ValueError(\"No variables found for grid rows.\")\n\n # Create the figure and the array of subplots\n figsize = len(x_vars) * height * aspect, len(y_vars) * height\n\n with _disable_autolayout():\n fig = plt.figure(figsize=figsize)\n\n axes = fig.subplots(len(y_vars), len(x_vars),\n sharex=\"col\", sharey=\"row\",\n squeeze=False)\n\n # Possibly remove upper axes to make a corner grid\n # Note: setting up the axes is usually the most time-intensive part\n # of using the PairGrid. We are foregoing the speed improvement that\n # we would get by just not setting up the hidden axes so that we can\n # avoid implementing fig.subplots ourselves. But worth thinking about.\n self._corner = corner\n if corner:\n hide_indices = np.triu_indices_from(axes, 1)\n for i, j in zip(*hide_indices):\n axes[i, j].remove()\n axes[i, j] = None\n\n self._figure = fig\n self.axes = axes\n self.data = data\n\n # Save what we are going to do with the diagonal\n self.diag_sharey = diag_sharey\n self.diag_vars = None\n self.diag_axes = None\n\n self._dropna = dropna\n\n # Label the axes\n self._add_axis_labels()\n\n # Sort out the hue variable\n self._hue_var = hue\n if hue is None:\n self.hue_names = hue_order = [\"_nolegend_\"]\n self.hue_vals = pd.Series([\"_nolegend_\"] * len(data),\n index=data.index)\n else:\n # We need hue_order and hue_names because the former is used to control\n # the order of drawing and the latter is used to control the order of\n # the legend. hue_names can become string-typed while hue_order must\n # retain the type of the input data. This is messy but results from\n # the fact that PairGrid can implement the hue-mapping logic itself\n # (and was originally written exclusively that way) but now can delegate\n # to the axes-level functions, while always handling legend creation.\n # See GH2307\n hue_names = hue_order = categorical_order(data[hue], hue_order)\n if dropna:\n # Filter NA from the list of unique hue names\n hue_names = list(filter(pd.notnull, hue_names))\n self.hue_names = hue_names\n self.hue_vals = data[hue]\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n self.hue_kws = hue_kws if hue_kws is not None else {}\n\n self._orig_palette = palette\n self._hue_order = hue_order\n self.palette = self._get_palette(data, hue, hue_order, palette)\n self._legend_data = {}\n\n # Make the plot look nice\n for ax in axes[:-1, :].flat:\n if ax is None:\n continue\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n ax.xaxis.label.set_visible(False)\n\n for ax in axes[:, 1:].flat:\n if ax is None:\n continue\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n ax.yaxis.label.set_visible(False)\n\n self._tight_layout_rect = [.01, .01, .99, .99]\n self._tight_layout_pad = layout_pad\n self._despine = despine\n if despine:\n utils.despine(fig=fig)\n self.tight_layout(pad=layout_pad)\n\n def map(self, func, **kwargs):\n \"\"\"Plot with the same function in every subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n row_indices, col_indices = np.indices(self.axes.shape)\n indices = zip(row_indices.flat, col_indices.flat)\n self._map_bivariate(func, indices, **kwargs)\n\n return self\n\n def map_lower(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the lower diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n indices = zip(*np.tril_indices_from(self.axes, -1))\n self._map_bivariate(func, indices, **kwargs)\n return self\n\n def map_upper(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the upper diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n indices = zip(*np.triu_indices_from(self.axes, 1))\n self._map_bivariate(func, indices, **kwargs)\n return self\n\n def map_offdiag(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the off-diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n if self.square_grid:\n self.map_lower(func, **kwargs)\n if not self._corner:\n self.map_upper(func, **kwargs)\n else:\n indices = []\n for i, (y_var) in enumerate(self.y_vars):\n for j, (x_var) in enumerate(self.x_vars):\n if x_var != y_var:\n indices.append((i, j))\n self._map_bivariate(func, indices, **kwargs)\n return self\n\n def map_diag(self, func, **kwargs):\n \"\"\"Plot with a univariate function on each diagonal subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take an x array as a positional argument and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n # Add special diagonal axes for the univariate plot\n if self.diag_axes is None:\n diag_vars = []\n diag_axes = []\n for i, y_var in enumerate(self.y_vars):\n for j, x_var in enumerate(self.x_vars):\n if x_var == y_var:\n\n # Make the density axes\n diag_vars.append(x_var)\n ax = self.axes[i, j]\n diag_ax = ax.twinx()\n diag_ax.set_axis_off()\n diag_axes.append(diag_ax)\n\n # Work around matplotlib bug\n # https://github.com/matplotlib/matplotlib/issues/15188\n if not plt.rcParams.get(\"ytick.left\", True):\n for tick in ax.yaxis.majorTicks:\n tick.tick1line.set_visible(False)\n\n # Remove main y axis from density axes in a corner plot\n if self._corner:\n ax.yaxis.set_visible(False)\n if self._despine:\n utils.despine(ax=ax, left=True)\n # TODO add optional density ticks (on the right)\n # when drawing a corner plot?\n\n if self.diag_sharey and diag_axes:\n for ax in diag_axes[1:]:\n share_axis(diag_axes[0], ax, \"y\")\n\n self.diag_vars = np.array(diag_vars, np.object_)\n self.diag_axes = np.array(diag_axes, np.object_)\n\n if \"hue\" not in signature(func).parameters:\n return self._map_diag_iter_hue(func, **kwargs)\n\n # Loop over diagonal variables and axes, making one plot in each\n for var, ax in zip(self.diag_vars, self.diag_axes):\n\n plot_kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n vector = self.data[var]\n if self._hue_var is not None:\n hue = self.data[self._hue_var]\n else:\n hue = None\n\n if self._dropna:\n not_na = vector.notna()\n if hue is not None:\n not_na &= hue.notna()\n vector = vector[not_na]\n if hue is not None:\n hue = hue[not_na]\n\n plot_kwargs.setdefault(\"hue\", hue)\n plot_kwargs.setdefault(\"hue_order\", self._hue_order)\n plot_kwargs.setdefault(\"palette\", self._orig_palette)\n func(x=vector, **plot_kwargs)\n ax.legend_ = None\n\n self._add_axis_labels()\n return self\n\n def _map_diag_iter_hue(self, func, **kwargs):\n \"\"\"Put marginal plot on each diagonal axes, iterating over hue.\"\"\"\n # Plot on each of the diagonal axes\n fixed_color = kwargs.pop(\"color\", None)\n\n for var, ax in zip(self.diag_vars, self.diag_axes):\n hue_grouped = self.data[var].groupby(self.hue_vals)\n\n plot_kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n for k, label_k in enumerate(self._hue_order):\n\n # Attempt to get data for this level, allowing for empty\n try:\n data_k = hue_grouped.get_group(label_k)\n except KeyError:\n data_k = pd.Series([], dtype=float)\n\n if fixed_color is None:\n color = self.palette[k]\n else:\n color = fixed_color\n\n if self._dropna:\n data_k = utils.remove_na(data_k)\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=data_k, label=label_k, color=color, **plot_kwargs)\n else:\n func(data_k, label=label_k, color=color, **plot_kwargs)\n\n self._add_axis_labels()\n\n return self\n\n def _map_bivariate(self, func, indices, **kwargs):\n \"\"\"Draw a bivariate plot on the indicated axes.\"\"\"\n # This is a hack to handle the fact that new distribution plots don't add\n # their artists onto the axes. This is probably superior in general, but\n # we'll need a better way to handle it in the axisgrid functions.\n from .distributions import histplot, kdeplot\n if func is histplot or func is kdeplot:\n self._extract_legend_handles = True\n\n kws = kwargs.copy() # Use copy as we insert other kwargs\n for i, j in indices:\n x_var = self.x_vars[j]\n y_var = self.y_vars[i]\n ax = self.axes[i, j]\n if ax is None: # i.e. we are in corner mode\n continue\n self._plot_bivariate(x_var, y_var, ax, func, **kws)\n self._add_axis_labels()\n\n if \"hue\" in signature(func).parameters:\n self.hue_names = list(self._legend_data)\n\n def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):\n \"\"\"Draw a bivariate plot on the specified axes.\"\"\"\n if \"hue\" not in signature(func).parameters:\n self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)\n return\n\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n if x_var == y_var:\n axes_vars = [x_var]\n else:\n axes_vars = [x_var, y_var]\n\n if self._hue_var is not None and self._hue_var not in axes_vars:\n axes_vars.append(self._hue_var)\n\n data = self.data[axes_vars]\n if self._dropna:\n data = data.dropna()\n\n x = data[x_var]\n y = data[y_var]\n if self._hue_var is None:\n hue = None\n else:\n hue = data.get(self._hue_var)\n\n if \"hue\" not in kwargs:\n kwargs.update({\n \"hue\": hue, \"hue_order\": self._hue_order, \"palette\": self._orig_palette,\n })\n func(x=x, y=y, **kwargs)\n\n self._update_legend_data(ax)\n\n def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs):\n \"\"\"Draw a bivariate plot while iterating over hue subsets.\"\"\"\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n if x_var == y_var:\n axes_vars = [x_var]\n else:\n axes_vars = [x_var, y_var]\n\n hue_grouped = self.data.groupby(self.hue_vals)\n for k, label_k in enumerate(self._hue_order):\n\n kws = kwargs.copy()\n\n # Attempt to get data for this level, allowing for empty\n try:\n data_k = hue_grouped.get_group(label_k)\n except KeyError:\n data_k = pd.DataFrame(columns=axes_vars,\n dtype=float)\n\n if self._dropna:\n data_k = data_k[axes_vars].dropna()\n\n x = data_k[x_var]\n y = data_k[y_var]\n\n for kw, val_list in self.hue_kws.items():\n kws[kw] = val_list[k]\n kws.setdefault(\"color\", self.palette[k])\n if self._hue_var is not None:\n kws[\"label\"] = label_k\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=x, y=y, **kws)\n else:\n func(x, y, **kws)\n\n self._update_legend_data(ax)\n\n def _add_axis_labels(self):\n \"\"\"Add labels to the left and bottom Axes.\"\"\"\n for ax, label in zip(self.axes[-1, :], self.x_vars):\n ax.set_xlabel(label)\n for ax, label in zip(self.axes[:, 0], self.y_vars):\n ax.set_ylabel(label)\n\n def _find_numeric_cols(self, data):\n \"\"\"Find which variables in a DataFrame are numeric.\"\"\"\n numeric_cols = []\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n numeric_cols.append(col)\n return numeric_cols"},{"col":4,"comment":"Plot with a bivariate function on the lower diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n ","endLoc":1390,"header":"def map_lower(self, func, **kwargs)","id":2205,"name":"map_lower","nodeType":"Function","startLoc":1377,"text":"def map_lower(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the lower diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n indices = zip(*np.tril_indices_from(self.axes, -1))\n self._map_bivariate(func, indices, **kwargs)\n return self"},{"col":0,"comment":"null","endLoc":214,"header":"def error_bars()","id":2206,"name":"error_bars","nodeType":"Function","startLoc":204,"text":"def error_bars():\n\n diamonds = sns.load_dataset(\"diamonds\")\n with sns.axes_style(\"whitegrid\"):\n g = sns.catplot(\n diamonds, x=\"carat\", y=\"clarity\", hue=\"clarity\", kind=\"point\",\n errorbar=(\"sd\", .5), join=False, legend=False, facet_kws={\"despine\": False},\n palette=\"ch:s=-.2,r=-.2,d=.4,l=.6_r\", scale=.75, capsize=.3,\n )\n g.ax.yaxis.set_inverted(False)\n return g.figure"},{"col":0,"comment":"null","endLoc":243,"header":"def properties()","id":2207,"name":"properties","nodeType":"Function","startLoc":217,"text":"def properties():\n\n f = mpl.figure.Figure(figsize=(5, 5))\n\n x = np.arange(1, 11)\n y = np.zeros_like(x)\n\n p = so.Plot(x, y)\n ps = 14\n plots = [\n p.add(so.Dot(pointsize=ps), color=map(str, x)),\n p.add(so.Dot(color=\".3\", pointsize=ps), alpha=x),\n p.add(so.Dot(color=\".9\", pointsize=ps, edgewidth=2), edgecolor=x),\n p.add(so.Dot(color=\".3\"), pointsize=x).scale(pointsize=(4, 18)),\n p.add(so.Dot(pointsize=ps, color=\".9\", edgecolor=\".2\"), edgewidth=x),\n p.add(so.Dot(pointsize=ps, color=\".3\"), marker=map(str, x)),\n p.add(so.Dot(pointsize=ps, color=\".3\", marker=\"x\"), stroke=x),\n ]\n\n with sns.axes_style(\"ticks\"):\n axs = f.subplots(len(plots))\n for p, ax in zip(plots, axs):\n p.on(ax).plot()\n ax.set(xticks=x, yticks=[], xticklabels=[], ylim=(-.2, .3))\n sns.despine(ax=ax, left=True)\n f.legends = []\n return f"},{"fileName":"_decorators.py","filePath":"seaborn","id":2208,"nodeType":"File","text":"from inspect import signature\n\n\ndef share_init_params_with_map(cls):\n \"\"\"Make cls.map a classmethod with same signature as cls.__init__.\"\"\"\n map_sig = signature(cls.map)\n init_sig = signature(cls.__init__)\n\n new = [v for k, v in init_sig.parameters.items() if k != \"self\"]\n new.insert(0, map_sig.parameters[\"cls\"])\n cls.map.__signature__ = map_sig.replace(parameters=new)\n cls.map.__doc__ = cls.__init__.__doc__\n\n cls.map = classmethod(cls.map)\n\n return cls\n"},{"fileName":"base.py","filePath":"seaborn/_stats","id":2209,"nodeType":"File","text":"\"\"\"Base module for statistical transformations.\"\"\"\nfrom __future__ import annotations\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Any\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from pandas import DataFrame\n from seaborn._core.groupby import GroupBy\n from seaborn._core.scales import Scale\n\n\n@dataclass\nclass Stat:\n \"\"\"Base class for objects that apply statistical transformations.\"\"\"\n\n # The class supports a partial-function application pattern. The object is\n # initialized with desired parameters and the result is a callable that\n # accepts and returns dataframes.\n\n # The statistical transformation logic should not add any state to the instance\n # beyond what is defined with the initialization parameters.\n\n # Subclasses can declare whether the orient dimension should be used in grouping\n # TODO consider whether this should be a parameter. Motivating example:\n # use the same KDE class violin plots and univariate density estimation.\n # In the former case, we would expect separate densities for each unique\n # value on the orient axis, but we would not in the latter case.\n group_by_orient: ClassVar[bool] = False\n\n def _check_param_one_of(self, param: Any, options: Iterable[Any]) -> None:\n \"\"\"Raise when parameter value is not one of a specified set.\"\"\"\n value = getattr(self, param)\n if value not in options:\n *most, last = options\n option_str = \", \".join(f\"{x!r}\" for x in most[:-1]) + f\" or {last!r}\"\n err = \" \".join([\n f\"The `{param}` parameter for `{self.__class__.__name__}` must be\",\n f\"one of {option_str}; not {value!r}.\",\n ])\n raise ValueError(err)\n\n def __call__(\n self,\n data: DataFrame,\n groupby: GroupBy,\n orient: str,\n scales: dict[str, Scale],\n ) -> DataFrame:\n \"\"\"Apply statistical transform to data subgroups and return combined result.\"\"\"\n return data\n"},{"col":0,"comment":"","endLoc":1,"header":"base.py#","id":2210,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Base module for statistical transformations.\"\"\"\n\nif TYPE_CHECKING:\n from pandas import DataFrame\n from seaborn._core.groupby import GroupBy\n from seaborn._core.scales import Scale"},{"fileName":"test_groupby.py","filePath":"tests/_core","id":2211,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.groupby import GroupBy\n\n\n@pytest.fixture\ndef df():\n\n return pd.DataFrame(\n columns=[\"a\", \"b\", \"x\", \"y\"],\n data=[\n [\"a\", \"g\", 1, .2],\n [\"b\", \"h\", 3, .5],\n [\"a\", \"f\", 2, .8],\n [\"a\", \"h\", 1, .3],\n [\"b\", \"f\", 2, .4],\n ]\n )\n\n\ndef test_init_from_list():\n g = GroupBy([\"a\", \"c\", \"b\"])\n assert g.order == {\"a\": None, \"c\": None, \"b\": None}\n\n\ndef test_init_from_dict():\n order = {\"a\": [3, 2, 1], \"c\": None, \"b\": [\"x\", \"y\", \"z\"]}\n g = GroupBy(order)\n assert g.order == order\n\n\ndef test_init_requires_order():\n\n with pytest.raises(ValueError, match=\"GroupBy requires at least one\"):\n GroupBy([])\n\n\ndef test_at_least_one_grouping_variable_required(df):\n\n with pytest.raises(ValueError, match=\"No grouping variables are present\"):\n GroupBy([\"z\"]).agg(df, x=\"mean\")\n\n\ndef test_agg_one_grouper(df):\n\n res = GroupBy([\"a\"]).agg(df, {\"y\": \"max\"})\n assert_array_equal(res.index, [0, 1])\n assert_array_equal(res.columns, [\"a\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\", \"b\"])\n assert_array_equal(res[\"y\"], [.8, .5])\n\n\ndef test_agg_two_groupers(df):\n\n res = GroupBy([\"a\", \"x\"]).agg(df, {\"y\": \"min\"})\n assert_array_equal(res.index, [0, 1, 2, 3, 4, 5])\n assert_array_equal(res.columns, [\"a\", \"x\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"])\n assert_array_equal(res[\"x\"], [1, 2, 3, 1, 2, 3])\n assert_array_equal(res[\"y\"], [.2, .8, np.nan, np.nan, .4, .5])\n\n\ndef test_agg_two_groupers_ordered(df):\n\n order = {\"b\": [\"h\", \"g\", \"f\"], \"x\": [3, 2, 1]}\n res = GroupBy(order).agg(df, {\"a\": \"min\", \"y\": lambda x: x.iloc[0]})\n assert_array_equal(res.index, [0, 1, 2, 3, 4, 5, 6, 7, 8])\n assert_array_equal(res.columns, [\"a\", \"b\", \"x\", \"y\"])\n assert_array_equal(res[\"b\"], [\"h\", \"h\", \"h\", \"g\", \"g\", \"g\", \"f\", \"f\", \"f\"])\n assert_array_equal(res[\"x\"], [3, 2, 1, 3, 2, 1, 3, 2, 1])\n\n T, F = True, False\n assert_array_equal(res[\"a\"].isna(), [F, T, F, T, T, F, T, F, T])\n assert_array_equal(res[\"a\"].dropna(), [\"b\", \"a\", \"a\", \"a\"])\n assert_array_equal(res[\"y\"].dropna(), [.5, .3, .2, .8])\n\n\ndef test_apply_no_grouper(df):\n\n df = df[[\"x\", \"y\"]]\n res = GroupBy([\"a\"]).apply(df, lambda x: x.sort_values(\"x\"))\n assert_array_equal(res.columns, [\"x\", \"y\"])\n assert_array_equal(res[\"x\"], df[\"x\"].sort_values())\n assert_array_equal(res[\"y\"], df.loc[np.argsort(df[\"x\"]), \"y\"])\n\n\ndef test_apply_one_grouper(df):\n\n res = GroupBy([\"a\"]).apply(df, lambda x: x.sort_values(\"x\"))\n assert_array_equal(res.index, [0, 1, 2, 3, 4])\n assert_array_equal(res.columns, [\"a\", \"b\", \"x\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\", \"a\", \"a\", \"b\", \"b\"])\n assert_array_equal(res[\"b\"], [\"g\", \"h\", \"f\", \"f\", \"h\"])\n assert_array_equal(res[\"x\"], [1, 1, 2, 2, 3])\n\n\ndef test_apply_mutate_columns(df):\n\n xx = np.arange(0, 5)\n hats = []\n\n def polyfit(df):\n fit = np.polyfit(df[\"x\"], df[\"y\"], 1)\n hat = np.polyval(fit, xx)\n hats.append(hat)\n return pd.DataFrame(dict(x=xx, y=hat))\n\n res = GroupBy([\"a\"]).apply(df, polyfit)\n assert_array_equal(res.index, np.arange(xx.size * 2))\n assert_array_equal(res.columns, [\"a\", \"x\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\"] * xx.size + [\"b\"] * xx.size)\n assert_array_equal(res[\"x\"], xx.tolist() + xx.tolist())\n assert_array_equal(res[\"y\"], np.concatenate(hats))\n\n\ndef test_apply_replace_columns(df):\n\n def add_sorted_cumsum(df):\n\n x = df[\"x\"].sort_values()\n z = df.loc[x.index, \"y\"].cumsum()\n return pd.DataFrame(dict(x=x.values, z=z.values))\n\n res = GroupBy([\"a\"]).apply(df, add_sorted_cumsum)\n assert_array_equal(res.index, df.index)\n assert_array_equal(res.columns, [\"a\", \"x\", \"z\"])\n assert_array_equal(res[\"a\"], [\"a\", \"a\", \"a\", \"b\", \"b\"])\n assert_array_equal(res[\"x\"], [1, 1, 2, 2, 3])\n assert_array_equal(res[\"z\"], [.2, .5, 1.3, .4, .9])\n"},{"col":0,"comment":"null","endLoc":23,"header":"@pytest.fixture\ndef df()","id":2212,"name":"df","nodeType":"Function","startLoc":11,"text":"@pytest.fixture\ndef df():\n\n return pd.DataFrame(\n columns=[\"a\", \"b\", \"x\", \"y\"],\n data=[\n [\"a\", \"g\", 1, .2],\n [\"b\", \"h\", 3, .5],\n [\"a\", \"f\", 2, .8],\n [\"a\", \"h\", 1, .3],\n [\"b\", \"f\", 2, .4],\n ]\n )"},{"col":0,"comment":"null","endLoc":28,"header":"def test_init_from_list()","id":2213,"name":"test_init_from_list","nodeType":"Function","startLoc":26,"text":"def test_init_from_list():\n g = GroupBy([\"a\", \"c\", \"b\"])\n assert g.order == {\"a\": None, \"c\": None, \"b\": None}"},{"col":0,"comment":"null","endLoc":34,"header":"def test_init_from_dict()","id":2214,"name":"test_init_from_dict","nodeType":"Function","startLoc":31,"text":"def test_init_from_dict():\n order = {\"a\": [3, 2, 1], \"c\": None, \"b\": [\"x\", \"y\", \"z\"]}\n g = GroupBy(order)\n assert g.order == order"},{"col":0,"comment":"null","endLoc":40,"header":"def test_init_requires_order()","id":2215,"name":"test_init_requires_order","nodeType":"Function","startLoc":37,"text":"def test_init_requires_order():\n\n with pytest.raises(ValueError, match=\"GroupBy requires at least one\"):\n GroupBy([])"},{"col":0,"comment":"null","endLoc":46,"header":"def test_at_least_one_grouping_variable_required(df)","id":2216,"name":"test_at_least_one_grouping_variable_required","nodeType":"Function","startLoc":43,"text":"def test_at_least_one_grouping_variable_required(df):\n\n with pytest.raises(ValueError, match=\"No grouping variables are present\"):\n GroupBy([\"z\"]).agg(df, x=\"mean\")"},{"col":0,"comment":"null","endLoc":55,"header":"def test_agg_one_grouper(df)","id":2217,"name":"test_agg_one_grouper","nodeType":"Function","startLoc":49,"text":"def test_agg_one_grouper(df):\n\n res = GroupBy([\"a\"]).agg(df, {\"y\": \"max\"})\n assert_array_equal(res.index, [0, 1])\n assert_array_equal(res.columns, [\"a\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\", \"b\"])\n assert_array_equal(res[\"y\"], [.8, .5])"},{"col":0,"comment":"null","endLoc":65,"header":"def test_agg_two_groupers(df)","id":2218,"name":"test_agg_two_groupers","nodeType":"Function","startLoc":58,"text":"def test_agg_two_groupers(df):\n\n res = GroupBy([\"a\", \"x\"]).agg(df, {\"y\": \"min\"})\n assert_array_equal(res.index, [0, 1, 2, 3, 4, 5])\n assert_array_equal(res.columns, [\"a\", \"x\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"])\n assert_array_equal(res[\"x\"], [1, 2, 3, 1, 2, 3])\n assert_array_equal(res[\"y\"], [.2, .8, np.nan, np.nan, .4, .5])"},{"col":0,"comment":"null","endLoc":80,"header":"def test_agg_two_groupers_ordered(df)","id":2219,"name":"test_agg_two_groupers_ordered","nodeType":"Function","startLoc":68,"text":"def test_agg_two_groupers_ordered(df):\n\n order = {\"b\": [\"h\", \"g\", \"f\"], \"x\": [3, 2, 1]}\n res = GroupBy(order).agg(df, {\"a\": \"min\", \"y\": lambda x: x.iloc[0]})\n assert_array_equal(res.index, [0, 1, 2, 3, 4, 5, 6, 7, 8])\n assert_array_equal(res.columns, [\"a\", \"b\", \"x\", \"y\"])\n assert_array_equal(res[\"b\"], [\"h\", \"h\", \"h\", \"g\", \"g\", \"g\", \"f\", \"f\", \"f\"])\n assert_array_equal(res[\"x\"], [3, 2, 1, 3, 2, 1, 3, 2, 1])\n\n T, F = True, False\n assert_array_equal(res[\"a\"].isna(), [F, T, F, T, T, F, T, F, T])\n assert_array_equal(res[\"a\"].dropna(), [\"b\", \"a\", \"a\", \"a\"])\n assert_array_equal(res[\"y\"].dropna(), [.5, .3, .2, .8])"},{"col":51,"endLoc":71,"id":2220,"nodeType":"Lambda","startLoc":71,"text":"lambda x: x.iloc[0]"},{"col":0,"comment":"null","endLoc":89,"header":"def test_apply_no_grouper(df)","id":2221,"name":"test_apply_no_grouper","nodeType":"Function","startLoc":83,"text":"def test_apply_no_grouper(df):\n\n df = df[[\"x\", \"y\"]]\n res = GroupBy([\"a\"]).apply(df, lambda x: x.sort_values(\"x\"))\n assert_array_equal(res.columns, [\"x\", \"y\"])\n assert_array_equal(res[\"x\"], df[\"x\"].sort_values())\n assert_array_equal(res[\"y\"], df.loc[np.argsort(df[\"x\"]), \"y\"])"},{"col":35,"endLoc":86,"id":2222,"nodeType":"Lambda","startLoc":86,"text":"lambda x: x.sort_values(\"x\")"},{"col":0,"comment":"null","endLoc":99,"header":"def test_apply_one_grouper(df)","id":2223,"name":"test_apply_one_grouper","nodeType":"Function","startLoc":92,"text":"def test_apply_one_grouper(df):\n\n res = GroupBy([\"a\"]).apply(df, lambda x: x.sort_values(\"x\"))\n assert_array_equal(res.index, [0, 1, 2, 3, 4])\n assert_array_equal(res.columns, [\"a\", \"b\", \"x\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\", \"a\", \"a\", \"b\", \"b\"])\n assert_array_equal(res[\"b\"], [\"g\", \"h\", \"f\", \"f\", \"h\"])\n assert_array_equal(res[\"x\"], [1, 1, 2, 2, 3])"},{"col":35,"endLoc":94,"id":2224,"nodeType":"Lambda","startLoc":94,"text":"lambda x: x.sort_values(\"x\")"},{"col":0,"comment":"null","endLoc":118,"header":"def test_apply_mutate_columns(df)","id":2225,"name":"test_apply_mutate_columns","nodeType":"Function","startLoc":102,"text":"def test_apply_mutate_columns(df):\n\n xx = np.arange(0, 5)\n hats = []\n\n def polyfit(df):\n fit = np.polyfit(df[\"x\"], df[\"y\"], 1)\n hat = np.polyval(fit, xx)\n hats.append(hat)\n return pd.DataFrame(dict(x=xx, y=hat))\n\n res = GroupBy([\"a\"]).apply(df, polyfit)\n assert_array_equal(res.index, np.arange(xx.size * 2))\n assert_array_equal(res.columns, [\"a\", \"x\", \"y\"])\n assert_array_equal(res[\"a\"], [\"a\"] * xx.size + [\"b\"] * xx.size)\n assert_array_equal(res[\"x\"], xx.tolist() + xx.tolist())\n assert_array_equal(res[\"y\"], np.concatenate(hats))"},{"id":2226,"name":"","nodeType":"Package"},{"id":2227,"name":"pyproject.toml","nodeType":"TextFile","path":"","text":"[build-system]\nrequires = [\"flit_core >=3.2,<4\"]\nbuild-backend = \"flit_core.buildapi\"\n\n[project]\nname = \"seaborn\"\ndescription = \"Statistical data visualization\"\nauthors = [{name = \"Michael Waskom\", email = \"mwaskom@gmail.com\"}]\nreadme = \"README.md\"\nlicense = {file = \"LICENSE.md\"}\ndynamic = [\"version\"]\nclassifiers = [\n \"Intended Audience :: Science/Research\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"License :: OSI Approved :: BSD License\",\n \"Topic :: Scientific/Engineering :: Visualization\",\n \"Topic :: Multimedia :: Graphics\",\n \"Operating System :: OS Independent\",\n \"Framework :: Matplotlib\",\n]\nrequires-python = \">=3.7\"\ndependencies = [\n \"numpy>=1.17\",\n \"pandas>=0.25\",\n \"matplotlib>=3.1,!=3.6.1\",\n \"typing_extensions; python_version < '3.8'\",\n]\n\n[project.optional-dependencies]\nstats = [\n \"scipy>=1.3\",\n \"statsmodels>=0.10\",\n]\ndev = [\n \"pytest\",\n \"pytest-cov\",\n \"pytest-xdist\",\n \"flake8\",\n \"mypy\",\n \"pandas-stubs\",\n \"pre-commit\",\n]\ndocs = [\n \"numpydoc\",\n \"nbconvert\",\n \"ipykernel\",\n \"sphinx-copybutton\",\n \"sphinx-issues\",\n \"sphinx-design\",\n \"pyyaml\",\n \"pydata_sphinx_theme==0.10.0rc2\",\n]\n\n[project.urls]\nSource = \"https://github.com/mwaskom/seaborn\"\nDocs = \"http://seaborn.pydata.org\"\n\n[tool.flit.sdist]\nexclude = [\"doc/_static/*.svg\"]\n"},{"col":4,"comment":"null","endLoc":968,"header":"def test_fill_artists(self, long_df)","id":2228,"name":"test_fill_artists","nodeType":"Function","startLoc":959,"text":"def test_fill_artists(self, long_df):\n\n for fill in [True, False]:\n f, ax = plt.subplots()\n kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"c\", fill=fill)\n for c in ax.collections:\n if fill or Version(mpl.__version__) >= Version(\"3.5.0b0\"):\n assert isinstance(c, mpl.collections.PathCollection)\n else:\n assert isinstance(c, mpl.collections.LineCollection)"},{"id":2229,"name":"tests/_marks","nodeType":"Package"},{"fileName":"test_bar.py","filePath":"tests/_marks","id":2230,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.colors import to_rgba, to_rgba_array\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.plot import Plot\nfrom seaborn._marks.bar import Bar, Bars\n\n\nclass TestBar:\n\n def plot_bars(self, variables, mark_kws, layer_kws):\n\n p = Plot(**variables).add(Bar(**mark_kws), **layer_kws).plot()\n ax = p._figure.axes[0]\n return [bar for barlist in ax.containers for bar in barlist]\n\n def check_bar(self, bar, x, y, width, height):\n\n assert bar.get_x() == pytest.approx(x)\n assert bar.get_y() == pytest.approx(y)\n assert bar.get_width() == pytest.approx(width)\n assert bar.get_height() == pytest.approx(height)\n\n def test_categorical_positions_vertical(self):\n\n x = [\"a\", \"b\"]\n y = [1, 2]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, i - w / 2, 0, w, y[i])\n\n def test_categorical_positions_horizontal(self):\n\n x = [1, 2]\n y = [\"a\", \"b\"]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, 0, i - w / 2, x[i], w)\n\n def test_numeric_positions_vertical(self):\n\n x = [1, 2]\n y = [3, 4]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, x[i] - w / 2, 0, w, y[i])\n\n def test_numeric_positions_horizontal(self):\n\n x = [1, 2]\n y = [3, 4]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {\"orient\": \"h\"})\n for i, bar in enumerate(bars):\n self.check_bar(bar, 0, y[i] - w / 2, x[i], w)\n\n def test_set_properties(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [1, 3, 2]\n\n mark = Bar(\n color=\".8\",\n alpha=.5,\n edgecolor=\".3\",\n edgealpha=.9,\n edgestyle=(2, 1),\n edgewidth=1.5,\n )\n\n p = Plot(x, y).add(mark).plot()\n ax = p._figure.axes[0]\n for bar in ax.patches:\n assert bar.get_facecolor() == to_rgba(mark.color, mark.alpha)\n assert bar.get_edgecolor() == to_rgba(mark.edgecolor, mark.edgealpha)\n # See comments in plotting method for why we need these adjustments\n assert bar.get_linewidth() == mark.edgewidth * 2\n expected_dashes = (mark.edgestyle[0] / 2, mark.edgestyle[1] / 2)\n assert bar.get_linestyle() == (0, expected_dashes)\n\n def test_mapped_properties(self):\n\n x = [\"a\", \"b\"]\n y = [1, 2]\n mark = Bar(alpha=.2)\n p = Plot(x, y, color=x, edgewidth=y).add(mark).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, bar in enumerate(ax.patches):\n assert bar.get_facecolor() == to_rgba(colors[i], mark.alpha)\n assert bar.get_edgecolor() == to_rgba(colors[i], 1)\n assert ax.patches[0].get_linewidth() < ax.patches[1].get_linewidth()\n\n def test_zero_height_skipped(self):\n\n p = Plot([\"a\", \"b\", \"c\"], [1, 0, 2]).add(Bar()).plot()\n ax = p._figure.axes[0]\n assert len(ax.patches) == 2\n\n def test_artist_kws_clip(self):\n\n p = Plot([\"a\", \"b\"], [1, 2]).add(Bar({\"clip_on\": False})).plot()\n patch = p._figure.axes[0].patches[0]\n assert patch.clipbox is None\n\n\nclass TestBars:\n\n @pytest.fixture\n def x(self):\n return pd.Series([4, 5, 6, 7, 8], name=\"x\")\n\n @pytest.fixture\n def y(self):\n return pd.Series([2, 8, 3, 5, 9], name=\"y\")\n\n @pytest.fixture\n def color(self):\n return pd.Series([\"a\", \"b\", \"c\", \"a\", \"c\"], name=\"color\")\n\n def test_positions(self, x, y):\n\n p = Plot(x, y).add(Bars()).plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n assert len(paths) == len(x)\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 0] == pytest.approx(x[i] - .5)\n assert verts[1, 0] == pytest.approx(x[i] + .5)\n assert verts[0, 1] == 0\n assert verts[3, 1] == y[i]\n\n def test_positions_horizontal(self, x, y):\n\n p = Plot(x=y, y=x).add(Bars(), orient=\"h\").plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n assert len(paths) == len(x)\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 1] == pytest.approx(x[i] - .5)\n assert verts[3, 1] == pytest.approx(x[i] + .5)\n assert verts[0, 0] == 0\n assert verts[1, 0] == y[i]\n\n def test_width(self, x, y):\n\n p = Plot(x, y).add(Bars(width=.4)).plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 0] == pytest.approx(x[i] - .2)\n assert verts[1, 0] == pytest.approx(x[i] + .2)\n\n def test_mapped_color_direct_alpha(self, x, y, color):\n\n alpha = .5\n p = Plot(x, y, color=color).add(Bars(alpha=alpha)).plot()\n ax = p._figure.axes[0]\n fcs = ax.collections[0].get_facecolors()\n C0, C1, C2, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n expected = to_rgba_array([C0, C1, C2, C0, C2], alpha)\n assert_array_equal(fcs, expected)\n\n def test_mapped_edgewidth(self, x, y):\n\n p = Plot(x, y, edgewidth=y).add(Bars()).plot()\n ax = p._figure.axes[0]\n lws = ax.collections[0].get_linewidths()\n assert_array_equal(np.argsort(lws), np.argsort(y))\n\n def test_auto_edgewidth(self):\n\n x0 = np.arange(10)\n x1 = np.arange(1000)\n\n p0 = Plot(x0, x0).add(Bars()).plot()\n p1 = Plot(x1, x1).add(Bars()).plot()\n\n lw0 = p0._figure.axes[0].collections[0].get_linewidths()\n lw1 = p1._figure.axes[0].collections[0].get_linewidths()\n\n assert (lw0 > lw1).all()\n\n def test_unfilled(self, x, y):\n\n p = Plot(x, y).add(Bars(fill=False, edgecolor=\"C4\")).plot()\n ax = p._figure.axes[0]\n fcs = ax.collections[0].get_facecolors()\n ecs = ax.collections[0].get_edgecolors()\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n assert_array_equal(fcs, to_rgba_array([colors[0]] * len(x), 0))\n assert_array_equal(ecs, to_rgba_array([colors[4]] * len(x), 1))\n"},{"col":4,"comment":"null","endLoc":983,"header":"def test_common_norm(self, rng)","id":2231,"name":"test_common_norm","nodeType":"Function","startLoc":970,"text":"def test_common_norm(self, rng):\n\n hue = np.repeat([\"a\", \"a\", \"a\", \"b\"], 40)\n x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], len(hue)).T\n x[hue == \"a\"] -= 2\n x[hue == \"b\"] += 2\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, hue=hue, common_norm=True, ax=ax1)\n kdeplot(x=x, y=y, hue=hue, common_norm=False, ax=ax2)\n\n n_seg_1 = sum(len(get_contour_coords(c)) > 0 for c in ax1.collections)\n n_seg_2 = sum(len(get_contour_coords(c)) > 0 for c in ax2.collections)\n assert n_seg_2 > n_seg_1"},{"className":"TestBar","col":0,"comment":"null","endLoc":111,"id":2232,"nodeType":"Class","startLoc":13,"text":"class TestBar:\n\n def plot_bars(self, variables, mark_kws, layer_kws):\n\n p = Plot(**variables).add(Bar(**mark_kws), **layer_kws).plot()\n ax = p._figure.axes[0]\n return [bar for barlist in ax.containers for bar in barlist]\n\n def check_bar(self, bar, x, y, width, height):\n\n assert bar.get_x() == pytest.approx(x)\n assert bar.get_y() == pytest.approx(y)\n assert bar.get_width() == pytest.approx(width)\n assert bar.get_height() == pytest.approx(height)\n\n def test_categorical_positions_vertical(self):\n\n x = [\"a\", \"b\"]\n y = [1, 2]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, i - w / 2, 0, w, y[i])\n\n def test_categorical_positions_horizontal(self):\n\n x = [1, 2]\n y = [\"a\", \"b\"]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, 0, i - w / 2, x[i], w)\n\n def test_numeric_positions_vertical(self):\n\n x = [1, 2]\n y = [3, 4]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, x[i] - w / 2, 0, w, y[i])\n\n def test_numeric_positions_horizontal(self):\n\n x = [1, 2]\n y = [3, 4]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {\"orient\": \"h\"})\n for i, bar in enumerate(bars):\n self.check_bar(bar, 0, y[i] - w / 2, x[i], w)\n\n def test_set_properties(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [1, 3, 2]\n\n mark = Bar(\n color=\".8\",\n alpha=.5,\n edgecolor=\".3\",\n edgealpha=.9,\n edgestyle=(2, 1),\n edgewidth=1.5,\n )\n\n p = Plot(x, y).add(mark).plot()\n ax = p._figure.axes[0]\n for bar in ax.patches:\n assert bar.get_facecolor() == to_rgba(mark.color, mark.alpha)\n assert bar.get_edgecolor() == to_rgba(mark.edgecolor, mark.edgealpha)\n # See comments in plotting method for why we need these adjustments\n assert bar.get_linewidth() == mark.edgewidth * 2\n expected_dashes = (mark.edgestyle[0] / 2, mark.edgestyle[1] / 2)\n assert bar.get_linestyle() == (0, expected_dashes)\n\n def test_mapped_properties(self):\n\n x = [\"a\", \"b\"]\n y = [1, 2]\n mark = Bar(alpha=.2)\n p = Plot(x, y, color=x, edgewidth=y).add(mark).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, bar in enumerate(ax.patches):\n assert bar.get_facecolor() == to_rgba(colors[i], mark.alpha)\n assert bar.get_edgecolor() == to_rgba(colors[i], 1)\n assert ax.patches[0].get_linewidth() < ax.patches[1].get_linewidth()\n\n def test_zero_height_skipped(self):\n\n p = Plot([\"a\", \"b\", \"c\"], [1, 0, 2]).add(Bar()).plot()\n ax = p._figure.axes[0]\n assert len(ax.patches) == 2\n\n def test_artist_kws_clip(self):\n\n p = Plot([\"a\", \"b\"], [1, 2]).add(Bar({\"clip_on\": False})).plot()\n patch = p._figure.axes[0].patches[0]\n assert patch.clipbox is None"},{"col":4,"comment":"null","endLoc":19,"header":"def plot_bars(self, variables, mark_kws, layer_kws)","id":2233,"name":"plot_bars","nodeType":"Function","startLoc":15,"text":"def plot_bars(self, variables, mark_kws, layer_kws):\n\n p = Plot(**variables).add(Bar(**mark_kws), **layer_kws).plot()\n ax = p._figure.axes[0]\n return [bar for barlist in ax.containers for bar in barlist]"},{"col":0,"comment":"Provide compatability for change in contour artist type in mpl3.5.","endLoc":49,"header":"def get_contour_coords(c)","id":2234,"name":"get_contour_coords","nodeType":"Function","startLoc":43,"text":"def get_contour_coords(c):\n \"\"\"Provide compatability for change in contour artist type in mpl3.5.\"\"\"\n # See https://github.com/matplotlib/matplotlib/issues/20906\n if isinstance(c, mpl.collections.LineCollection):\n return c.get_segments()\n elif isinstance(c, mpl.collections.PathCollection):\n return [p.vertices[:np.argmax(p.codes) + 1] for p in c.get_paths()]"},{"col":0,"comment":"null","endLoc":134,"header":"def test_apply_replace_columns(df)","id":2235,"name":"test_apply_replace_columns","nodeType":"Function","startLoc":121,"text":"def test_apply_replace_columns(df):\n\n def add_sorted_cumsum(df):\n\n x = df[\"x\"].sort_values()\n z = df.loc[x.index, \"y\"].cumsum()\n return pd.DataFrame(dict(x=x.values, z=z.values))\n\n res = GroupBy([\"a\"]).apply(df, add_sorted_cumsum)\n assert_array_equal(res.index, df.index)\n assert_array_equal(res.columns, [\"a\", \"x\", \"z\"])\n assert_array_equal(res[\"a\"], [\"a\", \"a\", \"a\", \"b\", \"b\"])\n assert_array_equal(res[\"x\"], [1, 1, 2, 2, 3])\n assert_array_equal(res[\"z\"], [.2, .5, 1.3, .4, .9])"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":2236,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":2237,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"col":4,"comment":"null","endLoc":1009,"header":"def test_log_scale(self, rng)","id":2238,"name":"test_log_scale","nodeType":"Function","startLoc":985,"text":"def test_log_scale(self, rng):\n\n x = rng.lognormal(0, 1, 100)\n y = rng.uniform(0, 1, 100)\n\n levels = .2, .5, 1\n\n f, ax = plt.subplots()\n kdeplot(x=x, y=y, log_scale=True, levels=levels, ax=ax)\n assert ax.get_xscale() == \"log\"\n assert ax.get_yscale() == \"log\"\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, log_scale=(10, False), levels=levels, ax=ax1)\n assert ax1.get_xscale() == \"log\"\n assert ax1.get_yscale() == \"linear\"\n\n p = _DistributionPlotter()\n kde = KDE()\n density, (xx, yy) = kde(np.log10(x), y)\n levels = p._quantile_to_level(density, levels)\n ax2.contour(10 ** xx, yy, density, levels=levels)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))"},{"col":4,"comment":"null","endLoc":1026,"header":"def test_bandwidth(self, rng)","id":2239,"name":"test_bandwidth","nodeType":"Function","startLoc":1011,"text":"def test_bandwidth(self, rng):\n\n n = 100\n x, y = rng.multivariate_normal([0, 0], [(.2, .5), (.5, 2)], n).T\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n kdeplot(x=x, y=y, ax=ax1)\n kdeplot(x=x, y=y, bw_adjust=2, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n seg1, seg2 = get_contour_coords(c1), get_contour_coords(c2)\n if seg1 + seg2:\n x1 = seg1[0][:, 0]\n x2 = seg2[0][:, 0]\n assert np.abs(x2).max() > np.abs(x1).max()"},{"col":4,"comment":"null","endLoc":26,"header":"def check_bar(self, bar, x, y, width, height)","id":2240,"name":"check_bar","nodeType":"Function","startLoc":21,"text":"def check_bar(self, bar, x, y, width, height):\n\n assert bar.get_x() == pytest.approx(x)\n assert bar.get_y() == pytest.approx(y)\n assert bar.get_width() == pytest.approx(width)\n assert bar.get_height() == pytest.approx(height)"},{"col":4,"comment":"null","endLoc":35,"header":"def test_categorical_positions_vertical(self)","id":2241,"name":"test_categorical_positions_vertical","nodeType":"Function","startLoc":28,"text":"def test_categorical_positions_vertical(self):\n\n x = [\"a\", \"b\"]\n y = [1, 2]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, i - w / 2, 0, w, y[i])"},{"col":4,"comment":"null","endLoc":1046,"header":"def test_weights(self, rng)","id":2242,"name":"test_weights","nodeType":"Function","startLoc":1028,"text":"def test_weights(self, rng):\n\n import warnings\n warnings.simplefilter(\"error\", np.VisibleDeprecationWarning)\n\n n = 100\n x, y = rng.multivariate_normal([1, 3], [(.2, .5), (.5, 2)], n).T\n hue = np.repeat([0, 1], n // 2)\n weights = rng.uniform(0, 1, n)\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n kdeplot(x=x, y=y, hue=hue, ax=ax1)\n kdeplot(x=x, y=y, hue=hue, weights=weights, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n if get_contour_coords(c1) and get_contour_coords(c2):\n seg1 = np.concatenate(get_contour_coords(c1), axis=0)\n seg2 = np.concatenate(get_contour_coords(c2), axis=0)\n assert not np.array_equal(seg1, seg2)"},{"col":4,"comment":"null","endLoc":1053,"header":"def test_hue_ignores_cmap(self, long_df)","id":2243,"name":"test_hue_ignores_cmap","nodeType":"Function","startLoc":1048,"text":"def test_hue_ignores_cmap(self, long_df):\n\n with pytest.warns(UserWarning, match=\"cmap parameter ignored\"):\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"c\", cmap=\"viridis\")\n\n assert_colors_equal(get_contour_color(ax.collections[0]), \"C0\")"},{"col":0,"comment":"Provide compatability for change in contour artist type in mpl3.5.","endLoc":61,"header":"def get_contour_color(c)","id":2244,"name":"get_contour_color","nodeType":"Function","startLoc":52,"text":"def get_contour_color(c):\n \"\"\"Provide compatability for change in contour artist type in mpl3.5.\"\"\"\n # See https://github.com/matplotlib/matplotlib/issues/20906\n if isinstance(c, mpl.collections.LineCollection):\n return c.get_color()\n elif isinstance(c, mpl.collections.PathCollection):\n if c.get_facecolor().size:\n return c.get_facecolor()\n else:\n return c.get_edgecolor()"},{"col":4,"comment":"null","endLoc":44,"header":"def test_categorical_positions_horizontal(self)","id":2245,"name":"test_categorical_positions_horizontal","nodeType":"Function","startLoc":37,"text":"def test_categorical_positions_horizontal(self):\n\n x = [1, 2]\n y = [\"a\", \"b\"]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, 0, i - w / 2, x[i], w)"},{"col":4,"comment":"null","endLoc":1061,"header":"def test_contour_line_colors(self, long_df)","id":2246,"name":"test_contour_line_colors","nodeType":"Function","startLoc":1055,"text":"def test_contour_line_colors(self, long_df):\n\n color = (.2, .9, .8, 1)\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", color=color)\n\n for c in ax.collections:\n assert_colors_equal(get_contour_color(c), color)"},{"col":4,"comment":"null","endLoc":1071,"header":"def test_plot(self, long_df, repeated_df)","id":2247,"name":"test_plot","nodeType":"Function","startLoc":864,"text":"def test_plot(self, long_df, repeated_df):\n\n f, ax = plt.subplots()\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n sort=False,\n estimator=None\n )\n p.plot(ax, {})\n line, = ax.lines\n assert_array_equal(line.get_xdata(), long_df.x.to_numpy())\n assert_array_equal(line.get_ydata(), long_df.y.to_numpy())\n\n ax.clear()\n p.plot(ax, {\"color\": \"k\", \"label\": \"test\"})\n line, = ax.lines\n assert line.get_color() == \"k\"\n assert line.get_label() == \"test\"\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n sort=True, estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n sorted_data = long_df.sort_values([\"x\", \"y\"])\n assert_array_equal(line.get_xdata(), sorted_data.x.to_numpy())\n assert_array_equal(line.get_ydata(), sorted_data.y.to_numpy())\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._hue_map.levels)\n for line, level in zip(ax.lines, p._hue_map.levels):\n assert line.get_color() == p._hue_map(level)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._size_map.levels)\n for line, level in zip(ax.lines, p._size_map.levels):\n assert line.get_linewidth() == p._size_map(level)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(p._hue_map.levels)\n assert len(ax.lines) == len(p._style_map.levels)\n for line, level in zip(ax.lines, p._hue_map.levels):\n assert line.get_color() == p._hue_map(level)\n assert line.get_marker() == p._style_map(level, \"marker\")\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n levels = product(p._hue_map.levels, p._style_map.levels)\n expected_line_count = len(p._hue_map.levels) * len(p._style_map.levels)\n assert len(ax.lines) == expected_line_count\n for line, (hue, style) in zip(ax.lines, levels):\n assert line.get_color() == p._hue_map(hue)\n assert line.get_marker() == p._style_map(style, \"marker\")\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n estimator=\"mean\", err_style=\"band\", errorbar=\"sd\", sort=True\n )\n\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n expected_data = long_df.groupby(\"x\").y.mean()\n assert_array_equal(line.get_xdata(), expected_data.index.to_numpy())\n assert np.allclose(line.get_ydata(), expected_data.to_numpy())\n assert len(ax.collections) == 1\n\n # Test that nans do not propagate to means or CIs\n\n p = _LinePlotter(\n variables=dict(\n x=[1, 1, 1, 2, 2, 2, 3, 3, 3],\n y=[1, 2, 3, 3, np.nan, 5, 4, 5, 6],\n ),\n estimator=\"mean\", err_style=\"band\", errorbar=\"ci\", n_boot=100, sort=True,\n )\n ax.clear()\n p.plot(ax, {})\n line, = ax.lines\n assert line.get_xdata().tolist() == [1, 2, 3]\n err_band = ax.collections[0].get_paths()\n assert len(err_band) == 1\n assert len(err_band[0].vertices) == 9\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n estimator=\"mean\", err_style=\"band\", errorbar=\"sd\"\n )\n\n ax.clear()\n p.plot(ax, {})\n assert len(ax.lines) == len(ax.collections) == len(p._hue_map.levels)\n for c in ax.collections:\n assert isinstance(c, mpl.collections.PolyCollection)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n estimator=\"mean\", err_style=\"bars\", errorbar=\"sd\"\n )\n\n ax.clear()\n p.plot(ax, {})\n n_lines = len(ax.lines)\n assert n_lines / 2 == len(ax.collections) == len(p._hue_map.levels)\n assert len(ax.collections) == len(p._hue_map.levels)\n for c in ax.collections:\n assert isinstance(c, mpl.collections.LineCollection)\n\n p = _LinePlotter(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", units=\"u\"),\n estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n n_units = len(repeated_df[\"u\"].unique())\n assert len(ax.lines) == n_units\n\n p = _LinePlotter(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", units=\"u\"),\n estimator=None\n )\n\n ax.clear()\n p.plot(ax, {})\n n_units *= len(repeated_df[\"a\"].unique())\n assert len(ax.lines) == n_units\n\n p.estimator = \"mean\"\n with pytest.raises(ValueError):\n p.plot(ax, {})\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n err_style=\"band\", err_kws={\"alpha\": .5},\n )\n\n ax.clear()\n p.plot(ax, {})\n for band in ax.collections:\n assert band.get_alpha() == .5\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n err_style=\"bars\", err_kws={\"elinewidth\": 2},\n )\n\n ax.clear()\n p.plot(ax, {})\n for lines in ax.collections:\n assert lines.get_linestyles() == 2\n\n p.err_style = \"invalid\"\n with pytest.raises(ValueError):\n p.plot(ax, {})\n\n x_str = long_df[\"x\"].astype(str)\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=x_str),\n )\n ax.clear()\n p.plot(ax, {})"},{"col":4,"comment":"null","endLoc":1070,"header":"def test_contour_line_cmap(self, long_df)","id":2248,"name":"test_contour_line_cmap","nodeType":"Function","startLoc":1063,"text":"def test_contour_line_cmap(self, long_df):\n\n color_list = color_palette(\"Blues\", 12)\n cmap = mpl.colors.ListedColormap(color_list)\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", cmap=cmap)\n for c in ax.collections:\n color = to_rgb(get_contour_color(c).squeeze())\n assert color in color_list"},{"col":4,"comment":"null","endLoc":53,"header":"def test_numeric_positions_vertical(self)","id":2249,"name":"test_numeric_positions_vertical","nodeType":"Function","startLoc":46,"text":"def test_numeric_positions_vertical(self):\n\n x = [1, 2]\n y = [3, 4]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {})\n for i, bar in enumerate(bars):\n self.check_bar(bar, x[i] - w / 2, 0, w, y[i])"},{"col":4,"comment":"null","endLoc":1084,"header":"def test_contour_fill_colors(self, long_df)","id":2250,"name":"test_contour_fill_colors","nodeType":"Function","startLoc":1072,"text":"def test_contour_fill_colors(self, long_df):\n\n n = 6\n color = (.2, .9, .8, 1)\n ax = kdeplot(\n data=long_df, x=\"x\", y=\"y\", fill=True, color=color, levels=n,\n )\n\n cmap = light_palette(color, reverse=True, as_cmap=True)\n lut = cmap(np.linspace(0, 1, 256))\n for c in ax.collections:\n color = c.get_facecolor().squeeze()\n assert color in lut"},{"col":4,"comment":"null","endLoc":62,"header":"def test_numeric_positions_horizontal(self)","id":2251,"name":"test_numeric_positions_horizontal","nodeType":"Function","startLoc":55,"text":"def test_numeric_positions_horizontal(self):\n\n x = [1, 2]\n y = [3, 4]\n w = .8\n bars = self.plot_bars({\"x\": x, \"y\": y}, {}, {\"orient\": \"h\"})\n for i, bar in enumerate(bars):\n self.check_bar(bar, 0, y[i] - w / 2, x[i], w)"},{"col":4,"comment":"null","endLoc":1089,"header":"def test_colorbar(self, long_df)","id":2252,"name":"test_colorbar","nodeType":"Function","startLoc":1086,"text":"def test_colorbar(self, long_df):\n\n ax = kdeplot(data=long_df, x=\"x\", y=\"y\", fill=True, cbar=True)\n assert len(ax.figure.axes) == 2"},{"col":4,"comment":"null","endLoc":86,"header":"def test_set_properties(self)","id":2253,"name":"test_set_properties","nodeType":"Function","startLoc":64,"text":"def test_set_properties(self):\n\n x = [\"a\", \"b\", \"c\"]\n y = [1, 3, 2]\n\n mark = Bar(\n color=\".8\",\n alpha=.5,\n edgecolor=\".3\",\n edgealpha=.9,\n edgestyle=(2, 1),\n edgewidth=1.5,\n )\n\n p = Plot(x, y).add(mark).plot()\n ax = p._figure.axes[0]\n for bar in ax.patches:\n assert bar.get_facecolor() == to_rgba(mark.color, mark.alpha)\n assert bar.get_edgecolor() == to_rgba(mark.edgecolor, mark.edgealpha)\n # See comments in plotting method for why we need these adjustments\n assert bar.get_linewidth() == mark.edgewidth * 2\n expected_dashes = (mark.edgestyle[0] / 2, mark.edgestyle[1] / 2)\n assert bar.get_linestyle() == (0, expected_dashes)"},{"col":4,"comment":"null","endLoc":1116,"header":"def test_levels_and_thresh(self, long_df)","id":2254,"name":"test_levels_and_thresh","nodeType":"Function","startLoc":1091,"text":"def test_levels_and_thresh(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(ncols=2)\n\n n = 8\n thresh = .1\n plot_kws = dict(data=long_df, x=\"x\", y=\"y\")\n kdeplot(**plot_kws, levels=n, thresh=thresh, ax=ax1)\n kdeplot(**plot_kws, levels=np.linspace(thresh, 1, n), ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n\n with pytest.raises(ValueError):\n kdeplot(**plot_kws, levels=[0, 1, 2])\n\n ax1.clear()\n ax2.clear()\n\n kdeplot(**plot_kws, levels=n, thresh=None, ax=ax1)\n kdeplot(**plot_kws, levels=n, thresh=0, ax=ax2)\n\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(get_contour_coords(c1), get_contour_coords(c2))\n for c1, c2 in zip(ax1.collections, ax2.collections):\n assert_array_equal(c1.get_facecolors(), c2.get_facecolors())"},{"fileName":"categorical.py","filePath":"seaborn","id":2255,"nodeType":"File","text":"from textwrap import dedent\nfrom numbers import Number\nimport warnings\nfrom colorsys import rgb_to_hls\nfrom functools import partial\n\nimport numpy as np\nimport pandas as pd\ntry:\n from scipy.stats import gaussian_kde\n _no_scipy = False\nexcept ImportError:\n from .external.kde import gaussian_kde\n _no_scipy = True\n\nimport matplotlib as mpl\nfrom matplotlib.collections import PatchCollection\nimport matplotlib.patches as Patches\nimport matplotlib.pyplot as plt\n\nfrom seaborn._oldcore import (\n variable_type,\n infer_orient,\n categorical_order,\n)\nfrom seaborn.relational import _RelationalPlotter\nfrom seaborn import utils\nfrom seaborn.utils import remove_na, _normal_quantile_func, _draw_figure, _default_color\nfrom seaborn._statistics import EstimateAggregator\nfrom seaborn.palettes import color_palette, husl_palette, light_palette, dark_palette\nfrom seaborn.axisgrid import FacetGrid, _facet_docs\n\n\n__all__ = [\n \"catplot\",\n \"stripplot\", \"swarmplot\",\n \"boxplot\", \"violinplot\", \"boxenplot\",\n \"pointplot\", \"barplot\", \"countplot\",\n]\n\n\n# Subclassing _RelationalPlotter for the legend machinery,\n# but probably should move that more centrally\nclass _CategoricalPlotterNew(_RelationalPlotter):\n\n semantics = \"x\", \"y\", \"hue\", \"units\"\n\n wide_structure = {\"x\": \"@columns\", \"y\": \"@values\", \"hue\": \"@columns\"}\n\n # flat_structure = {\"x\": \"@values\", \"y\": \"@values\"}\n flat_structure = {\"y\": \"@values\"}\n\n _legend_func = \"scatter\"\n _legend_attributes = [\"color\"]\n\n def __init__(\n self,\n data=None,\n variables={},\n order=None,\n orient=None,\n require_numeric=False,\n legend=\"auto\",\n ):\n\n super().__init__(data=data, variables=variables)\n\n # This method takes care of some bookkeeping that is necessary because the\n # original categorical plots (prior to the 2021 refactor) had some rules that\n # don't fit exactly into the logic of _core. It may be wise to have a second\n # round of refactoring that moves the logic deeper, but this will keep things\n # relatively sensible for now.\n\n # For wide data, orient determines assignment to x/y differently from the\n # wide_structure rules in _core. If we do decide to make orient part of the\n # _core variable assignment, we'll want to figure out how to express that.\n if self.input_format == \"wide\" and orient == \"h\":\n self.plot_data = self.plot_data.rename(columns={\"x\": \"y\", \"y\": \"x\"})\n orig_variables = set(self.variables)\n orig_x = self.variables.pop(\"x\", None)\n orig_y = self.variables.pop(\"y\", None)\n orig_x_type = self.var_types.pop(\"x\", None)\n orig_y_type = self.var_types.pop(\"y\", None)\n if \"x\" in orig_variables:\n self.variables[\"y\"] = orig_x\n self.var_types[\"y\"] = orig_x_type\n if \"y\" in orig_variables:\n self.variables[\"x\"] = orig_y\n self.var_types[\"x\"] = orig_y_type\n\n # The concept of an \"orientation\" is important to the original categorical\n # plots, but there's no provision for it in _core, so we need to do it here.\n # Note that it could be useful for the other functions in at least two ways\n # (orienting a univariate distribution plot from long-form data and selecting\n # the aggregation axis in lineplot), so we may want to eventually refactor it.\n self.orient = infer_orient(\n x=self.plot_data.get(\"x\", None),\n y=self.plot_data.get(\"y\", None),\n orient=orient,\n require_numeric=require_numeric,\n )\n\n self.legend = legend\n\n # Short-circuit in the case of an empty plot\n if not self.has_xy_data:\n return\n\n # Categorical plots can be \"univariate\" in which case they get an anonymous\n # category label on the opposite axis. Note: this duplicates code in the core\n # scale_categorical function. We need to do it here because of the next line.\n if self.cat_axis not in self.variables:\n self.variables[self.cat_axis] = None\n self.var_types[self.cat_axis] = \"categorical\"\n self.plot_data[self.cat_axis] = \"\"\n\n # Categorical variables have discrete levels that we need to track\n cat_levels = categorical_order(self.plot_data[self.cat_axis], order)\n self.var_levels[self.cat_axis] = cat_levels\n\n def _hue_backcompat(self, color, palette, hue_order, force_hue=False):\n \"\"\"Implement backwards compatibility for hue parametrization.\n\n Note: the force_hue parameter is used so that functions can be shown to\n pass existing tests during refactoring and then tested for new behavior.\n It can be removed after completion of the work.\n\n \"\"\"\n # The original categorical functions applied a palette to the categorical axis\n # by default. We want to require an explicit hue mapping, to be more consistent\n # with how things work elsewhere now. I don't think there's any good way to\n # do this gently -- because it's triggered by the default value of hue=None,\n # users would always get a warning, unless we introduce some sentinel \"default\"\n # argument for this change. That's possible, but asking users to set `hue=None`\n # on every call is annoying.\n # We are keeping the logic for implementing the old behavior in with the current\n # system so that (a) we can punt on that decision and (b) we can ensure that\n # refactored code passes old tests.\n default_behavior = color is None or palette is not None\n if force_hue and \"hue\" not in self.variables and default_behavior:\n self._redundant_hue = True\n self.plot_data[\"hue\"] = self.plot_data[self.cat_axis]\n self.variables[\"hue\"] = self.variables[self.cat_axis]\n self.var_types[\"hue\"] = \"categorical\"\n hue_order = self.var_levels[self.cat_axis]\n\n # Because we convert the categorical axis variable to string,\n # we need to update a dictionary palette too\n if isinstance(palette, dict):\n palette = {str(k): v for k, v in palette.items()}\n\n else:\n self._redundant_hue = False\n\n # Previously, categorical plots had a trick where color= could seed the palette.\n # Because that's an explicit parameterization, we are going to give it one\n # release cycle with a warning before removing.\n if \"hue\" in self.variables and palette is None and color is not None:\n if not isinstance(color, str):\n color = mpl.colors.to_hex(color)\n palette = f\"dark:{color}\"\n msg = (\n \"Setting a gradient palette using color= is deprecated and will be \"\n f\"removed in version 0.13. Set `palette='{palette}'` for same effect.\"\n )\n warnings.warn(msg, FutureWarning)\n\n return palette, hue_order\n\n def _palette_without_hue_backcompat(self, palette, hue_order):\n \"\"\"Provide one cycle where palette= implies hue= when not provided\"\"\"\n if \"hue\" not in self.variables and palette is not None:\n msg = \"Passing `palette` without assigning `hue` is deprecated.\"\n warnings.warn(msg, FutureWarning, stacklevel=3)\n self.legend = False\n self.plot_data[\"hue\"] = self.plot_data[self.cat_axis]\n self.variables[\"hue\"] = self.variables.get(self.cat_axis)\n self.var_types[\"hue\"] = self.var_types.get(self.cat_axis)\n hue_order = self.var_levels.get(self.cat_axis)\n return hue_order\n\n @property\n def cat_axis(self):\n return {\"v\": \"x\", \"h\": \"y\"}[self.orient]\n\n def _get_gray(self, colors):\n \"\"\"Get a grayscale value that looks good with color.\"\"\"\n if not len(colors):\n return None\n unique_colors = np.unique(colors, axis=0)\n light_vals = [rgb_to_hls(*rgb[:3])[1] for rgb in unique_colors]\n lum = min(light_vals) * .6\n return (lum, lum, lum)\n\n def _adjust_cat_axis(self, ax, axis):\n \"\"\"Set ticks and limits for a categorical variable.\"\"\"\n # Note: in theory, this could happen in _attach for all categorical axes\n # But two reasons not to do that:\n # - If it happens before plotting, autoscaling messes up the plot limits\n # - It would change existing plots from other seaborn functions\n if self.var_types[axis] != \"categorical\":\n return\n\n # If both x/y data are empty, the correct way to set up the plot is\n # somewhat undefined; because we don't add null category data to the plot in\n # this case we don't *have* a categorical axis (yet), so best to just bail.\n if self.plot_data[axis].empty:\n return\n\n # We can infer the total number of categories (including those from previous\n # plots that are not part of the plot we are currently making) from the number\n # of ticks, which matplotlib sets up while doing unit conversion. This feels\n # slightly risky, as if we are relying on something that may be a matplotlib\n # implementation detail. But I cannot think of a better way to keep track of\n # the state from previous categorical calls (see GH2516 for context)\n n = len(getattr(ax, f\"get_{axis}ticks\")())\n\n if axis == \"x\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, n - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n # Note limits that correspond to previously-inverted y axis\n ax.set_ylim(n - .5, -.5, auto=None)\n\n @property\n def _native_width(self):\n \"\"\"Return unit of width separating categories on native numeric scale.\"\"\"\n unique_values = np.unique(self.comp_data[self.cat_axis])\n if len(unique_values) > 1:\n native_width = np.nanmin(np.diff(unique_values))\n else:\n native_width = 1\n return native_width\n\n def _nested_offsets(self, width, dodge):\n \"\"\"Return offsets for each hue level for dodged plots.\"\"\"\n offsets = None\n if \"hue\" in self.variables:\n n_levels = len(self._hue_map.levels)\n if dodge:\n each_width = width / n_levels\n offsets = np.linspace(0, width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n return offsets\n\n # Note that the plotting methods here aim (in most cases) to produce the\n # exact same artists as the original (pre 0.12) version of the code, so\n # there is some weirdness that might not otherwise be clean or make sense in\n # this context, such as adding empty artists for combinations of variables\n # with no observations\n\n def plot_strips(\n self,\n jitter,\n dodge,\n color,\n edgecolor,\n plot_kws,\n ):\n\n width = .8 * self._native_width\n offsets = self._nested_offsets(width, dodge)\n\n if jitter is True:\n jlim = 0.1\n else:\n jlim = float(jitter)\n if \"hue\" in self.variables and dodge:\n jlim /= len(self._hue_map.levels)\n jlim *= self._native_width\n jitterer = partial(np.random.uniform, low=-jlim, high=+jlim)\n\n iter_vars = [self.cat_axis]\n if dodge:\n iter_vars.append(\"hue\")\n\n ax = self.ax\n dodge_move = jitter_move = 0\n\n for sub_vars, sub_data in self.iter_data(iter_vars,\n from_comp_data=True,\n allow_empty=True):\n if offsets is not None and (offsets != 0).any():\n dodge_move = offsets[sub_data[\"hue\"].map(self._hue_map.levels.index)]\n\n jitter_move = jitterer(size=len(sub_data)) if len(sub_data) > 1 else 0\n\n adjusted_data = sub_data[self.cat_axis] + dodge_move + jitter_move\n sub_data[self.cat_axis] = adjusted_data\n\n for var in \"xy\":\n if self._log_scaled(var):\n sub_data[var] = np.power(10, sub_data[var])\n\n ax = self._get_axes(sub_vars)\n points = ax.scatter(sub_data[\"x\"], sub_data[\"y\"], color=color, **plot_kws)\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(sub_data[\"hue\"]))\n\n if edgecolor == \"gray\": # XXX TODO change to \"auto\"\n points.set_edgecolors(self._get_gray(points.get_facecolors()))\n else:\n points.set_edgecolors(edgecolor)\n\n # Finalize the axes details\n if self.legend == \"auto\":\n show_legend = not self._redundant_hue and self.input_format != \"wide\"\n else:\n show_legend = bool(self.legend)\n\n if show_legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n ax.legend(title=self.legend_title)\n\n def plot_swarms(\n self,\n dodge,\n color,\n edgecolor,\n warn_thresh,\n plot_kws,\n ):\n\n width = .8 * self._native_width\n offsets = self._nested_offsets(width, dodge)\n\n iter_vars = [self.cat_axis]\n if dodge:\n iter_vars.append(\"hue\")\n\n ax = self.ax\n point_collections = {}\n dodge_move = 0\n\n for sub_vars, sub_data in self.iter_data(iter_vars,\n from_comp_data=True,\n allow_empty=True):\n\n if offsets is not None:\n dodge_move = offsets[sub_data[\"hue\"].map(self._hue_map.levels.index)]\n\n if not sub_data.empty:\n sub_data[self.cat_axis] = sub_data[self.cat_axis] + dodge_move\n\n for var in \"xy\":\n if self._log_scaled(var):\n sub_data[var] = np.power(10, sub_data[var])\n\n ax = self._get_axes(sub_vars)\n points = ax.scatter(sub_data[\"x\"], sub_data[\"y\"], color=color, **plot_kws)\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(sub_data[\"hue\"]))\n\n if edgecolor == \"gray\": # XXX TODO change to \"auto\"\n points.set_edgecolors(self._get_gray(points.get_facecolors()))\n else:\n points.set_edgecolors(edgecolor)\n\n if not sub_data.empty:\n point_collections[(ax, sub_data[self.cat_axis].iloc[0])] = points\n\n beeswarm = Beeswarm(\n width=width, orient=self.orient, warn_thresh=warn_thresh,\n )\n for (ax, center), points in point_collections.items():\n if points.get_offsets().shape[0] > 1:\n\n def draw(points, renderer, *, center=center):\n\n beeswarm(points, center)\n\n if self.orient == \"h\":\n scalex = False\n scaley = ax.get_autoscaley_on()\n else:\n scalex = ax.get_autoscalex_on()\n scaley = False\n\n # This prevents us from undoing the nice categorical axis limits\n # set in _adjust_cat_axis, because that method currently leave\n # the autoscale flag in its original setting. It may be better\n # to disable autoscaling there to avoid needing to do this.\n fixed_scale = self.var_types[self.cat_axis] == \"categorical\"\n ax.update_datalim(points.get_datalim(ax.transData))\n if not fixed_scale and (scalex or scaley):\n ax.autoscale_view(scalex=scalex, scaley=scaley)\n\n super(points.__class__, points).draw(renderer)\n\n points.draw = draw.__get__(points)\n\n _draw_figure(ax.figure)\n\n # Finalize the axes details\n if self.legend == \"auto\":\n show_legend = not self._redundant_hue and self.input_format != \"wide\"\n else:\n show_legend = bool(self.legend)\n\n if show_legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n ax.legend(title=self.legend_title)\n\n\nclass _CategoricalFacetPlotter(_CategoricalPlotterNew):\n\n semantics = _CategoricalPlotterNew.semantics + (\"col\", \"row\")\n\n\nclass _CategoricalPlotter:\n\n width = .8\n default_palette = \"light\"\n require_numeric = True\n\n def establish_variables(self, x=None, y=None, hue=None, data=None,\n orient=None, order=None, hue_order=None,\n units=None):\n \"\"\"Convert input specification into a common representation.\"\"\"\n # Option 1:\n # We are plotting a wide-form dataset\n # -----------------------------------\n if x is None and y is None:\n\n # Do a sanity check on the inputs\n if hue is not None:\n error = \"Cannot use `hue` without `x` and `y`\"\n raise ValueError(error)\n\n # No hue grouping with wide inputs\n plot_hues = None\n hue_title = None\n hue_names = None\n\n # No statistical units with wide inputs\n plot_units = None\n\n # We also won't get a axes labels here\n value_label = None\n group_label = None\n\n # Option 1a:\n # The input data is a Pandas DataFrame\n # ------------------------------------\n\n if isinstance(data, pd.DataFrame):\n\n # Order the data correctly\n if order is None:\n order = []\n # Reduce to just numeric columns\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n order.append(col)\n plot_data = data[order]\n group_names = order\n group_label = data.columns.name\n\n # Convert to a list of arrays, the common representation\n iter_data = plot_data.items()\n plot_data = [np.asarray(s, float) for k, s in iter_data]\n\n # Option 1b:\n # The input data is an array or list\n # ----------------------------------\n\n else:\n\n # We can't reorder the data\n if order is not None:\n error = \"Input data must be a pandas object to reorder\"\n raise ValueError(error)\n\n # The input data is an array\n if hasattr(data, \"shape\"):\n if len(data.shape) == 1:\n if np.isscalar(data[0]):\n plot_data = [data]\n else:\n plot_data = list(data)\n elif len(data.shape) == 2:\n nr, nc = data.shape\n if nr == 1 or nc == 1:\n plot_data = [data.ravel()]\n else:\n plot_data = [data[:, i] for i in range(nc)]\n else:\n error = (\"Input `data` can have no \"\n \"more than 2 dimensions\")\n raise ValueError(error)\n\n # Check if `data` is None to let us bail out here (for testing)\n elif data is None:\n plot_data = [[]]\n\n # The input data is a flat list\n elif np.isscalar(data[0]):\n plot_data = [data]\n\n # The input data is a nested list\n # This will catch some things that might fail later\n # but exhaustive checks are hard\n else:\n plot_data = data\n\n # Convert to a list of arrays, the common representation\n plot_data = [np.asarray(d, float) for d in plot_data]\n\n # The group names will just be numeric indices\n group_names = list(range(len(plot_data)))\n\n # Figure out the plotting orientation\n orient = \"h\" if str(orient).startswith(\"h\") else \"v\"\n\n # Option 2:\n # We are plotting a long-form dataset\n # -----------------------------------\n\n else:\n\n # See if we need to get variables from `data`\n if data is not None:\n x = data.get(x, x)\n y = data.get(y, y)\n hue = data.get(hue, hue)\n units = data.get(units, units)\n\n # Validate the inputs\n for var in [x, y, hue, units]:\n if isinstance(var, str):\n err = f\"Could not interpret input '{var}'\"\n raise ValueError(err)\n\n # Figure out the plotting orientation\n orient = infer_orient(\n x, y, orient, require_numeric=self.require_numeric\n )\n\n # Option 2a:\n # We are plotting a single set of data\n # ------------------------------------\n if x is None or y is None:\n\n # Determine where the data are\n vals = y if x is None else x\n\n # Put them into the common representation\n plot_data = [np.asarray(vals)]\n\n # Get a label for the value axis\n if hasattr(vals, \"name\"):\n value_label = vals.name\n else:\n value_label = None\n\n # This plot will not have group labels or hue nesting\n groups = None\n group_label = None\n group_names = []\n plot_hues = None\n hue_names = None\n hue_title = None\n plot_units = None\n\n # Option 2b:\n # We are grouping the data values by another variable\n # ---------------------------------------------------\n else:\n\n # Determine which role each variable will play\n if orient == \"v\":\n vals, groups = y, x\n else:\n vals, groups = x, y\n\n # Get the categorical axis label\n group_label = None\n if hasattr(groups, \"name\"):\n group_label = groups.name\n\n # Get the order on the categorical axis\n group_names = categorical_order(groups, order)\n\n # Group the numeric data\n plot_data, value_label = self._group_longform(vals, groups,\n group_names)\n\n # Now handle the hue levels for nested ordering\n if hue is None:\n plot_hues = None\n hue_title = None\n hue_names = None\n else:\n\n # Get the order of the hue levels\n hue_names = categorical_order(hue, hue_order)\n\n # Group the hue data\n plot_hues, hue_title = self._group_longform(hue, groups,\n group_names)\n\n # Now handle the units for nested observations\n if units is None:\n plot_units = None\n else:\n plot_units, _ = self._group_longform(units, groups,\n group_names)\n\n # Assign object attributes\n # ------------------------\n self.orient = orient\n self.plot_data = plot_data\n self.group_label = group_label\n self.value_label = value_label\n self.group_names = group_names\n self.plot_hues = plot_hues\n self.hue_title = hue_title\n self.hue_names = hue_names\n self.plot_units = plot_units\n\n def _group_longform(self, vals, grouper, order):\n \"\"\"Group a long-form variable by another with correct order.\"\"\"\n # Ensure that the groupby will work\n if not isinstance(vals, pd.Series):\n if isinstance(grouper, pd.Series):\n index = grouper.index\n else:\n index = None\n vals = pd.Series(vals, index=index)\n\n # Group the val data\n grouped_vals = vals.groupby(grouper)\n out_data = []\n for g in order:\n try:\n g_vals = grouped_vals.get_group(g)\n except KeyError:\n g_vals = np.array([])\n out_data.append(g_vals)\n\n # Get the vals axis label\n label = vals.name\n\n return out_data, label\n\n def establish_colors(self, color, palette, saturation):\n \"\"\"Get a list of colors for the main component of the plots.\"\"\"\n if self.hue_names is None:\n n_colors = len(self.plot_data)\n else:\n n_colors = len(self.hue_names)\n\n # Determine the main colors\n if color is None and palette is None:\n # Determine whether the current palette will have enough values\n # If not, we'll default to the husl palette so each is distinct\n current_palette = utils.get_color_cycle()\n if n_colors <= len(current_palette):\n colors = color_palette(n_colors=n_colors)\n else:\n colors = husl_palette(n_colors, l=.7) # noqa\n\n elif palette is None:\n # When passing a specific color, the interpretation depends\n # on whether there is a hue variable or not.\n # If so, we will make a blend palette so that the different\n # levels have some amount of variation.\n if self.hue_names is None:\n colors = [color] * n_colors\n else:\n if self.default_palette == \"light\":\n colors = light_palette(color, n_colors)\n elif self.default_palette == \"dark\":\n colors = dark_palette(color, n_colors)\n else:\n raise RuntimeError(\"No default palette specified\")\n else:\n\n # Let `palette` be a dict mapping level to color\n if isinstance(palette, dict):\n if self.hue_names is None:\n levels = self.group_names\n else:\n levels = self.hue_names\n palette = [palette[l] for l in levels]\n\n colors = color_palette(palette, n_colors)\n\n # Desaturate a bit because these are patches\n if saturation < 1:\n colors = color_palette(colors, desat=saturation)\n\n # Convert the colors to a common representations\n rgb_colors = color_palette(colors)\n\n # Determine the gray color to use for the lines framing the plot\n light_vals = [rgb_to_hls(*c)[1] for c in rgb_colors]\n lum = min(light_vals) * .6\n gray = mpl.colors.rgb2hex((lum, lum, lum))\n\n # Assign object attributes\n self.colors = rgb_colors\n self.gray = gray\n\n @property\n def hue_offsets(self):\n \"\"\"A list of center positions for plots when hue nesting is used.\"\"\"\n n_levels = len(self.hue_names)\n if self.dodge:\n each_width = self.width / n_levels\n offsets = np.linspace(0, self.width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n\n return offsets\n\n @property\n def nested_width(self):\n \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n if self.dodge:\n width = self.width / len(self.hue_names) * .98\n else:\n width = self.width\n return width\n\n def annotate_axes(self, ax):\n \"\"\"Add descriptive labels to an Axes object.\"\"\"\n if self.orient == \"v\":\n xlabel, ylabel = self.group_label, self.value_label\n else:\n xlabel, ylabel = self.value_label, self.group_label\n\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n group_names = self.group_names\n if not group_names:\n group_names = [\"\" for _ in range(len(self.plot_data))]\n\n if self.orient == \"v\":\n ax.set_xticks(np.arange(len(self.plot_data)))\n ax.set_xticklabels(group_names)\n else:\n ax.set_yticks(np.arange(len(self.plot_data)))\n ax.set_yticklabels(group_names)\n\n if self.orient == \"v\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, len(self.plot_data) - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n ax.set_ylim(-.5, len(self.plot_data) - .5, auto=None)\n\n if self.hue_names is not None:\n ax.legend(loc=\"best\", title=self.hue_title)\n\n def add_legend_data(self, ax, color, label):\n \"\"\"Add a dummy patch object so we can get legend data.\"\"\"\n rect = plt.Rectangle([0, 0], 0, 0,\n linewidth=self.linewidth / 2,\n edgecolor=self.gray,\n facecolor=color,\n label=label)\n ax.add_patch(rect)\n\n\nclass _BoxPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n\n self.dodge = dodge\n self.width = width\n self.fliersize = fliersize\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n def draw_boxplot(self, ax, kws):\n \"\"\"Use matplotlib to draw a boxplot on an Axes.\"\"\"\n vert = self.orient == \"v\"\n\n props = {}\n for obj in [\"box\", \"whisker\", \"cap\", \"median\", \"flier\"]:\n props[obj] = kws.pop(obj + \"props\", {})\n\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = np.asarray(remove_na(group_data))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[i],\n widths=self.width,\n **kws)\n color = self.colors[i]\n self.restyle_boxplot(artist_dict, color, props)\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = np.asarray(remove_na(group_data[hue_mask]))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n center = i + offsets[j]\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[center],\n widths=self.nested_width,\n **kws)\n self.restyle_boxplot(artist_dict, self.colors[j], props)\n # Add legend data, but just for one set of boxes\n\n def restyle_boxplot(self, artist_dict, color, props):\n \"\"\"Take a drawn matplotlib boxplot and make it look nice.\"\"\"\n for box in artist_dict[\"boxes\"]:\n box.update(dict(facecolor=color,\n zorder=.9,\n edgecolor=self.gray,\n linewidth=self.linewidth))\n box.update(props[\"box\"])\n for whisk in artist_dict[\"whiskers\"]:\n whisk.update(dict(color=self.gray,\n linewidth=self.linewidth,\n linestyle=\"-\"))\n whisk.update(props[\"whisker\"])\n for cap in artist_dict[\"caps\"]:\n cap.update(dict(color=self.gray,\n linewidth=self.linewidth))\n cap.update(props[\"cap\"])\n for med in artist_dict[\"medians\"]:\n med.update(dict(color=self.gray,\n linewidth=self.linewidth))\n med.update(props[\"median\"])\n for fly in artist_dict[\"fliers\"]:\n fly.update(dict(markerfacecolor=self.gray,\n marker=\"d\",\n markeredgecolor=self.gray,\n markersize=self.fliersize))\n fly.update(props[\"flier\"])\n\n def plot(self, ax, boxplot_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_boxplot(ax, boxplot_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _ViolinPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n self.estimate_densities(bw, cut, scale, scale_hue, gridsize)\n\n self.gridsize = gridsize\n self.width = width\n self.dodge = dodge\n\n if inner is not None:\n if not any([inner.startswith(\"quart\"),\n inner.startswith(\"box\"),\n inner.startswith(\"stick\"),\n inner.startswith(\"point\")]):\n err = f\"Inner style '{inner}' not recognized\"\n raise ValueError(err)\n self.inner = inner\n\n if split and self.hue_names is not None and len(self.hue_names) != 2:\n msg = \"There must be exactly two hue levels to use `split`.'\"\n raise ValueError(msg)\n self.split = split\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n def estimate_densities(self, bw, cut, scale, scale_hue, gridsize):\n \"\"\"Find the support and density for all of the data.\"\"\"\n # Initialize data structures to keep track of plotting data\n if self.hue_names is None:\n support = []\n density = []\n counts = np.zeros(len(self.plot_data))\n max_density = np.zeros(len(self.plot_data))\n else:\n support = [[] for _ in self.plot_data]\n density = [[] for _ in self.plot_data]\n size = len(self.group_names), len(self.hue_names)\n counts = np.zeros(size)\n max_density = np.zeros(size)\n\n for i, group_data in enumerate(self.plot_data):\n\n # Option 1: we have a single level of grouping\n # --------------------------------------------\n\n if self.plot_hues is None:\n\n # Strip missing datapoints\n kde_data = remove_na(group_data)\n\n # Handle special case of no data at this level\n if kde_data.size == 0:\n support.append(np.array([]))\n density.append(np.array([1.]))\n counts[i] = 0\n max_density[i] = 0\n continue\n\n # Handle special case of a single unique datapoint\n elif np.unique(kde_data).size == 1:\n support.append(np.unique(kde_data))\n density.append(np.array([1.]))\n counts[i] = 1\n max_density[i] = 0\n continue\n\n # Fit the KDE and get the used bandwidth size\n kde, bw_used = self.fit_kde(kde_data, bw)\n\n # Determine the support grid and get the density over it\n support_i = self.kde_support(kde_data, bw_used, cut, gridsize)\n density_i = kde.evaluate(support_i)\n\n # Update the data structures with these results\n support.append(support_i)\n density.append(density_i)\n counts[i] = kde_data.size\n max_density[i] = density_i.max()\n\n # Option 2: we have nested grouping by a hue variable\n # ---------------------------------------------------\n\n else:\n for j, hue_level in enumerate(self.hue_names):\n\n # Handle special case of no data at this category level\n if not group_data.size:\n support[i].append(np.array([]))\n density[i].append(np.array([1.]))\n counts[i, j] = 0\n max_density[i, j] = 0\n continue\n\n # Select out the observations for this hue level\n hue_mask = self.plot_hues[i] == hue_level\n\n # Strip missing datapoints\n kde_data = remove_na(group_data[hue_mask])\n\n # Handle special case of no data at this level\n if kde_data.size == 0:\n support[i].append(np.array([]))\n density[i].append(np.array([1.]))\n counts[i, j] = 0\n max_density[i, j] = 0\n continue\n\n # Handle special case of a single unique datapoint\n elif np.unique(kde_data).size == 1:\n support[i].append(np.unique(kde_data))\n density[i].append(np.array([1.]))\n counts[i, j] = 1\n max_density[i, j] = 0\n continue\n\n # Fit the KDE and get the used bandwidth size\n kde, bw_used = self.fit_kde(kde_data, bw)\n\n # Determine the support grid and get the density over it\n support_ij = self.kde_support(kde_data, bw_used,\n cut, gridsize)\n density_ij = kde.evaluate(support_ij)\n\n # Update the data structures with these results\n support[i].append(support_ij)\n density[i].append(density_ij)\n counts[i, j] = kde_data.size\n max_density[i, j] = density_ij.max()\n\n # Scale the height of the density curve.\n # For a violinplot the density is non-quantitative.\n # The objective here is to scale the curves relative to 1 so that\n # they can be multiplied by the width parameter during plotting.\n\n if scale == \"area\":\n self.scale_area(density, max_density, scale_hue)\n\n elif scale == \"width\":\n self.scale_width(density)\n\n elif scale == \"count\":\n self.scale_count(density, counts, scale_hue)\n\n else:\n raise ValueError(f\"scale method '{scale}' not recognized\")\n\n # Set object attributes that will be used while plotting\n self.support = support\n self.density = density\n\n def fit_kde(self, x, bw):\n \"\"\"Estimate a KDE for a vector of data with flexible bandwidth.\"\"\"\n kde = gaussian_kde(x, bw)\n\n # Extract the numeric bandwidth from the KDE object\n bw_used = kde.factor\n\n # At this point, bw will be a numeric scale factor.\n # To get the actual bandwidth of the kernel, we multiple by the\n # unbiased standard deviation of the data, which we will use\n # elsewhere to compute the range of the support.\n bw_used = bw_used * x.std(ddof=1)\n\n return kde, bw_used\n\n def kde_support(self, x, bw, cut, gridsize):\n \"\"\"Define a grid of support for the violin.\"\"\"\n support_min = x.min() - bw * cut\n support_max = x.max() + bw * cut\n return np.linspace(support_min, support_max, gridsize)\n\n def scale_area(self, density, max_density, scale_hue):\n \"\"\"Scale the relative area under the KDE curve.\n\n This essentially preserves the \"standard\" KDE scaling, but the\n resulting maximum density will be 1 so that the curve can be\n properly multiplied by the violin width.\n\n \"\"\"\n if self.hue_names is None:\n for d in density:\n if d.size > 1:\n d /= max_density.max()\n else:\n for i, group in enumerate(density):\n for d in group:\n if scale_hue:\n max = max_density[i].max()\n else:\n max = max_density.max()\n if d.size > 1:\n d /= max\n\n def scale_width(self, density):\n \"\"\"Scale each density curve to the same height.\"\"\"\n if self.hue_names is None:\n for d in density:\n d /= d.max()\n else:\n for group in density:\n for d in group:\n d /= d.max()\n\n def scale_count(self, density, counts, scale_hue):\n \"\"\"Scale each density curve by the number of observations.\"\"\"\n if self.hue_names is None:\n if counts.max() == 0:\n d = 0\n else:\n for count, d in zip(counts, density):\n d /= d.max()\n d *= count / counts.max()\n else:\n for i, group in enumerate(density):\n for j, d in enumerate(group):\n if counts[i].max() == 0:\n d = 0\n else:\n count = counts[i, j]\n if scale_hue:\n scaler = count / counts[i].max()\n else:\n scaler = count / counts.max()\n d /= d.max()\n d *= scaler\n\n @property\n def dwidth(self):\n\n if self.hue_names is None or not self.dodge:\n return self.width / 2\n elif self.split:\n return self.width / 2\n else:\n return self.width / (2 * len(self.hue_names))\n\n def draw_violins(self, ax):\n \"\"\"Draw the violins onto `ax`.\"\"\"\n fill_func = ax.fill_betweenx if self.orient == \"v\" else ax.fill_between\n for i, group_data in enumerate(self.plot_data):\n\n kws = dict(edgecolor=self.gray, linewidth=self.linewidth)\n\n # Option 1: we have a single level of grouping\n # --------------------------------------------\n\n if self.plot_hues is None:\n\n support, density = self.support[i], self.density[i]\n\n # Handle special case of no observations in this bin\n if support.size == 0:\n continue\n\n # Handle special case of a single observation\n elif support.size == 1:\n val = support.item()\n d = density.item()\n self.draw_single_observation(ax, i, val, d)\n continue\n\n # Draw the violin for this group\n grid = np.ones(self.gridsize) * i\n fill_func(support,\n grid - density * self.dwidth,\n grid + density * self.dwidth,\n facecolor=self.colors[i],\n **kws)\n\n # Draw the interior representation of the data\n if self.inner is None:\n continue\n\n # Get a nan-free vector of datapoints\n violin_data = remove_na(group_data)\n\n # Draw box and whisker information\n if self.inner.startswith(\"box\"):\n self.draw_box_lines(ax, violin_data, i)\n\n # Draw quartile lines\n elif self.inner.startswith(\"quart\"):\n self.draw_quartiles(ax, violin_data, support, density, i)\n\n # Draw stick observations\n elif self.inner.startswith(\"stick\"):\n self.draw_stick_lines(ax, violin_data, support, density, i)\n\n # Draw point observations\n elif self.inner.startswith(\"point\"):\n self.draw_points(ax, violin_data, i)\n\n # Option 2: we have nested grouping by a hue variable\n # ---------------------------------------------------\n\n else:\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n support, density = self.support[i][j], self.density[i][j]\n kws[\"facecolor\"] = self.colors[j]\n\n # Add legend data, but just for one set of violins\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle the special case where we have no observations\n if support.size == 0:\n continue\n\n # Handle the special case where we have one observation\n elif support.size == 1:\n val = support.item()\n d = density.item()\n if self.split:\n d = d / 2\n at_group = i + offsets[j]\n self.draw_single_observation(ax, at_group, val, d)\n continue\n\n # Option 2a: we are drawing a single split violin\n # -----------------------------------------------\n\n if self.split:\n\n grid = np.ones(self.gridsize) * i\n if j:\n fill_func(support,\n grid,\n grid + density * self.dwidth,\n **kws)\n else:\n fill_func(support,\n grid - density * self.dwidth,\n grid,\n **kws)\n\n # Draw the interior representation of the data\n if self.inner is None:\n continue\n\n # Get a nan-free vector of datapoints\n hue_mask = self.plot_hues[i] == hue_level\n violin_data = remove_na(group_data[hue_mask])\n\n # Draw quartile lines\n if self.inner.startswith(\"quart\"):\n self.draw_quartiles(ax, violin_data,\n support, density, i,\n [\"left\", \"right\"][j])\n\n # Draw stick observations\n elif self.inner.startswith(\"stick\"):\n self.draw_stick_lines(ax, violin_data,\n support, density, i,\n [\"left\", \"right\"][j])\n\n # The box and point interior plots are drawn for\n # all data at the group level, so we just do that once\n if j and any(self.plot_hues[0] == hue_level):\n continue\n\n # Get the whole vector for this group level\n violin_data = remove_na(group_data)\n\n # Draw box and whisker information\n if self.inner.startswith(\"box\"):\n self.draw_box_lines(ax, violin_data, i)\n\n # Draw point observations\n elif self.inner.startswith(\"point\"):\n self.draw_points(ax, violin_data, i)\n\n # Option 2b: we are drawing full nested violins\n # -----------------------------------------------\n\n else:\n grid = np.ones(self.gridsize) * (i + offsets[j])\n fill_func(support,\n grid - density * self.dwidth,\n grid + density * self.dwidth,\n **kws)\n\n # Draw the interior representation\n if self.inner is None:\n continue\n\n # Get a nan-free vector of datapoints\n hue_mask = self.plot_hues[i] == hue_level\n violin_data = remove_na(group_data[hue_mask])\n\n # Draw box and whisker information\n if self.inner.startswith(\"box\"):\n self.draw_box_lines(ax, violin_data, i + offsets[j])\n\n # Draw quartile lines\n elif self.inner.startswith(\"quart\"):\n self.draw_quartiles(ax, violin_data,\n support, density,\n i + offsets[j])\n\n # Draw stick observations\n elif self.inner.startswith(\"stick\"):\n self.draw_stick_lines(ax, violin_data,\n support, density,\n i + offsets[j])\n\n # Draw point observations\n elif self.inner.startswith(\"point\"):\n self.draw_points(ax, violin_data, i + offsets[j])\n\n def draw_single_observation(self, ax, at_group, at_quant, density):\n \"\"\"Draw a line to mark a single observation.\"\"\"\n d_width = density * self.dwidth\n if self.orient == \"v\":\n ax.plot([at_group - d_width, at_group + d_width],\n [at_quant, at_quant],\n color=self.gray,\n linewidth=self.linewidth)\n else:\n ax.plot([at_quant, at_quant],\n [at_group - d_width, at_group + d_width],\n color=self.gray,\n linewidth=self.linewidth)\n\n def draw_box_lines(self, ax, data, center):\n \"\"\"Draw boxplot information at center of the density.\"\"\"\n # Compute the boxplot statistics\n q25, q50, q75 = np.percentile(data, [25, 50, 75])\n whisker_lim = 1.5 * (q75 - q25)\n h1 = np.min(data[data >= (q25 - whisker_lim)])\n h2 = np.max(data[data <= (q75 + whisker_lim)])\n\n # Draw a boxplot using lines and a point\n if self.orient == \"v\":\n ax.plot([center, center], [h1, h2],\n linewidth=self.linewidth,\n color=self.gray)\n ax.plot([center, center], [q25, q75],\n linewidth=self.linewidth * 3,\n color=self.gray)\n ax.scatter(center, q50,\n zorder=3,\n color=\"white\",\n edgecolor=self.gray,\n s=np.square(self.linewidth * 2))\n else:\n ax.plot([h1, h2], [center, center],\n linewidth=self.linewidth,\n color=self.gray)\n ax.plot([q25, q75], [center, center],\n linewidth=self.linewidth * 3,\n color=self.gray)\n ax.scatter(q50, center,\n zorder=3,\n color=\"white\",\n edgecolor=self.gray,\n s=np.square(self.linewidth * 2))\n\n def draw_quartiles(self, ax, data, support, density, center, split=False):\n \"\"\"Draw the quartiles as lines at width of density.\"\"\"\n q25, q50, q75 = np.percentile(data, [25, 50, 75])\n\n self.draw_to_density(ax, center, q25, support, density, split,\n linewidth=self.linewidth,\n dashes=[self.linewidth * 1.5] * 2)\n self.draw_to_density(ax, center, q50, support, density, split,\n linewidth=self.linewidth,\n dashes=[self.linewidth * 3] * 2)\n self.draw_to_density(ax, center, q75, support, density, split,\n linewidth=self.linewidth,\n dashes=[self.linewidth * 1.5] * 2)\n\n def draw_points(self, ax, data, center):\n \"\"\"Draw individual observations as points at middle of the violin.\"\"\"\n kws = dict(s=np.square(self.linewidth * 2),\n color=self.gray,\n edgecolor=self.gray)\n\n grid = np.ones(len(data)) * center\n\n if self.orient == \"v\":\n ax.scatter(grid, data, **kws)\n else:\n ax.scatter(data, grid, **kws)\n\n def draw_stick_lines(self, ax, data, support, density,\n center, split=False):\n \"\"\"Draw individual observations as sticks at width of density.\"\"\"\n for val in data:\n self.draw_to_density(ax, center, val, support, density, split,\n linewidth=self.linewidth * .5)\n\n def draw_to_density(self, ax, center, val, support, density, split, **kws):\n \"\"\"Draw a line orthogonal to the value axis at width of density.\"\"\"\n idx = np.argmin(np.abs(support - val))\n width = self.dwidth * density[idx] * .99\n\n kws[\"color\"] = self.gray\n\n if self.orient == \"v\":\n if split == \"left\":\n ax.plot([center - width, center], [val, val], **kws)\n elif split == \"right\":\n ax.plot([center, center + width], [val, val], **kws)\n else:\n ax.plot([center - width, center + width], [val, val], **kws)\n else:\n if split == \"left\":\n ax.plot([val, val], [center - width, center], **kws)\n elif split == \"right\":\n ax.plot([val, val], [center, center + width], **kws)\n else:\n ax.plot([val, val], [center - width, center + width], **kws)\n\n def plot(self, ax):\n \"\"\"Make the violin plot.\"\"\"\n self.draw_violins(ax)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _CategoricalStatPlotter(_CategoricalPlotter):\n\n require_numeric = True\n\n @property\n def nested_width(self):\n \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n if self.dodge:\n width = self.width / len(self.hue_names)\n else:\n width = self.width\n return width\n\n def estimate_statistic(self, estimator, errorbar, n_boot, seed):\n\n if self.hue_names is None:\n statistic = []\n confint = []\n else:\n statistic = [[] for _ in self.plot_data]\n confint = [[] for _ in self.plot_data]\n\n var = {\"v\": \"y\", \"h\": \"x\"}[self.orient]\n\n agg = EstimateAggregator(estimator, errorbar, n_boot=n_boot, seed=seed)\n\n for i, group_data in enumerate(self.plot_data):\n\n # Option 1: we have a single layer of grouping\n # --------------------------------------------\n if self.plot_hues is None:\n\n df = pd.DataFrame({var: group_data})\n if self.plot_units is not None:\n df[\"units\"] = self.plot_units[i]\n\n res = agg(df, var)\n\n statistic.append(res[var])\n if errorbar is not None:\n confint.append((res[f\"{var}min\"], res[f\"{var}max\"]))\n\n # Option 2: we are grouping by a hue layer\n # ----------------------------------------\n\n else:\n for hue_level in self.hue_names:\n\n if not self.plot_hues[i].size:\n statistic[i].append(np.nan)\n if errorbar is not None:\n confint[i].append((np.nan, np.nan))\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n df = pd.DataFrame({var: group_data[hue_mask]})\n if self.plot_units is not None:\n df[\"units\"] = self.plot_units[i][hue_mask]\n\n res = agg(df, var)\n\n statistic[i].append(res[var])\n if errorbar is not None:\n confint[i].append((res[f\"{var}min\"], res[f\"{var}max\"]))\n\n # Save the resulting values for plotting\n self.statistic = np.array(statistic)\n self.confint = np.array(confint)\n\n def draw_confints(self, ax, at_group, confint, colors,\n errwidth=None, capsize=None, **kws):\n\n if errwidth is not None:\n kws.setdefault(\"lw\", errwidth)\n else:\n kws.setdefault(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.8)\n\n for at, (ci_low, ci_high), color in zip(at_group,\n confint,\n colors):\n if self.orient == \"v\":\n ax.plot([at, at], [ci_low, ci_high], color=color, **kws)\n if capsize is not None:\n ax.plot([at - capsize / 2, at + capsize / 2],\n [ci_low, ci_low], color=color, **kws)\n ax.plot([at - capsize / 2, at + capsize / 2],\n [ci_high, ci_high], color=color, **kws)\n else:\n ax.plot([ci_low, ci_high], [at, at], color=color, **kws)\n if capsize is not None:\n ax.plot([ci_low, ci_low],\n [at - capsize / 2, at + capsize / 2],\n color=color, **kws)\n ax.plot([ci_high, ci_high],\n [at - capsize / 2, at + capsize / 2],\n color=color, **kws)\n\n\nclass _BarPlotter(_CategoricalStatPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation, width,\n errcolor, errwidth, capsize, dodge):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient,\n order, hue_order, units)\n self.establish_colors(color, palette, saturation)\n self.estimate_statistic(estimator, errorbar, n_boot, seed)\n\n self.dodge = dodge\n self.width = width\n\n self.errcolor = errcolor\n self.errwidth = errwidth\n self.capsize = capsize\n\n def draw_bars(self, ax, kws):\n \"\"\"Draw the bars onto `ax`.\"\"\"\n # Get the right matplotlib function depending on the orientation\n barfunc = ax.bar if self.orient == \"v\" else ax.barh\n barpos = np.arange(len(self.statistic))\n\n if self.plot_hues is None:\n\n # Draw the bars\n barfunc(barpos, self.statistic, self.width,\n color=self.colors, align=\"center\", **kws)\n\n # Draw the confidence intervals\n errcolors = [self.errcolor] * len(barpos)\n self.draw_confints(ax,\n barpos,\n self.confint,\n errcolors,\n self.errwidth,\n self.capsize)\n\n else:\n\n for j, hue_level in enumerate(self.hue_names):\n\n # Draw the bars\n offpos = barpos + self.hue_offsets[j]\n barfunc(offpos, self.statistic[:, j], self.nested_width,\n color=self.colors[j], align=\"center\",\n label=hue_level, **kws)\n\n # Draw the confidence intervals\n if self.confint.size:\n confint = self.confint[:, j]\n errcolors = [self.errcolor] * len(offpos)\n self.draw_confints(ax,\n offpos,\n confint,\n errcolors,\n self.errwidth,\n self.capsize)\n\n def plot(self, ax, bar_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_bars(ax, bar_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _PointPlotter(_CategoricalStatPlotter):\n\n default_palette = \"dark\"\n\n def __init__(self, x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth=None, capsize=None):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient,\n order, hue_order, units)\n self.establish_colors(color, palette, 1)\n self.estimate_statistic(estimator, errorbar, n_boot, seed)\n\n # Override the default palette for single-color plots\n if hue is None and color is None and palette is None:\n self.colors = [color_palette()[0]] * len(self.colors)\n\n # Don't join single-layer plots with different colors\n if hue is None and palette is not None:\n join = False\n\n # Use a good default for `dodge=True`\n if dodge is True and self.hue_names is not None:\n dodge = .025 * len(self.hue_names)\n\n # Make sure we have a marker for each hue level\n if isinstance(markers, str):\n markers = [markers] * len(self.colors)\n self.markers = markers\n\n # Make sure we have a line style for each hue level\n if isinstance(linestyles, str):\n linestyles = [linestyles] * len(self.colors)\n self.linestyles = linestyles\n\n # Set the other plot components\n self.dodge = dodge\n self.join = join\n self.scale = scale\n self.errwidth = errwidth\n self.capsize = capsize\n\n @property\n def hue_offsets(self):\n \"\"\"Offsets relative to the center position for each hue level.\"\"\"\n if self.dodge:\n offset = np.linspace(0, self.dodge, len(self.hue_names))\n offset -= offset.mean()\n else:\n offset = np.zeros(len(self.hue_names))\n return offset\n\n def draw_points(self, ax):\n \"\"\"Draw the main data components of the plot.\"\"\"\n # Get the center positions on the categorical axis\n pointpos = np.arange(len(self.statistic))\n\n # Get the size of the plot elements\n lw = mpl.rcParams[\"lines.linewidth\"] * 1.8 * self.scale\n mew = lw * .75\n markersize = np.pi * np.square(lw) * 2\n\n if self.plot_hues is None:\n\n # Draw lines joining each estimate point\n if self.join:\n color = self.colors[0]\n ls = self.linestyles[0]\n if self.orient == \"h\":\n ax.plot(self.statistic, pointpos,\n color=color, ls=ls, lw=lw)\n else:\n ax.plot(pointpos, self.statistic,\n color=color, ls=ls, lw=lw)\n\n # Draw the confidence intervals\n self.draw_confints(ax, pointpos, self.confint, self.colors,\n self.errwidth, self.capsize)\n\n # Draw the estimate points\n marker = self.markers[0]\n colors = [mpl.colors.colorConverter.to_rgb(c) for c in self.colors]\n if self.orient == \"h\":\n x, y = self.statistic, pointpos\n else:\n x, y = pointpos, self.statistic\n ax.scatter(x, y,\n linewidth=mew, marker=marker, s=markersize,\n facecolor=colors, edgecolor=colors)\n\n else:\n\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Determine the values to plot for this level\n statistic = self.statistic[:, j]\n\n # Determine the position on the categorical and z axes\n offpos = pointpos + offsets[j]\n z = j + 1\n\n # Draw lines joining each estimate point\n if self.join:\n color = self.colors[j]\n ls = self.linestyles[j]\n if self.orient == \"h\":\n ax.plot(statistic, offpos, color=color,\n zorder=z, ls=ls, lw=lw)\n else:\n ax.plot(offpos, statistic, color=color,\n zorder=z, ls=ls, lw=lw)\n\n # Draw the confidence intervals\n if self.confint.size:\n confint = self.confint[:, j]\n errcolors = [self.colors[j]] * len(offpos)\n self.draw_confints(ax, offpos, confint, errcolors,\n self.errwidth, self.capsize,\n zorder=z)\n\n # Draw the estimate points\n n_points = len(remove_na(offpos))\n marker = self.markers[j]\n color = mpl.colors.colorConverter.to_rgb(self.colors[j])\n\n if self.orient == \"h\":\n x, y = statistic, offpos\n else:\n x, y = offpos, statistic\n\n if not len(remove_na(statistic)):\n x = y = [np.nan] * n_points\n\n ax.scatter(x, y, label=hue_level,\n facecolor=color, edgecolor=color,\n linewidth=mew, marker=marker, s=markersize,\n zorder=z)\n\n def plot(self, ax):\n \"\"\"Make the plot.\"\"\"\n self.draw_points(ax)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _CountPlotter(_BarPlotter):\n require_numeric = False\n\n\nclass _LVPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale, outlier_prop,\n trust_alpha, showfliers=True):\n\n self.width = width\n self.dodge = dodge\n self.saturation = saturation\n\n k_depth_methods = ['proportion', 'tukey', 'trustworthy', 'full']\n if not (k_depth in k_depth_methods or isinstance(k_depth, Number)):\n msg = (f'k_depth must be one of {k_depth_methods} or a number, '\n f'but {k_depth} was passed.')\n raise ValueError(msg)\n self.k_depth = k_depth\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n scales = ['linear', 'exponential', 'area']\n if scale not in scales:\n msg = f'scale must be one of {scales}, but {scale} was passed.'\n raise ValueError(msg)\n self.scale = scale\n\n if ((outlier_prop > 1) or (outlier_prop <= 0)):\n msg = f'outlier_prop {outlier_prop} not in range (0, 1]'\n raise ValueError(msg)\n self.outlier_prop = outlier_prop\n\n if not 0 < trust_alpha < 1:\n msg = f'trust_alpha {trust_alpha} not in range (0, 1)'\n raise ValueError(msg)\n self.trust_alpha = trust_alpha\n\n self.showfliers = showfliers\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n\n def _lv_box_ends(self, vals):\n \"\"\"Get the number of data points and calculate `depth` of\n letter-value plot.\"\"\"\n vals = np.asarray(vals)\n # Remove infinite values while handling a 'object' dtype\n # that can come from pd.Float64Dtype() input\n with pd.option_context('mode.use_inf_as_null', True):\n vals = vals[~pd.isnull(vals)]\n n = len(vals)\n p = self.outlier_prop\n\n # Select the depth, i.e. number of boxes to draw, based on the method\n if self.k_depth == 'full':\n # extend boxes to 100% of the data\n k = int(np.log2(n)) + 1\n elif self.k_depth == 'tukey':\n # This results with 5-8 points in each tail\n k = int(np.log2(n)) - 3\n elif self.k_depth == 'proportion':\n k = int(np.log2(n)) - int(np.log2(n * p)) + 1\n elif self.k_depth == 'trustworthy':\n point_conf = 2 * _normal_quantile_func(1 - self.trust_alpha / 2) ** 2\n k = int(np.log2(n / point_conf)) + 1\n else:\n k = int(self.k_depth) # allow having k as input\n # If the number happens to be less than 1, set k to 1\n if k < 1:\n k = 1\n\n # Calculate the upper end for each of the k boxes\n upper = [100 * (1 - 0.5 ** (i + 1)) for i in range(k, 0, -1)]\n # Calculate the lower end for each of the k boxes\n lower = [100 * (0.5 ** (i + 1)) for i in range(k, 0, -1)]\n # Stitch the box ends together\n percentile_ends = [(i, j) for i, j in zip(lower, upper)]\n box_ends = [np.percentile(vals, q) for q in percentile_ends]\n return box_ends, k\n\n def _lv_outliers(self, vals, k):\n \"\"\"Find the outliers based on the letter value depth.\"\"\"\n box_edge = 0.5 ** (k + 1)\n perc_ends = (100 * box_edge, 100 * (1 - box_edge))\n edges = np.percentile(vals, perc_ends)\n lower_out = vals[np.where(vals < edges[0])[0]]\n upper_out = vals[np.where(vals > edges[1])[0]]\n return np.concatenate((lower_out, upper_out))\n\n def _width_functions(self, width_func):\n # Dictionary of functions for computing the width of the boxes\n width_functions = {'linear': lambda h, i, k: (i + 1.) / k,\n 'exponential': lambda h, i, k: 2**(-k + i - 1),\n 'area': lambda h, i, k: (1 - 2**(-k + i - 2)) / h}\n return width_functions[width_func]\n\n def _lvplot(self, box_data, positions,\n color=[255. / 256., 185. / 256., 0.],\n widths=1, ax=None, box_kws=None,\n flier_kws=None,\n line_kws=None):\n\n # -- Default keyword dicts - based on\n # distributions.plot_univariate_histogram\n box_kws = {} if box_kws is None else box_kws.copy()\n flier_kws = {} if flier_kws is None else flier_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n\n # Set the default kwargs for the boxes\n box_default_kws = dict(edgecolor=self.gray,\n linewidth=self.linewidth)\n for k, v in box_default_kws.items():\n box_kws.setdefault(k, v)\n\n # Set the default kwargs for the lines denoting medians\n line_default_kws = dict(\n color=\".15\", alpha=0.45, solid_capstyle=\"butt\", linewidth=self.linewidth\n )\n for k, v in line_default_kws.items():\n line_kws.setdefault(k, v)\n\n # Set the default kwargs for the outliers scatterplot\n flier_default_kws = dict(marker='d', color=self.gray)\n for k, v in flier_default_kws.items():\n flier_kws.setdefault(k, v)\n\n vert = self.orient == \"v\"\n x = positions[0]\n box_data = np.asarray(box_data)\n\n # If we only have one data point, plot a line\n if len(box_data) == 1:\n line_kws.update({\n 'color': box_kws['edgecolor'],\n 'linestyle': box_kws.get('linestyle', '-'),\n 'linewidth': max(box_kws[\"linewidth\"], line_kws[\"linewidth\"])\n })\n ys = [box_data[0], box_data[0]]\n xs = [x - widths / 2, x + widths / 2]\n if vert:\n xx, yy = xs, ys\n else:\n xx, yy = ys, xs\n ax.plot(xx, yy, **line_kws)\n else:\n # Get the number of data points and calculate \"depth\" of\n # letter-value plot\n box_ends, k = self._lv_box_ends(box_data)\n\n # Anonymous functions for calculating the width and height\n # of the letter value boxes\n width = self._width_functions(self.scale)\n\n # Function to find height of boxes\n def height(b):\n return b[1] - b[0]\n\n # Functions to construct the letter value boxes\n def vert_perc_box(x, b, i, k, w):\n rect = Patches.Rectangle((x - widths * w / 2, b[0]),\n widths * w,\n height(b), fill=True)\n return rect\n\n def horz_perc_box(x, b, i, k, w):\n rect = Patches.Rectangle((b[0], x - widths * w / 2),\n height(b), widths * w,\n fill=True)\n return rect\n\n # Scale the width of the boxes so the biggest starts at 1\n w_area = np.array([width(height(b), i, k)\n for i, b in enumerate(box_ends)])\n w_area = w_area / np.max(w_area)\n\n # Calculate the medians\n y = np.median(box_data)\n\n # Calculate the outliers and plot (only if showfliers == True)\n outliers = []\n if self.showfliers:\n outliers = self._lv_outliers(box_data, k)\n hex_color = mpl.colors.rgb2hex(color)\n\n if vert:\n box_func = vert_perc_box\n xs_median = [x - widths / 2, x + widths / 2]\n ys_median = [y, y]\n xs_outliers = np.full(len(outliers), x)\n ys_outliers = outliers\n\n else:\n box_func = horz_perc_box\n xs_median = [y, y]\n ys_median = [x - widths / 2, x + widths / 2]\n xs_outliers = outliers\n ys_outliers = np.full(len(outliers), x)\n\n # Plot the medians\n ax.plot(\n xs_median,\n ys_median,\n **line_kws\n )\n\n # Plot outliers (if any)\n if len(outliers) > 0:\n ax.scatter(xs_outliers, ys_outliers,\n **flier_kws\n )\n\n # Construct a color map from the input color\n rgb = [hex_color, (1, 1, 1)]\n cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n # Make sure that the last boxes contain hue and are not pure white\n rgb = [hex_color, cmap(.85)]\n cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n\n # Update box_kws with `cmap` if not defined in dict until now\n box_kws.setdefault('cmap', cmap)\n\n boxes = [box_func(x, b[0], i, k, b[1])\n for i, b in enumerate(zip(box_ends, w_area))]\n\n collection = PatchCollection(boxes, **box_kws)\n\n # Set the color gradation, first box will have color=hex_color\n collection.set_array(np.array(np.linspace(1, 0, len(boxes))))\n\n # Plot the boxes\n ax.add_collection(collection)\n\n def draw_letter_value_plot(self, ax, box_kws=None, flier_kws=None,\n line_kws=None):\n \"\"\"Use matplotlib to draw a letter value plot on an Axes.\"\"\"\n\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = remove_na(group_data)\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n color = self.colors[i]\n\n self._lvplot(box_data,\n positions=[i],\n color=color,\n widths=self.width,\n ax=ax,\n box_kws=box_kws,\n flier_kws=flier_kws,\n line_kws=line_kws)\n\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = remove_na(group_data[hue_mask])\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n color = self.colors[j]\n center = i + offsets[j]\n self._lvplot(box_data,\n positions=[center],\n color=color,\n widths=self.nested_width,\n ax=ax,\n box_kws=box_kws,\n flier_kws=flier_kws,\n line_kws=line_kws)\n\n # Autoscale the values axis to make sure all patches are visible\n ax.autoscale_view(scalex=self.orient == \"h\", scaley=self.orient == \"v\")\n\n def plot(self, ax, box_kws, flier_kws, line_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_letter_value_plot(ax, box_kws, flier_kws, line_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\n_categorical_docs = dict(\n\n # Shared narrative docs\n categorical_narrative=dedent(\"\"\"\\\n .. note::\n This function always treats one of the variables as categorical and\n draws data at ordinal positions (0, 1, ... n) on the relevant axis,\n even when the data has a numeric or date type.\n\n See the :ref:`tutorial ` for more information.\\\n \"\"\"),\n\n new_categorical_narrative=dedent(\"\"\"\\\n .. note::\n By default, this function treats one of the variables as categorical\n and draws data at ordinal positions (0, 1, ... n) on the relevant axis.\n This can be disabled with the `native_scale` parameter.\n\n See the :ref:`tutorial ` for more information.\\\n \"\"\"),\n\n # Shared function parameters\n input_params=dedent(\"\"\"\\\n x, y, hue : names of variables in ``data`` or vector data, optional\n Inputs for plotting long-form data. See examples for interpretation.\\\n \"\"\"),\n string_input_params=dedent(\"\"\"\\\n x, y, hue : names of variables in ``data``\n Inputs for plotting long-form data. See examples for interpretation.\\\n \"\"\"),\n categorical_data=dedent(\"\"\"\\\n data : DataFrame, array, or list of arrays, optional\n Dataset for plotting. If ``x`` and ``y`` are absent, this is\n interpreted as wide-form. Otherwise it is expected to be long-form.\\\n \"\"\"),\n long_form_data=dedent(\"\"\"\\\n data : DataFrame\n Long-form (tidy) dataset for plotting. Each column should correspond\n to a variable, and each row should correspond to an observation.\\\n \"\"\"),\n order_vars=dedent(\"\"\"\\\n order, hue_order : lists of strings, optional\n Order to plot the categorical levels in; otherwise the levels are\n inferred from the data objects.\\\n \"\"\"),\n stat_api_params=dedent(\"\"\"\\\n estimator : string or callable that maps vector -> scalar, optional\n Statistical function to estimate within each categorical bin.\n errorbar : string, (string, number) tuple, callable or None\n Name of errorbar method (either \"ci\", \"pi\", \"se\", or \"sd\"), or a tuple\n with a method name and a level parameter, or a function that maps from a\n vector to a (min, max) interval, or None to hide errorbar.\n n_boot : int, optional\n Number of bootstrap samples used to compute confidence intervals.\n units : name of variable in ``data`` or vector data, optional\n Identifier of sampling units, which will be used to perform a\n multilevel bootstrap and account for repeated measures design.\n seed : int, numpy.random.Generator, or numpy.random.RandomState, optional\n Seed or random number generator for reproducible bootstrapping.\\\n \"\"\"),\n orient=dedent(\"\"\"\\\n orient : \"v\" | \"h\", optional\n Orientation of the plot (vertical or horizontal). This is usually\n inferred based on the type of the input variables, but it can be used\n to resolve ambiguity when both `x` and `y` are numeric or when\n plotting wide-form data.\\\n \"\"\"),\n color=dedent(\"\"\"\\\n color : matplotlib color, optional\n Single color for the elements in the plot.\\\n \"\"\"),\n palette=dedent(\"\"\"\\\n palette : palette name, list, or dict, optional\n Color palette that maps the hue variable. If the palette is a dictionary,\n keys should be names of levels and values should be matplotlib colors.\\\n \"\"\"),\n hue_norm=dedent(\"\"\"\\\n hue_norm : tuple or :class:`matplotlib.colors.Normalize` object\n Normalization in data units for colormap applied to the `hue`\n variable when it is numeric. Not relevant if `hue` is categorical.\\\n \"\"\"),\n saturation=dedent(\"\"\"\\\n saturation : float, optional\n Proportion of the original saturation to draw colors at. Large patches\n often look better with slightly desaturated colors, but set this to\n `1` if you want the plot colors to perfectly match the input color.\\\n \"\"\"),\n capsize=dedent(\"\"\"\\\n capsize : float, optional\n Width of the \"caps\" on error bars./\n \"\"\"),\n errwidth=dedent(\"\"\"\\\n errwidth : float, optional\n Thickness of error bar lines (and caps).\\\n \"\"\"),\n width=dedent(\"\"\"\\\n width : float, optional\n Width of a full element when not using hue nesting, or width of all the\n elements for one level of the major grouping variable.\\\n \"\"\"),\n dodge=dedent(\"\"\"\\\n dodge : bool, optional\n When hue nesting is used, whether elements should be shifted along the\n categorical axis.\\\n \"\"\"),\n linewidth=dedent(\"\"\"\\\n linewidth : float, optional\n Width of the gray lines that frame the plot elements.\\\n \"\"\"),\n native_scale=dedent(\"\"\"\\\n native_scale : bool, optional\n When True, numeric or datetime values on the categorical axis will maintain\n their original scaling rather than being converted to fixed indices.\\\n \"\"\"),\n formatter=dedent(\"\"\"\\\n formatter : callable, optional\n Function for converting categorical data into strings. Affects both grouping\n and tick labels.\\\n \"\"\"),\n legend=dedent(\"\"\"\\\nlegend : \"auto\", \"brief\", \"full\", or False\n How to draw the legend. If \"brief\", numeric `hue` and `size`\n variables will be represented with a sample of evenly spaced values.\n If \"full\", every group will get an entry in the legend. If \"auto\",\n choose between brief or full representation based on number of levels.\n If `False`, no legend data is added and no legend is drawn.\n \"\"\"),\n ax_in=dedent(\"\"\"\\\n ax : matplotlib Axes, optional\n Axes object to draw the plot onto, otherwise uses the current Axes.\\\n \"\"\"),\n ax_out=dedent(\"\"\"\\\n ax : matplotlib Axes\n Returns the Axes object with the plot drawn onto it.\\\n \"\"\"),\n\n # Shared see also\n boxplot=dedent(\"\"\"\\\n boxplot : A traditional box-and-whisker plot with a similar API.\\\n \"\"\"),\n violinplot=dedent(\"\"\"\\\n violinplot : A combination of boxplot and kernel density estimation.\\\n \"\"\"),\n stripplot=dedent(\"\"\"\\\n stripplot : A scatterplot where one variable is categorical. Can be used\n in conjunction with other plots to show each observation.\\\n \"\"\"),\n swarmplot=dedent(\"\"\"\\\n swarmplot : A categorical scatterplot where the points do not overlap. Can\n be used with other plots to show each observation.\\\n \"\"\"),\n barplot=dedent(\"\"\"\\\n barplot : Show point estimates and confidence intervals using bars.\\\n \"\"\"),\n countplot=dedent(\"\"\"\\\n countplot : Show the counts of observations in each categorical bin.\\\n \"\"\"),\n pointplot=dedent(\"\"\"\\\n pointplot : Show point estimates and confidence intervals using scatterplot\n glyphs.\\\n \"\"\"),\n catplot=dedent(\"\"\"\\\n catplot : Combine a categorical plot with a :class:`FacetGrid`.\\\n \"\"\"),\n boxenplot=dedent(\"\"\"\\\n boxenplot : An enhanced boxplot for larger datasets.\\\n \"\"\"),\n\n)\n\n_categorical_docs.update(_facet_docs)\n\n\ndef boxplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None,\n **kwargs\n):\n\n plotter = _BoxPlotter(x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth)\n\n if ax is None:\n ax = plt.gca()\n kwargs.update(dict(whis=whis))\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nboxplot.__doc__ = dedent(\"\"\"\\\n Draw a box plot to show distributions with respect to categories.\n\n A box plot (or box-and-whisker plot) shows the distribution of quantitative\n data in a way that facilitates comparisons between variables or across\n levels of a categorical variable. The box shows the quartiles of the\n dataset while the whiskers extend to show the rest of the distribution,\n except for points that are determined to be \"outliers\" using a method\n that is a function of the inter-quartile range.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n {dodge}\n fliersize : float, optional\n Size of the markers used to indicate outlier observations.\n {linewidth}\n whis : float, optional\n Maximum length of the plot whiskers as proportion of the\n interquartile range. Whiskers extend to the furthest datapoint\n within that range. More extreme points are marked as outliers.\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.boxplot`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {violinplot}\n {stripplot}\n {swarmplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/boxplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef violinplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n bw=\"scott\", cut=2, scale=\"area\", scale_hue=True, gridsize=100,\n width=.8, inner=\"box\", split=False, dodge=True, orient=None,\n linewidth=None, color=None, palette=None, saturation=.75,\n ax=None, **kwargs,\n):\n\n plotter = _ViolinPlotter(x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax)\n return ax\n\n\nviolinplot.__doc__ = dedent(\"\"\"\\\n Draw a combination of boxplot and kernel density estimate.\n\n A violin plot plays a similar role as a box and whisker plot. It shows the\n distribution of quantitative data across several levels of one (or more)\n categorical variables such that those distributions can be compared. Unlike\n a box plot, in which all of the plot components correspond to actual\n datapoints, the violin plot features a kernel density estimation of the\n underlying distribution.\n\n This can be an effective and attractive way to show multiple distributions\n of data at once, but keep in mind that the estimation procedure is\n influenced by the sample size, and violins for relatively small samples\n might look misleadingly smooth.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n bw : {{'scott', 'silverman', float}}, optional\n Either the name of a reference rule or the scale factor to use when\n computing the kernel bandwidth. The actual kernel size will be\n determined by multiplying the scale factor by the standard deviation of\n the data within each bin.\n cut : float, optional\n Distance, in units of bandwidth size, to extend the density past the\n extreme datapoints. Set to 0 to limit the violin range within the range\n of the observed data (i.e., to have the same effect as ``trim=True`` in\n ``ggplot``.\n scale : {{\"area\", \"count\", \"width\"}}, optional\n The method used to scale the width of each violin. If ``area``, each\n violin will have the same area. If ``count``, the width of the violins\n will be scaled by the number of observations in that bin. If ``width``,\n each violin will have the same width.\n scale_hue : bool, optional\n When nesting violins using a ``hue`` variable, this parameter\n determines whether the scaling is computed within each level of the\n major grouping variable (``scale_hue=True``) or across all the violins\n on the plot (``scale_hue=False``).\n gridsize : int, optional\n Number of points in the discrete grid used to compute the kernel\n density estimate.\n {width}\n inner : {{\"box\", \"quartile\", \"point\", \"stick\", None}}, optional\n Representation of the datapoints in the violin interior. If ``box``,\n draw a miniature boxplot. If ``quartiles``, draw the quartiles of the\n distribution. If ``point`` or ``stick``, show each underlying\n datapoint. Using ``None`` will draw unadorned violins.\n split : bool, optional\n When using hue nesting with a variable that takes two levels, setting\n ``split`` to True will draw half of a violin for each level. This can\n make it easier to directly compare the distributions.\n {dodge}\n {orient}\n {linewidth}\n {color}\n {palette}\n {saturation}\n {ax_in}\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {boxplot}\n {stripplot}\n {swarmplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/violinplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef boxenplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75,\n width=.8, dodge=True, k_depth='tukey', linewidth=None,\n scale='exponential', outlier_prop=0.007, trust_alpha=0.05,\n showfliers=True,\n ax=None, box_kws=None, flier_kws=None, line_kws=None,\n):\n plotter = _LVPlotter(x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale,\n outlier_prop, trust_alpha, showfliers)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, box_kws, flier_kws, line_kws)\n return ax\n\n\nboxenplot.__doc__ = dedent(\"\"\"\\\n Draw an enhanced box plot for larger datasets.\n\n This style of plot was originally named a \"letter value\" plot because it\n shows a large number of quantiles that are defined as \"letter values\". It\n is similar to a box plot in plotting a nonparametric representation of a\n distribution in which all features correspond to actual observations. By\n plotting more quantiles, it provides more information about the shape of\n the distribution, particularly in the tails. For a more extensive\n explanation, you can read the paper that introduced the plot:\n https://vita.had.co.nz/papers/letter-value-plot.html\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n {dodge}\n k_depth : {{\"tukey\", \"proportion\", \"trustworthy\", \"full\"}} or scalar\n The number of boxes, and by extension number of percentiles, to draw.\n All methods are detailed in Wickham's paper. Each makes different\n assumptions about the number of outliers and leverages different\n statistical properties. If \"proportion\", draw no more than\n `outlier_prop` extreme observations. If \"full\", draw `log(n)+1` boxes.\n {linewidth}\n scale : {{\"exponential\", \"linear\", \"area\"}}, optional\n Method to use for the width of the letter value boxes. All give similar\n results visually. \"linear\" reduces the width by a constant linear\n factor, \"exponential\" uses the proportion of data not covered, \"area\"\n is proportional to the percentage of data covered.\n outlier_prop : float, optional\n Proportion of data believed to be outliers. Must be in the range\n (0, 1]. Used to determine the number of boxes to plot when\n `k_depth=\"proportion\"`.\n trust_alpha : float, optional\n Confidence level for a box to be plotted. Used to determine the\n number of boxes to plot when `k_depth=\"trustworthy\"`. Must be in the\n range (0, 1).\n showfliers : bool, optional\n If False, suppress the plotting of outliers.\n {ax_in}\n box_kws: dict, optional\n Keyword arguments for the box artists; passed to\n :class:`matplotlib.patches.Rectangle`.\n line_kws: dict, optional\n Keyword arguments for the line denoting the median; passed to\n :meth:`matplotlib.axes.Axes.plot`.\n flier_kws: dict, optional\n Keyword arguments for the scatter denoting the outlier observations;\n passed to :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {violinplot}\n {boxplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/boxenplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef stripplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n jitter=True, dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0,\n hue_norm=None, native_scale=False, formatter=None, legend=\"auto\",\n ax=None, **kwargs\n):\n\n p = _CategoricalPlotterNew(\n data=data,\n variables=_CategoricalPlotterNew.get_semantics(locals()),\n order=order,\n orient=orient,\n require_numeric=False,\n legend=legend,\n )\n\n if ax is None:\n ax = plt.gca()\n\n if p.var_types.get(p.cat_axis) == \"categorical\" or not native_scale:\n p.scale_categorical(p.cat_axis, order=order, formatter=formatter)\n\n p._attach(ax)\n\n hue_order = p._palette_without_hue_backcompat(palette, hue_order)\n palette, hue_order = p._hue_backcompat(color, palette, hue_order)\n\n color = _default_color(ax.scatter, hue, color, kwargs)\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # XXX Copying possibly bad default decisions from original code for now\n kwargs.setdefault(\"zorder\", 3)\n size = kwargs.get(\"s\", size)\n\n kwargs.update(dict(\n s=size ** 2,\n edgecolor=edgecolor,\n linewidth=linewidth)\n )\n\n p.plot_strips(\n jitter=jitter,\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n plot_kws=kwargs,\n )\n\n # XXX this happens inside a plotting method in the distribution plots\n # but maybe it's better out here? Alternatively, we have an open issue\n # suggesting that _attach could add default axes labels, which seems smart.\n p._add_axis_labels(ax)\n p._adjust_cat_axis(ax, axis=p.cat_axis)\n\n return ax\n\n\nstripplot.__doc__ = dedent(\"\"\"\\\n Draw a categorical scatterplot using jitter to reduce overplotting.\n\n A strip plot can be drawn on its own, but it is also a good complement\n to a box or violin plot in cases where you want to show all observations\n along with some representation of the underlying distribution.\n\n {new_categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n jitter : float, ``True``/``1`` is special-cased, optional\n Amount of jitter (only along the categorical axis) to apply. This\n can be useful when you have many points and they overlap, so that\n it is easier to see the distribution. You can specify the amount\n of jitter (half the width of the uniform random variable support),\n or just use ``True`` for a good default.\n dodge : bool, optional\n When using ``hue`` nesting, setting this to ``True`` will separate\n the strips for different hue levels along the categorical axis.\n Otherwise, the points for each level will be plotted on top of\n each other.\n {orient}\n {color}\n {palette}\n size : float, optional\n Radius of the markers, in points.\n edgecolor : matplotlib color, \"gray\" is special-cased, optional\n Color of the lines around each point. If you pass ``\"gray\"``, the\n brightness is determined by the color palette used for the body\n of the points.\n {linewidth}\n {native_scale}\n {formatter}\n {legend}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {swarmplot}\n {boxplot}\n {violinplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/stripplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef swarmplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0, hue_norm=None,\n native_scale=False, formatter=None, legend=\"auto\", warn_thresh=.05,\n ax=None, **kwargs\n):\n\n p = _CategoricalPlotterNew(\n data=data,\n variables=_CategoricalPlotterNew.get_semantics(locals()),\n order=order,\n orient=orient,\n require_numeric=False,\n legend=legend,\n )\n\n if ax is None:\n ax = plt.gca()\n\n if p.var_types.get(p.cat_axis) == \"categorical\" or not native_scale:\n p.scale_categorical(p.cat_axis, order=order, formatter=formatter)\n\n p._attach(ax)\n\n if not p.has_xy_data:\n return ax\n\n hue_order = p._palette_without_hue_backcompat(palette, hue_order)\n palette, hue_order = p._hue_backcompat(color, palette, hue_order)\n\n color = _default_color(ax.scatter, hue, color, kwargs)\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # XXX Copying possibly bad default decisions from original code for now\n kwargs.setdefault(\"zorder\", 3)\n size = kwargs.get(\"s\", size)\n\n if linewidth is None:\n linewidth = size / 10\n\n kwargs.update(dict(\n s=size ** 2,\n linewidth=linewidth,\n ))\n\n p.plot_swarms(\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n warn_thresh=warn_thresh,\n plot_kws=kwargs,\n )\n\n p._add_axis_labels(ax)\n p._adjust_cat_axis(ax, axis=p.cat_axis)\n\n return ax\n\n\nswarmplot.__doc__ = dedent(\"\"\"\\\n Draw a categorical scatterplot with points adjusted to be non-overlapping.\n\n This function is similar to :func:`stripplot`, but the points are adjusted\n (only along the categorical axis) so that they don't overlap. This gives a\n better representation of the distribution of values, but it does not scale\n well to large numbers of observations. This style of plot is sometimes\n called a \"beeswarm\".\n\n A swarm plot can be drawn on its own, but it is also a good complement\n to a box or violin plot in cases where you want to show all observations\n along with some representation of the underlying distribution.\n\n {new_categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n dodge : bool, optional\n When using ``hue`` nesting, setting this to ``True`` will separate\n the strips for different hue levels along the categorical axis.\n Otherwise, the points for each level will be plotted in one swarm.\n {orient}\n {color}\n {palette}\n size : float, optional\n Radius of the markers, in points.\n edgecolor : matplotlib color, \"gray\" is special-cased, optional\n Color of the lines around each point. If you pass ``\"gray\"``, the\n brightness is determined by the color palette used for the body\n of the points.\n {linewidth}\n {native_scale}\n {formatter}\n {legend}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {boxplot}\n {violinplot}\n {stripplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/swarmplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef barplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True, ci=\"deprecated\",\n ax=None,\n **kwargs,\n):\n\n errorbar = utils._deprecate_ci(errorbar, ci)\n\n # Be backwards compatible with len passed directly, which\n # does not work in Series.agg (maybe a pandas bug?)\n if estimator is len:\n estimator = \"size\"\n\n plotter = _BarPlotter(x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation,\n width, errcolor, errwidth, capsize, dodge)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nbarplot.__doc__ = dedent(\"\"\"\\\n Show point estimates and errors as rectangular bars.\n\n A bar plot represents an estimate of central tendency for a numeric\n variable with the height of each rectangle and provides some indication of\n the uncertainty around that estimate using error bars. Bar plots include 0\n in the quantitative axis range, and they are a good choice when 0 is a\n meaningful value for the quantitative variable, and you want to make\n comparisons against it.\n\n For datasets where 0 is not a meaningful value, a point plot will allow you\n to focus on differences between levels of one or more categorical\n variables.\n\n It is also important to keep in mind that a bar plot shows only the mean\n (or other estimator) value, but in many cases it may be more informative to\n show the distribution of values at each level of the categorical variables.\n In that case, other approaches such as a box or violin plot may be more\n appropriate.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {stat_api_params}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n errcolor : matplotlib color\n Color used for the error bar lines.\n {errwidth}\n {capsize}\n {dodge}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {countplot}\n {pointplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/barplot.rst\n\n\n \"\"\").format(**_categorical_docs)\n\n\ndef pointplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, units=None, seed=None,\n markers=\"o\", linestyles=\"-\", dodge=False, join=True, scale=1,\n orient=None, color=None, palette=None, errwidth=None, ci=\"deprecated\",\n capsize=None, ax=None,\n):\n\n errorbar = utils._deprecate_ci(errorbar, ci)\n\n plotter = _PointPlotter(x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth, capsize)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax)\n return ax\n\n\npointplot.__doc__ = dedent(\"\"\"\\\n Show point estimates and errors using dot marks.\n\n A point plot represents an estimate of central tendency for a numeric\n variable by the position of the dot and provides some indication of the\n uncertainty around that estimate using error bars.\n\n Point plots can be more useful than bar plots for focusing comparisons\n between different levels of one or more categorical variables. They are\n particularly adept at showing interactions: how the relationship between\n levels of one categorical variable changes across levels of a second\n categorical variable. The lines that join each point from the same `hue`\n level allow interactions to be judged by differences in slope, which is\n easier for the eyes than comparing the heights of several groups of points\n or bars.\n\n It is important to keep in mind that a point plot shows only the mean (or\n other estimator) value, but in many cases it may be more informative to\n show the distribution of values at each level of the categorical variables.\n In that case, other approaches such as a box or violin plot may be more\n appropriate.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {stat_api_params}\n markers : string or list of strings, optional\n Markers to use for each of the ``hue`` levels.\n linestyles : string or list of strings, optional\n Line styles to use for each of the ``hue`` levels.\n dodge : bool or float, optional\n Amount to separate the points for each level of the ``hue`` variable\n along the categorical axis.\n join : bool, optional\n If ``True``, lines will be drawn between point estimates at the same\n ``hue`` level.\n scale : float, optional\n Scale factor for the plot elements.\n {orient}\n {color}\n {palette}\n {errwidth}\n {capsize}\n {ax_in}\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {barplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/pointplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef countplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n dodge=True, ax=None, **kwargs\n):\n\n estimator = \"size\"\n errorbar = None\n n_boot = 0\n units = None\n seed = None\n errcolor = None\n errwidth = None\n capsize = None\n\n if x is None and y is not None:\n orient = \"h\"\n x = y\n elif y is None and x is not None:\n orient = \"v\"\n y = x\n elif x is not None and y is not None:\n raise ValueError(\"Cannot pass values for both `x` and `y`\")\n\n plotter = _CountPlotter(\n x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation,\n width, errcolor, errwidth, capsize, dodge\n )\n\n plotter.value_label = \"count\"\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax\n\n\ncountplot.__doc__ = dedent(\"\"\"\\\n Show the counts of observations in each categorical bin using bars.\n\n A count plot can be thought of as a histogram across a categorical, instead\n of quantitative, variable. The basic API and options are identical to those\n for :func:`barplot`, so you can compare counts across nested variables.\n\n Note that the newer :func:`histplot` function offers more functionality, although\n its default behavior is somewhat different.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {dodge}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {barplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/countplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\ndef catplot(\n data=None, *, x=None, y=None, hue=None, row=None, col=None,\n col_wrap=None, estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000,\n units=None, seed=None, order=None, hue_order=None, row_order=None,\n col_order=None, height=5, aspect=1, kind=\"strip\", native_scale=False,\n formatter=None, orient=None, color=None, palette=None, hue_norm=None,\n legend=\"auto\", legend_out=True, sharex=True, sharey=True,\n margin_titles=False, facet_kws=None, ci=\"deprecated\",\n **kwargs\n):\n\n # Determine the plotting function\n try:\n plot_func = globals()[kind + \"plot\"]\n except KeyError:\n err = f\"Plot kind '{kind}' is not recognized\"\n raise ValueError(err)\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\"catplot is a figure-level function and does not accept \"\n f\"target axes. You may wish to try {kind}plot\")\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n refactored_kinds = [\"strip\", \"swarm\"]\n if kind in refactored_kinds:\n\n p = _CategoricalFacetPlotter(\n data=data,\n variables=_CategoricalFacetPlotter.get_semantics(locals()),\n order=order,\n orient=orient,\n require_numeric=False,\n legend=legend,\n )\n\n # XXX Copying a fair amount from displot, which is not ideal\n\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n\n # Adapt the plot_data dataframe for use with FacetGrid\n data = p.plot_data.rename(columns=p.variables)\n data = data.loc[:, ~data.columns.duplicated()]\n\n col_name = p.variables.get(\"col\", None)\n row_name = p.variables.get(\"row\", None)\n\n if facet_kws is None:\n facet_kws = {}\n\n g = FacetGrid(\n data=data, row=row_name, col=col_name,\n col_wrap=col_wrap, row_order=row_order,\n col_order=col_order, height=height,\n sharex=sharex, sharey=sharey,\n aspect=aspect,\n **facet_kws,\n )\n\n # Capture this here because scale_categorical is going to insert a (null)\n # x variable even if it is empty. It's not clear whether that needs to\n # happen or if disabling that is the cleaner solution.\n has_xy_data = p.has_xy_data\n\n if not native_scale or p.var_types[p.cat_axis] == \"categorical\":\n p.scale_categorical(p.cat_axis, order=order, formatter=formatter)\n\n p._attach(g)\n\n if not has_xy_data:\n return g\n\n hue_order = p._palette_without_hue_backcompat(palette, hue_order)\n palette, hue_order = p._hue_backcompat(color, palette, hue_order)\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # Set a default color\n # Otherwise each artist will be plotted separately and trip the color cycle\n if hue is None and color is None:\n color = \"C0\"\n\n if kind == \"strip\":\n\n # TODO get these defaults programmatically?\n jitter = kwargs.pop(\"jitter\", True)\n dodge = kwargs.pop(\"dodge\", False)\n edgecolor = kwargs.pop(\"edgecolor\", \"gray\") # XXX TODO default\n\n plot_kws = kwargs.copy()\n\n # XXX Copying possibly bad default decisions from original code for now\n plot_kws.setdefault(\"zorder\", 3)\n plot_kws.setdefault(\"s\", plot_kws.pop(\"size\", 5) ** 2)\n plot_kws.setdefault(\"linewidth\", 0)\n\n p.plot_strips(\n jitter=jitter,\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n plot_kws=plot_kws,\n )\n\n elif kind == \"swarm\":\n\n # TODO get these defaults programmatically?\n dodge = kwargs.pop(\"dodge\", False)\n edgecolor = kwargs.pop(\"edgecolor\", \"gray\") # XXX TODO default\n warn_thresh = kwargs.pop(\"warn_thresh\", .05)\n\n plot_kws = kwargs.copy()\n\n # XXX Copying possibly bad default decisions from original code for now\n plot_kws.setdefault(\"zorder\", 3)\n plot_kws.setdefault(\"s\", plot_kws.pop(\"size\", 5) ** 2)\n\n if plot_kws.setdefault(\"linewidth\", 0) is None:\n plot_kws[\"linewidth\"] = np.sqrt(plot_kws[\"s\"]) / 10\n\n p.plot_swarms(\n dodge=dodge,\n color=color,\n edgecolor=edgecolor,\n warn_thresh=warn_thresh,\n plot_kws=plot_kws,\n )\n\n # XXX best way to do this housekeeping?\n for ax in g.axes.flat:\n p._adjust_cat_axis(ax, axis=p.cat_axis)\n\n g.set_axis_labels(\n p.variables.get(\"x\", None),\n p.variables.get(\"y\", None),\n )\n g.set_titles()\n g.tight_layout()\n\n # XXX Hack to get the legend data in the right place\n for ax in g.axes.flat:\n g._update_legend_data(ax)\n ax.legend_ = None\n\n if legend and (hue is not None) and (hue not in [x, row, col]):\n g.add_legend(title=hue, label_order=hue_order)\n\n return g\n\n # Don't allow usage of forthcoming functionality\n if native_scale is True:\n err = f\"native_scale not yet implemented for `kind={kind}`\"\n raise ValueError(err)\n if formatter is not None:\n err = f\"formatter not yet implemented for `kind={kind}`\"\n raise ValueError(err)\n\n # Alias the input variables to determine categorical order and palette\n # correctly in the case of a count plot\n if kind == \"count\":\n if x is None and y is not None:\n x_, y_, orient = y, y, \"h\"\n elif y is None and x is not None:\n x_, y_, orient = x, x, \"v\"\n else:\n raise ValueError(\"Either `x` or `y` must be None for kind='count'\")\n else:\n x_, y_ = x, y\n\n # Determine the order for the whole dataset, which will be used in all\n # facets to ensure representation of all data in the final plot\n plotter_class = {\n \"box\": _BoxPlotter,\n \"violin\": _ViolinPlotter,\n \"boxen\": _LVPlotter,\n \"bar\": _BarPlotter,\n \"point\": _PointPlotter,\n \"count\": _CountPlotter,\n }[kind]\n p = _CategoricalPlotter()\n p.require_numeric = plotter_class.require_numeric\n p.establish_variables(x_, y_, hue, data, orient, order, hue_order)\n if (\n order is not None\n or (sharex and p.orient == \"v\")\n or (sharey and p.orient == \"h\")\n ):\n # Sync categorical axis between facets to have the same categories\n order = p.group_names\n elif color is None and hue is None:\n msg = (\n \"Setting `{}=False` with `color=None` may cause different levels of the \"\n \"`{}` variable to share colors. This will change in a future version.\"\n )\n if not sharex and p.orient == \"v\":\n warnings.warn(msg.format(\"sharex\", \"x\"), UserWarning)\n if not sharey and p.orient == \"h\":\n warnings.warn(msg.format(\"sharey\", \"y\"), UserWarning)\n\n hue_order = p.hue_names\n\n # Determine the palette to use\n # (FacetGrid will pass a value for ``color`` to the plotting function\n # so we need to define ``palette`` to get default behavior for the\n # categorical functions\n p.establish_colors(color, palette, 1)\n if kind != \"point\" or hue is not None:\n palette = p.colors\n\n # Determine keyword arguments for the facets\n facet_kws = {} if facet_kws is None else facet_kws\n facet_kws.update(\n data=data, row=row, col=col,\n row_order=row_order, col_order=col_order,\n col_wrap=col_wrap, height=height, aspect=aspect,\n sharex=sharex, sharey=sharey,\n legend_out=legend_out, margin_titles=margin_titles,\n dropna=False,\n )\n\n # Determine keyword arguments for the plotting function\n plot_kws = dict(\n order=order, hue_order=hue_order,\n orient=orient, color=color, palette=palette,\n )\n plot_kws.update(kwargs)\n\n if kind in [\"bar\", \"point\"]:\n errorbar = utils._deprecate_ci(errorbar, ci)\n plot_kws.update(\n estimator=estimator, errorbar=errorbar,\n n_boot=n_boot, units=units, seed=seed,\n )\n\n # Initialize the facets\n g = FacetGrid(**facet_kws)\n\n # Draw the plot onto the facets\n g.map_dataframe(plot_func, x=x, y=y, hue=hue, **plot_kws)\n\n if p.orient == \"h\":\n g.set_axis_labels(p.value_label, p.group_label)\n else:\n g.set_axis_labels(p.group_label, p.value_label)\n\n # Special case axis labels for a count type plot\n if kind == \"count\":\n if x is None:\n g.set_axis_labels(x_var=\"count\")\n if y is None:\n g.set_axis_labels(y_var=\"count\")\n\n if legend and (hue is not None) and (hue not in [x, row, col]):\n hue_order = list(map(utils.to_utf8, hue_order))\n g.add_legend(title=hue, label_order=hue_order)\n\n return g\n\n\ncatplot.__doc__ = dedent(\"\"\"\\\n Figure-level interface for drawing categorical plots onto a FacetGrid.\n\n This function provides access to several axes-level functions that\n show the relationship between a numerical and one or more categorical\n variables using one of several visual representations. The `kind`\n parameter selects the underlying axes-level function to use:\n\n Categorical scatterplots:\n\n - :func:`stripplot` (with `kind=\"strip\"`; the default)\n - :func:`swarmplot` (with `kind=\"swarm\"`)\n\n Categorical distribution plots:\n\n - :func:`boxplot` (with `kind=\"box\"`)\n - :func:`violinplot` (with `kind=\"violin\"`)\n - :func:`boxenplot` (with `kind=\"boxen\"`)\n\n Categorical estimate plots:\n\n - :func:`pointplot` (with `kind=\"point\"`)\n - :func:`barplot` (with `kind=\"bar\"`)\n - :func:`countplot` (with `kind=\"count\"`)\n\n Extra keyword arguments are passed to the underlying function, so you\n should refer to the documentation for each to see kind-specific options.\n\n Note that unlike when using the axes-level functions directly, data must be\n passed in a long-form DataFrame with variables specified by passing strings\n to `x`, `y`, `hue`, etc.\n\n {categorical_narrative}\n\n After plotting, the :class:`FacetGrid` with the plot is returned and can\n be used directly to tweak supporting plot details or add other layers.\n\n Parameters\n ----------\n {long_form_data}\n {string_input_params}\n row, col : names of variables in `data`, optional\n Categorical variables that will determine the faceting of the grid.\n {col_wrap}\n {stat_api_params}\n {order_vars}\n row_order, col_order : lists of strings, optional\n Order to organize the rows and/or columns of the grid in, otherwise the\n orders are inferred from the data objects.\n {height}\n {aspect}\n kind : str, optional\n The kind of plot to draw, corresponds to the name of a categorical\n axes-level plotting function. Options are: \"strip\", \"swarm\", \"box\", \"violin\",\n \"boxen\", \"point\", \"bar\", or \"count\".\n {native_scale}\n {formatter}\n {orient}\n {color}\n {palette}\n {hue_norm}\n legend : str or bool, optional\n Set to `False` to disable the legend. With `strip` or `swarm` plots,\n this also accepts a string, as described in the axes-level docstrings.\n {legend_out}\n {share_xy}\n {margin_titles}\n facet_kws : dict, optional\n Dictionary of other keyword arguments to pass to :class:`FacetGrid`.\n kwargs : key, value pairings\n Other keyword arguments are passed through to the underlying plotting\n function.\n\n Returns\n -------\n g : :class:`FacetGrid`\n Returns the :class:`FacetGrid` object with the plot on it for further\n tweaking.\n\n Examples\n --------\n\n .. include:: ../docstrings/catplot.rst\n\n \"\"\").format(**_categorical_docs)\n\n\nclass Beeswarm:\n \"\"\"Modifies a scatterplot artist to show a beeswarm plot.\"\"\"\n def __init__(self, orient=\"v\", width=0.8, warn_thresh=.05):\n\n # XXX should we keep the orient parameterization or specify the swarm axis?\n\n self.orient = orient\n self.width = width\n self.warn_thresh = warn_thresh\n\n def __call__(self, points, center):\n \"\"\"Swarm `points`, a PathCollection, around the `center` position.\"\"\"\n # Convert from point size (area) to diameter\n\n ax = points.axes\n dpi = ax.figure.dpi\n\n # Get the original positions of the points\n orig_xy_data = points.get_offsets()\n\n # Reset the categorical positions to the center line\n cat_idx = 1 if self.orient == \"h\" else 0\n orig_xy_data[:, cat_idx] = center\n\n # Transform the data coordinates to point coordinates.\n # We'll figure out the swarm positions in the latter\n # and then convert back to data coordinates and replot\n orig_x_data, orig_y_data = orig_xy_data.T\n orig_xy = ax.transData.transform(orig_xy_data)\n\n # Order the variables so that x is the categorical axis\n if self.orient == \"h\":\n orig_xy = orig_xy[:, [1, 0]]\n\n # Add a column with each point's radius\n sizes = points.get_sizes()\n if sizes.size == 1:\n sizes = np.repeat(sizes, orig_xy.shape[0])\n edge = points.get_linewidth().item()\n radii = (np.sqrt(sizes) + edge) / 2 * (dpi / 72)\n orig_xy = np.c_[orig_xy, radii]\n\n # Sort along the value axis to facilitate the beeswarm\n sorter = np.argsort(orig_xy[:, 1])\n orig_xyr = orig_xy[sorter]\n\n # Adjust points along the categorical axis to prevent overlaps\n new_xyr = np.empty_like(orig_xyr)\n new_xyr[sorter] = self.beeswarm(orig_xyr)\n\n # Transform the point coordinates back to data coordinates\n if self.orient == \"h\":\n new_xy = new_xyr[:, [1, 0]]\n else:\n new_xy = new_xyr[:, :2]\n new_x_data, new_y_data = ax.transData.inverted().transform(new_xy).T\n\n swarm_axis = {\"h\": \"y\", \"v\": \"x\"}[self.orient]\n log_scale = getattr(ax, f\"get_{swarm_axis}scale\")() == \"log\"\n\n # Add gutters\n if self.orient == \"h\":\n self.add_gutters(new_y_data, center, log_scale=log_scale)\n else:\n self.add_gutters(new_x_data, center, log_scale=log_scale)\n\n # Reposition the points so they do not overlap\n if self.orient == \"h\":\n points.set_offsets(np.c_[orig_x_data, new_y_data])\n else:\n points.set_offsets(np.c_[new_x_data, orig_y_data])\n\n def beeswarm(self, orig_xyr):\n \"\"\"Adjust x position of points to avoid overlaps.\"\"\"\n # In this method, `x` is always the categorical axis\n # Center of the swarm, in point coordinates\n midline = orig_xyr[0, 0]\n\n # Start the swarm with the first point\n swarm = np.atleast_2d(orig_xyr[0])\n\n # Loop over the remaining points\n for xyr_i in orig_xyr[1:]:\n\n # Find the points in the swarm that could possibly\n # overlap with the point we are currently placing\n neighbors = self.could_overlap(xyr_i, swarm)\n\n # Find positions that would be valid individually\n # with respect to each of the swarm neighbors\n candidates = self.position_candidates(xyr_i, neighbors)\n\n # Sort candidates by their centrality\n offsets = np.abs(candidates[:, 0] - midline)\n candidates = candidates[np.argsort(offsets)]\n\n # Find the first candidate that does not overlap any neighbors\n new_xyr_i = self.first_non_overlapping_candidate(candidates, neighbors)\n\n # Place it into the swarm\n swarm = np.vstack([swarm, new_xyr_i])\n\n return swarm\n\n def could_overlap(self, xyr_i, swarm):\n \"\"\"Return a list of all swarm points that could overlap with target.\"\"\"\n # Because we work backwards through the swarm and can short-circuit,\n # the for-loop is faster than vectorization\n _, y_i, r_i = xyr_i\n neighbors = []\n for xyr_j in reversed(swarm):\n _, y_j, r_j = xyr_j\n if (y_i - y_j) < (r_i + r_j):\n neighbors.append(xyr_j)\n else:\n break\n return np.array(neighbors)[::-1]\n\n def position_candidates(self, xyr_i, neighbors):\n \"\"\"Return a list of coordinates that might be valid by adjusting x.\"\"\"\n candidates = [xyr_i]\n x_i, y_i, r_i = xyr_i\n left_first = True\n for x_j, y_j, r_j in neighbors:\n dy = y_i - y_j\n dx = np.sqrt(max((r_i + r_j) ** 2 - dy ** 2, 0)) * 1.05\n cl, cr = (x_j - dx, y_i, r_i), (x_j + dx, y_i, r_i)\n if left_first:\n new_candidates = [cl, cr]\n else:\n new_candidates = [cr, cl]\n candidates.extend(new_candidates)\n left_first = not left_first\n return np.array(candidates)\n\n def first_non_overlapping_candidate(self, candidates, neighbors):\n \"\"\"Find the first candidate that does not overlap with the swarm.\"\"\"\n\n # If we have no neighbors, all candidates are good.\n if len(neighbors) == 0:\n return candidates[0]\n\n neighbors_x = neighbors[:, 0]\n neighbors_y = neighbors[:, 1]\n neighbors_r = neighbors[:, 2]\n\n for xyr_i in candidates:\n\n x_i, y_i, r_i = xyr_i\n\n dx = neighbors_x - x_i\n dy = neighbors_y - y_i\n sq_distances = np.square(dx) + np.square(dy)\n\n sep_needed = np.square(neighbors_r + r_i)\n\n # Good candidate does not overlap any of neighbors which means that\n # squared distance between candidate and any of the neighbors has\n # to be at least square of the summed radii\n good_candidate = np.all(sq_distances >= sep_needed)\n\n if good_candidate:\n return xyr_i\n\n raise RuntimeError(\n \"No non-overlapping candidates found. This should not happen.\"\n )\n\n def add_gutters(self, points, center, log_scale=False):\n \"\"\"Stop points from extending beyond their territory.\"\"\"\n half_width = self.width / 2\n if log_scale:\n low_gutter = 10 ** (np.log10(center) - half_width)\n else:\n low_gutter = center - half_width\n off_low = points < low_gutter\n if off_low.any():\n points[off_low] = low_gutter\n if log_scale:\n high_gutter = 10 ** (np.log10(center) + half_width)\n else:\n high_gutter = center + half_width\n off_high = points > high_gutter\n if off_high.any():\n points[off_high] = high_gutter\n\n gutter_prop = (off_high + off_low).sum() / len(points)\n if gutter_prop > self.warn_thresh:\n msg = (\n \"{:.1%} of the points cannot be placed; you may want \"\n \"to decrease the size of the markers or use stripplot.\"\n ).format(gutter_prop)\n warnings.warn(msg, UserWarning)\n\n return points\n"},{"col":0,"comment":"\n Compute the quantile function of the standard normal distribution.\n\n This wrapper exists because we are dropping scipy as a mandatory dependency\n but statistics.NormalDist was added to the standard library in 3.8.\n\n ","endLoc":74,"header":"def _normal_quantile_func(q)","id":2256,"name":"_normal_quantile_func","nodeType":"Function","startLoc":54,"text":"def _normal_quantile_func(q):\n \"\"\"\n Compute the quantile function of the standard normal distribution.\n\n This wrapper exists because we are dropping scipy as a mandatory dependency\n but statistics.NormalDist was added to the standard library in 3.8.\n\n \"\"\"\n try:\n from statistics import NormalDist\n qf = np.vectorize(NormalDist().inv_cdf)\n except ImportError:\n try:\n from scipy.stats import norm\n qf = norm.ppf\n except ImportError:\n msg = (\n \"Standard normal quantile functions require either Python>=3.8 or scipy\"\n )\n raise RuntimeError(msg)\n return qf(q)"},{"col":4,"comment":"null","endLoc":99,"header":"def test_mapped_properties(self)","id":2257,"name":"test_mapped_properties","nodeType":"Function","startLoc":88,"text":"def test_mapped_properties(self):\n\n x = [\"a\", \"b\"]\n y = [1, 2]\n mark = Bar(alpha=.2)\n p = Plot(x, y, color=x, edgewidth=y).add(mark).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, bar in enumerate(ax.patches):\n assert bar.get_facecolor() == to_rgba(colors[i], mark.alpha)\n assert bar.get_edgecolor() == to_rgba(colors[i], 1)\n assert ax.patches[0].get_linewidth() < ax.patches[1].get_linewidth()"},{"fileName":"plot.py","filePath":"seaborn/_core","id":2259,"nodeType":"File","text":"\"\"\"The classes for specifying and compiling a declarative visualization.\"\"\"\nfrom __future__ import annotations\n\nimport io\nimport os\nimport re\nimport sys\nimport inspect\nimport itertools\nimport textwrap\nfrom contextlib import contextmanager\nfrom collections import abc\nfrom collections.abc import Callable, Generator\nfrom typing import Any, List, Optional, cast\n\nfrom cycler import cycler\nimport pandas as pd\nfrom pandas import DataFrame, Series, Index\nimport matplotlib as mpl\nfrom matplotlib.axes import Axes\nfrom matplotlib.artist import Artist\nfrom matplotlib.figure import Figure\n\nfrom seaborn._marks.base import Mark\nfrom seaborn._stats.base import Stat\nfrom seaborn._core.data import PlotData\nfrom seaborn._core.moves import Move\nfrom seaborn._core.scales import Scale\nfrom seaborn._core.subplots import Subplots\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._core.properties import PROPERTIES, Property\nfrom seaborn._core.typing import (\n DataSource,\n VariableSpec,\n VariableSpecList,\n OrderSpec,\n Default,\n)\nfrom seaborn._core.rules import categorical_order\nfrom seaborn._compat import set_scale_obj, set_layout_engine\nfrom seaborn.rcmod import axes_style, plotting_context\nfrom seaborn.palettes import color_palette\nfrom seaborn.external.version import Version\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from matplotlib.figure import SubFigure\n\n\nif sys.version_info >= (3, 8):\n from typing import TypedDict\nelse:\n from typing_extensions import TypedDict\n\n\ndefault = Default()\n\n\n# ---- Definitions for internal specs --------------------------------- #\n\n\nclass Layer(TypedDict, total=False):\n\n mark: Mark # TODO allow list?\n stat: Stat | None # TODO allow list?\n move: Move | list[Move] | None\n data: PlotData\n source: DataSource\n vars: dict[str, VariableSpec]\n orient: str\n legend: bool\n\n\nclass FacetSpec(TypedDict, total=False):\n\n variables: dict[str, VariableSpec]\n structure: dict[str, list[str]]\n wrap: int | None\n\n\nclass PairSpec(TypedDict, total=False):\n\n variables: dict[str, VariableSpec]\n structure: dict[str, list[str]]\n cross: bool\n wrap: int | None\n\n\n# --- Local helpers ----------------------------------------------------------------\n\n\n@contextmanager\ndef theme_context(params: dict[str, Any]) -> Generator:\n \"\"\"Temporarily modify specifc matplotlib rcParams.\"\"\"\n orig_params = {k: mpl.rcParams[k] for k in params}\n color_codes = \"bgrmyck\"\n nice_colors = [*color_palette(\"deep6\"), (.15, .15, .15)]\n orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes]\n # TODO how to allow this to reflect the color cycle when relevant?\n try:\n mpl.rcParams.update(params)\n for (code, color) in zip(color_codes, nice_colors):\n mpl.colors.colorConverter.colors[code] = color\n mpl.colors.colorConverter.cache[code] = color\n yield\n finally:\n mpl.rcParams.update(orig_params)\n for (code, color) in zip(color_codes, orig_colors):\n mpl.colors.colorConverter.colors[code] = color\n mpl.colors.colorConverter.cache[code] = color\n\n\ndef build_plot_signature(cls):\n \"\"\"\n Decorator function for giving Plot a useful signature.\n\n Currently this mostly saves us some duplicated typing, but we would\n like eventually to have a way of registering new semantic properties,\n at which point dynamic signature generation would become more important.\n\n \"\"\"\n sig = inspect.signature(cls)\n params = [\n inspect.Parameter(\"args\", inspect.Parameter.VAR_POSITIONAL),\n inspect.Parameter(\"data\", inspect.Parameter.KEYWORD_ONLY, default=None)\n ]\n params.extend([\n inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None)\n for name in PROPERTIES\n ])\n new_sig = sig.replace(parameters=params)\n cls.__signature__ = new_sig\n\n known_properties = textwrap.fill(\n \", \".join([f\"|{p}|\" for p in PROPERTIES]),\n width=78, subsequent_indent=\" \" * 8,\n )\n\n if cls.__doc__ is not None: # support python -OO mode\n cls.__doc__ = cls.__doc__.format(known_properties=known_properties)\n\n return cls\n\n\n# ---- The main interface for declarative plotting -------------------- #\n\n\n@build_plot_signature\nclass Plot:\n \"\"\"\n An interface for declaratively specifying statistical graphics.\n\n Plots are constructed by initializing this class and adding one or more\n layers, comprising a `Mark` and optional `Stat` or `Move`. Additionally,\n faceting variables or variable pairings may be defined to divide the space\n into multiple subplots. The mappings from data values to visual properties\n can be parametrized using scales, although the plot will try to infer good\n defaults when scales are not explicitly defined.\n\n The constructor accepts a data source (a :class:`pandas.DataFrame` or\n dictionary with columnar values) and variable assignments. Variables can be\n passed as keys to the data source or directly as data vectors. If multiple\n data-containing objects are provided, they will be index-aligned.\n\n The data source and variables defined in the constructor will be used for\n all layers in the plot, unless overridden or disabled when adding a layer.\n\n The following variables can be defined in the constructor:\n {known_properties}\n\n The `data`, `x`, and `y` variables can be passed as positional arguments or\n using keywords. Whether the first positional argument is interpreted as a\n data source or `x` variable depends on its type.\n\n The methods of this class return a copy of the instance; use chaining to\n build up a plot through multiple calls. Methods can be called in any order.\n\n Most methods only add information to the plot spec; no actual processing\n happens until the plot is shown or saved. It is also possible to compile\n the plot without rendering it to access the lower-level representation.\n\n \"\"\"\n _data: PlotData\n _layers: list[Layer]\n\n _scales: dict[str, Scale]\n _shares: dict[str, bool | str]\n _limits: dict[str, tuple[Any, Any]]\n _labels: dict[str, str | Callable[[str], str]]\n _theme: dict[str, Any]\n\n _facet_spec: FacetSpec\n _pair_spec: PairSpec\n\n _figure_spec: dict[str, Any]\n _subplot_spec: dict[str, Any]\n _layout_spec: dict[str, Any]\n\n def __init__(\n self,\n *args: DataSource | VariableSpec,\n data: DataSource = None,\n **variables: VariableSpec,\n ):\n\n if args:\n data, variables = self._resolve_positionals(args, data, variables)\n\n unknown = [x for x in variables if x not in PROPERTIES]\n if unknown:\n err = f\"Plot() got unexpected keyword argument(s): {', '.join(unknown)}\"\n raise TypeError(err)\n\n self._data = PlotData(data, variables)\n\n self._layers = []\n\n self._scales = {}\n self._shares = {}\n self._limits = {}\n self._labels = {}\n self._theme = {}\n\n self._facet_spec = {}\n self._pair_spec = {}\n\n self._figure_spec = {}\n self._subplot_spec = {}\n self._layout_spec = {}\n\n self._target = None\n\n def _resolve_positionals(\n self,\n args: tuple[DataSource | VariableSpec, ...],\n data: DataSource,\n variables: dict[str, VariableSpec],\n ) -> tuple[DataSource, dict[str, VariableSpec]]:\n \"\"\"Handle positional arguments, which may contain data / x / y.\"\"\"\n if len(args) > 3:\n err = \"Plot() accepts no more than 3 positional arguments (data, x, y).\"\n raise TypeError(err)\n\n # TODO need some clearer way to differentiate data / vector here\n # (There might be an abstract DataFrame class to use here?)\n if isinstance(args[0], (abc.Mapping, pd.DataFrame)):\n if data is not None:\n raise TypeError(\"`data` given by both name and position.\")\n data, args = args[0], args[1:]\n\n if len(args) == 2:\n x, y = args\n elif len(args) == 1:\n x, y = *args, None\n else:\n x = y = None\n\n for name, var in zip(\"yx\", (y, x)):\n if var is not None:\n if name in variables:\n raise TypeError(f\"`{name}` given by both name and position.\")\n # Keep coordinates at the front of the variables dict\n # Cast type because we know this isn't a DataSource at this point\n variables = {name: cast(VariableSpec, var), **variables}\n\n return data, variables\n\n def __add__(self, other):\n\n if isinstance(other, Mark) or isinstance(other, Stat):\n raise TypeError(\"Sorry, this isn't ggplot! Perhaps try Plot.add?\")\n\n other_type = other.__class__.__name__\n raise TypeError(f\"Unsupported operand type(s) for +: 'Plot' and '{other_type}\")\n\n def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n\n return self.plot()._repr_png_()\n\n # TODO _repr_svg_?\n\n def _clone(self) -> Plot:\n \"\"\"Generate a new object with the same information as the current spec.\"\"\"\n new = Plot()\n\n # TODO any way to enforce that data does not get mutated?\n new._data = self._data\n\n new._layers.extend(self._layers)\n\n new._scales.update(self._scales)\n new._shares.update(self._shares)\n new._limits.update(self._limits)\n new._labels.update(self._labels)\n new._theme.update(self._theme)\n\n new._facet_spec.update(self._facet_spec)\n new._pair_spec.update(self._pair_spec)\n\n new._figure_spec.update(self._figure_spec)\n new._subplot_spec.update(self._subplot_spec)\n new._layout_spec.update(self._layout_spec)\n\n new._target = self._target\n\n return new\n\n def _theme_with_defaults(self) -> dict[str, Any]:\n\n style_groups = [\n \"axes\", \"figure\", \"font\", \"grid\", \"hatch\", \"legend\", \"lines\",\n \"mathtext\", \"markers\", \"patch\", \"savefig\", \"scatter\",\n \"xaxis\", \"xtick\", \"yaxis\", \"ytick\",\n ]\n base = {\n k: mpl.rcParamsDefault[k] for k in mpl.rcParams\n if any(k.startswith(p) for p in style_groups)\n }\n theme = {\n **base,\n **axes_style(\"darkgrid\"),\n **plotting_context(\"notebook\"),\n \"axes.prop_cycle\": cycler(\"color\", color_palette(\"deep\")),\n }\n theme.update(self._theme)\n return theme\n\n @property\n def _variables(self) -> list[str]:\n\n variables = (\n list(self._data.frame)\n + list(self._pair_spec.get(\"variables\", []))\n + list(self._facet_spec.get(\"variables\", []))\n )\n for layer in self._layers:\n variables.extend(v for v in layer[\"vars\"] if v not in variables)\n\n # Coerce to str in return to appease mypy; we know these will only\n # ever be strings but I don't think we can type a DataFrame that way yet\n return [str(v) for v in variables]\n\n def on(self, target: Axes | SubFigure | Figure) -> Plot:\n \"\"\"\n Provide existing Matplotlib figure or axes for drawing the plot.\n\n When using this method, you will also need to explicitly call a method that\n triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you\n want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot`\n first to compile the plot without rendering it.\n\n Parameters\n ----------\n target : Axes, SubFigure, or Figure\n Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add\n artists without otherwise modifying the figure. Otherwise, subplots will be\n created within the space of the given :class:`matplotlib.figure.Figure` or\n :class:`matplotlib.figure.SubFigure`.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.on.rst\n\n \"\"\"\n accepted_types: tuple # Allow tuple of various length\n if hasattr(mpl.figure, \"SubFigure\"): # Added in mpl 3.4\n accepted_types = (\n mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure\n )\n accepted_types_str = (\n f\"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}\"\n )\n else:\n accepted_types = mpl.axes.Axes, mpl.figure.Figure\n accepted_types_str = f\"{mpl.axes.Axes} or {mpl.figure.Figure}\"\n\n if not isinstance(target, accepted_types):\n err = (\n f\"The `Plot.on` target must be an instance of {accepted_types_str}. \"\n f\"You passed an instance of {target.__class__} instead.\"\n )\n raise TypeError(err)\n\n new = self._clone()\n new._target = target\n\n return new\n\n def add(\n self,\n mark: Mark,\n *transforms: Stat | Mark,\n orient: str | None = None,\n legend: bool = True,\n data: DataSource = None,\n **variables: VariableSpec,\n ) -> Plot:\n \"\"\"\n Specify a layer of the visualization in terms of mark and data transform(s).\n\n This is the main method for specifying how the data should be visualized.\n It can be called multiple times with different arguments to define\n a plot with multiple layers.\n\n Parameters\n ----------\n mark : :class:`Mark`\n The visual representation of the data to use in this layer.\n transforms : :class:`Stat` or :class:`Move`\n Objects representing transforms to be applied before plotting the data.\n Currently, at most one :class:`Stat` can be used, and it\n must be passed first. This constraint will be relaxed in the future.\n orient : \"x\", \"y\", \"v\", or \"h\"\n The orientation of the mark, which also affects how transforms are computed.\n Typically corresponds to the axis that defines groups for aggregation.\n The \"v\" (vertical) and \"h\" (horizontal) options are synonyms for \"x\" / \"y\",\n but may be more intuitive with some marks. When not provided, an\n orientation will be inferred from characteristics of the data and scales.\n legend : bool\n Option to suppress the mark/mappings for this layer from the legend.\n data : DataFrame or dict\n Data source to override the global source provided in the constructor.\n variables : data vectors or identifiers\n Additional layer-specific variables, including variables that will be\n passed directly to the transforms without scaling.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.add.rst\n\n \"\"\"\n if not isinstance(mark, Mark):\n msg = f\"mark must be a Mark instance, not {type(mark)!r}.\"\n raise TypeError(msg)\n\n # TODO This API for transforms was a late decision, and previously Plot.add\n # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances.\n # It will take some work to refactor the internals so that Stat and Move are\n # treated identically, and until then well need to \"unpack\" the transforms\n # here and enforce limitations on the order / types.\n\n stat: Optional[Stat]\n move: Optional[List[Move]]\n error = False\n if not transforms:\n stat, move = None, None\n elif isinstance(transforms[0], Stat):\n stat = transforms[0]\n move = [m for m in transforms[1:] if isinstance(m, Move)]\n error = len(move) != len(transforms) - 1\n else:\n stat = None\n move = [m for m in transforms if isinstance(m, Move)]\n error = len(move) != len(transforms)\n\n if error:\n msg = \" \".join([\n \"Transforms must have at most one Stat type (in the first position),\",\n \"and all others must be a Move type. Given transform type(s):\",\n \", \".join(str(type(t).__name__) for t in transforms) + \".\"\n ])\n raise TypeError(msg)\n\n new = self._clone()\n new._layers.append({\n \"mark\": mark,\n \"stat\": stat,\n \"move\": move,\n # TODO it doesn't work to supply scalars to variables, but it should\n \"vars\": variables,\n \"source\": data,\n \"legend\": legend,\n \"orient\": {\"v\": \"x\", \"h\": \"y\"}.get(orient, orient), # type: ignore\n })\n\n return new\n\n def pair(\n self,\n x: VariableSpecList = None,\n y: VariableSpecList = None,\n wrap: int | None = None,\n cross: bool = True,\n ) -> Plot:\n \"\"\"\n Produce subplots by pairing multiple `x` and/or `y` variables.\n\n Parameters\n ----------\n x, y : sequence(s) of data vectors or identifiers\n Variables that will define the grid of subplots.\n wrap : int\n When using only `x` or `y`, \"wrap\" subplots across a two-dimensional grid\n with this many columns (when using `x`) or rows (when using `y`).\n cross : bool\n When False, zip the `x` and `y` lists such that the first subplot gets the\n first pair, the second gets the second pair, etc. Otherwise, create a\n two-dimensional grid from the cartesian product of the lists.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.pair.rst\n\n \"\"\"\n # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows\n # This may also be possible by setting `wrap=1`, but is that too unobvious?\n # TODO PairGrid features not currently implemented: diagonals, corner\n\n pair_spec: PairSpec = {}\n\n axes = {\"x\": [] if x is None else x, \"y\": [] if y is None else y}\n for axis, arg in axes.items():\n if isinstance(arg, (str, int)):\n err = f\"You must pass a sequence of variable keys to `{axis}`\"\n raise TypeError(err)\n\n pair_spec[\"variables\"] = {}\n pair_spec[\"structure\"] = {}\n\n for axis in \"xy\":\n keys = []\n for i, col in enumerate(axes[axis]):\n key = f\"{axis}{i}\"\n keys.append(key)\n pair_spec[\"variables\"][key] = col\n\n if keys:\n pair_spec[\"structure\"][axis] = keys\n\n if not cross and len(axes[\"x\"]) != len(axes[\"y\"]):\n err = \"Lengths of the `x` and `y` lists must match with cross=False\"\n raise ValueError(err)\n\n pair_spec[\"cross\"] = cross\n pair_spec[\"wrap\"] = wrap\n\n new = self._clone()\n new._pair_spec.update(pair_spec)\n return new\n\n def facet(\n self,\n col: VariableSpec = None,\n row: VariableSpec = None,\n order: OrderSpec | dict[str, OrderSpec] = None,\n wrap: int | None = None,\n ) -> Plot:\n \"\"\"\n Produce subplots with conditional subsets of the data.\n\n Parameters\n ----------\n col, row : data vectors or identifiers\n Variables used to define subsets along the columns and/or rows of the grid.\n Can be references to the global data source passed in the constructor.\n order : list of strings, or dict with dimensional keys\n Define the order of the faceting variables.\n wrap : int\n When using only `col` or `row`, wrap subplots across a two-dimensional\n grid with this many subplots on the faceting dimension.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.facet.rst\n\n \"\"\"\n variables: dict[str, VariableSpec] = {}\n if col is not None:\n variables[\"col\"] = col\n if row is not None:\n variables[\"row\"] = row\n\n structure = {}\n if isinstance(order, dict):\n for dim in [\"col\", \"row\"]:\n dim_order = order.get(dim)\n if dim_order is not None:\n structure[dim] = list(dim_order)\n elif order is not None:\n if col is not None and row is not None:\n err = \" \".join([\n \"When faceting on both col= and row=, passing `order` as a list\"\n \"is ambiguous. Use a dict with 'col' and/or 'row' keys instead.\"\n ])\n raise RuntimeError(err)\n elif col is not None:\n structure[\"col\"] = list(order)\n elif row is not None:\n structure[\"row\"] = list(order)\n\n spec: FacetSpec = {\n \"variables\": variables,\n \"structure\": structure,\n \"wrap\": wrap,\n }\n\n new = self._clone()\n new._facet_spec.update(spec)\n\n return new\n\n # TODO def twin()?\n\n def scale(self, **scales: Scale) -> Plot:\n \"\"\"\n Specify mappings from data units to visual properties.\n\n Keywords correspond to variables defined in the plot, including coordinate\n variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).\n\n A number of \"magic\" arguments are accepted, including:\n - The name of a transform (e.g., `\"log\"`, `\"sqrt\"`)\n - The name of a palette (e.g., `\"viridis\"`, `\"muted\"`)\n - A tuple of values, defining the output range (e.g. `(1, 5)`)\n - A dict, implying a :class:`Nominal` scale (e.g. `{\"a\": .2, \"b\": .5}`)\n - A list of values, implying a :class:`Nominal` scale (e.g. `[\"b\", \"r\"]`)\n\n For more explicit control, pass a scale spec object such as :class:`Continuous`\n or :class:`Nominal`. Or use `None` to use an \"identity\" scale, which treats data\n values as literally encoding visual properties.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.scale.rst\n\n \"\"\"\n new = self._clone()\n new._scales.update(scales)\n return new\n\n def share(self, **shares: bool | str) -> Plot:\n \"\"\"\n Control sharing of axis limits and ticks across subplots.\n\n Keywords correspond to variables defined in the plot, and values can be\n boolean (to share across all subplots), or one of \"row\" or \"col\" (to share\n more selectively across one dimension of a grid).\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.share.rst\n\n \"\"\"\n new = self._clone()\n new._shares.update(shares)\n return new\n\n def limit(self, **limits: tuple[Any, Any]) -> Plot:\n \"\"\"\n Control the range of visible data.\n\n Keywords correspond to variables defined in the plot, and values are a\n `(min, max)` tuple (where either can be `None` to leave unset).\n\n Limits apply only to the axis; data outside the visible range are\n still used for any stat transforms and added to the plot.\n\n Behavior for non-coordinate variables is currently undefined.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.limit.rst\n\n \"\"\"\n new = self._clone()\n new._limits.update(limits)\n return new\n\n def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot:\n \"\"\"\n Control the labels and titles for axes, legends, and subplots.\n\n Additional keywords correspond to variables defined in the plot.\n Values can be one of the following types:\n\n - string (used literally; pass \"\" to clear the default label)\n - function (called on the default label)\n\n For coordinate variables, the value sets the axis label.\n For semantic variables, the value sets the legend title.\n For faceting variables, `title=` modifies the subplot-specific label,\n while `col=` and/or `row=` add a label for the faceting variable.\n When using a single subplot, `title=` sets its title.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.label.rst\n\n\n \"\"\"\n new = self._clone()\n if title is not None:\n new._labels[\"title\"] = title\n new._labels.update(variables)\n return new\n\n def layout(\n self,\n *,\n size: tuple[float, float] | Default = default,\n engine: str | None | Default = default,\n ) -> Plot:\n \"\"\"\n Control the figure size and layout.\n\n .. note::\n\n Default figure sizes and the API for specifying the figure size are subject\n to change in future \"experimental\" releases of the objects API. The default\n layout engine may also change.\n\n Parameters\n ----------\n size : (width, height)\n Size of the resulting figure, in inches. Size is inclusive of legend when\n using pyplot, but not otherwise.\n engine : {{\"tight\", \"constrained\", None}}\n Name of method for automatically adjusting the layout to remove overlap.\n The default depends on whether :meth:`Plot.on` is used.\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.layout.rst\n\n \"\"\"\n # TODO add an \"auto\" mode for figsize that roughly scales with the rcParams\n # figsize (so that works), but expands to prevent subplots from being squished\n # Also should we have height=, aspect=, exclusive with figsize? Or working\n # with figsize when only one is defined?\n\n new = self._clone()\n\n if size is not default:\n new._figure_spec[\"figsize\"] = size\n if engine is not default:\n new._layout_spec[\"engine\"] = engine\n\n return new\n\n # TODO def legend (ugh)\n\n def theme(self, *args: dict[str, Any]) -> Plot:\n \"\"\"\n Control the default appearance of elements in the plot.\n\n .. note::\n\n The API for customizing plot appearance is not yet finalized.\n Currently, the only valid argument is a dict of matplotlib rc parameters.\n (This dict must be passed as a positional argument.)\n\n It is likely that this method will be enhanced in future releases.\n\n Matplotlib rc parameters are documented on the following page:\n https://matplotlib.org/stable/tutorials/introductory/customizing.html\n\n Examples\n --------\n .. include:: ../docstrings/objects.Plot.theme.rst\n\n \"\"\"\n new = self._clone()\n\n # We can skip this whole block on Python 3.8+ with positional-only syntax\n nargs = len(args)\n if nargs != 1:\n err = f\"theme() takes 1 positional argument, but {nargs} were given\"\n raise TypeError(err)\n\n rc = args[0]\n new._theme.update(rc)\n\n return new\n\n def save(self, loc, **kwargs) -> Plot:\n \"\"\"\n Compile the plot and write it to a buffer or file on disk.\n\n Parameters\n ----------\n loc : str, path, or buffer\n Location on disk to save the figure, or a buffer to write into.\n kwargs\n Other keyword arguments are passed through to\n :meth:`matplotlib.figure.Figure.savefig`.\n\n \"\"\"\n # TODO expose important keyword arguments in our signature?\n with theme_context(self._theme_with_defaults()):\n self._plot().save(loc, **kwargs)\n return self\n\n def show(self, **kwargs) -> None:\n \"\"\"\n Compile the plot and display it by hooking into pyplot.\n\n Calling this method is not necessary to render a plot in notebook context,\n but it may be in other environments (e.g., in a terminal). After compiling the\n plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters).\n\n Unlike other :class:`Plot` methods, there is no return value. This should be\n the last method you call when specifying a plot.\n\n \"\"\"\n # TODO make pyplot configurable at the class level, and when not using,\n # import IPython.display and call on self to populate cell output?\n\n # Keep an eye on whether matplotlib implements \"attaching\" an existing\n # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024\n\n self.plot(pyplot=True).show(**kwargs)\n\n def plot(self, pyplot: bool = False) -> Plotter:\n \"\"\"\n Compile the plot spec and return the Plotter object.\n \"\"\"\n with theme_context(self._theme_with_defaults()):\n return self._plot(pyplot)\n\n def _plot(self, pyplot: bool = False) -> Plotter:\n\n # TODO if we have _target object, pyplot should be determined by whether it\n # is hooked into the pyplot state machine (how do we check?)\n\n plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults())\n\n # Process the variable assignments and initialize the figure\n common, layers = plotter._extract_data(self)\n plotter._setup_figure(self, common, layers)\n\n # Process the scale spec for coordinate variables and transform their data\n coord_vars = [v for v in self._variables if re.match(r\"^x|y\", v)]\n plotter._setup_scales(self, common, layers, coord_vars)\n\n # Apply statistical transform(s)\n plotter._compute_stats(self, layers)\n\n # Process scale spec for semantic variables and coordinates computed by stat\n plotter._setup_scales(self, common, layers)\n\n # TODO Remove these after updating other methods\n # ---- Maybe have debug= param that attaches these when True?\n plotter._data = common\n plotter._layers = layers\n\n # Process the data for each layer and add matplotlib artists\n for layer in layers:\n plotter._plot_layer(self, layer)\n\n # Add various figure decorations\n plotter._make_legend(self)\n plotter._finalize_figure(self)\n\n return plotter\n\n\n# ---- The plot compilation engine ---------------------------------------------- #\n\n\nclass Plotter:\n \"\"\"\n Engine for compiling a :class:`Plot` spec into a Matplotlib figure.\n\n This class is not intended to be instantiated directly by users.\n\n \"\"\"\n # TODO decide if we ever want these (Plot.plot(debug=True))?\n _data: PlotData\n _layers: list[Layer]\n _figure: Figure\n\n def __init__(self, pyplot: bool, theme: dict[str, Any]):\n\n self._pyplot = pyplot\n self._theme = theme\n self._legend_contents: list[tuple[\n tuple[str, str | int], list[Artist], list[str],\n ]] = []\n self._scales: dict[str, Scale] = {}\n\n def save(self, loc, **kwargs) -> Plotter: # TODO type args\n kwargs.setdefault(\"dpi\", 96)\n try:\n loc = os.path.expanduser(loc)\n except TypeError:\n # loc may be a buffer in which case that would not work\n pass\n self._figure.savefig(loc, **kwargs)\n return self\n\n def show(self, **kwargs) -> None:\n \"\"\"\n Display the plot by hooking into pyplot.\n\n This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.\n\n \"\"\"\n # TODO if we did not create the Plotter with pyplot, is it possible to do this?\n # If not we should clearly raise.\n import matplotlib.pyplot as plt\n with theme_context(self._theme):\n plt.show(**kwargs)\n\n # TODO API for accessing the underlying matplotlib objects\n # TODO what else is useful in the public API for this class?\n\n def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n\n # TODO better to do this through a Jupyter hook? e.g.\n # ipy = IPython.core.formatters.get_ipython()\n # fmt = ipy.display_formatter.formatters[\"text/html\"]\n # fmt.for_type(Plot, ...)\n # Would like to have a svg option too, not sure how to make that flexible\n\n # TODO use matplotlib backend directly instead of going through savefig?\n\n # TODO perhaps have self.show() flip a switch to disable this, so that\n # user does not end up with two versions of the figure in the output\n\n # TODO use bbox_inches=\"tight\" like the inline backend?\n # pro: better results, con: (sometimes) confusing results\n # Better solution would be to default (with option to change)\n # to using constrained/tight layout.\n\n # TODO need to decide what the right default behavior here is:\n # - Use dpi=72 to match default InlineBackend figure size?\n # - Accept a generic \"scaling\" somewhere and scale DPI from that,\n # either with 1x -> 72 or 1x -> 96 and the default scaling be .75?\n # - Listen to rcParams? InlineBackend behavior makes that so complicated :(\n # - Do we ever want to *not* use retina mode at this point?\n\n from PIL import Image\n\n dpi = 96\n buffer = io.BytesIO()\n\n with theme_context(self._theme):\n self._figure.savefig(buffer, dpi=dpi * 2, format=\"png\", bbox_inches=\"tight\")\n data = buffer.getvalue()\n\n scaling = .85 / 2\n w, h = Image.open(buffer).size\n metadata = {\"width\": w * scaling, \"height\": h * scaling}\n return data, metadata\n\n def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]:\n\n common_data = (\n p._data\n .join(None, p._facet_spec.get(\"variables\"))\n .join(None, p._pair_spec.get(\"variables\"))\n )\n\n layers: list[Layer] = []\n for layer in p._layers:\n spec = layer.copy()\n spec[\"data\"] = common_data.join(layer.get(\"source\"), layer.get(\"vars\"))\n layers.append(spec)\n\n return common_data, layers\n\n def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str:\n\n label: str\n if var in p._labels:\n manual_label = p._labels[var]\n if callable(manual_label) and auto_label is not None:\n label = manual_label(auto_label)\n else:\n label = cast(str, manual_label)\n elif auto_label is None:\n label = \"\"\n else:\n label = auto_label\n return label\n\n def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None:\n\n # --- Parsing the faceting/pairing parameterization to specify figure grid\n\n subplot_spec = p._subplot_spec.copy()\n facet_spec = p._facet_spec.copy()\n pair_spec = p._pair_spec.copy()\n\n for axis in \"xy\":\n if axis in p._shares:\n subplot_spec[f\"share{axis}\"] = p._shares[axis]\n\n for dim in [\"col\", \"row\"]:\n if dim in common.frame and dim not in facet_spec[\"structure\"]:\n order = categorical_order(common.frame[dim])\n facet_spec[\"structure\"][dim] = order\n\n self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec)\n\n # --- Figure initialization\n self._figure = subplots.init_figure(\n pair_spec, self._pyplot, p._figure_spec, p._target,\n )\n\n # --- Figure annotation\n for sub in subplots:\n ax = sub[\"ax\"]\n for axis in \"xy\":\n axis_key = sub[axis]\n\n # ~~ Axis labels\n\n # TODO Should we make it possible to use only one x/y label for\n # all rows/columns in a faceted plot? Maybe using sub{axis}label,\n # although the alignments of the labels from that method leaves\n # something to be desired (in terms of how it defines 'centered').\n names = [\n common.names.get(axis_key),\n *(layer[\"data\"].names.get(axis_key) for layer in layers)\n ]\n auto_label = next((name for name in names if name is not None), None)\n label = self._resolve_label(p, axis_key, auto_label)\n ax.set(**{f\"{axis}label\": label})\n\n # ~~ Decoration visibility\n\n # TODO there should be some override (in Plot.layout?) so that\n # axis / tick labels can be shown on interior shared axes if desired\n\n axis_obj = getattr(ax, f\"{axis}axis\")\n visible_side = {\"x\": \"bottom\", \"y\": \"left\"}.get(axis)\n show_axis_label = (\n sub[visible_side]\n or not p._pair_spec.get(\"cross\", True)\n or (\n axis in p._pair_spec.get(\"structure\", {})\n and bool(p._pair_spec.get(\"wrap\"))\n )\n )\n axis_obj.get_label().set_visible(show_axis_label)\n\n show_tick_labels = (\n show_axis_label\n or subplot_spec.get(f\"share{axis}\") not in (\n True, \"all\", {\"x\": \"col\", \"y\": \"row\"}[axis]\n )\n )\n for group in (\"major\", \"minor\"):\n for t in getattr(axis_obj, f\"get_{group}ticklabels\")():\n t.set_visible(show_tick_labels)\n\n # TODO we want right-side titles for row facets in most cases?\n # Let's have what we currently call \"margin titles\" but properly using the\n # ax.set_title interface (see my gist)\n title_parts = []\n for dim in [\"col\", \"row\"]:\n if sub[dim] is not None:\n val = self._resolve_label(p, \"title\", f\"{sub[dim]}\")\n if dim in p._labels:\n key = self._resolve_label(p, dim, common.names.get(dim))\n val = f\"{key} {val}\"\n title_parts.append(val)\n\n has_col = sub[\"col\"] is not None\n has_row = sub[\"row\"] is not None\n show_title = (\n has_col and has_row\n or (has_col or has_row) and p._facet_spec.get(\"wrap\")\n or (has_col and sub[\"top\"])\n # TODO or has_row and sub[\"right\"] and \n or has_row # TODO and not \n )\n if title_parts:\n title = \" | \".join(title_parts)\n title_text = ax.set_title(title)\n title_text.set_visible(show_title)\n elif not (has_col or has_row):\n title = self._resolve_label(p, \"title\", None)\n title_text = ax.set_title(title)\n\n def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None:\n\n grouping_vars = [v for v in PROPERTIES if v not in \"xy\"]\n grouping_vars += [\"col\", \"row\", \"group\"]\n\n pair_vars = spec._pair_spec.get(\"structure\", {})\n\n for layer in layers:\n\n data = layer[\"data\"]\n mark = layer[\"mark\"]\n stat = layer[\"stat\"]\n\n if stat is None:\n continue\n\n iter_axes = itertools.product(*[\n pair_vars.get(axis, [axis]) for axis in \"xy\"\n ])\n\n old = data.frame\n\n if pair_vars:\n data.frames = {}\n data.frame = data.frame.iloc[:0] # TODO to simplify typing\n\n for coord_vars in iter_axes:\n\n pairings = \"xy\", coord_vars\n\n df = old.copy()\n scales = self._scales.copy()\n\n for axis, var in zip(*pairings):\n if axis != var:\n df = df.rename(columns={var: axis})\n drop_cols = [x for x in df if re.match(rf\"{axis}\\d+\", str(x))]\n df = df.drop(drop_cols, axis=1)\n scales[axis] = scales[var]\n\n orient = layer[\"orient\"] or mark._infer_orient(scales)\n\n if stat.group_by_orient:\n grouper = [orient, *grouping_vars]\n else:\n grouper = grouping_vars\n groupby = GroupBy(grouper)\n res = stat(df, groupby, orient, scales)\n\n if pair_vars:\n data.frames[coord_vars] = res\n else:\n data.frame = res\n\n def _get_scale(\n self, spec: Plot, var: str, prop: Property, values: Series\n ) -> Scale:\n\n if var in spec._scales:\n arg = spec._scales[var]\n if arg is None or isinstance(arg, Scale):\n scale = arg\n else:\n scale = prop.infer_scale(arg, values)\n else:\n scale = prop.default_scale(values)\n\n return scale\n\n def _get_subplot_data(self, df, var, view, share_state):\n\n if share_state in [True, \"all\"]:\n # The all-shared case is easiest, every subplot sees all the data\n seed_values = df[var]\n else:\n # Otherwise, we need to setup separate scales for different subplots\n if share_state in [False, \"none\"]:\n # Fully independent axes are also easy: use each subplot's data\n idx = self._get_subplot_index(df, view)\n elif share_state in df:\n # Sharing within row/col is more complicated\n use_rows = df[share_state] == view[share_state]\n idx = df.index[use_rows]\n else:\n # This configuration doesn't make much sense, but it's fine\n idx = df.index\n\n seed_values = df.loc[idx, var]\n\n return seed_values\n\n def _setup_scales(\n self, p: Plot,\n common: PlotData,\n layers: list[Layer],\n variables: list[str] | None = None,\n ) -> None:\n\n if variables is None:\n # Add variables that have data but not a scale, which happens\n # because this method can be called multiple time, to handle\n # variables added during the Stat transform.\n variables = []\n for layer in layers:\n variables.extend(layer[\"data\"].frame.columns)\n for df in layer[\"data\"].frames.values():\n variables.extend(str(v) for v in df if v not in variables)\n variables = [v for v in variables if v not in self._scales]\n\n for var in variables:\n\n # Determine whether this is a coordinate variable\n # (i.e., x/y, paired x/y, or derivative such as xmax)\n m = re.match(r\"^(?P(?Px|y)\\d*).*\", var)\n if m is None:\n coord = axis = None\n else:\n coord = m[\"coord\"]\n axis = m[\"axis\"]\n\n # Get keys that handle things like x0, xmax, properly where relevant\n prop_key = var if axis is None else axis\n scale_key = var if coord is None else coord\n\n if prop_key not in PROPERTIES:\n continue\n\n # Concatenate layers, using only the relevant coordinate and faceting vars,\n # This is unnecessarily wasteful, as layer data will often be redundant.\n # But figuring out the minimal amount we need is more complicated.\n cols = [var, \"col\", \"row\"]\n parts = [common.frame.filter(cols)]\n for layer in layers:\n parts.append(layer[\"data\"].frame.filter(cols))\n for df in layer[\"data\"].frames.values():\n parts.append(df.filter(cols))\n var_df = pd.concat(parts, ignore_index=True)\n\n prop = PROPERTIES[prop_key]\n scale = self._get_scale(p, scale_key, prop, var_df[var])\n\n if scale_key not in p._variables:\n # TODO this implies that the variable was added by the stat\n # It allows downstream orientation inference to work properly.\n # But it feels rather hacky, so ideally revisit.\n scale._priority = 0 # type: ignore\n\n if axis is None:\n # We could think about having a broader concept of (un)shared properties\n # In general, not something you want to do (different scales in facets)\n # But could make sense e.g. with paired plots. Build later.\n share_state = None\n subplots = []\n else:\n share_state = self._subplots.subplot_spec[f\"share{axis}\"]\n subplots = [view for view in self._subplots if view[axis] == coord]\n\n # Shared categorical axes are broken on matplotlib<3.4.0.\n # https://github.com/matplotlib/matplotlib/pull/18308\n # This only affects us when sharing *paired* axes. This is a novel/niche\n # behavior, so we will raise rather than hack together a workaround.\n if axis is not None and Version(mpl.__version__) < Version(\"3.4.0\"):\n from seaborn._core.scales import Nominal\n paired_axis = axis in p._pair_spec.get(\"structure\", {})\n cat_scale = isinstance(scale, Nominal)\n ok_dim = {\"x\": \"col\", \"y\": \"row\"}[axis]\n shared_axes = share_state not in [False, \"none\", ok_dim]\n if paired_axis and cat_scale and shared_axes:\n err = \"Sharing paired categorical axes requires matplotlib>=3.4.0\"\n raise RuntimeError(err)\n\n if scale is None:\n self._scales[var] = Scale._identity()\n else:\n self._scales[var] = scale._setup(var_df[var], prop)\n\n # Everything below here applies only to coordinate variables\n # We additionally skip it when we're working with a value\n # that is derived from a coordinate we've already processed.\n # e.g., the Stat consumed y and added ymin/ymax. In that case,\n # we've already setup the y scale and ymin/max are in scale space.\n if axis is None or (var != coord and coord in p._variables):\n continue\n\n # Set up an empty series to receive the transformed values.\n # We need this to handle piecemeal transforms of categories -> floats.\n transformed_data = []\n for layer in layers:\n index = layer[\"data\"].frame.index\n empty_series = pd.Series(dtype=float, index=index, name=var)\n transformed_data.append(empty_series)\n\n for view in subplots:\n\n axis_obj = getattr(view[\"ax\"], f\"{axis}axis\")\n seed_values = self._get_subplot_data(var_df, var, view, share_state)\n view_scale = scale._setup(seed_values, prop, axis=axis_obj)\n set_scale_obj(view[\"ax\"], axis, view_scale._matplotlib_scale)\n\n for layer, new_series in zip(layers, transformed_data):\n layer_df = layer[\"data\"].frame\n if var in layer_df:\n idx = self._get_subplot_index(layer_df, view)\n new_series.loc[idx] = view_scale(layer_df.loc[idx, var])\n\n # Now the transformed data series are complete, set update the layer data\n for layer, new_series in zip(layers, transformed_data):\n layer_df = layer[\"data\"].frame\n if var in layer_df:\n layer_df[var] = new_series\n\n def _plot_layer(self, p: Plot, layer: Layer) -> None:\n\n data = layer[\"data\"]\n mark = layer[\"mark\"]\n move = layer[\"move\"]\n\n default_grouping_vars = [\"col\", \"row\", \"group\"] # TODO where best to define?\n grouping_properties = [v for v in PROPERTIES if v[0] not in \"xy\"]\n\n pair_variables = p._pair_spec.get(\"structure\", {})\n\n for subplots, df, scales in self._generate_pairings(data, pair_variables):\n\n orient = layer[\"orient\"] or mark._infer_orient(scales)\n\n def get_order(var):\n # Ignore order for x/y: they have been scaled to numeric indices,\n # so any original order is no longer valid. Default ordering rules\n # sorted unique numbers will correctly reconstruct intended order\n # TODO This is tricky, make sure we add some tests for this\n if var not in \"xy\" and var in scales:\n return getattr(scales[var], \"order\", None)\n\n if \"width\" in mark._mappable_props:\n width = mark._resolve(df, \"width\", None)\n else:\n width = 0.8 if \"width\" not in df else df[\"width\"] # TODO what default?\n if orient in df:\n df[\"width\"] = width * scales[orient]._spacing(df[orient])\n\n if \"baseline\" in mark._mappable_props:\n # TODO what marks should have this?\n # If we can set baseline with, e.g., Bar(), then the\n # \"other\" (e.g. y for x oriented bars) parameterization\n # is somewhat ambiguous.\n baseline = mark._resolve(df, \"baseline\", None)\n else:\n # TODO unlike width, we might not want to add baseline to data\n # if the mark doesn't use it. Practically, there is a concern about\n # Mark abstraction like Area / Ribbon\n baseline = 0 if \"baseline\" not in df else df[\"baseline\"]\n df[\"baseline\"] = baseline\n\n if move is not None:\n moves = move if isinstance(move, list) else [move]\n for move_step in moves:\n move_by = getattr(move_step, \"by\", None)\n if move_by is None:\n move_by = grouping_properties\n move_groupers = [*move_by, *default_grouping_vars]\n if move_step.group_by_orient:\n move_groupers.insert(0, orient)\n order = {var: get_order(var) for var in move_groupers}\n groupby = GroupBy(order)\n df = move_step(df, groupby, orient, scales)\n\n df = self._unscale_coords(subplots, df, orient)\n\n grouping_vars = mark._grouping_props + default_grouping_vars\n split_generator = self._setup_split_generator(grouping_vars, df, subplots)\n\n mark._plot(split_generator, scales, orient)\n\n # TODO is this the right place for this?\n for view in self._subplots:\n view[\"ax\"].autoscale_view()\n\n if layer[\"legend\"]:\n self._update_legend_contents(p, mark, data, scales)\n\n def _unscale_coords(\n self, subplots: list[dict], df: DataFrame, orient: str,\n ) -> DataFrame:\n # TODO do we still have numbers in the variable name at this point?\n coord_cols = [c for c in df if re.match(r\"^[xy]\\D*$\", str(c))]\n drop_cols = [*coord_cols, \"width\"] if \"width\" in df else coord_cols\n out_df = (\n df\n .drop(drop_cols, axis=1)\n .reindex(df.columns, axis=1) # So unscaled columns retain their place\n .copy(deep=False)\n )\n\n for view in subplots:\n view_df = self._filter_subplot_data(df, view)\n axes_df = view_df[coord_cols]\n for var, values in axes_df.items():\n\n axis = getattr(view[\"ax\"], f\"{str(var)[0]}axis\")\n # TODO see https://github.com/matplotlib/matplotlib/issues/22713\n transform = axis.get_transform().inverted().transform\n inverted = transform(values)\n out_df.loc[values.index, str(var)] = inverted\n\n if var == orient and \"width\" in view_df:\n width = view_df[\"width\"]\n out_df.loc[values.index, \"width\"] = (\n transform(values + width / 2) - transform(values - width / 2)\n )\n\n return out_df\n\n def _generate_pairings(\n self, data: PlotData, pair_variables: dict,\n ) -> Generator[\n tuple[list[dict], DataFrame, dict[str, Scale]], None, None\n ]:\n # TODO retype return with subplot_spec or similar\n\n iter_axes = itertools.product(*[\n pair_variables.get(axis, [axis]) for axis in \"xy\"\n ])\n\n for x, y in iter_axes:\n\n subplots = []\n for view in self._subplots:\n if (view[\"x\"] == x) and (view[\"y\"] == y):\n subplots.append(view)\n\n if data.frame.empty and data.frames:\n out_df = data.frames[(x, y)].copy()\n elif not pair_variables:\n out_df = data.frame.copy()\n else:\n if data.frame.empty and data.frames:\n out_df = data.frames[(x, y)].copy()\n else:\n out_df = data.frame.copy()\n\n scales = self._scales.copy()\n if x in out_df:\n scales[\"x\"] = self._scales[x]\n if y in out_df:\n scales[\"y\"] = self._scales[y]\n\n for axis, var in zip(\"xy\", (x, y)):\n if axis != var:\n out_df = out_df.rename(columns={var: axis})\n cols = [col for col in out_df if re.match(rf\"{axis}\\d+\", str(col))]\n out_df = out_df.drop(cols, axis=1)\n\n yield subplots, out_df, scales\n\n def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index:\n\n dims = df.columns.intersection([\"col\", \"row\"])\n if dims.empty:\n return df.index\n\n keep_rows = pd.Series(True, df.index, dtype=bool)\n for dim in dims:\n keep_rows &= df[dim] == subplot[dim]\n return df.index[keep_rows]\n\n def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame:\n # TODO note redundancies with preceding function ... needs refactoring\n dims = df.columns.intersection([\"col\", \"row\"])\n if dims.empty:\n return df\n\n keep_rows = pd.Series(True, df.index, dtype=bool)\n for dim in dims:\n keep_rows &= df[dim] == subplot[dim]\n return df[keep_rows]\n\n def _setup_split_generator(\n self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]],\n ) -> Callable[[], Generator]:\n\n allow_empty = False # TODO will need to recreate previous categorical plots\n\n grouping_keys = []\n grouping_vars = [\n v for v in grouping_vars if v in df and v not in [\"col\", \"row\"]\n ]\n for var in grouping_vars:\n order = getattr(self._scales[var], \"order\", None)\n if order is None:\n order = categorical_order(df[var])\n grouping_keys.append(order)\n\n def split_generator(keep_na=False) -> Generator:\n\n for view in subplots:\n\n axes_df = self._filter_subplot_data(df, view)\n\n with pd.option_context(\"mode.use_inf_as_null\", True):\n if keep_na:\n # The simpler thing to do would be x.dropna().reindex(x.index).\n # But that doesn't work with the way that the subset iteration\n # is written below, which assumes data for grouping vars.\n # Matplotlib (usually?) masks nan data, so this should \"work\".\n # Downstream code can also drop these rows, at some speed cost.\n present = axes_df.notna().all(axis=1)\n nulled = {}\n for axis in \"xy\":\n if axis in axes_df:\n nulled[axis] = axes_df[axis].where(present)\n axes_df = axes_df.assign(**nulled)\n else:\n axes_df = axes_df.dropna()\n\n subplot_keys = {}\n for dim in [\"col\", \"row\"]:\n if view[dim] is not None:\n subplot_keys[dim] = view[dim]\n\n if not grouping_vars or not any(grouping_keys):\n yield subplot_keys, axes_df.copy(), view[\"ax\"]\n continue\n\n grouped_df = axes_df.groupby(grouping_vars, sort=False, as_index=False)\n\n for key in itertools.product(*grouping_keys):\n\n # Pandas fails with singleton tuple inputs\n pd_key = key[0] if len(key) == 1 else key\n\n try:\n df_subset = grouped_df.get_group(pd_key)\n except KeyError:\n # TODO (from initial work on categorical plots refactor)\n # We are adding this to allow backwards compatability\n # with the empty artists that old categorical plots would\n # add (before 0.12), which we may decide to break, in which\n # case this option could be removed\n df_subset = axes_df.loc[[]]\n\n if df_subset.empty and not allow_empty:\n continue\n\n sub_vars = dict(zip(grouping_vars, key))\n sub_vars.update(subplot_keys)\n\n # TODO need copy(deep=...) policy (here, above, anywhere else?)\n yield sub_vars, df_subset.copy(), view[\"ax\"]\n\n return split_generator\n\n def _update_legend_contents(\n self,\n p: Plot,\n mark: Mark,\n data: PlotData,\n scales: dict[str, Scale],\n ) -> None:\n \"\"\"Add legend artists / labels for one layer in the plot.\"\"\"\n if data.frame.empty and data.frames:\n legend_vars: list[str] = []\n for frame in data.frames.values():\n frame_vars = frame.columns.intersection(list(scales))\n legend_vars.extend(v for v in frame_vars if v not in legend_vars)\n else:\n legend_vars = list(data.frame.columns.intersection(list(scales)))\n\n # First pass: Identify the values that will be shown for each variable\n schema: list[tuple[\n tuple[str, str | int], list[str], tuple[list, list[str]]\n ]] = []\n schema = []\n for var in legend_vars:\n var_legend = scales[var]._legend\n if var_legend is not None:\n values, labels = var_legend\n for (_, part_id), part_vars, _ in schema:\n if data.ids[var] == part_id:\n # Allow multiple plot semantics to represent same data variable\n part_vars.append(var)\n break\n else:\n title = self._resolve_label(p, var, data.names[var])\n entry = (title, data.ids[var]), [var], (values, labels)\n schema.append(entry)\n\n # Second pass, generate an artist corresponding to each value\n contents: list[tuple[tuple[str, str | int], Any, list[str]]] = []\n for key, variables, (values, labels) in schema:\n artists = []\n for val in values:\n artist = mark._legend_artist(variables, val, scales)\n if artist is not None:\n artists.append(artist)\n if artists:\n contents.append((key, artists, labels))\n\n self._legend_contents.extend(contents)\n\n def _make_legend(self, p: Plot) -> None:\n \"\"\"Create the legend artist(s) and add onto the figure.\"\"\"\n # Combine artists representing same information across layers\n # Input list has an entry for each distinct variable in each layer\n # Output dict has an entry for each distinct variable\n merged_contents: dict[\n tuple[str, str | int], tuple[list[Artist], list[str]],\n ] = {}\n for key, new_artists, labels in self._legend_contents:\n # Key is (name, id); we need the id to resolve variable uniqueness,\n # but will need the name in the next step to title the legend\n if key in merged_contents:\n # Copy so inplace updates don't propagate back to legend_contents\n existing_artists = merged_contents[key][0]\n for i, artist in enumerate(existing_artists):\n # Matplotlib accepts a tuple of artists and will overlay them\n if isinstance(artist, tuple):\n artist += new_artists[i],\n else:\n existing_artists[i] = artist, new_artists[i]\n else:\n merged_contents[key] = new_artists.copy(), labels\n\n # TODO explain\n loc = \"center right\" if self._pyplot else \"center left\"\n\n base_legend = None\n for (name, _), (handles, labels) in merged_contents.items():\n\n legend = mpl.legend.Legend(\n self._figure,\n handles,\n labels,\n title=name,\n loc=loc,\n bbox_to_anchor=(.98, .55),\n )\n\n if base_legend:\n # Matplotlib has no public API for this so it is a bit of a hack.\n # Ideally we'd define our own legend class with more flexibility,\n # but that is a lot of work!\n base_legend_box = base_legend.get_children()[0]\n this_legend_box = legend.get_children()[0]\n base_legend_box.get_children().extend(this_legend_box.get_children())\n else:\n base_legend = legend\n self._figure.legends.append(legend)\n\n def _finalize_figure(self, p: Plot) -> None:\n\n for sub in self._subplots:\n ax = sub[\"ax\"]\n for axis in \"xy\":\n axis_key = sub[axis]\n\n # Axis limits\n if axis_key in p._limits:\n convert_units = getattr(ax, f\"{axis}axis\").convert_units\n a, b = p._limits[axis_key]\n lo = a if a is None else convert_units(a)\n hi = b if b is None else convert_units(b)\n if isinstance(a, str):\n lo = cast(float, lo) - 0.5\n if isinstance(b, str):\n hi = cast(float, hi) + 0.5\n ax.set(**{f\"{axis}lim\": (lo, hi)})\n\n engine_default = None if p._target is not None else \"tight\"\n layout_engine = p._layout_spec.get(\"engine\", engine_default)\n set_layout_engine(self._figure, layout_engine)\n"},{"col":0,"comment":"null","endLoc":77,"header":"def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]","id":2260,"name":"contextmanager","nodeType":"Function","startLoc":77,"text":"def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ..."},{"col":4,"comment":"null","endLoc":1125,"header":"def test_quantile_to_level(self, rng)","id":2261,"name":"test_quantile_to_level","nodeType":"Function","startLoc":1118,"text":"def test_quantile_to_level(self, rng):\n\n x = rng.uniform(0, 1, 100000)\n isoprop = np.linspace(.1, 1, 6)\n\n levels = _DistributionPlotter()._quantile_to_level(x, isoprop)\n for h, p in zip(levels, isoprop):\n assert (x[x <= h].sum() / x.sum()) == pytest.approx(p, abs=1e-4)"},{"col":4,"comment":"null","endLoc":1130,"header":"def test_input_checking(self, long_df)","id":2262,"name":"test_input_checking","nodeType":"Function","startLoc":1127,"text":"def test_input_checking(self, long_df):\n\n with pytest.raises(TypeError, match=\"The x variable is categorical,\"):\n kdeplot(data=long_df, x=\"a\", y=\"y\")"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":215,"id":2263,"name":"TypedDict","nodeType":"Attribute","startLoc":215,"text":"TypedDict"},{"className":"_CategoricalPlotterNew","col":0,"comment":"null","endLoc":411,"id":2264,"nodeType":"Class","startLoc":44,"text":"class _CategoricalPlotterNew(_RelationalPlotter):\n\n semantics = \"x\", \"y\", \"hue\", \"units\"\n\n wide_structure = {\"x\": \"@columns\", \"y\": \"@values\", \"hue\": \"@columns\"}\n\n # flat_structure = {\"x\": \"@values\", \"y\": \"@values\"}\n flat_structure = {\"y\": \"@values\"}\n\n _legend_func = \"scatter\"\n _legend_attributes = [\"color\"]\n\n def __init__(\n self,\n data=None,\n variables={},\n order=None,\n orient=None,\n require_numeric=False,\n legend=\"auto\",\n ):\n\n super().__init__(data=data, variables=variables)\n\n # This method takes care of some bookkeeping that is necessary because the\n # original categorical plots (prior to the 2021 refactor) had some rules that\n # don't fit exactly into the logic of _core. It may be wise to have a second\n # round of refactoring that moves the logic deeper, but this will keep things\n # relatively sensible for now.\n\n # For wide data, orient determines assignment to x/y differently from the\n # wide_structure rules in _core. If we do decide to make orient part of the\n # _core variable assignment, we'll want to figure out how to express that.\n if self.input_format == \"wide\" and orient == \"h\":\n self.plot_data = self.plot_data.rename(columns={\"x\": \"y\", \"y\": \"x\"})\n orig_variables = set(self.variables)\n orig_x = self.variables.pop(\"x\", None)\n orig_y = self.variables.pop(\"y\", None)\n orig_x_type = self.var_types.pop(\"x\", None)\n orig_y_type = self.var_types.pop(\"y\", None)\n if \"x\" in orig_variables:\n self.variables[\"y\"] = orig_x\n self.var_types[\"y\"] = orig_x_type\n if \"y\" in orig_variables:\n self.variables[\"x\"] = orig_y\n self.var_types[\"x\"] = orig_y_type\n\n # The concept of an \"orientation\" is important to the original categorical\n # plots, but there's no provision for it in _core, so we need to do it here.\n # Note that it could be useful for the other functions in at least two ways\n # (orienting a univariate distribution plot from long-form data and selecting\n # the aggregation axis in lineplot), so we may want to eventually refactor it.\n self.orient = infer_orient(\n x=self.plot_data.get(\"x\", None),\n y=self.plot_data.get(\"y\", None),\n orient=orient,\n require_numeric=require_numeric,\n )\n\n self.legend = legend\n\n # Short-circuit in the case of an empty plot\n if not self.has_xy_data:\n return\n\n # Categorical plots can be \"univariate\" in which case they get an anonymous\n # category label on the opposite axis. Note: this duplicates code in the core\n # scale_categorical function. We need to do it here because of the next line.\n if self.cat_axis not in self.variables:\n self.variables[self.cat_axis] = None\n self.var_types[self.cat_axis] = \"categorical\"\n self.plot_data[self.cat_axis] = \"\"\n\n # Categorical variables have discrete levels that we need to track\n cat_levels = categorical_order(self.plot_data[self.cat_axis], order)\n self.var_levels[self.cat_axis] = cat_levels\n\n def _hue_backcompat(self, color, palette, hue_order, force_hue=False):\n \"\"\"Implement backwards compatibility for hue parametrization.\n\n Note: the force_hue parameter is used so that functions can be shown to\n pass existing tests during refactoring and then tested for new behavior.\n It can be removed after completion of the work.\n\n \"\"\"\n # The original categorical functions applied a palette to the categorical axis\n # by default. We want to require an explicit hue mapping, to be more consistent\n # with how things work elsewhere now. I don't think there's any good way to\n # do this gently -- because it's triggered by the default value of hue=None,\n # users would always get a warning, unless we introduce some sentinel \"default\"\n # argument for this change. That's possible, but asking users to set `hue=None`\n # on every call is annoying.\n # We are keeping the logic for implementing the old behavior in with the current\n # system so that (a) we can punt on that decision and (b) we can ensure that\n # refactored code passes old tests.\n default_behavior = color is None or palette is not None\n if force_hue and \"hue\" not in self.variables and default_behavior:\n self._redundant_hue = True\n self.plot_data[\"hue\"] = self.plot_data[self.cat_axis]\n self.variables[\"hue\"] = self.variables[self.cat_axis]\n self.var_types[\"hue\"] = \"categorical\"\n hue_order = self.var_levels[self.cat_axis]\n\n # Because we convert the categorical axis variable to string,\n # we need to update a dictionary palette too\n if isinstance(palette, dict):\n palette = {str(k): v for k, v in palette.items()}\n\n else:\n self._redundant_hue = False\n\n # Previously, categorical plots had a trick where color= could seed the palette.\n # Because that's an explicit parameterization, we are going to give it one\n # release cycle with a warning before removing.\n if \"hue\" in self.variables and palette is None and color is not None:\n if not isinstance(color, str):\n color = mpl.colors.to_hex(color)\n palette = f\"dark:{color}\"\n msg = (\n \"Setting a gradient palette using color= is deprecated and will be \"\n f\"removed in version 0.13. Set `palette='{palette}'` for same effect.\"\n )\n warnings.warn(msg, FutureWarning)\n\n return palette, hue_order\n\n def _palette_without_hue_backcompat(self, palette, hue_order):\n \"\"\"Provide one cycle where palette= implies hue= when not provided\"\"\"\n if \"hue\" not in self.variables and palette is not None:\n msg = \"Passing `palette` without assigning `hue` is deprecated.\"\n warnings.warn(msg, FutureWarning, stacklevel=3)\n self.legend = False\n self.plot_data[\"hue\"] = self.plot_data[self.cat_axis]\n self.variables[\"hue\"] = self.variables.get(self.cat_axis)\n self.var_types[\"hue\"] = self.var_types.get(self.cat_axis)\n hue_order = self.var_levels.get(self.cat_axis)\n return hue_order\n\n @property\n def cat_axis(self):\n return {\"v\": \"x\", \"h\": \"y\"}[self.orient]\n\n def _get_gray(self, colors):\n \"\"\"Get a grayscale value that looks good with color.\"\"\"\n if not len(colors):\n return None\n unique_colors = np.unique(colors, axis=0)\n light_vals = [rgb_to_hls(*rgb[:3])[1] for rgb in unique_colors]\n lum = min(light_vals) * .6\n return (lum, lum, lum)\n\n def _adjust_cat_axis(self, ax, axis):\n \"\"\"Set ticks and limits for a categorical variable.\"\"\"\n # Note: in theory, this could happen in _attach for all categorical axes\n # But two reasons not to do that:\n # - If it happens before plotting, autoscaling messes up the plot limits\n # - It would change existing plots from other seaborn functions\n if self.var_types[axis] != \"categorical\":\n return\n\n # If both x/y data are empty, the correct way to set up the plot is\n # somewhat undefined; because we don't add null category data to the plot in\n # this case we don't *have* a categorical axis (yet), so best to just bail.\n if self.plot_data[axis].empty:\n return\n\n # We can infer the total number of categories (including those from previous\n # plots that are not part of the plot we are currently making) from the number\n # of ticks, which matplotlib sets up while doing unit conversion. This feels\n # slightly risky, as if we are relying on something that may be a matplotlib\n # implementation detail. But I cannot think of a better way to keep track of\n # the state from previous categorical calls (see GH2516 for context)\n n = len(getattr(ax, f\"get_{axis}ticks\")())\n\n if axis == \"x\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, n - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n # Note limits that correspond to previously-inverted y axis\n ax.set_ylim(n - .5, -.5, auto=None)\n\n @property\n def _native_width(self):\n \"\"\"Return unit of width separating categories on native numeric scale.\"\"\"\n unique_values = np.unique(self.comp_data[self.cat_axis])\n if len(unique_values) > 1:\n native_width = np.nanmin(np.diff(unique_values))\n else:\n native_width = 1\n return native_width\n\n def _nested_offsets(self, width, dodge):\n \"\"\"Return offsets for each hue level for dodged plots.\"\"\"\n offsets = None\n if \"hue\" in self.variables:\n n_levels = len(self._hue_map.levels)\n if dodge:\n each_width = width / n_levels\n offsets = np.linspace(0, width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n return offsets\n\n # Note that the plotting methods here aim (in most cases) to produce the\n # exact same artists as the original (pre 0.12) version of the code, so\n # there is some weirdness that might not otherwise be clean or make sense in\n # this context, such as adding empty artists for combinations of variables\n # with no observations\n\n def plot_strips(\n self,\n jitter,\n dodge,\n color,\n edgecolor,\n plot_kws,\n ):\n\n width = .8 * self._native_width\n offsets = self._nested_offsets(width, dodge)\n\n if jitter is True:\n jlim = 0.1\n else:\n jlim = float(jitter)\n if \"hue\" in self.variables and dodge:\n jlim /= len(self._hue_map.levels)\n jlim *= self._native_width\n jitterer = partial(np.random.uniform, low=-jlim, high=+jlim)\n\n iter_vars = [self.cat_axis]\n if dodge:\n iter_vars.append(\"hue\")\n\n ax = self.ax\n dodge_move = jitter_move = 0\n\n for sub_vars, sub_data in self.iter_data(iter_vars,\n from_comp_data=True,\n allow_empty=True):\n if offsets is not None and (offsets != 0).any():\n dodge_move = offsets[sub_data[\"hue\"].map(self._hue_map.levels.index)]\n\n jitter_move = jitterer(size=len(sub_data)) if len(sub_data) > 1 else 0\n\n adjusted_data = sub_data[self.cat_axis] + dodge_move + jitter_move\n sub_data[self.cat_axis] = adjusted_data\n\n for var in \"xy\":\n if self._log_scaled(var):\n sub_data[var] = np.power(10, sub_data[var])\n\n ax = self._get_axes(sub_vars)\n points = ax.scatter(sub_data[\"x\"], sub_data[\"y\"], color=color, **plot_kws)\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(sub_data[\"hue\"]))\n\n if edgecolor == \"gray\": # XXX TODO change to \"auto\"\n points.set_edgecolors(self._get_gray(points.get_facecolors()))\n else:\n points.set_edgecolors(edgecolor)\n\n # Finalize the axes details\n if self.legend == \"auto\":\n show_legend = not self._redundant_hue and self.input_format != \"wide\"\n else:\n show_legend = bool(self.legend)\n\n if show_legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n ax.legend(title=self.legend_title)\n\n def plot_swarms(\n self,\n dodge,\n color,\n edgecolor,\n warn_thresh,\n plot_kws,\n ):\n\n width = .8 * self._native_width\n offsets = self._nested_offsets(width, dodge)\n\n iter_vars = [self.cat_axis]\n if dodge:\n iter_vars.append(\"hue\")\n\n ax = self.ax\n point_collections = {}\n dodge_move = 0\n\n for sub_vars, sub_data in self.iter_data(iter_vars,\n from_comp_data=True,\n allow_empty=True):\n\n if offsets is not None:\n dodge_move = offsets[sub_data[\"hue\"].map(self._hue_map.levels.index)]\n\n if not sub_data.empty:\n sub_data[self.cat_axis] = sub_data[self.cat_axis] + dodge_move\n\n for var in \"xy\":\n if self._log_scaled(var):\n sub_data[var] = np.power(10, sub_data[var])\n\n ax = self._get_axes(sub_vars)\n points = ax.scatter(sub_data[\"x\"], sub_data[\"y\"], color=color, **plot_kws)\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(sub_data[\"hue\"]))\n\n if edgecolor == \"gray\": # XXX TODO change to \"auto\"\n points.set_edgecolors(self._get_gray(points.get_facecolors()))\n else:\n points.set_edgecolors(edgecolor)\n\n if not sub_data.empty:\n point_collections[(ax, sub_data[self.cat_axis].iloc[0])] = points\n\n beeswarm = Beeswarm(\n width=width, orient=self.orient, warn_thresh=warn_thresh,\n )\n for (ax, center), points in point_collections.items():\n if points.get_offsets().shape[0] > 1:\n\n def draw(points, renderer, *, center=center):\n\n beeswarm(points, center)\n\n if self.orient == \"h\":\n scalex = False\n scaley = ax.get_autoscaley_on()\n else:\n scalex = ax.get_autoscalex_on()\n scaley = False\n\n # This prevents us from undoing the nice categorical axis limits\n # set in _adjust_cat_axis, because that method currently leave\n # the autoscale flag in its original setting. It may be better\n # to disable autoscaling there to avoid needing to do this.\n fixed_scale = self.var_types[self.cat_axis] == \"categorical\"\n ax.update_datalim(points.get_datalim(ax.transData))\n if not fixed_scale and (scalex or scaley):\n ax.autoscale_view(scalex=scalex, scaley=scaley)\n\n super(points.__class__, points).draw(renderer)\n\n points.draw = draw.__get__(points)\n\n _draw_figure(ax.figure)\n\n # Finalize the axes details\n if self.legend == \"auto\":\n show_legend = not self._redundant_hue and self.input_format != \"wide\"\n else:\n show_legend = bool(self.legend)\n\n if show_legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n ax.legend(title=self.legend_title)"},{"col":4,"comment":"Implement backwards compatibility for hue parametrization.\n\n Note: the force_hue parameter is used so that functions can be shown to\n pass existing tests during refactoring and then tested for new behavior.\n It can be removed after completion of the work.\n\n ","endLoc":168,"header":"def _hue_backcompat(self, color, palette, hue_order, force_hue=False)","id":2265,"name":"_hue_backcompat","nodeType":"Function","startLoc":121,"text":"def _hue_backcompat(self, color, palette, hue_order, force_hue=False):\n \"\"\"Implement backwards compatibility for hue parametrization.\n\n Note: the force_hue parameter is used so that functions can be shown to\n pass existing tests during refactoring and then tested for new behavior.\n It can be removed after completion of the work.\n\n \"\"\"\n # The original categorical functions applied a palette to the categorical axis\n # by default. We want to require an explicit hue mapping, to be more consistent\n # with how things work elsewhere now. I don't think there's any good way to\n # do this gently -- because it's triggered by the default value of hue=None,\n # users would always get a warning, unless we introduce some sentinel \"default\"\n # argument for this change. That's possible, but asking users to set `hue=None`\n # on every call is annoying.\n # We are keeping the logic for implementing the old behavior in with the current\n # system so that (a) we can punt on that decision and (b) we can ensure that\n # refactored code passes old tests.\n default_behavior = color is None or palette is not None\n if force_hue and \"hue\" not in self.variables and default_behavior:\n self._redundant_hue = True\n self.plot_data[\"hue\"] = self.plot_data[self.cat_axis]\n self.variables[\"hue\"] = self.variables[self.cat_axis]\n self.var_types[\"hue\"] = \"categorical\"\n hue_order = self.var_levels[self.cat_axis]\n\n # Because we convert the categorical axis variable to string,\n # we need to update a dictionary palette too\n if isinstance(palette, dict):\n palette = {str(k): v for k, v in palette.items()}\n\n else:\n self._redundant_hue = False\n\n # Previously, categorical plots had a trick where color= could seed the palette.\n # Because that's an explicit parameterization, we are going to give it one\n # release cycle with a warning before removing.\n if \"hue\" in self.variables and palette is None and color is not None:\n if not isinstance(color, str):\n color = mpl.colors.to_hex(color)\n palette = f\"dark:{color}\"\n msg = (\n \"Setting a gradient palette using color= is deprecated and will be \"\n f\"removed in version 0.13. Set `palette='{palette}'` for same effect.\"\n )\n warnings.warn(msg, FutureWarning)\n\n return palette, hue_order"},{"className":"Layer","col":0,"comment":"null","endLoc":71,"id":2266,"nodeType":"Class","startLoc":62,"text":"class Layer(TypedDict, total=False):\n\n mark: Mark # TODO allow list?\n stat: Stat | None # TODO allow list?\n move: Move | list[Move] | None\n data: PlotData\n source: DataSource\n vars: dict[str, VariableSpec]\n orient: str\n legend: bool"},{"attributeType":"Mark","col":4,"comment":"null","endLoc":64,"id":2267,"name":"mark","nodeType":"Attribute","startLoc":64,"text":"mark"},{"attributeType":"Stat | None","col":4,"comment":"null","endLoc":65,"id":2268,"name":"stat","nodeType":"Attribute","startLoc":65,"text":"stat"},{"className":"TestHistPlotUnivariate","col":0,"comment":"null","endLoc":1817,"id":2269,"nodeType":"Class","startLoc":1133,"text":"class TestHistPlotUnivariate(SharedAxesLevelTests):\n\n func = staticmethod(histplot)\n\n def get_last_color(self, ax, element=\"bars\", fill=True):\n\n if element == \"bars\":\n if fill:\n return ax.patches[-1].get_facecolor()\n else:\n return ax.patches[-1].get_edgecolor()\n else:\n if fill:\n artist = ax.collections[-1]\n facecolor = artist.get_facecolor()\n edgecolor = artist.get_edgecolor()\n assert_colors_equal(facecolor, edgecolor, check_alpha=False)\n return facecolor\n else:\n return ax.lines[-1].get_color()\n\n @pytest.mark.parametrize(\n \"element,fill\",\n itertools.product([\"bars\", \"step\", \"poly\"], [True, False]),\n )\n def test_color(self, long_df, element, fill):\n\n super().test_color(long_df, element=element, fill=fill)\n\n @pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, axs = plt.subplots(3)\n for vector, ax in zip(vectors, axs):\n histplot(data=long_df, ax=ax, **{variable: vector})\n\n bars = [ax.patches for ax in axs]\n for a_bars, b_bars in itertools.product(bars, bars):\n for a, b in zip(a_bars, b_bars):\n assert_array_equal(a.get_height(), b.get_height())\n assert_array_equal(a.get_xy(), b.get_xy())\n\n def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=wide_df, ax=ax1, common_bins=False)\n\n for col in wide_df.columns[::-1]:\n histplot(data=wide_df, x=col, ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_height()\n assert a.get_xy() == b.get_xy()\n\n def test_flat_vector(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=long_df[\"x\"], ax=ax1)\n histplot(data=long_df, x=\"x\", ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_height()\n assert a.get_xy() == b.get_xy()\n\n def test_empty_data(self):\n\n ax = histplot(x=[])\n assert not ax.patches\n\n def test_variable_assignment(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=long_df, x=\"x\", ax=ax1)\n histplot(data=long_df, y=\"x\", ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_width()\n\n @pytest.mark.parametrize(\"element\", [\"bars\", \"step\", \"poly\"])\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\", \"stack\", \"fill\"])\n def test_hue_fill_colors(self, long_df, multiple, element):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=multiple, bins=1,\n fill=True, element=element, legend=False,\n )\n\n palette = color_palette()\n\n if multiple == \"layer\":\n if element == \"bars\":\n a = .5\n else:\n a = .25\n else:\n a = .75\n\n for bar, color in zip(ax.patches[::-1], palette):\n assert_colors_equal(bar.get_facecolor(), to_rgba(color, a))\n\n for poly, color in zip(ax.collections[::-1], palette):\n assert_colors_equal(poly.get_facecolor(), to_rgba(color, a))\n\n def test_hue_stack(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\", bins=n, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"stack\", ax=ax2)\n\n layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))\n stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))\n assert_array_equal(layer_heights, stack_heights)\n\n stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))\n assert_array_equal(\n stack_xys[..., 1] + stack_heights,\n stack_heights.cumsum(axis=0),\n )\n\n def test_hue_fill(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\", bins=n, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"fill\", ax=ax2)\n\n layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))\n stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))\n assert_array_almost_equal(\n layer_heights / layer_heights.sum(axis=0), stack_heights\n )\n\n stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))\n assert_array_almost_equal(\n (stack_xys[..., 1] + stack_heights) / stack_heights.sum(axis=0),\n stack_heights.cumsum(axis=0),\n )\n\n def test_hue_dodge(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n bw = 2\n\n kws = dict(data=long_df, x=\"x\", hue=\"c\", binwidth=bw, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"dodge\", ax=ax2)\n\n layer_heights = [b.get_height() for b in ax1.patches]\n dodge_heights = [b.get_height() for b in ax2.patches]\n assert_array_equal(layer_heights, dodge_heights)\n\n layer_xs = np.reshape([b.get_x() for b in ax1.patches], (2, -1))\n dodge_xs = np.reshape([b.get_x() for b in ax2.patches], (2, -1))\n assert_array_almost_equal(layer_xs[1], dodge_xs[1])\n assert_array_almost_equal(layer_xs[0], dodge_xs[0] - bw / 2)\n\n def test_hue_as_numpy_dodged(self, long_df):\n # https://github.com/mwaskom/seaborn/issues/2452\n\n ax = histplot(\n long_df,\n x=\"y\", hue=long_df[\"a\"].to_numpy(),\n multiple=\"dodge\", bins=1,\n )\n # Note hue order reversal\n assert ax.patches[1].get_x() < ax.patches[0].get_x()\n\n def test_multiple_input_check(self, flat_series):\n\n with pytest.raises(ValueError, match=\"`multiple` must be\"):\n histplot(flat_series, multiple=\"invalid\")\n\n def test_element_input_check(self, flat_series):\n\n with pytest.raises(ValueError, match=\"`element` must be\"):\n histplot(flat_series, element=\"invalid\")\n\n def test_count_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"count\")\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == len(flat_series)\n\n def test_density_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"density\")\n bar_heights = [b.get_height() for b in ax.patches]\n bar_widths = [b.get_width() for b in ax.patches]\n assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)\n\n def test_density_stat_common_norm(self, long_df):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=\"density\", common_norm=True, element=\"bars\",\n )\n bar_heights = [b.get_height() for b in ax.patches]\n bar_widths = [b.get_width() for b in ax.patches]\n assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)\n\n def test_density_stat_unique_norm(self, long_df):\n\n n = 10\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=\"density\", bins=n, common_norm=False, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for bars in bar_groups:\n bar_heights = [b.get_height() for b in bars]\n bar_widths = [b.get_width() for b in bars]\n bar_areas = np.multiply(bar_heights, bar_widths)\n assert bar_areas.sum() == pytest.approx(1)\n\n @pytest.fixture(params=[\"probability\", \"proportion\"])\n def height_norm_arg(self, request):\n return request.param\n\n def test_probability_stat(self, flat_series, height_norm_arg):\n\n ax = histplot(flat_series, stat=height_norm_arg)\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == pytest.approx(1)\n\n def test_probability_stat_common_norm(self, long_df, height_norm_arg):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=height_norm_arg, common_norm=True, element=\"bars\",\n )\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == pytest.approx(1)\n\n def test_probability_stat_unique_norm(self, long_df, height_norm_arg):\n\n n = 10\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=height_norm_arg, bins=n, common_norm=False, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for bars in bar_groups:\n bar_heights = [b.get_height() for b in bars]\n assert sum(bar_heights) == pytest.approx(1)\n\n def test_percent_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"percent\")\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == 100\n\n def test_common_bins(self, long_df):\n\n n = 10\n ax = histplot(\n long_df, x=\"x\", hue=\"a\", common_bins=True, bins=n, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n assert_array_equal(\n [b.get_xy() for b in bar_groups[0]],\n [b.get_xy() for b in bar_groups[1]]\n )\n\n def test_unique_bins(self, wide_df):\n\n ax = histplot(wide_df, common_bins=False, bins=10, element=\"bars\")\n\n bar_groups = np.split(np.array(ax.patches), len(wide_df.columns))\n\n for i, col in enumerate(wide_df.columns[::-1]):\n bars = bar_groups[i]\n start = bars[0].get_x()\n stop = bars[-1].get_x() + bars[-1].get_width()\n assert_array_almost_equal(start, wide_df[col].min())\n assert_array_almost_equal(stop, wide_df[col].max())\n\n def test_weights_with_missing(self, missing_df):\n\n ax = histplot(missing_df, x=\"x\", weights=\"s\", bins=5)\n\n bar_heights = [bar.get_height() for bar in ax.patches]\n total_weight = missing_df[[\"x\", \"s\"]].dropna()[\"s\"].sum()\n assert sum(bar_heights) == pytest.approx(total_weight)\n\n def test_weight_norm(self, rng):\n\n vals = rng.normal(0, 1, 50)\n x = np.concatenate([vals, vals])\n w = np.repeat([1, 2], 50)\n ax = histplot(\n x=x, weights=w, hue=w, common_norm=True, stat=\"density\", bins=5\n )\n\n # Recall that artists are added in reverse of hue order\n y1 = [bar.get_height() for bar in ax.patches[:5]]\n y2 = [bar.get_height() for bar in ax.patches[5:]]\n\n assert sum(y1) == 2 * sum(y2)\n\n def test_discrete(self, long_df):\n\n ax = histplot(long_df, x=\"s\", discrete=True)\n\n data_min = long_df[\"s\"].min()\n data_max = long_df[\"s\"].max()\n assert len(ax.patches) == (data_max - data_min + 1)\n\n for i, bar in enumerate(ax.patches):\n assert bar.get_width() == 1\n assert bar.get_x() == (data_min + i - .5)\n\n def test_discrete_categorical_default(self, long_df):\n\n ax = histplot(long_df, x=\"a\")\n for i, bar in enumerate(ax.patches):\n assert bar.get_width() == 1\n\n def test_categorical_yaxis_inversion(self, long_df):\n\n ax = histplot(long_df, y=\"a\")\n ymax, ymin = ax.get_ylim()\n assert ymax > ymin\n\n @pytest.mark.skipif(\n Version(np.__version__) < Version(\"1.17\"),\n reason=\"Histogram over datetime64 requires numpy >= 1.17\",\n )\n def test_datetime_scale(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(x=long_df[\"t\"], fill=True, ax=ax1)\n histplot(x=long_df[\"t\"], fill=False, ax=ax2)\n assert ax1.get_xlim() == ax2.get_xlim()\n\n @pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde(self, flat_series, stat):\n\n ax = histplot(\n flat_series, kde=True, stat=stat, kde_kws={\"cut\": 10}\n )\n\n bar_widths = [b.get_width() for b in ax.patches]\n bar_heights = [b.get_height() for b in ax.patches]\n hist_area = np.multiply(bar_widths, bar_heights).sum()\n\n density, = ax.lines\n kde_area = integrate(density.get_ydata(), density.get_xdata())\n\n assert kde_area == pytest.approx(hist_area)\n\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\"])\n @pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde_with_hue(self, long_df, stat, multiple):\n\n n = 10\n ax = histplot(\n long_df, x=\"x\", hue=\"c\", multiple=multiple,\n kde=True, stat=stat, element=\"bars\",\n kde_kws={\"cut\": 10}, bins=n,\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for i, bars in enumerate(bar_groups):\n bar_widths = [b.get_width() for b in bars]\n bar_heights = [b.get_height() for b in bars]\n hist_area = np.multiply(bar_widths, bar_heights).sum()\n\n x, y = ax.lines[i].get_xydata().T\n kde_area = integrate(y, x)\n\n if multiple == \"layer\":\n assert kde_area == pytest.approx(hist_area)\n elif multiple == \"dodge\":\n assert kde_area == pytest.approx(hist_area * 2)\n\n def test_kde_default_cut(self, flat_series):\n\n ax = histplot(flat_series, kde=True)\n support = ax.lines[0].get_xdata()\n assert support.min() == flat_series.min()\n assert support.max() == flat_series.max()\n\n def test_kde_hue(self, long_df):\n\n n = 10\n ax = histplot(data=long_df, x=\"x\", hue=\"a\", kde=True, bins=n)\n\n for bar, line in zip(ax.patches[::n], ax.lines):\n assert_colors_equal(\n bar.get_facecolor(), line.get_color(), check_alpha=False\n )\n\n def test_kde_yaxis(self, flat_series):\n\n f, ax = plt.subplots()\n histplot(x=flat_series, kde=True)\n histplot(y=flat_series, kde=True)\n\n x, y = ax.lines\n assert_array_equal(x.get_xdata(), y.get_ydata())\n assert_array_equal(x.get_ydata(), y.get_xdata())\n\n def test_kde_line_kws(self, flat_series):\n\n lw = 5\n ax = histplot(flat_series, kde=True, line_kws=dict(lw=lw))\n assert ax.lines[0].get_linewidth() == lw\n\n def test_kde_singular_data(self):\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n ax = histplot(x=np.ones(10), kde=True)\n assert not ax.lines\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n ax = histplot(x=[5], kde=True)\n assert not ax.lines\n\n def test_element_default(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(long_df, x=\"x\", ax=ax1)\n histplot(long_df, x=\"x\", ax=ax2, element=\"bars\")\n assert len(ax1.patches) == len(ax2.patches)\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(long_df, x=\"x\", hue=\"a\", ax=ax1)\n histplot(long_df, x=\"x\", hue=\"a\", ax=ax2, element=\"bars\")\n assert len(ax1.patches) == len(ax2.patches)\n\n def test_bars_no_fill(self, flat_series):\n\n alpha = .5\n ax = histplot(flat_series, element=\"bars\", fill=False, alpha=alpha)\n for bar in ax.patches:\n assert bar.get_facecolor() == (0, 0, 0, 0)\n assert bar.get_edgecolor()[-1] == alpha\n\n def test_step_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=True, bins=n, ax=ax1)\n histplot(flat_series, element=\"step\", fill=True, bins=n, ax=ax2)\n\n bar_heights = [b.get_height() for b in ax1.patches]\n bar_widths = [b.get_width() for b in ax1.patches]\n bar_edges = [b.get_x() for b in ax1.patches]\n\n fill = ax2.collections[0]\n x, y = fill.get_paths()[0].vertices[::-1].T\n\n assert_array_equal(x[1:2 * n:2], bar_edges)\n assert_array_equal(y[1:2 * n:2], bar_heights)\n\n assert x[n * 2] == bar_edges[-1] + bar_widths[-1]\n assert y[n * 2] == bar_heights[-1]\n\n def test_poly_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=True, bins=n, ax=ax1)\n histplot(flat_series, element=\"poly\", fill=True, bins=n, ax=ax2)\n\n bar_heights = np.array([b.get_height() for b in ax1.patches])\n bar_widths = np.array([b.get_width() for b in ax1.patches])\n bar_edges = np.array([b.get_x() for b in ax1.patches])\n\n fill = ax2.collections[0]\n x, y = fill.get_paths()[0].vertices[::-1].T\n\n assert_array_equal(x[1:n + 1], bar_edges + bar_widths / 2)\n assert_array_equal(y[1:n + 1], bar_heights)\n\n def test_poly_no_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=False, bins=n, ax=ax1)\n histplot(flat_series, element=\"poly\", fill=False, bins=n, ax=ax2)\n\n bar_heights = np.array([b.get_height() for b in ax1.patches])\n bar_widths = np.array([b.get_width() for b in ax1.patches])\n bar_edges = np.array([b.get_x() for b in ax1.patches])\n\n x, y = ax2.lines[0].get_xydata().T\n\n assert_array_equal(x, bar_edges + bar_widths / 2)\n assert_array_equal(y, bar_heights)\n\n def test_step_no_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(flat_series, element=\"bars\", fill=False, ax=ax1)\n histplot(flat_series, element=\"step\", fill=False, ax=ax2)\n\n bar_heights = [b.get_height() for b in ax1.patches]\n bar_widths = [b.get_width() for b in ax1.patches]\n bar_edges = [b.get_x() for b in ax1.patches]\n\n x, y = ax2.lines[0].get_xydata().T\n\n assert_array_equal(x[:-1], bar_edges)\n assert_array_equal(y[:-1], bar_heights)\n assert x[-1] == bar_edges[-1] + bar_widths[-1]\n assert y[-1] == y[-2]\n\n def test_step_fill_xy(self, flat_series):\n\n f, ax = plt.subplots()\n\n histplot(x=flat_series, element=\"step\", fill=True)\n histplot(y=flat_series, element=\"step\", fill=True)\n\n xverts = ax.collections[0].get_paths()[0].vertices\n yverts = ax.collections[1].get_paths()[0].vertices\n\n assert_array_equal(xverts, yverts[:, ::-1])\n\n def test_step_no_fill_xy(self, flat_series):\n\n f, ax = plt.subplots()\n\n histplot(x=flat_series, element=\"step\", fill=False)\n histplot(y=flat_series, element=\"step\", fill=False)\n\n xline, yline = ax.lines\n\n assert_array_equal(xline.get_xdata(), yline.get_ydata())\n assert_array_equal(xline.get_ydata(), yline.get_xdata())\n\n def test_weighted_histogram(self):\n\n ax = histplot(x=[0, 1, 2], weights=[1, 2, 3], discrete=True)\n\n bar_heights = [b.get_height() for b in ax.patches]\n assert bar_heights == [1, 2, 3]\n\n def test_weights_with_auto_bins(self, long_df):\n\n with pytest.warns(UserWarning):\n ax = histplot(long_df, x=\"x\", weights=\"f\")\n assert len(ax.patches) == 10\n\n def test_shrink(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n bw = 2\n shrink = .4\n\n histplot(long_df, x=\"x\", binwidth=bw, ax=ax1)\n histplot(long_df, x=\"x\", binwidth=bw, shrink=shrink, ax=ax2)\n\n for p1, p2 in zip(ax1.patches, ax2.patches):\n\n w1, w2 = p1.get_width(), p2.get_width()\n assert w2 == pytest.approx(shrink * w1)\n\n x1, x2 = p1.get_x(), p2.get_x()\n assert (x2 + w2 / 2) == pytest.approx(x1 + w1 / 2)\n\n def test_log_scale_explicit(self, rng):\n\n x = rng.lognormal(0, 2, 1000)\n ax = histplot(x, log_scale=True, binwidth=1)\n\n bar_widths = [b.get_width() for b in ax.patches]\n steps = np.divide(bar_widths[1:], bar_widths[:-1])\n assert np.allclose(steps, 10)\n\n def test_log_scale_implicit(self, rng):\n\n x = rng.lognormal(0, 2, 1000)\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n histplot(x, binwidth=1, ax=ax)\n\n bar_widths = [b.get_width() for b in ax.patches]\n steps = np.divide(bar_widths[1:], bar_widths[:-1])\n assert np.allclose(steps, 10)\n\n def test_log_scale_dodge(self, rng):\n\n x = rng.lognormal(0, 2, 100)\n hue = np.repeat([\"a\", \"b\"], 50)\n ax = histplot(x=x, hue=hue, bins=5, log_scale=True, multiple=\"dodge\")\n x_min = np.log([b.get_x() for b in ax.patches])\n x_max = np.log([b.get_x() + b.get_width() for b in ax.patches])\n assert np.unique(np.round(x_max - x_min, 10)).size == 1\n\n @pytest.mark.parametrize(\n \"fill\", [True, False],\n )\n def test_auto_linewidth(self, flat_series, fill):\n\n get_lw = lambda ax: ax.patches[0].get_linewidth() # noqa: E731\n\n kws = dict(element=\"bars\", fill=fill)\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(flat_series, **kws, bins=10, ax=ax1)\n histplot(flat_series, **kws, bins=100, ax=ax2)\n assert get_lw(ax1) > get_lw(ax2)\n\n f, ax1 = plt.subplots(figsize=(10, 5))\n f, ax2 = plt.subplots(figsize=(2, 5))\n histplot(flat_series, **kws, bins=30, ax=ax1)\n histplot(flat_series, **kws, bins=30, ax=ax2)\n assert get_lw(ax1) > get_lw(ax2)\n\n f, ax1 = plt.subplots(figsize=(4, 5))\n f, ax2 = plt.subplots(figsize=(4, 5))\n histplot(flat_series, **kws, bins=30, ax=ax1)\n histplot(10 ** flat_series, **kws, bins=30, log_scale=True, ax=ax2)\n assert get_lw(ax1) == pytest.approx(get_lw(ax2))\n\n f, ax1 = plt.subplots(figsize=(4, 5))\n f, ax2 = plt.subplots(figsize=(4, 5))\n histplot(y=[0, 1, 1], **kws, discrete=True, ax=ax1)\n histplot(y=[\"a\", \"b\", \"b\"], **kws, ax=ax2)\n assert get_lw(ax1) == pytest.approx(get_lw(ax2))\n\n def test_bar_kwargs(self, flat_series):\n\n lw = 2\n ec = (1, .2, .9, .5)\n ax = histplot(flat_series, binwidth=1, ec=ec, lw=lw)\n for bar in ax.patches:\n assert_colors_equal(bar.get_edgecolor(), ec)\n assert bar.get_linewidth() == lw\n\n def test_step_fill_kwargs(self, flat_series):\n\n lw = 2\n ec = (1, .2, .9, .5)\n ax = histplot(flat_series, element=\"step\", ec=ec, lw=lw)\n poly = ax.collections[0]\n assert_colors_equal(poly.get_edgecolor(), ec)\n assert poly.get_linewidth() == lw\n\n def test_step_line_kwargs(self, flat_series):\n\n lw = 2\n ls = \"--\"\n ax = histplot(flat_series, element=\"step\", fill=False, lw=lw, ls=ls)\n line = ax.lines[0]\n assert line.get_linewidth() == lw\n assert line.get_linestyle() == ls"},{"attributeType":"Move | list | None","col":4,"comment":"null","endLoc":66,"id":2270,"name":"move","nodeType":"Attribute","startLoc":66,"text":"move"},{"col":4,"comment":"null","endLoc":1152,"header":"def get_last_color(self, ax, element=\"bars\", fill=True)","id":2271,"name":"get_last_color","nodeType":"Function","startLoc":1137,"text":"def get_last_color(self, ax, element=\"bars\", fill=True):\n\n if element == \"bars\":\n if fill:\n return ax.patches[-1].get_facecolor()\n else:\n return ax.patches[-1].get_edgecolor()\n else:\n if fill:\n artist = ax.collections[-1]\n facecolor = artist.get_facecolor()\n edgecolor = artist.get_edgecolor()\n assert_colors_equal(facecolor, edgecolor, check_alpha=False)\n return facecolor\n else:\n return ax.lines[-1].get_color()"},{"attributeType":"PlotData","col":4,"comment":"null","endLoc":67,"id":2272,"name":"data","nodeType":"Attribute","startLoc":67,"text":"data"},{"attributeType":"Mapping | None","col":4,"comment":"null","endLoc":68,"id":2273,"name":"source","nodeType":"Attribute","startLoc":68,"text":"source"},{"attributeType":"dict","col":4,"comment":"null","endLoc":69,"id":2274,"name":"vars","nodeType":"Attribute","startLoc":69,"text":"vars"},{"attributeType":"str","col":4,"comment":"null","endLoc":70,"id":2275,"name":"orient","nodeType":"Attribute","startLoc":70,"text":"orient"},{"fileName":"test_axisgrid.py","filePath":"tests","id":2276,"nodeType":"File","text":"import numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport pytest\nimport numpy.testing as npt\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\ntry:\n import pandas.testing as tm\nexcept ImportError:\n import pandas.util.testing as tm\n\nfrom seaborn._oldcore import categorical_order\nfrom seaborn import rcmod\nfrom seaborn.palettes import color_palette\nfrom seaborn.relational import scatterplot\nfrom seaborn.distributions import histplot, kdeplot, distplot\nfrom seaborn.categorical import pointplot\nfrom seaborn import axisgrid as ag\nfrom seaborn._testing import (\n assert_plots_equal,\n assert_colors_equal,\n)\n\nrs = np.random.RandomState(0)\n\n\nclass TestFacetGrid:\n\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n y=rs.gamma(4, size=60),\n a=np.repeat(list(\"abc\"), 20),\n b=np.tile(list(\"mn\"), 30),\n c=np.tile(list(\"tuv\"), 20),\n d=np.tile(list(\"abcdefghijkl\"), 5)))\n\n def test_self_data(self):\n\n g = ag.FacetGrid(self.df)\n assert g.data is self.df\n\n def test_self_figure(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.figure, plt.Figure)\n assert g.figure is g._figure\n\n def test_self_axes(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)\n\n def test_axes_array_size(self):\n\n g = ag.FacetGrid(self.df)\n assert g.axes.shape == (1, 1)\n\n g = ag.FacetGrid(self.df, row=\"a\")\n assert g.axes.shape == (3, 1)\n\n g = ag.FacetGrid(self.df, col=\"b\")\n assert g.axes.shape == (1, 2)\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n assert g.axes.shape == (1, 1)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n assert g.axes.shape == (3, 2)\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)\n\n def test_single_axes(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.ax, plt.Axes)\n\n g = ag.FacetGrid(self.df, row=\"a\")\n with pytest.raises(AttributeError):\n g.ax\n\n g = ag.FacetGrid(self.df, col=\"a\")\n with pytest.raises(AttributeError):\n g.ax\n\n g = ag.FacetGrid(self.df, col=\"a\", row=\"b\")\n with pytest.raises(AttributeError):\n g.ax\n\n def test_col_wrap(self):\n\n n = len(self.df.d.unique())\n\n g = ag.FacetGrid(self.df, col=\"d\")\n assert g.axes.shape == (1, n)\n assert g.facet_axis(0, 8) is g.axes[0, 8]\n\n g_wrap = ag.FacetGrid(self.df, col=\"d\", col_wrap=4)\n assert g_wrap.axes.shape == (n,)\n assert g_wrap.facet_axis(0, 8) is g_wrap.axes[8]\n assert g_wrap._ncol == 4\n assert g_wrap._nrow == (n / 4)\n\n with pytest.raises(ValueError):\n g = ag.FacetGrid(self.df, row=\"b\", col=\"d\", col_wrap=4)\n\n df = self.df.copy()\n df.loc[df.d == \"j\"] = np.nan\n g_missing = ag.FacetGrid(df, col=\"d\")\n assert g_missing.axes.shape == (1, n - 1)\n\n g_missing_wrap = ag.FacetGrid(df, col=\"d\", col_wrap=4)\n assert g_missing_wrap.axes.shape == (n - 1,)\n\n g = ag.FacetGrid(self.df, col=\"d\", col_wrap=1)\n assert len(list(g.facet_data())) == n\n\n def test_normal_axes(self):\n\n null = np.empty(0, object).flat\n\n g = ag.FacetGrid(self.df)\n npt.assert_array_equal(g._bottom_axes, g.axes.flat)\n npt.assert_array_equal(g._not_bottom_axes, null)\n npt.assert_array_equal(g._left_axes, g.axes.flat)\n npt.assert_array_equal(g._not_left_axes, null)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, col=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes.flat)\n npt.assert_array_equal(g._not_bottom_axes, null)\n npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, row=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)\n npt.assert_array_equal(g._left_axes, g.axes.flat)\n npt.assert_array_equal(g._not_left_axes, null)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, col=\"a\", row=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)\n npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)\n npt.assert_array_equal(g._inner_axes, g.axes[:-1, 1:].flat)\n\n def test_wrapped_axes(self):\n\n null = np.empty(0, object).flat\n\n g = ag.FacetGrid(self.df, col=\"a\", col_wrap=2)\n npt.assert_array_equal(g._bottom_axes,\n g.axes[np.array([1, 2])].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:1].flat)\n npt.assert_array_equal(g._left_axes, g.axes[np.array([0, 2])].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[np.array([1])].flat)\n npt.assert_array_equal(g._inner_axes, null)\n\n def test_axes_dict(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.axes_dict, dict)\n assert not g.axes_dict\n\n g = ag.FacetGrid(self.df, row=\"c\")\n assert list(g.axes_dict.keys()) == g.row_names\n for (name, ax) in zip(g.row_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, col=\"c\")\n assert list(g.axes_dict.keys()) == g.col_names\n for (name, ax) in zip(g.col_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, col=\"a\", col_wrap=2)\n assert list(g.axes_dict.keys()) == g.col_names\n for (name, ax) in zip(g.col_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"c\")\n for (row_var, col_var), ax in g.axes_dict.items():\n i = g.row_names.index(row_var)\n j = g.col_names.index(col_var)\n assert g.axes[i, j] is ax\n\n def test_figure_size(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 9))\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", height=6)\n npt.assert_array_equal(g.figure.get_size_inches(), (12, 18))\n\n g = ag.FacetGrid(self.df, col=\"c\", height=4, aspect=.5)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n\n def test_figure_size_with_legend(self):\n\n g = ag.FacetGrid(self.df, col=\"a\", hue=\"c\", height=4, aspect=.5)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n g.add_legend()\n assert g.figure.get_size_inches()[0] > 6\n\n g = ag.FacetGrid(self.df, col=\"a\", hue=\"c\", height=4, aspect=.5,\n legend_out=False)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n g.add_legend()\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n\n def test_legend_data(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n palette = color_palette(n_colors=3)\n\n assert g._legend.get_title().get_text() == \"a\"\n\n a_levels = sorted(self.df.a.unique())\n\n lines = g._legend.get_lines()\n assert len(lines) == len(a_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == len(a_levels)\n\n for label, level in zip(labels, a_levels):\n assert label.get_text() == level\n\n def test_legend_data_missing_level(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\", hue_order=list(\"azbc\"))\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n\n c1, c2, c3, c4 = color_palette(n_colors=4)\n palette = [c1, c3, c4]\n\n assert g._legend.get_title().get_text() == \"a\"\n\n a_levels = sorted(self.df.a.unique())\n\n lines = g._legend.get_lines()\n assert len(lines) == len(a_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == 4\n\n for label, level in zip(labels, list(\"azbc\")):\n assert label.get_text() == level\n\n def test_get_boolean_legend_data(self):\n\n self.df[\"b_bool\"] = self.df.b == \"m\"\n g = ag.FacetGrid(self.df, hue=\"b_bool\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n palette = color_palette(n_colors=2)\n\n assert g._legend.get_title().get_text() == \"b_bool\"\n\n b_levels = list(map(str, categorical_order(self.df.b_bool)))\n\n lines = g._legend.get_lines()\n assert len(lines) == len(b_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == len(b_levels)\n\n for label, level in zip(labels, b_levels):\n assert label.get_text() == level\n\n def test_legend_tuples(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\")\n g.map(plt.plot, \"x\", \"y\")\n\n handles, labels = g.ax.get_legend_handles_labels()\n label_tuples = [(\"\", l) for l in labels]\n legend_data = dict(zip(label_tuples, handles))\n g.add_legend(legend_data, label_tuples)\n for entry, label in zip(g._legend.get_texts(), labels):\n assert entry.get_text() == label\n\n def test_legend_options(self):\n\n g = ag.FacetGrid(self.df, hue=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n\n g1 = ag.FacetGrid(self.df, hue=\"b\", legend_out=False)\n g1.add_legend(adjust_subtitles=True)\n\n g1 = ag.FacetGrid(self.df, hue=\"b\", legend_out=False)\n g1.add_legend(adjust_subtitles=False)\n\n def test_legendout_with_colwrap(self):\n\n g = ag.FacetGrid(self.df, col=\"d\", hue='b',\n col_wrap=4, legend_out=False)\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n g.add_legend()\n\n def test_legend_tight_layout(self):\n\n g = ag.FacetGrid(self.df, hue='b')\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n g.add_legend()\n g.tight_layout()\n\n axes_right_edge = g.ax.get_window_extent().xmax\n legend_left_edge = g._legend.get_window_extent().xmin\n\n assert axes_right_edge < legend_left_edge\n\n def test_subplot_kws(self):\n\n g = ag.FacetGrid(self.df, despine=False,\n subplot_kws=dict(projection=\"polar\"))\n for ax in g.axes.flat:\n assert \"PolarAxesSubplot\" in str(type(ax))\n\n def test_gridspec_kws(self):\n ratios = [3, 1, 2]\n\n gskws = dict(width_ratios=ratios)\n g = ag.FacetGrid(self.df, col='c', row='a', gridspec_kws=gskws)\n\n for ax in g.axes.flat:\n ax.set_xticks([])\n ax.set_yticks([])\n\n g.figure.tight_layout()\n\n for (l, m, r) in g.axes:\n assert l.get_position().width > m.get_position().width\n assert r.get_position().width > m.get_position().width\n\n def test_gridspec_kws_col_wrap(self):\n ratios = [3, 1, 2, 1, 1]\n\n gskws = dict(width_ratios=ratios)\n with pytest.warns(UserWarning):\n ag.FacetGrid(self.df, col='d', col_wrap=5, gridspec_kws=gskws)\n\n def test_data_generator(self):\n\n g = ag.FacetGrid(self.df, row=\"a\")\n d = list(g.facet_data())\n assert len(d) == 3\n\n tup, data = d[0]\n assert tup == (0, 0, 0)\n assert (data[\"a\"] == \"a\").all()\n\n tup, data = d[1]\n assert tup == (1, 0, 0)\n assert (data[\"a\"] == \"b\").all()\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n d = list(g.facet_data())\n assert len(d) == 6\n\n tup, data = d[0]\n assert tup == (0, 0, 0)\n assert (data[\"a\"] == \"a\").all()\n assert (data[\"b\"] == \"m\").all()\n\n tup, data = d[1]\n assert tup == (0, 1, 0)\n assert (data[\"a\"] == \"a\").all()\n assert (data[\"b\"] == \"n\").all()\n\n tup, data = d[2]\n assert tup == (1, 0, 0)\n assert (data[\"a\"] == \"b\").all()\n assert (data[\"b\"] == \"m\").all()\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n d = list(g.facet_data())\n assert len(d) == 3\n tup, data = d[1]\n assert tup == (0, 0, 1)\n assert (data[\"c\"] == \"u\").all()\n\n def test_map(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n\n lines = g.axes[0, 0].lines\n assert len(lines) == 3\n\n line1, _, _ = lines\n assert line1.get_linewidth() == 3\n x, y = line1.get_data()\n mask = (self.df.a == \"a\") & (self.df.b == \"m\") & (self.df.c == \"t\")\n npt.assert_array_equal(x, self.df.x[mask])\n npt.assert_array_equal(y, self.df.y[mask])\n\n def test_map_dataframe(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n\n def plot(x, y, data=None, **kws):\n plt.plot(data[x], data[y], **kws)\n # Modify __module__ so this doesn't look like a seaborn function\n plot.__module__ = \"test\"\n\n g.map_dataframe(plot, \"x\", \"y\", linestyle=\"--\")\n\n lines = g.axes[0, 0].lines\n assert len(g.axes[0, 0].lines) == 3\n\n line1, _, _ = lines\n assert line1.get_linestyle() == \"--\"\n x, y = line1.get_data()\n mask = (self.df.a == \"a\") & (self.df.b == \"m\") & (self.df.c == \"t\")\n npt.assert_array_equal(x, self.df.x[mask])\n npt.assert_array_equal(y, self.df.y[mask])\n\n def test_set(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n xlim = (-2, 5)\n ylim = (3, 6)\n xticks = [-2, 0, 3, 5]\n yticks = [3, 4.5, 6]\n g.set(xlim=xlim, ylim=ylim, xticks=xticks, yticks=yticks)\n for ax in g.axes.flat:\n npt.assert_array_equal(ax.get_xlim(), xlim)\n npt.assert_array_equal(ax.get_ylim(), ylim)\n npt.assert_array_equal(ax.get_xticks(), xticks)\n npt.assert_array_equal(ax.get_yticks(), yticks)\n\n def test_set_titles(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"a = a | b = m\"\n assert g.axes[0, 1].get_title() == \"a = a | b = n\"\n assert g.axes[1, 0].get_title() == \"a = b | b = m\"\n\n # Test a provided title\n g.set_titles(\"{row_var} == {row_name} \\\\/ {col_var} == {col_name}\")\n assert g.axes[0, 0].get_title() == \"a == a \\\\/ b == m\"\n assert g.axes[0, 1].get_title() == \"a == a \\\\/ b == n\"\n assert g.axes[1, 0].get_title() == \"a == b \\\\/ b == m\"\n\n # Test a single row\n g = ag.FacetGrid(self.df, col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"b = m\"\n assert g.axes[0, 1].get_title() == \"b = n\"\n\n # test with dropna=False\n g = ag.FacetGrid(self.df, col=\"b\", hue=\"b\", dropna=False)\n g.map(plt.plot, 'x', 'y')\n\n def test_set_titles_margin_titles(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", margin_titles=True)\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"b = m\"\n assert g.axes[0, 1].get_title() == \"b = n\"\n assert g.axes[1, 0].get_title() == \"\"\n\n # Test the row \"titles\"\n assert g.axes[0, 1].texts[0].get_text() == \"a = a\"\n assert g.axes[1, 1].texts[0].get_text() == \"a = b\"\n assert g.axes[0, 1].texts[0] is g._margin_titles_texts[0]\n\n # Test provided titles\n g.set_titles(col_template=\"{col_name}\", row_template=\"{row_name}\")\n assert g.axes[0, 0].get_title() == \"m\"\n assert g.axes[0, 1].get_title() == \"n\"\n assert g.axes[1, 0].get_title() == \"\"\n\n assert len(g.axes[1, 1].texts) == 1\n assert g.axes[1, 1].texts[0].get_text() == \"b\"\n\n def test_set_ticklabels(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n ax = g.axes[-1, 0]\n xlab = [l.get_text() + \"h\" for l in ax.get_xticklabels()]\n ylab = [l.get_text() + \"i\" for l in ax.get_yticklabels()]\n\n g.set_xticklabels(xlab)\n g.set_yticklabels(ylab)\n got_x = [l.get_text() for l in g.axes[-1, 1].get_xticklabels()]\n got_y = [l.get_text() for l in g.axes[0, 0].get_yticklabels()]\n npt.assert_array_equal(got_x, xlab)\n npt.assert_array_equal(got_y, ylab)\n\n x, y = np.arange(10), np.arange(10)\n df = pd.DataFrame(np.c_[x, y], columns=[\"x\", \"y\"])\n g = ag.FacetGrid(df).map_dataframe(pointplot, x=\"x\", y=\"y\", order=x)\n g.set_xticklabels(step=2)\n got_x = [int(l.get_text()) for l in g.axes[0, 0].get_xticklabels()]\n npt.assert_array_equal(x[::2], got_x)\n\n g = ag.FacetGrid(self.df, col=\"d\", col_wrap=5)\n g.map(plt.plot, \"x\", \"y\")\n g.set_xticklabels(rotation=45)\n g.set_yticklabels(rotation=75)\n for ax in g._bottom_axes:\n for l in ax.get_xticklabels():\n assert l.get_rotation() == 45\n for ax in g._left_axes:\n for l in ax.get_yticklabels():\n assert l.get_rotation() == 75\n\n def test_set_axis_labels(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n xlab = 'xx'\n ylab = 'yy'\n\n g.set_axis_labels(xlab, ylab)\n\n got_x = [ax.get_xlabel() for ax in g.axes[-1, :]]\n got_y = [ax.get_ylabel() for ax in g.axes[:, 0]]\n npt.assert_array_equal(got_x, xlab)\n npt.assert_array_equal(got_y, ylab)\n\n for ax in g.axes.flat:\n ax.set(xlabel=\"x\", ylabel=\"y\")\n\n g.set_axis_labels(xlab, ylab)\n for ax in g._not_bottom_axes:\n assert not ax.get_xlabel()\n for ax in g._not_left_axes:\n assert not ax.get_ylabel()\n\n def test_axis_lims(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", xlim=(0, 4), ylim=(-2, 3))\n assert g.axes[0, 0].get_xlim() == (0, 4)\n assert g.axes[0, 0].get_ylim() == (-2, 3)\n\n def test_data_orders(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n\n assert g.row_names == list(\"abc\")\n assert g.col_names == list(\"mn\")\n assert g.hue_names == list(\"tuv\")\n assert g.axes.shape == (3, 2)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\",\n row_order=list(\"bca\"),\n col_order=list(\"nm\"),\n hue_order=list(\"vtu\"))\n\n assert g.row_names == list(\"bca\")\n assert g.col_names == list(\"nm\")\n assert g.hue_names == list(\"vtu\")\n assert g.axes.shape == (3, 2)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\",\n row_order=list(\"bcda\"),\n col_order=list(\"nom\"),\n hue_order=list(\"qvtu\"))\n\n assert g.row_names == list(\"bcda\")\n assert g.col_names == list(\"nom\")\n assert g.hue_names == list(\"qvtu\")\n assert g.axes.shape == (4, 3)\n\n def test_palette(self):\n\n rcmod.set()\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n assert g._colors == color_palette(n_colors=len(self.df.c.unique()))\n\n g = ag.FacetGrid(self.df, hue=\"d\")\n assert g._colors == color_palette(\"husl\", len(self.df.d.unique()))\n\n g = ag.FacetGrid(self.df, hue=\"c\", palette=\"Set2\")\n assert g._colors == color_palette(\"Set2\", len(self.df.c.unique()))\n\n dict_pal = dict(t=\"red\", u=\"green\", v=\"blue\")\n list_pal = color_palette([\"red\", \"green\", \"blue\"], 3)\n g = ag.FacetGrid(self.df, hue=\"c\", palette=dict_pal)\n assert g._colors == list_pal\n\n list_pal = color_palette([\"green\", \"blue\", \"red\"], 3)\n g = ag.FacetGrid(self.df, hue=\"c\", hue_order=list(\"uvt\"),\n palette=dict_pal)\n assert g._colors == list_pal\n\n def test_hue_kws(self):\n\n kws = dict(marker=[\"o\", \"s\", \"D\"])\n g = ag.FacetGrid(self.df, hue=\"c\", hue_kws=kws)\n g.map(plt.plot, \"x\", \"y\")\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker\n\n def test_dropna(self):\n\n df = self.df.copy()\n hasna = pd.Series(np.tile(np.arange(6), 10), dtype=float)\n hasna[hasna == 5] = np.nan\n df[\"hasna\"] = hasna\n g = ag.FacetGrid(df, dropna=False, row=\"hasna\")\n assert g._not_na.sum() == 60\n\n g = ag.FacetGrid(df, dropna=True, row=\"hasna\")\n assert g._not_na.sum() == 50\n\n def test_categorical_column_missing_categories(self):\n\n df = self.df.copy()\n df['a'] = df['a'].astype('category')\n\n g = ag.FacetGrid(df[df['a'] == 'a'], col=\"a\", col_wrap=1)\n\n assert g.axes.shape == (len(df['a'].cat.categories),)\n\n def test_categorical_warning(self):\n\n g = ag.FacetGrid(self.df, col=\"b\")\n with pytest.warns(UserWarning):\n g.map(pointplot, \"b\", \"x\")\n\n def test_refline(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.refline()\n for ax in g.axes.flat:\n assert not ax.lines\n\n refx = refy = 0.5\n hline = np.array([[0, refy], [1, refy]])\n vline = np.array([[refx, 0], [refx, 1]])\n g.refline(x=refx, y=refy)\n for ax in g.axes.flat:\n assert ax.lines[0].get_color() == '.5'\n assert ax.lines[0].get_linestyle() == '--'\n assert len(ax.lines) == 2\n npt.assert_array_equal(ax.lines[0].get_xydata(), vline)\n npt.assert_array_equal(ax.lines[1].get_xydata(), hline)\n\n color, linestyle = 'red', '-'\n g.refline(x=refx, color=color, linestyle=linestyle)\n npt.assert_array_equal(g.axes[0, 0].lines[-1].get_xydata(), vline)\n assert g.axes[0, 0].lines[-1].get_color() == color\n assert g.axes[0, 0].lines[-1].get_linestyle() == linestyle\n\n def test_apply(self, long_df):\n\n def f(grid, color):\n grid.figure.set_facecolor(color)\n\n color = (.1, .6, .3, .9)\n g = ag.FacetGrid(long_df)\n res = g.apply(f, color)\n assert res is g\n assert g.figure.get_facecolor() == color\n\n def test_pipe(self, long_df):\n\n def f(grid, color):\n grid.figure.set_facecolor(color)\n return color\n\n color = (.1, .6, .3, .9)\n g = ag.FacetGrid(long_df)\n res = g.pipe(f, color)\n assert res == color\n assert g.figure.get_facecolor() == color\n\n def test_tick_params(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n color = \"blue\"\n pad = 3\n g.tick_params(pad=pad, color=color)\n for ax in g.axes.flat:\n for axis in [\"xaxis\", \"yaxis\"]:\n for tick in getattr(ax, axis).get_major_ticks():\n assert mpl.colors.same_color(tick.tick1line.get_color(), color)\n assert mpl.colors.same_color(tick.tick2line.get_color(), color)\n assert tick.get_pad() == pad\n\n\nclass TestPairGrid:\n\n rs = np.random.RandomState(sum(map(ord, \"PairGrid\")))\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n y=rs.randint(0, 4, size=(60)),\n z=rs.gamma(3, size=60),\n a=np.repeat(list(\"abc\"), 20),\n b=np.repeat(list(\"abcdefghijkl\"), 5)))\n\n def test_self_data(self):\n\n g = ag.PairGrid(self.df)\n assert g.data is self.df\n\n def test_ignore_datelike_data(self):\n\n df = self.df.copy()\n df['date'] = pd.date_range('2010-01-01', periods=len(df), freq='d')\n result = ag.PairGrid(self.df).data\n expected = df.drop('date', axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_self_figure(self):\n\n g = ag.PairGrid(self.df)\n assert isinstance(g.figure, plt.Figure)\n assert g.figure is g._figure\n\n def test_self_axes(self):\n\n g = ag.PairGrid(self.df)\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)\n\n def test_default_axes(self):\n\n g = ag.PairGrid(self.df)\n assert g.axes.shape == (3, 3)\n assert g.x_vars == [\"x\", \"y\", \"z\"]\n assert g.y_vars == [\"x\", \"y\", \"z\"]\n assert g.square_grid\n\n @pytest.mark.parametrize(\"vars\", [[\"z\", \"x\"], np.array([\"z\", \"x\"])])\n def test_specific_square_axes(self, vars):\n\n g = ag.PairGrid(self.df, vars=vars)\n assert g.axes.shape == (len(vars), len(vars))\n assert g.x_vars == list(vars)\n assert g.y_vars == list(vars)\n assert g.square_grid\n\n def test_remove_hue_from_default(self):\n\n hue = \"z\"\n g = ag.PairGrid(self.df, hue=hue)\n assert hue not in g.x_vars\n assert hue not in g.y_vars\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, hue=hue, vars=vars)\n assert hue in g.x_vars\n assert hue in g.y_vars\n\n @pytest.mark.parametrize(\n \"x_vars, y_vars\",\n [\n ([\"x\", \"y\"], [\"z\", \"y\", \"x\"]),\n ([\"x\", \"y\"], \"z\"),\n (np.array([\"x\", \"y\"]), np.array([\"z\", \"y\", \"x\"])),\n ],\n )\n def test_specific_nonsquare_axes(self, x_vars, y_vars):\n\n g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n assert g.axes.shape == (len(y_vars), len(x_vars))\n assert g.x_vars == list(x_vars)\n assert g.y_vars == list(y_vars)\n assert not g.square_grid\n\n def test_corner(self):\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=plot_vars, corner=True)\n corner_size = sum(i + 1 for i in range(len(plot_vars)))\n assert len(g.figure.axes) == corner_size\n\n g.map_diag(plt.hist)\n assert len(g.figure.axes) == (corner_size + len(plot_vars))\n\n for ax in np.diag(g.axes):\n assert not ax.yaxis.get_visible()\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=plot_vars, corner=True)\n g.map(scatterplot)\n assert len(g.figure.axes) == corner_size\n assert g.axes[0, 0].get_ylabel() == \"x\"\n\n def test_size(self):\n\n g1 = ag.PairGrid(self.df, height=3)\n npt.assert_array_equal(g1.fig.get_size_inches(), (9, 9))\n\n g2 = ag.PairGrid(self.df, height=4, aspect=.5)\n npt.assert_array_equal(g2.fig.get_size_inches(), (6, 12))\n\n g3 = ag.PairGrid(self.df, y_vars=[\"z\"], x_vars=[\"x\", \"y\"],\n height=2, aspect=2)\n npt.assert_array_equal(g3.fig.get_size_inches(), (8, 2))\n\n def test_empty_grid(self):\n\n with pytest.raises(ValueError, match=\"No variables found\"):\n ag.PairGrid(self.df[[\"a\", \"b\"]])\n\n def test_map(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g1 = ag.PairGrid(self.df)\n g1.map(plt.scatter)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n g2 = ag.PairGrid(self.df, hue=\"a\")\n g2.map(plt.scatter)\n\n for i, axes_i in enumerate(g2.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n for k, k_level in enumerate(self.df.a.unique()):\n x_in_k = x_in[self.df.a == k_level]\n y_in_k = y_in[self.df.a == k_level]\n x_out, y_out = ax.collections[k].get_offsets().T\n npt.assert_array_equal(x_in_k, x_out)\n npt.assert_array_equal(y_in_k, y_out)\n\n def test_map_nonsquare(self):\n\n x_vars = [\"x\"]\n y_vars = [\"y\", \"z\"]\n g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g.map(plt.scatter)\n\n x_in = self.df.x\n for i, i_var in enumerate(y_vars):\n ax = g.axes[i, 0]\n y_in = self.df[i_var]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n def test_map_lower(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_lower(plt.scatter)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.triu_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_map_upper(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_upper(plt.scatter)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_map_mixed_funcsig(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=vars)\n g.map_lower(scatterplot)\n g.map_upper(plt.scatter)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n def test_map_diag(self):\n\n g = ag.PairGrid(self.df)\n g.map_diag(plt.hist)\n\n for var, ax in zip(g.diag_vars, g.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist)\n\n for ax in g.diag_axes:\n assert len(ax.patches) == 30\n\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist, histtype='step')\n\n for ax in g.diag_axes:\n for ptch in ax.patches:\n assert not ptch.fill\n\n def test_map_diag_rectangular(self):\n\n x_vars = [\"x\", \"y\"]\n y_vars = [\"x\", \"z\", \"y\"]\n g1 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g1.map_diag(plt.hist)\n g1.map_offdiag(plt.scatter)\n\n assert set(g1.diag_vars) == (set(x_vars) & set(y_vars))\n\n for var, ax in zip(g1.diag_vars, g1.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n for j, x_var in enumerate(x_vars):\n for i, y_var in enumerate(y_vars):\n\n ax = g1.axes[i, j]\n if x_var == y_var:\n diag_ax = g1.diag_axes[j] # because fewer x than y vars\n assert ax.bbox.bounds == diag_ax.bbox.bounds\n\n else:\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, self.df[x_var])\n assert_array_equal(y, self.df[y_var])\n\n g2 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars, hue=\"a\")\n g2.map_diag(plt.hist)\n g2.map_offdiag(plt.scatter)\n\n assert set(g2.diag_vars) == (set(x_vars) & set(y_vars))\n\n for ax in g2.diag_axes:\n assert len(ax.patches) == 30\n\n x_vars = [\"x\", \"y\", \"z\"]\n y_vars = [\"x\", \"z\"]\n g3 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g3.map_diag(plt.hist)\n g3.map_offdiag(plt.scatter)\n\n assert set(g3.diag_vars) == (set(x_vars) & set(y_vars))\n\n for var, ax in zip(g3.diag_vars, g3.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n for j, x_var in enumerate(x_vars):\n for i, y_var in enumerate(y_vars):\n\n ax = g3.axes[i, j]\n if x_var == y_var:\n diag_ax = g3.diag_axes[i] # because fewer y than x vars\n assert ax.bbox.bounds == diag_ax.bbox.bounds\n else:\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, self.df[x_var])\n assert_array_equal(y, self.df[y_var])\n\n def test_map_diag_color(self):\n\n color = \"red\"\n\n g1 = ag.PairGrid(self.df)\n g1.map_diag(plt.hist, color=color)\n\n for ax in g1.diag_axes:\n for patch in ax.patches:\n assert_colors_equal(patch.get_facecolor(), color)\n\n g2 = ag.PairGrid(self.df)\n g2.map_diag(kdeplot, color='red')\n\n for ax in g2.diag_axes:\n for line in ax.lines:\n assert_colors_equal(line.get_color(), color)\n\n def test_map_diag_palette(self):\n\n palette = \"muted\"\n pal = color_palette(palette, n_colors=len(self.df.a.unique()))\n g = ag.PairGrid(self.df, hue=\"a\", palette=palette)\n g.map_diag(kdeplot)\n\n for ax in g.diag_axes:\n for line, color in zip(ax.lines[::-1], pal):\n assert_colors_equal(line.get_color(), color)\n\n def test_map_diag_and_offdiag(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_offdiag(plt.scatter)\n g.map_diag(plt.hist)\n\n for ax in g.diag_axes:\n assert len(ax.patches) == 10\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_diag_sharey(self):\n\n g = ag.PairGrid(self.df, diag_sharey=True)\n g.map_diag(kdeplot)\n for ax in g.diag_axes[1:]:\n assert ax.get_ylim() == g.diag_axes[0].get_ylim()\n\n def test_map_diag_matplotlib(self):\n\n bins = 10\n g = ag.PairGrid(self.df)\n g.map_diag(plt.hist, bins=bins)\n for ax in g.diag_axes:\n assert len(ax.patches) == bins\n\n levels = len(self.df[\"a\"].unique())\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist, bins=bins)\n for ax in g.diag_axes:\n assert len(ax.patches) == (bins * levels)\n\n def test_palette(self):\n\n rcmod.set()\n\n g = ag.PairGrid(self.df, hue=\"a\")\n assert g.palette == color_palette(n_colors=len(self.df.a.unique()))\n\n g = ag.PairGrid(self.df, hue=\"b\")\n assert g.palette == color_palette(\"husl\", len(self.df.b.unique()))\n\n g = ag.PairGrid(self.df, hue=\"a\", palette=\"Set2\")\n assert g.palette == color_palette(\"Set2\", len(self.df.a.unique()))\n\n dict_pal = dict(a=\"red\", b=\"green\", c=\"blue\")\n list_pal = color_palette([\"red\", \"green\", \"blue\"])\n g = ag.PairGrid(self.df, hue=\"a\", palette=dict_pal)\n assert g.palette == list_pal\n\n list_pal = color_palette([\"blue\", \"red\", \"green\"])\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=list(\"cab\"),\n palette=dict_pal)\n assert g.palette == list_pal\n\n def test_hue_kws(self):\n\n kws = dict(marker=[\"o\", \"s\", \"d\", \"+\"])\n g = ag.PairGrid(self.df, hue=\"a\", hue_kws=kws)\n g.map(plt.plot)\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_kws=kws,\n hue_order=list(\"dcab\"))\n g.map(plt.plot)\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker\n\n def test_hue_order(self):\n\n order = list(\"dcab\")\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_diag(plt.plot)\n\n for line, level in zip(g.axes[0, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_lower(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_upper(plt.plot)\n\n for line, level in zip(g.axes[0, 1].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"y\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n def test_hue_order_missing_level(self):\n\n order = list(\"dcaeb\")\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_diag(plt.plot)\n\n for line, level in zip(g.axes[0, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_lower(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_upper(plt.plot)\n\n for line, level in zip(g.axes[0, 1].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"y\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n def test_hue_in_map(self, long_df):\n\n g = ag.PairGrid(long_df, vars=[\"x\", \"y\"])\n g.map(scatterplot, hue=long_df[\"a\"])\n ax = g.axes.flat[0]\n points = ax.collections[0]\n assert len(set(map(tuple, points.get_facecolors()))) == 3\n\n def test_nondefault_index(self):\n\n df = self.df.copy().set_index(\"b\")\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g1 = ag.PairGrid(df)\n g1.map(plt.scatter)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[plot_vars[j]]\n y_in = self.df[plot_vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n g2 = ag.PairGrid(df, hue=\"a\")\n g2.map(plt.scatter)\n\n for i, axes_i in enumerate(g2.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[plot_vars[j]]\n y_in = self.df[plot_vars[i]]\n for k, k_level in enumerate(self.df.a.unique()):\n x_in_k = x_in[self.df.a == k_level]\n y_in_k = y_in[self.df.a == k_level]\n x_out, y_out = ax.collections[k].get_offsets().T\n npt.assert_array_equal(x_in_k, x_out)\n npt.assert_array_equal(y_in_k, y_out)\n\n @pytest.mark.parametrize(\"func\", [scatterplot, plt.scatter])\n def test_dropna(self, func):\n\n df = self.df.copy()\n n_null = 20\n df.loc[np.arange(n_null), \"x\"] = np.nan\n\n plot_vars = [\"x\", \"y\", \"z\"]\n\n g1 = ag.PairGrid(df, vars=plot_vars, dropna=True)\n g1.map(func)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = df[plot_vars[j]]\n y_in = df[plot_vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n\n n_valid = (x_in * y_in).notnull().sum()\n\n assert n_valid == len(x_out)\n assert n_valid == len(y_out)\n\n g1.map_diag(histplot)\n for i, ax in enumerate(g1.diag_axes):\n var = plot_vars[i]\n count = sum(p.get_height() for p in ax.patches)\n assert count == df[var].notna().sum()\n\n def test_histplot_legend(self):\n\n # Tests _extract_legend_handles\n g = ag.PairGrid(self.df, vars=[\"x\", \"y\"], hue=\"a\")\n g.map_offdiag(histplot)\n g.add_legend()\n\n assert len(g._legend.legendHandles) == len(self.df[\"a\"].unique())\n\n def test_pairplot(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.pairplot(self.df)\n\n for ax in g.diag_axes:\n assert len(ax.patches) > 1\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n g = ag.pairplot(self.df, hue=\"a\")\n n = len(self.df.a.unique())\n\n for ax in g.diag_axes:\n assert len(ax.collections) == n\n\n def test_pairplot_reg(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.pairplot(self.df, diag_kind=\"hist\", kind=\"reg\")\n\n for ax in g.diag_axes:\n assert len(ax.patches)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_pairplot_reg_hue(self):\n\n markers = [\"o\", \"s\", \"d\"]\n g = ag.pairplot(self.df, kind=\"reg\", hue=\"a\", markers=markers)\n\n ax = g.axes[-1, 0]\n c1 = ax.collections[0]\n c2 = ax.collections[2]\n\n assert not np.array_equal(c1.get_facecolor(), c2.get_facecolor())\n assert not np.array_equal(\n c1.get_paths()[0].vertices, c2.get_paths()[0].vertices,\n )\n\n def test_pairplot_diag_kde(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.pairplot(self.df, diag_kind=\"kde\")\n\n for ax in g.diag_axes:\n assert len(ax.collections) == 1\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_pairplot_kde(self):\n\n f, ax1 = plt.subplots()\n kdeplot(data=self.df, x=\"x\", y=\"y\", ax=ax1)\n\n g = ag.pairplot(self.df, kind=\"kde\")\n ax2 = g.axes[1, 0]\n\n assert_plots_equal(ax1, ax2, labels=False)\n\n def test_pairplot_hist(self):\n\n f, ax1 = plt.subplots()\n histplot(data=self.df, x=\"x\", y=\"y\", ax=ax1)\n\n g = ag.pairplot(self.df, kind=\"hist\")\n ax2 = g.axes[1, 0]\n\n assert_plots_equal(ax1, ax2, labels=False)\n\n def test_pairplot_markers(self):\n\n vars = [\"x\", \"y\", \"z\"]\n markers = [\"o\", \"X\", \"s\"]\n g = ag.pairplot(self.df, hue=\"a\", vars=vars, markers=markers)\n m1 = g._legend.legendHandles[0].get_paths()[0]\n m2 = g._legend.legendHandles[1].get_paths()[0]\n assert m1 != m2\n\n with pytest.warns(UserWarning):\n g = ag.pairplot(self.df, hue=\"a\", vars=vars, markers=markers[:-2])\n\n def test_corner_despine(self):\n\n g = ag.PairGrid(self.df, corner=True, despine=False)\n g.map_diag(histplot)\n assert g.axes[0, 0].spines[\"top\"].get_visible()\n\n def test_corner_set(self):\n\n g = ag.PairGrid(self.df, corner=True, despine=False)\n g.set(xlim=(0, 10))\n assert g.axes[-1, 0].get_xlim() == (0, 10)\n\n def test_legend(self):\n\n g1 = ag.pairplot(self.df, hue=\"a\")\n assert isinstance(g1.legend, mpl.legend.Legend)\n\n g2 = ag.pairplot(self.df)\n assert g2.legend is None\n\n def test_tick_params(self):\n\n g = ag.PairGrid(self.df)\n color = \"red\"\n pad = 3\n g.tick_params(pad=pad, color=color)\n for ax in g.axes.flat:\n for axis in [\"xaxis\", \"yaxis\"]:\n for tick in getattr(ax, axis).get_major_ticks():\n assert mpl.colors.same_color(tick.tick1line.get_color(), color)\n assert mpl.colors.same_color(tick.tick2line.get_color(), color)\n assert tick.get_pad() == pad\n\n\nclass TestJointGrid:\n\n rs = np.random.RandomState(sum(map(ord, \"JointGrid\")))\n x = rs.randn(100)\n y = rs.randn(100)\n x_na = x.copy()\n x_na[10] = np.nan\n x_na[20] = np.nan\n data = pd.DataFrame(dict(x=x, y=y, x_na=x_na))\n\n def test_margin_grid_from_lists(self):\n\n g = ag.JointGrid(x=self.x.tolist(), y=self.y.tolist())\n npt.assert_array_equal(g.x, self.x)\n npt.assert_array_equal(g.y, self.y)\n\n def test_margin_grid_from_arrays(self):\n\n g = ag.JointGrid(x=self.x, y=self.y)\n npt.assert_array_equal(g.x, self.x)\n npt.assert_array_equal(g.y, self.y)\n\n def test_margin_grid_from_series(self):\n\n g = ag.JointGrid(x=self.data.x, y=self.data.y)\n npt.assert_array_equal(g.x, self.x)\n npt.assert_array_equal(g.y, self.y)\n\n def test_margin_grid_from_dataframe(self):\n\n g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n npt.assert_array_equal(g.x, self.x)\n npt.assert_array_equal(g.y, self.y)\n\n def test_margin_grid_from_dataframe_bad_variable(self):\n\n with pytest.raises(ValueError):\n ag.JointGrid(x=\"x\", y=\"bad_column\", data=self.data)\n\n def test_margin_grid_axis_labels(self):\n\n g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n\n xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()\n assert xlabel == \"x\"\n assert ylabel == \"y\"\n\n g.set_axis_labels(\"x variable\", \"y variable\")\n xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()\n assert xlabel == \"x variable\"\n assert ylabel == \"y variable\"\n\n def test_dropna(self):\n\n g = ag.JointGrid(x=\"x_na\", y=\"y\", data=self.data, dropna=False)\n assert len(g.x) == len(self.x_na)\n\n g = ag.JointGrid(x=\"x_na\", y=\"y\", data=self.data, dropna=True)\n assert len(g.x) == pd.notnull(self.x_na).sum()\n\n def test_axlims(self):\n\n lim = (-3, 3)\n g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data, xlim=lim, ylim=lim)\n\n assert g.ax_joint.get_xlim() == lim\n assert g.ax_joint.get_ylim() == lim\n\n assert g.ax_marg_x.get_xlim() == lim\n assert g.ax_marg_y.get_ylim() == lim\n\n def test_marginal_ticks(self):\n\n g = ag.JointGrid(marginal_ticks=False)\n assert not sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())\n assert not sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())\n\n g = ag.JointGrid(marginal_ticks=True)\n assert sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())\n assert sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())\n\n def test_bivariate_plot(self):\n\n g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n g.plot_joint(plt.plot)\n\n x, y = g.ax_joint.lines[0].get_xydata().T\n npt.assert_array_equal(x, self.x)\n npt.assert_array_equal(y, self.y)\n\n def test_univariate_plot(self):\n\n g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n g.plot_marginals(kdeplot)\n\n _, y1 = g.ax_marg_x.lines[0].get_xydata().T\n y2, _ = g.ax_marg_y.lines[0].get_xydata().T\n npt.assert_array_equal(y1, y2)\n\n def test_univariate_plot_distplot(self):\n\n bins = 10\n g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n with pytest.warns(UserWarning):\n g.plot_marginals(distplot, bins=bins)\n assert len(g.ax_marg_x.patches) == bins\n assert len(g.ax_marg_y.patches) == bins\n for x, y in zip(g.ax_marg_x.patches, g.ax_marg_y.patches):\n assert x.get_height() == y.get_width()\n\n def test_univariate_plot_matplotlib(self):\n\n bins = 10\n g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n g.plot_marginals(plt.hist, bins=bins)\n assert len(g.ax_marg_x.patches) == bins\n assert len(g.ax_marg_y.patches) == bins\n\n def test_plot(self):\n\n g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n g.plot(plt.plot, kdeplot)\n\n x, y = g.ax_joint.lines[0].get_xydata().T\n npt.assert_array_equal(x, self.x)\n npt.assert_array_equal(y, self.x)\n\n _, y1 = g.ax_marg_x.lines[0].get_xydata().T\n y2, _ = g.ax_marg_y.lines[0].get_xydata().T\n npt.assert_array_equal(y1, y2)\n\n def test_space(self):\n\n g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data, space=0)\n\n joint_bounds = g.ax_joint.bbox.bounds\n marg_x_bounds = g.ax_marg_x.bbox.bounds\n marg_y_bounds = g.ax_marg_y.bbox.bounds\n\n assert joint_bounds[2] == marg_x_bounds[2]\n assert joint_bounds[3] == marg_y_bounds[3]\n\n @pytest.mark.parametrize(\n \"as_vector\", [True, False],\n )\n def test_hue(self, long_df, as_vector):\n\n if as_vector:\n data = None\n x, y, hue = long_df[\"x\"], long_df[\"y\"], long_df[\"a\"]\n else:\n data = long_df\n x, y, hue = \"x\", \"y\", \"a\"\n\n g = ag.JointGrid(data=data, x=x, y=y, hue=hue)\n g.plot_joint(scatterplot)\n g.plot_marginals(histplot)\n\n g2 = ag.JointGrid()\n scatterplot(data=long_df, x=x, y=y, hue=hue, ax=g2.ax_joint)\n histplot(data=long_df, x=x, hue=hue, ax=g2.ax_marg_x)\n histplot(data=long_df, y=y, hue=hue, ax=g2.ax_marg_y)\n\n assert_plots_equal(g.ax_joint, g2.ax_joint)\n assert_plots_equal(g.ax_marg_x, g2.ax_marg_x, labels=False)\n assert_plots_equal(g.ax_marg_y, g2.ax_marg_y, labels=False)\n\n def test_refline(self):\n\n g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n g.plot(scatterplot, histplot)\n g.refline()\n assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines\n\n refx = refy = 0.5\n hline = np.array([[0, refy], [1, refy]])\n vline = np.array([[refx, 0], [refx, 1]])\n g.refline(x=refx, y=refy, joint=False, marginal=False)\n assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines\n\n g.refline(x=refx, y=refy)\n assert g.ax_joint.lines[0].get_color() == '.5'\n assert g.ax_joint.lines[0].get_linestyle() == '--'\n assert len(g.ax_joint.lines) == 2\n assert len(g.ax_marg_x.lines) == 1\n assert len(g.ax_marg_y.lines) == 1\n npt.assert_array_equal(g.ax_joint.lines[0].get_xydata(), vline)\n npt.assert_array_equal(g.ax_joint.lines[1].get_xydata(), hline)\n npt.assert_array_equal(g.ax_marg_x.lines[0].get_xydata(), vline)\n npt.assert_array_equal(g.ax_marg_y.lines[0].get_xydata(), hline)\n\n color, linestyle = 'red', '-'\n g.refline(x=refx, marginal=False, color=color, linestyle=linestyle)\n npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), vline)\n assert g.ax_joint.lines[-1].get_color() == color\n assert g.ax_joint.lines[-1].get_linestyle() == linestyle\n assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n g.refline(x=refx, joint=False)\n npt.assert_array_equal(g.ax_marg_x.lines[-1].get_xydata(), vline)\n assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines) + 1\n\n g.refline(y=refy, joint=False)\n npt.assert_array_equal(g.ax_marg_y.lines[-1].get_xydata(), hline)\n assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n g.refline(y=refy, marginal=False)\n npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), hline)\n assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n\nclass TestJointPlot:\n\n rs = np.random.RandomState(sum(map(ord, \"jointplot\")))\n x = rs.randn(100)\n y = rs.randn(100)\n data = pd.DataFrame(dict(x=x, y=y))\n\n def test_scatter(self):\n\n g = ag.jointplot(x=\"x\", y=\"y\", data=self.data)\n assert len(g.ax_joint.collections) == 1\n\n x, y = g.ax_joint.collections[0].get_offsets().T\n assert_array_equal(self.x, x)\n assert_array_equal(self.y, y)\n\n assert_array_almost_equal(\n [b.get_x() for b in g.ax_marg_x.patches],\n np.histogram_bin_edges(self.x, \"auto\")[:-1],\n )\n\n assert_array_almost_equal(\n [b.get_y() for b in g.ax_marg_y.patches],\n np.histogram_bin_edges(self.y, \"auto\")[:-1],\n )\n\n def test_scatter_hue(self, long_df):\n\n g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\")\n\n g2 = ag.JointGrid()\n scatterplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", ax=g2.ax_joint)\n kdeplot(data=long_df, x=\"x\", hue=\"a\", ax=g2.ax_marg_x, fill=True)\n kdeplot(data=long_df, y=\"y\", hue=\"a\", ax=g2.ax_marg_y, fill=True)\n\n assert_plots_equal(g1.ax_joint, g2.ax_joint)\n assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n def test_reg(self):\n\n g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"reg\")\n assert len(g.ax_joint.collections) == 2\n\n x, y = g.ax_joint.collections[0].get_offsets().T\n assert_array_equal(self.x, x)\n assert_array_equal(self.y, y)\n\n assert g.ax_marg_x.patches\n assert g.ax_marg_y.patches\n\n assert g.ax_marg_x.lines\n assert g.ax_marg_y.lines\n\n def test_resid(self):\n\n g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"resid\")\n assert g.ax_joint.collections\n assert g.ax_joint.lines\n assert not g.ax_marg_x.lines\n assert not g.ax_marg_y.lines\n\n def test_hist(self, long_df):\n\n bins = 3, 6\n g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", kind=\"hist\", bins=bins)\n\n g2 = ag.JointGrid()\n histplot(data=long_df, x=\"x\", y=\"y\", ax=g2.ax_joint, bins=bins)\n histplot(data=long_df, x=\"x\", ax=g2.ax_marg_x, bins=bins[0])\n histplot(data=long_df, y=\"y\", ax=g2.ax_marg_y, bins=bins[1])\n\n assert_plots_equal(g1.ax_joint, g2.ax_joint)\n assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n def test_hex(self):\n\n g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"hex\")\n assert g.ax_joint.collections\n assert g.ax_marg_x.patches\n assert g.ax_marg_y.patches\n\n def test_kde(self, long_df):\n\n g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", kind=\"kde\")\n\n g2 = ag.JointGrid()\n kdeplot(data=long_df, x=\"x\", y=\"y\", ax=g2.ax_joint)\n kdeplot(data=long_df, x=\"x\", ax=g2.ax_marg_x)\n kdeplot(data=long_df, y=\"y\", ax=g2.ax_marg_y)\n\n assert_plots_equal(g1.ax_joint, g2.ax_joint)\n assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n def test_kde_hue(self, long_df):\n\n g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", kind=\"kde\")\n\n g2 = ag.JointGrid()\n kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", ax=g2.ax_joint)\n kdeplot(data=long_df, x=\"x\", hue=\"a\", ax=g2.ax_marg_x)\n kdeplot(data=long_df, y=\"y\", hue=\"a\", ax=g2.ax_marg_y)\n\n assert_plots_equal(g1.ax_joint, g2.ax_joint)\n assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n def test_color(self):\n\n g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, color=\"purple\")\n\n scatter_color = g.ax_joint.collections[0].get_facecolor()\n assert_colors_equal(scatter_color, \"purple\")\n\n hist_color = g.ax_marg_x.patches[0].get_facecolor()[:3]\n assert_colors_equal(hist_color, \"purple\")\n\n def test_palette(self, long_df):\n\n kws = dict(data=long_df, hue=\"a\", palette=\"Set2\")\n\n g1 = ag.jointplot(x=\"x\", y=\"y\", **kws)\n\n g2 = ag.JointGrid()\n scatterplot(x=\"x\", y=\"y\", ax=g2.ax_joint, **kws)\n kdeplot(x=\"x\", ax=g2.ax_marg_x, fill=True, **kws)\n kdeplot(y=\"y\", ax=g2.ax_marg_y, fill=True, **kws)\n\n assert_plots_equal(g1.ax_joint, g2.ax_joint)\n assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n def test_hex_customise(self):\n\n # test that default gridsize can be overridden\n g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"hex\",\n joint_kws=dict(gridsize=5))\n assert len(g.ax_joint.collections) == 1\n a = g.ax_joint.collections[0].get_array()\n assert a.shape[0] == 28 # 28 hexagons expected for gridsize 5\n\n def test_bad_kind(self):\n\n with pytest.raises(ValueError):\n ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"not_a_kind\")\n\n def test_unsupported_hue_kind(self):\n\n for kind in [\"reg\", \"resid\", \"hex\"]:\n with pytest.raises(ValueError):\n ag.jointplot(x=\"x\", y=\"y\", hue=\"a\", data=self.data, kind=kind)\n\n def test_leaky_dict(self):\n # Validate input dicts are unchanged by jointplot plotting function\n\n for kwarg in (\"joint_kws\", \"marginal_kws\"):\n for kind in (\"hex\", \"kde\", \"resid\", \"reg\", \"scatter\"):\n empty_dict = {}\n ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=kind,\n **{kwarg: empty_dict})\n assert empty_dict == {}\n\n def test_distplot_kwarg_warning(self, long_df):\n\n with pytest.warns(UserWarning):\n g = ag.jointplot(data=long_df, x=\"x\", y=\"y\", marginal_kws=dict(rug=True))\n assert g.ax_marg_x.patches\n\n def test_ax_warning(self, long_df):\n\n ax = plt.gca()\n with pytest.warns(UserWarning):\n g = ag.jointplot(data=long_df, x=\"x\", y=\"y\", ax=ax)\n assert g.ax_joint.collections\n"},{"attributeType":"bool","col":4,"comment":"null","endLoc":71,"id":2277,"name":"legend","nodeType":"Attribute","startLoc":71,"text":"legend"},{"col":4,"comment":"null","endLoc":105,"header":"def test_zero_height_skipped(self)","id":2278,"name":"test_zero_height_skipped","nodeType":"Function","startLoc":101,"text":"def test_zero_height_skipped(self):\n\n p = Plot([\"a\", \"b\", \"c\"], [1, 0, 2]).add(Bar()).plot()\n ax = p._figure.axes[0]\n assert len(ax.patches) == 2"},{"col":0,"comment":"null","endLoc":2846,"header":"def pointplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, units=None, seed=None,\n markers=\"o\", linestyles=\"-\", dodge=False, join=True, scale=1,\n orient=None, color=None, palette=None, errwidth=None, ci=\"deprecated\",\n capsize=None, ax=None,\n)","id":2279,"name":"pointplot","nodeType":"Function","startLoc":2827,"text":"def pointplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=1000, units=None, seed=None,\n markers=\"o\", linestyles=\"-\", dodge=False, join=True, scale=1,\n orient=None, color=None, palette=None, errwidth=None, ci=\"deprecated\",\n capsize=None, ax=None,\n):\n\n errorbar = utils._deprecate_ci(errorbar, ci)\n\n plotter = _PointPlotter(x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth, capsize)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax)\n return ax"},{"className":"Plotter","col":0,"comment":"\n Engine for compiling a :class:`Plot` spec into a Matplotlib figure.\n\n This class is not intended to be instantiated directly by users.\n\n ","endLoc":1649,"id":2280,"nodeType":"Class","startLoc":862,"text":"class Plotter:\n \"\"\"\n Engine for compiling a :class:`Plot` spec into a Matplotlib figure.\n\n This class is not intended to be instantiated directly by users.\n\n \"\"\"\n # TODO decide if we ever want these (Plot.plot(debug=True))?\n _data: PlotData\n _layers: list[Layer]\n _figure: Figure\n\n def __init__(self, pyplot: bool, theme: dict[str, Any]):\n\n self._pyplot = pyplot\n self._theme = theme\n self._legend_contents: list[tuple[\n tuple[str, str | int], list[Artist], list[str],\n ]] = []\n self._scales: dict[str, Scale] = {}\n\n def save(self, loc, **kwargs) -> Plotter: # TODO type args\n kwargs.setdefault(\"dpi\", 96)\n try:\n loc = os.path.expanduser(loc)\n except TypeError:\n # loc may be a buffer in which case that would not work\n pass\n self._figure.savefig(loc, **kwargs)\n return self\n\n def show(self, **kwargs) -> None:\n \"\"\"\n Display the plot by hooking into pyplot.\n\n This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.\n\n \"\"\"\n # TODO if we did not create the Plotter with pyplot, is it possible to do this?\n # If not we should clearly raise.\n import matplotlib.pyplot as plt\n with theme_context(self._theme):\n plt.show(**kwargs)\n\n # TODO API for accessing the underlying matplotlib objects\n # TODO what else is useful in the public API for this class?\n\n def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n\n # TODO better to do this through a Jupyter hook? e.g.\n # ipy = IPython.core.formatters.get_ipython()\n # fmt = ipy.display_formatter.formatters[\"text/html\"]\n # fmt.for_type(Plot, ...)\n # Would like to have a svg option too, not sure how to make that flexible\n\n # TODO use matplotlib backend directly instead of going through savefig?\n\n # TODO perhaps have self.show() flip a switch to disable this, so that\n # user does not end up with two versions of the figure in the output\n\n # TODO use bbox_inches=\"tight\" like the inline backend?\n # pro: better results, con: (sometimes) confusing results\n # Better solution would be to default (with option to change)\n # to using constrained/tight layout.\n\n # TODO need to decide what the right default behavior here is:\n # - Use dpi=72 to match default InlineBackend figure size?\n # - Accept a generic \"scaling\" somewhere and scale DPI from that,\n # either with 1x -> 72 or 1x -> 96 and the default scaling be .75?\n # - Listen to rcParams? InlineBackend behavior makes that so complicated :(\n # - Do we ever want to *not* use retina mode at this point?\n\n from PIL import Image\n\n dpi = 96\n buffer = io.BytesIO()\n\n with theme_context(self._theme):\n self._figure.savefig(buffer, dpi=dpi * 2, format=\"png\", bbox_inches=\"tight\")\n data = buffer.getvalue()\n\n scaling = .85 / 2\n w, h = Image.open(buffer).size\n metadata = {\"width\": w * scaling, \"height\": h * scaling}\n return data, metadata\n\n def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]:\n\n common_data = (\n p._data\n .join(None, p._facet_spec.get(\"variables\"))\n .join(None, p._pair_spec.get(\"variables\"))\n )\n\n layers: list[Layer] = []\n for layer in p._layers:\n spec = layer.copy()\n spec[\"data\"] = common_data.join(layer.get(\"source\"), layer.get(\"vars\"))\n layers.append(spec)\n\n return common_data, layers\n\n def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str:\n\n label: str\n if var in p._labels:\n manual_label = p._labels[var]\n if callable(manual_label) and auto_label is not None:\n label = manual_label(auto_label)\n else:\n label = cast(str, manual_label)\n elif auto_label is None:\n label = \"\"\n else:\n label = auto_label\n return label\n\n def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None:\n\n # --- Parsing the faceting/pairing parameterization to specify figure grid\n\n subplot_spec = p._subplot_spec.copy()\n facet_spec = p._facet_spec.copy()\n pair_spec = p._pair_spec.copy()\n\n for axis in \"xy\":\n if axis in p._shares:\n subplot_spec[f\"share{axis}\"] = p._shares[axis]\n\n for dim in [\"col\", \"row\"]:\n if dim in common.frame and dim not in facet_spec[\"structure\"]:\n order = categorical_order(common.frame[dim])\n facet_spec[\"structure\"][dim] = order\n\n self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec)\n\n # --- Figure initialization\n self._figure = subplots.init_figure(\n pair_spec, self._pyplot, p._figure_spec, p._target,\n )\n\n # --- Figure annotation\n for sub in subplots:\n ax = sub[\"ax\"]\n for axis in \"xy\":\n axis_key = sub[axis]\n\n # ~~ Axis labels\n\n # TODO Should we make it possible to use only one x/y label for\n # all rows/columns in a faceted plot? Maybe using sub{axis}label,\n # although the alignments of the labels from that method leaves\n # something to be desired (in terms of how it defines 'centered').\n names = [\n common.names.get(axis_key),\n *(layer[\"data\"].names.get(axis_key) for layer in layers)\n ]\n auto_label = next((name for name in names if name is not None), None)\n label = self._resolve_label(p, axis_key, auto_label)\n ax.set(**{f\"{axis}label\": label})\n\n # ~~ Decoration visibility\n\n # TODO there should be some override (in Plot.layout?) so that\n # axis / tick labels can be shown on interior shared axes if desired\n\n axis_obj = getattr(ax, f\"{axis}axis\")\n visible_side = {\"x\": \"bottom\", \"y\": \"left\"}.get(axis)\n show_axis_label = (\n sub[visible_side]\n or not p._pair_spec.get(\"cross\", True)\n or (\n axis in p._pair_spec.get(\"structure\", {})\n and bool(p._pair_spec.get(\"wrap\"))\n )\n )\n axis_obj.get_label().set_visible(show_axis_label)\n\n show_tick_labels = (\n show_axis_label\n or subplot_spec.get(f\"share{axis}\") not in (\n True, \"all\", {\"x\": \"col\", \"y\": \"row\"}[axis]\n )\n )\n for group in (\"major\", \"minor\"):\n for t in getattr(axis_obj, f\"get_{group}ticklabels\")():\n t.set_visible(show_tick_labels)\n\n # TODO we want right-side titles for row facets in most cases?\n # Let's have what we currently call \"margin titles\" but properly using the\n # ax.set_title interface (see my gist)\n title_parts = []\n for dim in [\"col\", \"row\"]:\n if sub[dim] is not None:\n val = self._resolve_label(p, \"title\", f\"{sub[dim]}\")\n if dim in p._labels:\n key = self._resolve_label(p, dim, common.names.get(dim))\n val = f\"{key} {val}\"\n title_parts.append(val)\n\n has_col = sub[\"col\"] is not None\n has_row = sub[\"row\"] is not None\n show_title = (\n has_col and has_row\n or (has_col or has_row) and p._facet_spec.get(\"wrap\")\n or (has_col and sub[\"top\"])\n # TODO or has_row and sub[\"right\"] and \n or has_row # TODO and not \n )\n if title_parts:\n title = \" | \".join(title_parts)\n title_text = ax.set_title(title)\n title_text.set_visible(show_title)\n elif not (has_col or has_row):\n title = self._resolve_label(p, \"title\", None)\n title_text = ax.set_title(title)\n\n def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None:\n\n grouping_vars = [v for v in PROPERTIES if v not in \"xy\"]\n grouping_vars += [\"col\", \"row\", \"group\"]\n\n pair_vars = spec._pair_spec.get(\"structure\", {})\n\n for layer in layers:\n\n data = layer[\"data\"]\n mark = layer[\"mark\"]\n stat = layer[\"stat\"]\n\n if stat is None:\n continue\n\n iter_axes = itertools.product(*[\n pair_vars.get(axis, [axis]) for axis in \"xy\"\n ])\n\n old = data.frame\n\n if pair_vars:\n data.frames = {}\n data.frame = data.frame.iloc[:0] # TODO to simplify typing\n\n for coord_vars in iter_axes:\n\n pairings = \"xy\", coord_vars\n\n df = old.copy()\n scales = self._scales.copy()\n\n for axis, var in zip(*pairings):\n if axis != var:\n df = df.rename(columns={var: axis})\n drop_cols = [x for x in df if re.match(rf\"{axis}\\d+\", str(x))]\n df = df.drop(drop_cols, axis=1)\n scales[axis] = scales[var]\n\n orient = layer[\"orient\"] or mark._infer_orient(scales)\n\n if stat.group_by_orient:\n grouper = [orient, *grouping_vars]\n else:\n grouper = grouping_vars\n groupby = GroupBy(grouper)\n res = stat(df, groupby, orient, scales)\n\n if pair_vars:\n data.frames[coord_vars] = res\n else:\n data.frame = res\n\n def _get_scale(\n self, spec: Plot, var: str, prop: Property, values: Series\n ) -> Scale:\n\n if var in spec._scales:\n arg = spec._scales[var]\n if arg is None or isinstance(arg, Scale):\n scale = arg\n else:\n scale = prop.infer_scale(arg, values)\n else:\n scale = prop.default_scale(values)\n\n return scale\n\n def _get_subplot_data(self, df, var, view, share_state):\n\n if share_state in [True, \"all\"]:\n # The all-shared case is easiest, every subplot sees all the data\n seed_values = df[var]\n else:\n # Otherwise, we need to setup separate scales for different subplots\n if share_state in [False, \"none\"]:\n # Fully independent axes are also easy: use each subplot's data\n idx = self._get_subplot_index(df, view)\n elif share_state in df:\n # Sharing within row/col is more complicated\n use_rows = df[share_state] == view[share_state]\n idx = df.index[use_rows]\n else:\n # This configuration doesn't make much sense, but it's fine\n idx = df.index\n\n seed_values = df.loc[idx, var]\n\n return seed_values\n\n def _setup_scales(\n self, p: Plot,\n common: PlotData,\n layers: list[Layer],\n variables: list[str] | None = None,\n ) -> None:\n\n if variables is None:\n # Add variables that have data but not a scale, which happens\n # because this method can be called multiple time, to handle\n # variables added during the Stat transform.\n variables = []\n for layer in layers:\n variables.extend(layer[\"data\"].frame.columns)\n for df in layer[\"data\"].frames.values():\n variables.extend(str(v) for v in df if v not in variables)\n variables = [v for v in variables if v not in self._scales]\n\n for var in variables:\n\n # Determine whether this is a coordinate variable\n # (i.e., x/y, paired x/y, or derivative such as xmax)\n m = re.match(r\"^(?P(?Px|y)\\d*).*\", var)\n if m is None:\n coord = axis = None\n else:\n coord = m[\"coord\"]\n axis = m[\"axis\"]\n\n # Get keys that handle things like x0, xmax, properly where relevant\n prop_key = var if axis is None else axis\n scale_key = var if coord is None else coord\n\n if prop_key not in PROPERTIES:\n continue\n\n # Concatenate layers, using only the relevant coordinate and faceting vars,\n # This is unnecessarily wasteful, as layer data will often be redundant.\n # But figuring out the minimal amount we need is more complicated.\n cols = [var, \"col\", \"row\"]\n parts = [common.frame.filter(cols)]\n for layer in layers:\n parts.append(layer[\"data\"].frame.filter(cols))\n for df in layer[\"data\"].frames.values():\n parts.append(df.filter(cols))\n var_df = pd.concat(parts, ignore_index=True)\n\n prop = PROPERTIES[prop_key]\n scale = self._get_scale(p, scale_key, prop, var_df[var])\n\n if scale_key not in p._variables:\n # TODO this implies that the variable was added by the stat\n # It allows downstream orientation inference to work properly.\n # But it feels rather hacky, so ideally revisit.\n scale._priority = 0 # type: ignore\n\n if axis is None:\n # We could think about having a broader concept of (un)shared properties\n # In general, not something you want to do (different scales in facets)\n # But could make sense e.g. with paired plots. Build later.\n share_state = None\n subplots = []\n else:\n share_state = self._subplots.subplot_spec[f\"share{axis}\"]\n subplots = [view for view in self._subplots if view[axis] == coord]\n\n # Shared categorical axes are broken on matplotlib<3.4.0.\n # https://github.com/matplotlib/matplotlib/pull/18308\n # This only affects us when sharing *paired* axes. This is a novel/niche\n # behavior, so we will raise rather than hack together a workaround.\n if axis is not None and Version(mpl.__version__) < Version(\"3.4.0\"):\n from seaborn._core.scales import Nominal\n paired_axis = axis in p._pair_spec.get(\"structure\", {})\n cat_scale = isinstance(scale, Nominal)\n ok_dim = {\"x\": \"col\", \"y\": \"row\"}[axis]\n shared_axes = share_state not in [False, \"none\", ok_dim]\n if paired_axis and cat_scale and shared_axes:\n err = \"Sharing paired categorical axes requires matplotlib>=3.4.0\"\n raise RuntimeError(err)\n\n if scale is None:\n self._scales[var] = Scale._identity()\n else:\n self._scales[var] = scale._setup(var_df[var], prop)\n\n # Everything below here applies only to coordinate variables\n # We additionally skip it when we're working with a value\n # that is derived from a coordinate we've already processed.\n # e.g., the Stat consumed y and added ymin/ymax. In that case,\n # we've already setup the y scale and ymin/max are in scale space.\n if axis is None or (var != coord and coord in p._variables):\n continue\n\n # Set up an empty series to receive the transformed values.\n # We need this to handle piecemeal transforms of categories -> floats.\n transformed_data = []\n for layer in layers:\n index = layer[\"data\"].frame.index\n empty_series = pd.Series(dtype=float, index=index, name=var)\n transformed_data.append(empty_series)\n\n for view in subplots:\n\n axis_obj = getattr(view[\"ax\"], f\"{axis}axis\")\n seed_values = self._get_subplot_data(var_df, var, view, share_state)\n view_scale = scale._setup(seed_values, prop, axis=axis_obj)\n set_scale_obj(view[\"ax\"], axis, view_scale._matplotlib_scale)\n\n for layer, new_series in zip(layers, transformed_data):\n layer_df = layer[\"data\"].frame\n if var in layer_df:\n idx = self._get_subplot_index(layer_df, view)\n new_series.loc[idx] = view_scale(layer_df.loc[idx, var])\n\n # Now the transformed data series are complete, set update the layer data\n for layer, new_series in zip(layers, transformed_data):\n layer_df = layer[\"data\"].frame\n if var in layer_df:\n layer_df[var] = new_series\n\n def _plot_layer(self, p: Plot, layer: Layer) -> None:\n\n data = layer[\"data\"]\n mark = layer[\"mark\"]\n move = layer[\"move\"]\n\n default_grouping_vars = [\"col\", \"row\", \"group\"] # TODO where best to define?\n grouping_properties = [v for v in PROPERTIES if v[0] not in \"xy\"]\n\n pair_variables = p._pair_spec.get(\"structure\", {})\n\n for subplots, df, scales in self._generate_pairings(data, pair_variables):\n\n orient = layer[\"orient\"] or mark._infer_orient(scales)\n\n def get_order(var):\n # Ignore order for x/y: they have been scaled to numeric indices,\n # so any original order is no longer valid. Default ordering rules\n # sorted unique numbers will correctly reconstruct intended order\n # TODO This is tricky, make sure we add some tests for this\n if var not in \"xy\" and var in scales:\n return getattr(scales[var], \"order\", None)\n\n if \"width\" in mark._mappable_props:\n width = mark._resolve(df, \"width\", None)\n else:\n width = 0.8 if \"width\" not in df else df[\"width\"] # TODO what default?\n if orient in df:\n df[\"width\"] = width * scales[orient]._spacing(df[orient])\n\n if \"baseline\" in mark._mappable_props:\n # TODO what marks should have this?\n # If we can set baseline with, e.g., Bar(), then the\n # \"other\" (e.g. y for x oriented bars) parameterization\n # is somewhat ambiguous.\n baseline = mark._resolve(df, \"baseline\", None)\n else:\n # TODO unlike width, we might not want to add baseline to data\n # if the mark doesn't use it. Practically, there is a concern about\n # Mark abstraction like Area / Ribbon\n baseline = 0 if \"baseline\" not in df else df[\"baseline\"]\n df[\"baseline\"] = baseline\n\n if move is not None:\n moves = move if isinstance(move, list) else [move]\n for move_step in moves:\n move_by = getattr(move_step, \"by\", None)\n if move_by is None:\n move_by = grouping_properties\n move_groupers = [*move_by, *default_grouping_vars]\n if move_step.group_by_orient:\n move_groupers.insert(0, orient)\n order = {var: get_order(var) for var in move_groupers}\n groupby = GroupBy(order)\n df = move_step(df, groupby, orient, scales)\n\n df = self._unscale_coords(subplots, df, orient)\n\n grouping_vars = mark._grouping_props + default_grouping_vars\n split_generator = self._setup_split_generator(grouping_vars, df, subplots)\n\n mark._plot(split_generator, scales, orient)\n\n # TODO is this the right place for this?\n for view in self._subplots:\n view[\"ax\"].autoscale_view()\n\n if layer[\"legend\"]:\n self._update_legend_contents(p, mark, data, scales)\n\n def _unscale_coords(\n self, subplots: list[dict], df: DataFrame, orient: str,\n ) -> DataFrame:\n # TODO do we still have numbers in the variable name at this point?\n coord_cols = [c for c in df if re.match(r\"^[xy]\\D*$\", str(c))]\n drop_cols = [*coord_cols, \"width\"] if \"width\" in df else coord_cols\n out_df = (\n df\n .drop(drop_cols, axis=1)\n .reindex(df.columns, axis=1) # So unscaled columns retain their place\n .copy(deep=False)\n )\n\n for view in subplots:\n view_df = self._filter_subplot_data(df, view)\n axes_df = view_df[coord_cols]\n for var, values in axes_df.items():\n\n axis = getattr(view[\"ax\"], f\"{str(var)[0]}axis\")\n # TODO see https://github.com/matplotlib/matplotlib/issues/22713\n transform = axis.get_transform().inverted().transform\n inverted = transform(values)\n out_df.loc[values.index, str(var)] = inverted\n\n if var == orient and \"width\" in view_df:\n width = view_df[\"width\"]\n out_df.loc[values.index, \"width\"] = (\n transform(values + width / 2) - transform(values - width / 2)\n )\n\n return out_df\n\n def _generate_pairings(\n self, data: PlotData, pair_variables: dict,\n ) -> Generator[\n tuple[list[dict], DataFrame, dict[str, Scale]], None, None\n ]:\n # TODO retype return with subplot_spec or similar\n\n iter_axes = itertools.product(*[\n pair_variables.get(axis, [axis]) for axis in \"xy\"\n ])\n\n for x, y in iter_axes:\n\n subplots = []\n for view in self._subplots:\n if (view[\"x\"] == x) and (view[\"y\"] == y):\n subplots.append(view)\n\n if data.frame.empty and data.frames:\n out_df = data.frames[(x, y)].copy()\n elif not pair_variables:\n out_df = data.frame.copy()\n else:\n if data.frame.empty and data.frames:\n out_df = data.frames[(x, y)].copy()\n else:\n out_df = data.frame.copy()\n\n scales = self._scales.copy()\n if x in out_df:\n scales[\"x\"] = self._scales[x]\n if y in out_df:\n scales[\"y\"] = self._scales[y]\n\n for axis, var in zip(\"xy\", (x, y)):\n if axis != var:\n out_df = out_df.rename(columns={var: axis})\n cols = [col for col in out_df if re.match(rf\"{axis}\\d+\", str(col))]\n out_df = out_df.drop(cols, axis=1)\n\n yield subplots, out_df, scales\n\n def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index:\n\n dims = df.columns.intersection([\"col\", \"row\"])\n if dims.empty:\n return df.index\n\n keep_rows = pd.Series(True, df.index, dtype=bool)\n for dim in dims:\n keep_rows &= df[dim] == subplot[dim]\n return df.index[keep_rows]\n\n def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame:\n # TODO note redundancies with preceding function ... needs refactoring\n dims = df.columns.intersection([\"col\", \"row\"])\n if dims.empty:\n return df\n\n keep_rows = pd.Series(True, df.index, dtype=bool)\n for dim in dims:\n keep_rows &= df[dim] == subplot[dim]\n return df[keep_rows]\n\n def _setup_split_generator(\n self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]],\n ) -> Callable[[], Generator]:\n\n allow_empty = False # TODO will need to recreate previous categorical plots\n\n grouping_keys = []\n grouping_vars = [\n v for v in grouping_vars if v in df and v not in [\"col\", \"row\"]\n ]\n for var in grouping_vars:\n order = getattr(self._scales[var], \"order\", None)\n if order is None:\n order = categorical_order(df[var])\n grouping_keys.append(order)\n\n def split_generator(keep_na=False) -> Generator:\n\n for view in subplots:\n\n axes_df = self._filter_subplot_data(df, view)\n\n with pd.option_context(\"mode.use_inf_as_null\", True):\n if keep_na:\n # The simpler thing to do would be x.dropna().reindex(x.index).\n # But that doesn't work with the way that the subset iteration\n # is written below, which assumes data for grouping vars.\n # Matplotlib (usually?) masks nan data, so this should \"work\".\n # Downstream code can also drop these rows, at some speed cost.\n present = axes_df.notna().all(axis=1)\n nulled = {}\n for axis in \"xy\":\n if axis in axes_df:\n nulled[axis] = axes_df[axis].where(present)\n axes_df = axes_df.assign(**nulled)\n else:\n axes_df = axes_df.dropna()\n\n subplot_keys = {}\n for dim in [\"col\", \"row\"]:\n if view[dim] is not None:\n subplot_keys[dim] = view[dim]\n\n if not grouping_vars or not any(grouping_keys):\n yield subplot_keys, axes_df.copy(), view[\"ax\"]\n continue\n\n grouped_df = axes_df.groupby(grouping_vars, sort=False, as_index=False)\n\n for key in itertools.product(*grouping_keys):\n\n # Pandas fails with singleton tuple inputs\n pd_key = key[0] if len(key) == 1 else key\n\n try:\n df_subset = grouped_df.get_group(pd_key)\n except KeyError:\n # TODO (from initial work on categorical plots refactor)\n # We are adding this to allow backwards compatability\n # with the empty artists that old categorical plots would\n # add (before 0.12), which we may decide to break, in which\n # case this option could be removed\n df_subset = axes_df.loc[[]]\n\n if df_subset.empty and not allow_empty:\n continue\n\n sub_vars = dict(zip(grouping_vars, key))\n sub_vars.update(subplot_keys)\n\n # TODO need copy(deep=...) policy (here, above, anywhere else?)\n yield sub_vars, df_subset.copy(), view[\"ax\"]\n\n return split_generator\n\n def _update_legend_contents(\n self,\n p: Plot,\n mark: Mark,\n data: PlotData,\n scales: dict[str, Scale],\n ) -> None:\n \"\"\"Add legend artists / labels for one layer in the plot.\"\"\"\n if data.frame.empty and data.frames:\n legend_vars: list[str] = []\n for frame in data.frames.values():\n frame_vars = frame.columns.intersection(list(scales))\n legend_vars.extend(v for v in frame_vars if v not in legend_vars)\n else:\n legend_vars = list(data.frame.columns.intersection(list(scales)))\n\n # First pass: Identify the values that will be shown for each variable\n schema: list[tuple[\n tuple[str, str | int], list[str], tuple[list, list[str]]\n ]] = []\n schema = []\n for var in legend_vars:\n var_legend = scales[var]._legend\n if var_legend is not None:\n values, labels = var_legend\n for (_, part_id), part_vars, _ in schema:\n if data.ids[var] == part_id:\n # Allow multiple plot semantics to represent same data variable\n part_vars.append(var)\n break\n else:\n title = self._resolve_label(p, var, data.names[var])\n entry = (title, data.ids[var]), [var], (values, labels)\n schema.append(entry)\n\n # Second pass, generate an artist corresponding to each value\n contents: list[tuple[tuple[str, str | int], Any, list[str]]] = []\n for key, variables, (values, labels) in schema:\n artists = []\n for val in values:\n artist = mark._legend_artist(variables, val, scales)\n if artist is not None:\n artists.append(artist)\n if artists:\n contents.append((key, artists, labels))\n\n self._legend_contents.extend(contents)\n\n def _make_legend(self, p: Plot) -> None:\n \"\"\"Create the legend artist(s) and add onto the figure.\"\"\"\n # Combine artists representing same information across layers\n # Input list has an entry for each distinct variable in each layer\n # Output dict has an entry for each distinct variable\n merged_contents: dict[\n tuple[str, str | int], tuple[list[Artist], list[str]],\n ] = {}\n for key, new_artists, labels in self._legend_contents:\n # Key is (name, id); we need the id to resolve variable uniqueness,\n # but will need the name in the next step to title the legend\n if key in merged_contents:\n # Copy so inplace updates don't propagate back to legend_contents\n existing_artists = merged_contents[key][0]\n for i, artist in enumerate(existing_artists):\n # Matplotlib accepts a tuple of artists and will overlay them\n if isinstance(artist, tuple):\n artist += new_artists[i],\n else:\n existing_artists[i] = artist, new_artists[i]\n else:\n merged_contents[key] = new_artists.copy(), labels\n\n # TODO explain\n loc = \"center right\" if self._pyplot else \"center left\"\n\n base_legend = None\n for (name, _), (handles, labels) in merged_contents.items():\n\n legend = mpl.legend.Legend(\n self._figure,\n handles,\n labels,\n title=name,\n loc=loc,\n bbox_to_anchor=(.98, .55),\n )\n\n if base_legend:\n # Matplotlib has no public API for this so it is a bit of a hack.\n # Ideally we'd define our own legend class with more flexibility,\n # but that is a lot of work!\n base_legend_box = base_legend.get_children()[0]\n this_legend_box = legend.get_children()[0]\n base_legend_box.get_children().extend(this_legend_box.get_children())\n else:\n base_legend = legend\n self._figure.legends.append(legend)\n\n def _finalize_figure(self, p: Plot) -> None:\n\n for sub in self._subplots:\n ax = sub[\"ax\"]\n for axis in \"xy\":\n axis_key = sub[axis]\n\n # Axis limits\n if axis_key in p._limits:\n convert_units = getattr(ax, f\"{axis}axis\").convert_units\n a, b = p._limits[axis_key]\n lo = a if a is None else convert_units(a)\n hi = b if b is None else convert_units(b)\n if isinstance(a, str):\n lo = cast(float, lo) - 0.5\n if isinstance(b, str):\n hi = cast(float, hi) + 0.5\n ax.set(**{f\"{axis}lim\": (lo, hi)})\n\n engine_default = None if p._target is not None else \"tight\"\n layout_engine = p._layout_spec.get(\"engine\", engine_default)\n set_layout_engine(self._figure, layout_engine)"},{"col":4,"comment":"null","endLoc":962,"header":"def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]","id":2281,"name":"_extract_data","nodeType":"Function","startLoc":948,"text":"def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]:\n\n common_data = (\n p._data\n .join(None, p._facet_spec.get(\"variables\"))\n .join(None, p._pair_spec.get(\"variables\"))\n )\n\n layers: list[Layer] = []\n for layer in p._layers:\n spec = layer.copy()\n spec[\"data\"] = common_data.join(layer.get(\"source\"), layer.get(\"vars\"))\n layers.append(spec)\n\n return common_data, layers"},{"col":4,"comment":"Initialize the plotter.","endLoc":1633,"header":"def __init__(self, x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth=None, capsize=None)","id":2282,"name":"__init__","nodeType":"Function","startLoc":1596,"text":"def __init__(self, x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth=None, capsize=None):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient,\n order, hue_order, units)\n self.establish_colors(color, palette, 1)\n self.estimate_statistic(estimator, errorbar, n_boot, seed)\n\n # Override the default palette for single-color plots\n if hue is None and color is None and palette is None:\n self.colors = [color_palette()[0]] * len(self.colors)\n\n # Don't join single-layer plots with different colors\n if hue is None and palette is not None:\n join = False\n\n # Use a good default for `dodge=True`\n if dodge is True and self.hue_names is not None:\n dodge = .025 * len(self.hue_names)\n\n # Make sure we have a marker for each hue level\n if isinstance(markers, str):\n markers = [markers] * len(self.colors)\n self.markers = markers\n\n # Make sure we have a line style for each hue level\n if isinstance(linestyles, str):\n linestyles = [linestyles] * len(self.colors)\n self.linestyles = linestyles\n\n # Set the other plot components\n self.dodge = dodge\n self.join = join\n self.scale = scale\n self.errwidth = errwidth\n self.capsize = capsize"},{"col":4,"comment":"null","endLoc":111,"header":"def test_artist_kws_clip(self)","id":2283,"name":"test_artist_kws_clip","nodeType":"Function","startLoc":107,"text":"def test_artist_kws_clip(self):\n\n p = Plot([\"a\", \"b\"], [1, 2]).add(Bar({\"clip_on\": False})).plot()\n patch = p._figure.axes[0].patches[0]\n assert patch.clipbox is None"},{"id":2284,"name":"doc/tools","nodeType":"Package"},{"fileName":"nb_to_doc.py","filePath":"doc/tools","id":2285,"nodeType":"File","text":"#! /usr/bin/env python\n\"\"\"Execute a .ipynb file, write out a processed .rst and clean .ipynb.\n\nSome functions in this script were copied from the nbstripout tool:\n\nCopyright (c) 2015 Min RK, Florian Rathgeber, Michael McNeil Forbes\n2019 Casper da Costa-Luis\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"\nimport os\nimport sys\nimport nbformat\nfrom nbconvert import RSTExporter\nfrom nbconvert.preprocessors import (\n ExecutePreprocessor,\n TagRemovePreprocessor,\n ExtractOutputPreprocessor\n)\nfrom traitlets.config import Config\n\n\nclass MetadataError(Exception):\n pass\n\n\ndef pop_recursive(d, key, default=None):\n \"\"\"dict.pop(key) where `key` is a `.`-delimited list of nested keys.\n >>> d = {'a': {'b': 1, 'c': 2}}\n >>> pop_recursive(d, 'a.c')\n 2\n >>> d\n {'a': {'b': 1}}\n \"\"\"\n nested = key.split('.')\n current = d\n for k in nested[:-1]:\n if hasattr(current, 'get'):\n current = current.get(k, {})\n else:\n return default\n if not hasattr(current, 'pop'):\n return default\n return current.pop(nested[-1], default)\n\n\ndef strip_output(nb):\n \"\"\"\n Strip the outputs, execution count/prompt number and miscellaneous\n metadata from a notebook object, unless specified to keep either the\n outputs or counts.\n \"\"\"\n keys = {'metadata': [], 'cell': {'metadata': [\"execution\"]}}\n\n nb.metadata.pop('signature', None)\n nb.metadata.pop('widgets', None)\n\n for field in keys['metadata']:\n pop_recursive(nb.metadata, field)\n\n if 'NB_KERNEL' in os.environ:\n nb.metadata['kernelspec']['name'] = os.environ['NB_KERNEL']\n nb.metadata['kernelspec']['display_name'] = os.environ['NB_KERNEL']\n\n for cell in nb.cells:\n\n if 'outputs' in cell:\n cell['outputs'] = []\n if 'prompt_number' in cell:\n cell['prompt_number'] = None\n if 'execution_count' in cell:\n cell['execution_count'] = None\n\n # Always remove this metadata\n for output_style in ['collapsed', 'scrolled']:\n if output_style in cell.metadata:\n cell.metadata[output_style] = False\n if 'metadata' in cell:\n for field in ['collapsed', 'scrolled', 'ExecuteTime']:\n cell.metadata.pop(field, None)\n for (extra, fields) in keys['cell'].items():\n if extra in cell:\n for field in fields:\n pop_recursive(getattr(cell, extra), field)\n return nb\n\n\nif __name__ == \"__main__\":\n\n # Get the desired ipynb file path and parse into components\n _, fpath, outdir = sys.argv\n basedir, fname = os.path.split(fpath)\n fstem = fname[:-6]\n\n # Read the notebook\n with open(fpath) as f:\n nb = nbformat.read(f, as_version=4)\n\n # Run the notebook\n kernel = os.environ.get(\"NB_KERNEL\", None)\n if kernel is None:\n kernel = nb[\"metadata\"][\"kernelspec\"][\"name\"]\n ep = ExecutePreprocessor(\n timeout=600,\n kernel_name=kernel,\n extra_arguments=[\"--InlineBackend.rc=figure.dpi=88\"]\n )\n ep.preprocess(nb, {\"metadata\": {\"path\": basedir}})\n\n # Remove plain text execution result outputs\n for cell in nb.get(\"cells\", {}):\n if \"show-output\" in cell[\"metadata\"].get(\"tags\", []):\n continue\n fields = cell.get(\"outputs\", [])\n for field in fields:\n if field[\"output_type\"] == \"execute_result\":\n data_keys = field[\"data\"].keys()\n for key in list(data_keys):\n if key == \"text/plain\":\n field[\"data\"].pop(key)\n if not field[\"data\"]:\n fields.remove(field)\n\n # Convert to .rst formats\n exp = RSTExporter()\n\n c = Config()\n c.TagRemovePreprocessor.remove_cell_tags = {\"hide\"}\n c.TagRemovePreprocessor.remove_input_tags = {\"hide-input\"}\n c.TagRemovePreprocessor.remove_all_outputs_tags = {\"hide-output\"}\n c.ExtractOutputPreprocessor.output_filename_template = \\\n f\"{fstem}_files/{fstem}_\" + \"{cell_index}_{index}{extension}\"\n\n exp.register_preprocessor(TagRemovePreprocessor(config=c), True)\n exp.register_preprocessor(ExtractOutputPreprocessor(config=c), True)\n\n body, resources = exp.from_notebook_node(nb)\n\n # Clean the output on the notebook and save a .ipynb back to disk\n nb = strip_output(nb)\n with open(fpath, \"wt\") as f:\n nbformat.write(nb, f)\n\n # Write the .rst file\n rst_path = os.path.join(outdir, f\"{fstem}.rst\")\n with open(rst_path, \"w\") as f:\n f.write(body)\n\n # Write the individual image outputs\n imdir = os.path.join(outdir, f\"{fstem}_files\")\n if not os.path.exists(imdir):\n os.mkdir(imdir)\n\n for imname, imdata in resources[\"outputs\"].items():\n if imname.startswith(fstem):\n impath = os.path.join(outdir, f\"{imname}\")\n with open(impath, \"wb\") as f:\n f.write(imdata)\n"},{"col":0,"comment":"null","endLoc":271,"header":"def objects_interface()","id":2286,"name":"objects_interface","nodeType":"Function","startLoc":246,"text":"def objects_interface():\n\n f = mpl.figure.Figure(figsize=(5, 4))\n C = sns.color_palette(\"deep\")\n ax = f.subplots()\n fontsize = 22\n rects = [((.135, .50), .69), ((.275, .38), .26), ((.59, .38), .40)]\n for i, (xy, w) in enumerate(rects):\n ax.add_artist(mpl.patches.Rectangle(xy, w, .09, color=C[i], alpha=.2, lw=0))\n ax.text(0, .52, \"Plot(data, 'x', 'y', color='var1')\", size=fontsize, color=\".2\")\n ax.text(0, .40, \".add(Dot(alpha=.5), marker='var2')\", size=fontsize, color=\".2\")\n annots = [\n (\"Mapped\\nin all layers\", (.48, .62), (0, 55)),\n (\"Set directly\", (.41, .35), (0, -55)),\n (\"Mapped\\nin this layer\", (.80, .35), (0, -55)),\n ]\n for i, (text, xy, xytext) in enumerate(annots):\n ax.annotate(\n text, xy, xytext,\n textcoords=\"offset points\", fontsize=18, ha=\"center\", va=\"center\",\n arrowprops=dict(arrowstyle=\"->\", linewidth=1.5, color=C[i]), color=C[i],\n )\n ax.set_axis_off()\n f.subplots_adjust(0, 0, 1, 1)\n\n return f"},{"className":"TestBars","col":0,"comment":"null","endLoc":202,"id":2287,"nodeType":"Class","startLoc":114,"text":"class TestBars:\n\n @pytest.fixture\n def x(self):\n return pd.Series([4, 5, 6, 7, 8], name=\"x\")\n\n @pytest.fixture\n def y(self):\n return pd.Series([2, 8, 3, 5, 9], name=\"y\")\n\n @pytest.fixture\n def color(self):\n return pd.Series([\"a\", \"b\", \"c\", \"a\", \"c\"], name=\"color\")\n\n def test_positions(self, x, y):\n\n p = Plot(x, y).add(Bars()).plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n assert len(paths) == len(x)\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 0] == pytest.approx(x[i] - .5)\n assert verts[1, 0] == pytest.approx(x[i] + .5)\n assert verts[0, 1] == 0\n assert verts[3, 1] == y[i]\n\n def test_positions_horizontal(self, x, y):\n\n p = Plot(x=y, y=x).add(Bars(), orient=\"h\").plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n assert len(paths) == len(x)\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 1] == pytest.approx(x[i] - .5)\n assert verts[3, 1] == pytest.approx(x[i] + .5)\n assert verts[0, 0] == 0\n assert verts[1, 0] == y[i]\n\n def test_width(self, x, y):\n\n p = Plot(x, y).add(Bars(width=.4)).plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 0] == pytest.approx(x[i] - .2)\n assert verts[1, 0] == pytest.approx(x[i] + .2)\n\n def test_mapped_color_direct_alpha(self, x, y, color):\n\n alpha = .5\n p = Plot(x, y, color=color).add(Bars(alpha=alpha)).plot()\n ax = p._figure.axes[0]\n fcs = ax.collections[0].get_facecolors()\n C0, C1, C2, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n expected = to_rgba_array([C0, C1, C2, C0, C2], alpha)\n assert_array_equal(fcs, expected)\n\n def test_mapped_edgewidth(self, x, y):\n\n p = Plot(x, y, edgewidth=y).add(Bars()).plot()\n ax = p._figure.axes[0]\n lws = ax.collections[0].get_linewidths()\n assert_array_equal(np.argsort(lws), np.argsort(y))\n\n def test_auto_edgewidth(self):\n\n x0 = np.arange(10)\n x1 = np.arange(1000)\n\n p0 = Plot(x0, x0).add(Bars()).plot()\n p1 = Plot(x1, x1).add(Bars()).plot()\n\n lw0 = p0._figure.axes[0].collections[0].get_linewidths()\n lw1 = p1._figure.axes[0].collections[0].get_linewidths()\n\n assert (lw0 > lw1).all()\n\n def test_unfilled(self, x, y):\n\n p = Plot(x, y).add(Bars(fill=False, edgecolor=\"C4\")).plot()\n ax = p._figure.axes[0]\n fcs = ax.collections[0].get_facecolors()\n ecs = ax.collections[0].get_edgecolors()\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n assert_array_equal(fcs, to_rgba_array([colors[0]] * len(x), 0))\n assert_array_equal(ecs, to_rgba_array([colors[4]] * len(x), 1))"},{"col":4,"comment":"null","endLoc":118,"header":"@pytest.fixture\n def x(self)","id":2288,"name":"x","nodeType":"Function","startLoc":116,"text":"@pytest.fixture\n def x(self):\n return pd.Series([4, 5, 6, 7, 8], name=\"x\")"},{"col":4,"comment":"null","endLoc":122,"header":"@pytest.fixture\n def y(self)","id":2289,"name":"y","nodeType":"Function","startLoc":120,"text":"@pytest.fixture\n def y(self):\n return pd.Series([2, 8, 3, 5, 9], name=\"y\")"},{"col":4,"comment":"null","endLoc":126,"header":"@pytest.fixture\n def color(self)","id":2290,"name":"color","nodeType":"Function","startLoc":124,"text":"@pytest.fixture\n def color(self):\n return pd.Series([\"a\", \"b\", \"c\", \"a\", \"c\"], name=\"color\")"},{"col":4,"comment":"null","endLoc":139,"header":"def test_positions(self, x, y)","id":2291,"name":"test_positions","nodeType":"Function","startLoc":128,"text":"def test_positions(self, x, y):\n\n p = Plot(x, y).add(Bars()).plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n assert len(paths) == len(x)\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 0] == pytest.approx(x[i] - .5)\n assert verts[1, 0] == pytest.approx(x[i] + .5)\n assert verts[0, 1] == 0\n assert verts[3, 1] == y[i]"},{"className":"TestFacetGrid","col":0,"comment":"null","endLoc":710,"id":2292,"nodeType":"Class","startLoc":29,"text":"class TestFacetGrid:\n\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n y=rs.gamma(4, size=60),\n a=np.repeat(list(\"abc\"), 20),\n b=np.tile(list(\"mn\"), 30),\n c=np.tile(list(\"tuv\"), 20),\n d=np.tile(list(\"abcdefghijkl\"), 5)))\n\n def test_self_data(self):\n\n g = ag.FacetGrid(self.df)\n assert g.data is self.df\n\n def test_self_figure(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.figure, plt.Figure)\n assert g.figure is g._figure\n\n def test_self_axes(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)\n\n def test_axes_array_size(self):\n\n g = ag.FacetGrid(self.df)\n assert g.axes.shape == (1, 1)\n\n g = ag.FacetGrid(self.df, row=\"a\")\n assert g.axes.shape == (3, 1)\n\n g = ag.FacetGrid(self.df, col=\"b\")\n assert g.axes.shape == (1, 2)\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n assert g.axes.shape == (1, 1)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n assert g.axes.shape == (3, 2)\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)\n\n def test_single_axes(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.ax, plt.Axes)\n\n g = ag.FacetGrid(self.df, row=\"a\")\n with pytest.raises(AttributeError):\n g.ax\n\n g = ag.FacetGrid(self.df, col=\"a\")\n with pytest.raises(AttributeError):\n g.ax\n\n g = ag.FacetGrid(self.df, col=\"a\", row=\"b\")\n with pytest.raises(AttributeError):\n g.ax\n\n def test_col_wrap(self):\n\n n = len(self.df.d.unique())\n\n g = ag.FacetGrid(self.df, col=\"d\")\n assert g.axes.shape == (1, n)\n assert g.facet_axis(0, 8) is g.axes[0, 8]\n\n g_wrap = ag.FacetGrid(self.df, col=\"d\", col_wrap=4)\n assert g_wrap.axes.shape == (n,)\n assert g_wrap.facet_axis(0, 8) is g_wrap.axes[8]\n assert g_wrap._ncol == 4\n assert g_wrap._nrow == (n / 4)\n\n with pytest.raises(ValueError):\n g = ag.FacetGrid(self.df, row=\"b\", col=\"d\", col_wrap=4)\n\n df = self.df.copy()\n df.loc[df.d == \"j\"] = np.nan\n g_missing = ag.FacetGrid(df, col=\"d\")\n assert g_missing.axes.shape == (1, n - 1)\n\n g_missing_wrap = ag.FacetGrid(df, col=\"d\", col_wrap=4)\n assert g_missing_wrap.axes.shape == (n - 1,)\n\n g = ag.FacetGrid(self.df, col=\"d\", col_wrap=1)\n assert len(list(g.facet_data())) == n\n\n def test_normal_axes(self):\n\n null = np.empty(0, object).flat\n\n g = ag.FacetGrid(self.df)\n npt.assert_array_equal(g._bottom_axes, g.axes.flat)\n npt.assert_array_equal(g._not_bottom_axes, null)\n npt.assert_array_equal(g._left_axes, g.axes.flat)\n npt.assert_array_equal(g._not_left_axes, null)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, col=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes.flat)\n npt.assert_array_equal(g._not_bottom_axes, null)\n npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, row=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)\n npt.assert_array_equal(g._left_axes, g.axes.flat)\n npt.assert_array_equal(g._not_left_axes, null)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, col=\"a\", row=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)\n npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)\n npt.assert_array_equal(g._inner_axes, g.axes[:-1, 1:].flat)\n\n def test_wrapped_axes(self):\n\n null = np.empty(0, object).flat\n\n g = ag.FacetGrid(self.df, col=\"a\", col_wrap=2)\n npt.assert_array_equal(g._bottom_axes,\n g.axes[np.array([1, 2])].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:1].flat)\n npt.assert_array_equal(g._left_axes, g.axes[np.array([0, 2])].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[np.array([1])].flat)\n npt.assert_array_equal(g._inner_axes, null)\n\n def test_axes_dict(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.axes_dict, dict)\n assert not g.axes_dict\n\n g = ag.FacetGrid(self.df, row=\"c\")\n assert list(g.axes_dict.keys()) == g.row_names\n for (name, ax) in zip(g.row_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, col=\"c\")\n assert list(g.axes_dict.keys()) == g.col_names\n for (name, ax) in zip(g.col_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, col=\"a\", col_wrap=2)\n assert list(g.axes_dict.keys()) == g.col_names\n for (name, ax) in zip(g.col_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"c\")\n for (row_var, col_var), ax in g.axes_dict.items():\n i = g.row_names.index(row_var)\n j = g.col_names.index(col_var)\n assert g.axes[i, j] is ax\n\n def test_figure_size(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 9))\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", height=6)\n npt.assert_array_equal(g.figure.get_size_inches(), (12, 18))\n\n g = ag.FacetGrid(self.df, col=\"c\", height=4, aspect=.5)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n\n def test_figure_size_with_legend(self):\n\n g = ag.FacetGrid(self.df, col=\"a\", hue=\"c\", height=4, aspect=.5)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n g.add_legend()\n assert g.figure.get_size_inches()[0] > 6\n\n g = ag.FacetGrid(self.df, col=\"a\", hue=\"c\", height=4, aspect=.5,\n legend_out=False)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n g.add_legend()\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n\n def test_legend_data(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n palette = color_palette(n_colors=3)\n\n assert g._legend.get_title().get_text() == \"a\"\n\n a_levels = sorted(self.df.a.unique())\n\n lines = g._legend.get_lines()\n assert len(lines) == len(a_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == len(a_levels)\n\n for label, level in zip(labels, a_levels):\n assert label.get_text() == level\n\n def test_legend_data_missing_level(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\", hue_order=list(\"azbc\"))\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n\n c1, c2, c3, c4 = color_palette(n_colors=4)\n palette = [c1, c3, c4]\n\n assert g._legend.get_title().get_text() == \"a\"\n\n a_levels = sorted(self.df.a.unique())\n\n lines = g._legend.get_lines()\n assert len(lines) == len(a_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == 4\n\n for label, level in zip(labels, list(\"azbc\")):\n assert label.get_text() == level\n\n def test_get_boolean_legend_data(self):\n\n self.df[\"b_bool\"] = self.df.b == \"m\"\n g = ag.FacetGrid(self.df, hue=\"b_bool\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n palette = color_palette(n_colors=2)\n\n assert g._legend.get_title().get_text() == \"b_bool\"\n\n b_levels = list(map(str, categorical_order(self.df.b_bool)))\n\n lines = g._legend.get_lines()\n assert len(lines) == len(b_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == len(b_levels)\n\n for label, level in zip(labels, b_levels):\n assert label.get_text() == level\n\n def test_legend_tuples(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\")\n g.map(plt.plot, \"x\", \"y\")\n\n handles, labels = g.ax.get_legend_handles_labels()\n label_tuples = [(\"\", l) for l in labels]\n legend_data = dict(zip(label_tuples, handles))\n g.add_legend(legend_data, label_tuples)\n for entry, label in zip(g._legend.get_texts(), labels):\n assert entry.get_text() == label\n\n def test_legend_options(self):\n\n g = ag.FacetGrid(self.df, hue=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n\n g1 = ag.FacetGrid(self.df, hue=\"b\", legend_out=False)\n g1.add_legend(adjust_subtitles=True)\n\n g1 = ag.FacetGrid(self.df, hue=\"b\", legend_out=False)\n g1.add_legend(adjust_subtitles=False)\n\n def test_legendout_with_colwrap(self):\n\n g = ag.FacetGrid(self.df, col=\"d\", hue='b',\n col_wrap=4, legend_out=False)\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n g.add_legend()\n\n def test_legend_tight_layout(self):\n\n g = ag.FacetGrid(self.df, hue='b')\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n g.add_legend()\n g.tight_layout()\n\n axes_right_edge = g.ax.get_window_extent().xmax\n legend_left_edge = g._legend.get_window_extent().xmin\n\n assert axes_right_edge < legend_left_edge\n\n def test_subplot_kws(self):\n\n g = ag.FacetGrid(self.df, despine=False,\n subplot_kws=dict(projection=\"polar\"))\n for ax in g.axes.flat:\n assert \"PolarAxesSubplot\" in str(type(ax))\n\n def test_gridspec_kws(self):\n ratios = [3, 1, 2]\n\n gskws = dict(width_ratios=ratios)\n g = ag.FacetGrid(self.df, col='c', row='a', gridspec_kws=gskws)\n\n for ax in g.axes.flat:\n ax.set_xticks([])\n ax.set_yticks([])\n\n g.figure.tight_layout()\n\n for (l, m, r) in g.axes:\n assert l.get_position().width > m.get_position().width\n assert r.get_position().width > m.get_position().width\n\n def test_gridspec_kws_col_wrap(self):\n ratios = [3, 1, 2, 1, 1]\n\n gskws = dict(width_ratios=ratios)\n with pytest.warns(UserWarning):\n ag.FacetGrid(self.df, col='d', col_wrap=5, gridspec_kws=gskws)\n\n def test_data_generator(self):\n\n g = ag.FacetGrid(self.df, row=\"a\")\n d = list(g.facet_data())\n assert len(d) == 3\n\n tup, data = d[0]\n assert tup == (0, 0, 0)\n assert (data[\"a\"] == \"a\").all()\n\n tup, data = d[1]\n assert tup == (1, 0, 0)\n assert (data[\"a\"] == \"b\").all()\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n d = list(g.facet_data())\n assert len(d) == 6\n\n tup, data = d[0]\n assert tup == (0, 0, 0)\n assert (data[\"a\"] == \"a\").all()\n assert (data[\"b\"] == \"m\").all()\n\n tup, data = d[1]\n assert tup == (0, 1, 0)\n assert (data[\"a\"] == \"a\").all()\n assert (data[\"b\"] == \"n\").all()\n\n tup, data = d[2]\n assert tup == (1, 0, 0)\n assert (data[\"a\"] == \"b\").all()\n assert (data[\"b\"] == \"m\").all()\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n d = list(g.facet_data())\n assert len(d) == 3\n tup, data = d[1]\n assert tup == (0, 0, 1)\n assert (data[\"c\"] == \"u\").all()\n\n def test_map(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n\n lines = g.axes[0, 0].lines\n assert len(lines) == 3\n\n line1, _, _ = lines\n assert line1.get_linewidth() == 3\n x, y = line1.get_data()\n mask = (self.df.a == \"a\") & (self.df.b == \"m\") & (self.df.c == \"t\")\n npt.assert_array_equal(x, self.df.x[mask])\n npt.assert_array_equal(y, self.df.y[mask])\n\n def test_map_dataframe(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n\n def plot(x, y, data=None, **kws):\n plt.plot(data[x], data[y], **kws)\n # Modify __module__ so this doesn't look like a seaborn function\n plot.__module__ = \"test\"\n\n g.map_dataframe(plot, \"x\", \"y\", linestyle=\"--\")\n\n lines = g.axes[0, 0].lines\n assert len(g.axes[0, 0].lines) == 3\n\n line1, _, _ = lines\n assert line1.get_linestyle() == \"--\"\n x, y = line1.get_data()\n mask = (self.df.a == \"a\") & (self.df.b == \"m\") & (self.df.c == \"t\")\n npt.assert_array_equal(x, self.df.x[mask])\n npt.assert_array_equal(y, self.df.y[mask])\n\n def test_set(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n xlim = (-2, 5)\n ylim = (3, 6)\n xticks = [-2, 0, 3, 5]\n yticks = [3, 4.5, 6]\n g.set(xlim=xlim, ylim=ylim, xticks=xticks, yticks=yticks)\n for ax in g.axes.flat:\n npt.assert_array_equal(ax.get_xlim(), xlim)\n npt.assert_array_equal(ax.get_ylim(), ylim)\n npt.assert_array_equal(ax.get_xticks(), xticks)\n npt.assert_array_equal(ax.get_yticks(), yticks)\n\n def test_set_titles(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"a = a | b = m\"\n assert g.axes[0, 1].get_title() == \"a = a | b = n\"\n assert g.axes[1, 0].get_title() == \"a = b | b = m\"\n\n # Test a provided title\n g.set_titles(\"{row_var} == {row_name} \\\\/ {col_var} == {col_name}\")\n assert g.axes[0, 0].get_title() == \"a == a \\\\/ b == m\"\n assert g.axes[0, 1].get_title() == \"a == a \\\\/ b == n\"\n assert g.axes[1, 0].get_title() == \"a == b \\\\/ b == m\"\n\n # Test a single row\n g = ag.FacetGrid(self.df, col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"b = m\"\n assert g.axes[0, 1].get_title() == \"b = n\"\n\n # test with dropna=False\n g = ag.FacetGrid(self.df, col=\"b\", hue=\"b\", dropna=False)\n g.map(plt.plot, 'x', 'y')\n\n def test_set_titles_margin_titles(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", margin_titles=True)\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"b = m\"\n assert g.axes[0, 1].get_title() == \"b = n\"\n assert g.axes[1, 0].get_title() == \"\"\n\n # Test the row \"titles\"\n assert g.axes[0, 1].texts[0].get_text() == \"a = a\"\n assert g.axes[1, 1].texts[0].get_text() == \"a = b\"\n assert g.axes[0, 1].texts[0] is g._margin_titles_texts[0]\n\n # Test provided titles\n g.set_titles(col_template=\"{col_name}\", row_template=\"{row_name}\")\n assert g.axes[0, 0].get_title() == \"m\"\n assert g.axes[0, 1].get_title() == \"n\"\n assert g.axes[1, 0].get_title() == \"\"\n\n assert len(g.axes[1, 1].texts) == 1\n assert g.axes[1, 1].texts[0].get_text() == \"b\"\n\n def test_set_ticklabels(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n ax = g.axes[-1, 0]\n xlab = [l.get_text() + \"h\" for l in ax.get_xticklabels()]\n ylab = [l.get_text() + \"i\" for l in ax.get_yticklabels()]\n\n g.set_xticklabels(xlab)\n g.set_yticklabels(ylab)\n got_x = [l.get_text() for l in g.axes[-1, 1].get_xticklabels()]\n got_y = [l.get_text() for l in g.axes[0, 0].get_yticklabels()]\n npt.assert_array_equal(got_x, xlab)\n npt.assert_array_equal(got_y, ylab)\n\n x, y = np.arange(10), np.arange(10)\n df = pd.DataFrame(np.c_[x, y], columns=[\"x\", \"y\"])\n g = ag.FacetGrid(df).map_dataframe(pointplot, x=\"x\", y=\"y\", order=x)\n g.set_xticklabels(step=2)\n got_x = [int(l.get_text()) for l in g.axes[0, 0].get_xticklabels()]\n npt.assert_array_equal(x[::2], got_x)\n\n g = ag.FacetGrid(self.df, col=\"d\", col_wrap=5)\n g.map(plt.plot, \"x\", \"y\")\n g.set_xticklabels(rotation=45)\n g.set_yticklabels(rotation=75)\n for ax in g._bottom_axes:\n for l in ax.get_xticklabels():\n assert l.get_rotation() == 45\n for ax in g._left_axes:\n for l in ax.get_yticklabels():\n assert l.get_rotation() == 75\n\n def test_set_axis_labels(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n xlab = 'xx'\n ylab = 'yy'\n\n g.set_axis_labels(xlab, ylab)\n\n got_x = [ax.get_xlabel() for ax in g.axes[-1, :]]\n got_y = [ax.get_ylabel() for ax in g.axes[:, 0]]\n npt.assert_array_equal(got_x, xlab)\n npt.assert_array_equal(got_y, ylab)\n\n for ax in g.axes.flat:\n ax.set(xlabel=\"x\", ylabel=\"y\")\n\n g.set_axis_labels(xlab, ylab)\n for ax in g._not_bottom_axes:\n assert not ax.get_xlabel()\n for ax in g._not_left_axes:\n assert not ax.get_ylabel()\n\n def test_axis_lims(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", xlim=(0, 4), ylim=(-2, 3))\n assert g.axes[0, 0].get_xlim() == (0, 4)\n assert g.axes[0, 0].get_ylim() == (-2, 3)\n\n def test_data_orders(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n\n assert g.row_names == list(\"abc\")\n assert g.col_names == list(\"mn\")\n assert g.hue_names == list(\"tuv\")\n assert g.axes.shape == (3, 2)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\",\n row_order=list(\"bca\"),\n col_order=list(\"nm\"),\n hue_order=list(\"vtu\"))\n\n assert g.row_names == list(\"bca\")\n assert g.col_names == list(\"nm\")\n assert g.hue_names == list(\"vtu\")\n assert g.axes.shape == (3, 2)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\",\n row_order=list(\"bcda\"),\n col_order=list(\"nom\"),\n hue_order=list(\"qvtu\"))\n\n assert g.row_names == list(\"bcda\")\n assert g.col_names == list(\"nom\")\n assert g.hue_names == list(\"qvtu\")\n assert g.axes.shape == (4, 3)\n\n def test_palette(self):\n\n rcmod.set()\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n assert g._colors == color_palette(n_colors=len(self.df.c.unique()))\n\n g = ag.FacetGrid(self.df, hue=\"d\")\n assert g._colors == color_palette(\"husl\", len(self.df.d.unique()))\n\n g = ag.FacetGrid(self.df, hue=\"c\", palette=\"Set2\")\n assert g._colors == color_palette(\"Set2\", len(self.df.c.unique()))\n\n dict_pal = dict(t=\"red\", u=\"green\", v=\"blue\")\n list_pal = color_palette([\"red\", \"green\", \"blue\"], 3)\n g = ag.FacetGrid(self.df, hue=\"c\", palette=dict_pal)\n assert g._colors == list_pal\n\n list_pal = color_palette([\"green\", \"blue\", \"red\"], 3)\n g = ag.FacetGrid(self.df, hue=\"c\", hue_order=list(\"uvt\"),\n palette=dict_pal)\n assert g._colors == list_pal\n\n def test_hue_kws(self):\n\n kws = dict(marker=[\"o\", \"s\", \"D\"])\n g = ag.FacetGrid(self.df, hue=\"c\", hue_kws=kws)\n g.map(plt.plot, \"x\", \"y\")\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker\n\n def test_dropna(self):\n\n df = self.df.copy()\n hasna = pd.Series(np.tile(np.arange(6), 10), dtype=float)\n hasna[hasna == 5] = np.nan\n df[\"hasna\"] = hasna\n g = ag.FacetGrid(df, dropna=False, row=\"hasna\")\n assert g._not_na.sum() == 60\n\n g = ag.FacetGrid(df, dropna=True, row=\"hasna\")\n assert g._not_na.sum() == 50\n\n def test_categorical_column_missing_categories(self):\n\n df = self.df.copy()\n df['a'] = df['a'].astype('category')\n\n g = ag.FacetGrid(df[df['a'] == 'a'], col=\"a\", col_wrap=1)\n\n assert g.axes.shape == (len(df['a'].cat.categories),)\n\n def test_categorical_warning(self):\n\n g = ag.FacetGrid(self.df, col=\"b\")\n with pytest.warns(UserWarning):\n g.map(pointplot, \"b\", \"x\")\n\n def test_refline(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.refline()\n for ax in g.axes.flat:\n assert not ax.lines\n\n refx = refy = 0.5\n hline = np.array([[0, refy], [1, refy]])\n vline = np.array([[refx, 0], [refx, 1]])\n g.refline(x=refx, y=refy)\n for ax in g.axes.flat:\n assert ax.lines[0].get_color() == '.5'\n assert ax.lines[0].get_linestyle() == '--'\n assert len(ax.lines) == 2\n npt.assert_array_equal(ax.lines[0].get_xydata(), vline)\n npt.assert_array_equal(ax.lines[1].get_xydata(), hline)\n\n color, linestyle = 'red', '-'\n g.refline(x=refx, color=color, linestyle=linestyle)\n npt.assert_array_equal(g.axes[0, 0].lines[-1].get_xydata(), vline)\n assert g.axes[0, 0].lines[-1].get_color() == color\n assert g.axes[0, 0].lines[-1].get_linestyle() == linestyle\n\n def test_apply(self, long_df):\n\n def f(grid, color):\n grid.figure.set_facecolor(color)\n\n color = (.1, .6, .3, .9)\n g = ag.FacetGrid(long_df)\n res = g.apply(f, color)\n assert res is g\n assert g.figure.get_facecolor() == color\n\n def test_pipe(self, long_df):\n\n def f(grid, color):\n grid.figure.set_facecolor(color)\n return color\n\n color = (.1, .6, .3, .9)\n g = ag.FacetGrid(long_df)\n res = g.pipe(f, color)\n assert res == color\n assert g.figure.get_facecolor() == color\n\n def test_tick_params(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n color = \"blue\"\n pad = 3\n g.tick_params(pad=pad, color=color)\n for ax in g.axes.flat:\n for axis in [\"xaxis\", \"yaxis\"]:\n for tick in getattr(ax, axis).get_major_ticks():\n assert mpl.colors.same_color(tick.tick1line.get_color(), color)\n assert mpl.colors.same_color(tick.tick2line.get_color(), color)\n assert tick.get_pad() == pad"},{"col":4,"comment":"null","endLoc":41,"header":"def test_self_data(self)","id":2293,"name":"test_self_data","nodeType":"Function","startLoc":38,"text":"def test_self_data(self):\n\n g = ag.FacetGrid(self.df)\n assert g.data is self.df"},{"col":4,"comment":"null","endLoc":152,"header":"def test_positions_horizontal(self, x, y)","id":2294,"name":"test_positions_horizontal","nodeType":"Function","startLoc":141,"text":"def test_positions_horizontal(self, x, y):\n\n p = Plot(x=y, y=x).add(Bars(), orient=\"h\").plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n assert len(paths) == len(x)\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 1] == pytest.approx(x[i] - .5)\n assert verts[3, 1] == pytest.approx(x[i] + .5)\n assert verts[0, 0] == 0\n assert verts[1, 0] == y[i]"},{"col":4,"comment":"null","endLoc":47,"header":"def test_self_figure(self)","id":2295,"name":"test_self_figure","nodeType":"Function","startLoc":43,"text":"def test_self_figure(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.figure, plt.Figure)\n assert g.figure is g._figure"},{"col":0,"comment":"null","endLoc":284,"header":"def relational()","id":2296,"name":"relational","nodeType":"Function","startLoc":274,"text":"def relational():\n\n mpg = sns.load_dataset(\"mpg\")\n with sns.axes_style(\"ticks\"):\n g = sns.relplot(\n data=mpg, x=\"horsepower\", y=\"mpg\", size=\"displacement\", hue=\"weight\",\n sizes=(50, 500), hue_norm=(2000, 4500), alpha=.75, legend=False,\n palette=\"ch:start=-.5,rot=.7,dark=.3,light=.7_r\",\n )\n g.figure.set_size_inches(5, 5)\n return g.figure"},{"col":0,"comment":"null","endLoc":297,"header":"def distributions()","id":2297,"name":"distributions","nodeType":"Function","startLoc":287,"text":"def distributions():\n\n penguins = sns.load_dataset(\"penguins\").dropna()\n with sns.axes_style(\"white\"):\n g = sns.displot(\n penguins, x=\"flipper_length_mm\", row=\"island\",\n binwidth=4, kde=True, line_kws=dict(linewidth=2), legend=False,\n )\n sns.despine(left=True)\n g.figure.set_size_inches(5, 5)\n return g.figure"},{"col":4,"comment":"null","endLoc":53,"header":"def test_self_axes(self)","id":2298,"name":"test_self_axes","nodeType":"Function","startLoc":49,"text":"def test_self_axes(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)"},{"className":"MetadataError","col":0,"comment":"null","endLoc":42,"id":2299,"nodeType":"Class","startLoc":41,"text":"class MetadataError(Exception):\n pass"},{"col":4,"comment":"null","endLoc":162,"header":"def test_width(self, x, y)","id":2300,"name":"test_width","nodeType":"Function","startLoc":154,"text":"def test_width(self, x, y):\n\n p = Plot(x, y).add(Bars(width=.4)).plot()\n ax = p._figure.axes[0]\n paths = ax.collections[0].get_paths()\n for i, path in enumerate(paths):\n verts = path.vertices\n assert verts[0, 0] == pytest.approx(x[i] - .2)\n assert verts[1, 0] == pytest.approx(x[i] + .2)"},{"className":"Exception","col":0,"comment":"null","endLoc":1947,"id":2301,"nodeType":"Class","startLoc":1947,"text":"class Exception(BaseException): ..."},{"col":4,"comment":"null","endLoc":72,"header":"def test_axes_array_size(self)","id":2302,"name":"test_axes_array_size","nodeType":"Function","startLoc":55,"text":"def test_axes_array_size(self):\n\n g = ag.FacetGrid(self.df)\n assert g.axes.shape == (1, 1)\n\n g = ag.FacetGrid(self.df, row=\"a\")\n assert g.axes.shape == (3, 1)\n\n g = ag.FacetGrid(self.df, col=\"b\")\n assert g.axes.shape == (1, 2)\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n assert g.axes.shape == (1, 1)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n assert g.axes.shape == (3, 2)\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)"},{"className":"BaseException","col":0,"comment":"null","endLoc":1939,"id":2303,"nodeType":"Class","startLoc":1927,"text":"class BaseException:\n args: tuple[Any, ...]\n __cause__: BaseException | None\n __context__: BaseException | None\n __suppress_context__: bool\n __traceback__: TracebackType | None\n def __init__(self, *args: object) -> None: ...\n def __setstate__(self, __state: dict[str, Any] | None) -> None: ...\n def with_traceback(self, __tb: TracebackType | None) -> Self: ...\n if sys.version_info >= (3, 11):\n # only present after add_note() is called\n __notes__: list[str]\n def add_note(self, __note: str) -> None: ..."},{"col":4,"comment":"null","endLoc":1934,"header":"def __setstate__(self, __state: dict[str, Any] | None) -> None","id":2304,"name":"__setstate__","nodeType":"Function","startLoc":1934,"text":"def __setstate__(self, __state: dict[str, Any] | None) -> None: ..."},{"col":4,"comment":"null","endLoc":1935,"header":"def with_traceback(self, __tb: TracebackType | None) -> Self","id":2305,"name":"with_traceback","nodeType":"Function","startLoc":1935,"text":"def with_traceback(self, __tb: TracebackType | None) -> Self: ..."},{"attributeType":"(Any, ...)","col":4,"comment":"null","endLoc":1928,"id":2306,"name":"args","nodeType":"Attribute","startLoc":1928,"text":"args"},{"col":0,"comment":"null","endLoc":310,"header":"def categorical()","id":2307,"name":"categorical","nodeType":"Function","startLoc":300,"text":"def categorical():\n\n penguins = sns.load_dataset(\"penguins\").dropna()\n with sns.axes_style(\"whitegrid\"):\n g = sns.catplot(\n penguins, x=\"sex\", y=\"body_mass_g\", hue=\"island\", col=\"sex\",\n kind=\"box\", whis=np.inf, legend=False, sharex=False,\n )\n sns.despine(left=True)\n g.figure.set_size_inches(5, 5)\n return g.figure"},{"col":0,"comment":"null","endLoc":324,"header":"def regression()","id":2308,"name":"regression","nodeType":"Function","startLoc":313,"text":"def regression():\n\n anscombe = sns.load_dataset(\"anscombe\")\n with sns.axes_style(\"white\"):\n g = sns.lmplot(\n anscombe, x=\"x\", y=\"y\", hue=\"dataset\", col=\"dataset\", col_wrap=2,\n scatter_kws=dict(edgecolor=\".2\", facecolor=\".7\", s=80),\n line_kws=dict(lw=4), ci=None,\n )\n g.set(xlim=(2, None), ylim=(2, None))\n g.figure.set_size_inches(5, 5)\n return g.figure"},{"col":4,"comment":"null","endLoc":172,"header":"def test_mapped_color_direct_alpha(self, x, y, color)","id":2309,"name":"test_mapped_color_direct_alpha","nodeType":"Function","startLoc":164,"text":"def test_mapped_color_direct_alpha(self, x, y, color):\n\n alpha = .5\n p = Plot(x, y, color=color).add(Bars(alpha=alpha)).plot()\n ax = p._figure.axes[0]\n fcs = ax.collections[0].get_facecolors()\n C0, C1, C2, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n expected = to_rgba_array([C0, C1, C2, C0, C2], alpha)\n assert_array_equal(fcs, expected)"},{"attributeType":"BaseException | None","col":4,"comment":"null","endLoc":1929,"id":2310,"name":"__cause__","nodeType":"Attribute","startLoc":1929,"text":"__cause__"},{"col":4,"comment":"null","endLoc":179,"header":"def test_mapped_edgewidth(self, x, y)","id":2311,"name":"test_mapped_edgewidth","nodeType":"Function","startLoc":174,"text":"def test_mapped_edgewidth(self, x, y):\n\n p = Plot(x, y, edgewidth=y).add(Bars()).plot()\n ax = p._figure.axes[0]\n lws = ax.collections[0].get_linewidths()\n assert_array_equal(np.argsort(lws), np.argsort(y))"},{"attributeType":"BaseException | None","col":4,"comment":"null","endLoc":1930,"id":2312,"name":"__context__","nodeType":"Attribute","startLoc":1930,"text":"__context__"},{"col":4,"comment":"null","endLoc":89,"header":"def test_single_axes(self)","id":2313,"name":"test_single_axes","nodeType":"Function","startLoc":74,"text":"def test_single_axes(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.ax, plt.Axes)\n\n g = ag.FacetGrid(self.df, row=\"a\")\n with pytest.raises(AttributeError):\n g.ax\n\n g = ag.FacetGrid(self.df, col=\"a\")\n with pytest.raises(AttributeError):\n g.ax\n\n g = ag.FacetGrid(self.df, col=\"a\", row=\"b\")\n with pytest.raises(AttributeError):\n g.ax"},{"attributeType":"bool","col":4,"comment":"null","endLoc":1931,"id":2314,"name":"__suppress_context__","nodeType":"Attribute","startLoc":1931,"text":"__suppress_context__"},{"attributeType":"TracebackType | None","col":4,"comment":"null","endLoc":1932,"id":2315,"name":"__traceback__","nodeType":"Attribute","startLoc":1932,"text":"__traceback__"},{"col":4,"comment":"null","endLoc":192,"header":"def test_auto_edgewidth(self)","id":2316,"name":"test_auto_edgewidth","nodeType":"Function","startLoc":181,"text":"def test_auto_edgewidth(self):\n\n x0 = np.arange(10)\n x1 = np.arange(1000)\n\n p0 = Plot(x0, x0).add(Bars()).plot()\n p1 = Plot(x1, x1).add(Bars()).plot()\n\n lw0 = p0._figure.axes[0].collections[0].get_linewidths()\n lw1 = p1._figure.axes[0].collections[0].get_linewidths()\n\n assert (lw0 > lw1).all()"},{"col":0,"comment":"dict.pop(key) where `key` is a `.`-delimited list of nested keys.\n >>> d = {'a': {'b': 1, 'c': 2}}\n >>> pop_recursive(d, 'a.c')\n 2\n >>> d\n {'a': {'b': 1}}\n ","endLoc":62,"header":"def pop_recursive(d, key, default=None)","id":2317,"name":"pop_recursive","nodeType":"Function","startLoc":45,"text":"def pop_recursive(d, key, default=None):\n \"\"\"dict.pop(key) where `key` is a `.`-delimited list of nested keys.\n >>> d = {'a': {'b': 1, 'c': 2}}\n >>> pop_recursive(d, 'a.c')\n 2\n >>> d\n {'a': {'b': 1}}\n \"\"\"\n nested = key.split('.')\n current = d\n for k in nested[:-1]:\n if hasattr(current, 'get'):\n current = current.get(k, {})\n else:\n return default\n if not hasattr(current, 'pop'):\n return default\n return current.pop(nested[-1], default)"},{"col":4,"comment":"null","endLoc":977,"header":"def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str","id":2318,"name":"_resolve_label","nodeType":"Function","startLoc":964,"text":"def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str:\n\n label: str\n if var in p._labels:\n manual_label = p._labels[var]\n if callable(manual_label) and auto_label is not None:\n label = manual_label(auto_label)\n else:\n label = cast(str, manual_label)\n elif auto_label is None:\n label = \"\"\n else:\n label = auto_label\n return label"},{"col":0,"comment":"null","endLoc":337,"header":"def axis_grids()","id":2319,"name":"axis_grids","nodeType":"Function","startLoc":327,"text":"def axis_grids():\n\n penguins = sns.load_dataset(\"penguins\").sample(200, random_state=0)\n with sns.axes_style(\"ticks\"):\n g = sns.pairplot(\n penguins.drop(\"flipper_length_mm\", axis=1),\n diag_kind=\"kde\", diag_kws=dict(fill=False),\n plot_kws=dict(s=40, fc=\"none\", ec=\"C0\", alpha=.75, linewidth=.75),\n )\n g.figure.set_size_inches(5, 5)\n return g.figure"},{"col":0,"comment":"\n Strip the outputs, execution count/prompt number and miscellaneous\n metadata from a notebook object, unless specified to keep either the\n outputs or counts.\n ","endLoc":103,"header":"def strip_output(nb)","id":2320,"name":"strip_output","nodeType":"Function","startLoc":65,"text":"def strip_output(nb):\n \"\"\"\n Strip the outputs, execution count/prompt number and miscellaneous\n metadata from a notebook object, unless specified to keep either the\n outputs or counts.\n \"\"\"\n keys = {'metadata': [], 'cell': {'metadata': [\"execution\"]}}\n\n nb.metadata.pop('signature', None)\n nb.metadata.pop('widgets', None)\n\n for field in keys['metadata']:\n pop_recursive(nb.metadata, field)\n\n if 'NB_KERNEL' in os.environ:\n nb.metadata['kernelspec']['name'] = os.environ['NB_KERNEL']\n nb.metadata['kernelspec']['display_name'] = os.environ['NB_KERNEL']\n\n for cell in nb.cells:\n\n if 'outputs' in cell:\n cell['outputs'] = []\n if 'prompt_number' in cell:\n cell['prompt_number'] = None\n if 'execution_count' in cell:\n cell['execution_count'] = None\n\n # Always remove this metadata\n for output_style in ['collapsed', 'scrolled']:\n if output_style in cell.metadata:\n cell.metadata[output_style] = False\n if 'metadata' in cell:\n for field in ['collapsed', 'scrolled', 'ExecuteTime']:\n cell.metadata.pop(field, None)\n for (extra, fields) in keys['cell'].items():\n if extra in cell:\n for field in fields:\n pop_recursive(getattr(cell, extra), field)\n return nb"},{"col":4,"comment":"null","endLoc":117,"header":"def test_col_wrap(self)","id":2321,"name":"test_col_wrap","nodeType":"Function","startLoc":91,"text":"def test_col_wrap(self):\n\n n = len(self.df.d.unique())\n\n g = ag.FacetGrid(self.df, col=\"d\")\n assert g.axes.shape == (1, n)\n assert g.facet_axis(0, 8) is g.axes[0, 8]\n\n g_wrap = ag.FacetGrid(self.df, col=\"d\", col_wrap=4)\n assert g_wrap.axes.shape == (n,)\n assert g_wrap.facet_axis(0, 8) is g_wrap.axes[8]\n assert g_wrap._ncol == 4\n assert g_wrap._nrow == (n / 4)\n\n with pytest.raises(ValueError):\n g = ag.FacetGrid(self.df, row=\"b\", col=\"d\", col_wrap=4)\n\n df = self.df.copy()\n df.loc[df.d == \"j\"] = np.nan\n g_missing = ag.FacetGrid(df, col=\"d\")\n assert g_missing.axes.shape == (1, n - 1)\n\n g_missing_wrap = ag.FacetGrid(df, col=\"d\", col_wrap=4)\n assert g_missing_wrap.axes.shape == (n - 1,)\n\n g = ag.FacetGrid(self.df, col=\"d\", col_wrap=1)\n assert len(list(g.facet_data())) == n"},{"col":4,"comment":"null","endLoc":1160,"header":"@pytest.mark.parametrize(\n \"element,fill\",\n itertools.product([\"bars\", \"step\", \"poly\"], [True, False]),\n )\n def test_color(self, long_df, element, fill)","id":2322,"name":"test_color","nodeType":"Function","startLoc":1154,"text":"@pytest.mark.parametrize(\n \"element,fill\",\n itertools.product([\"bars\", \"step\", \"poly\"], [True, False]),\n )\n def test_color(self, long_df, element, fill):\n\n super().test_color(long_df, element=element, fill=fill)"},{"col":4,"comment":"null","endLoc":1077,"header":"def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None","id":2323,"name":"_setup_figure","nodeType":"Function","startLoc":979,"text":"def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None:\n\n # --- Parsing the faceting/pairing parameterization to specify figure grid\n\n subplot_spec = p._subplot_spec.copy()\n facet_spec = p._facet_spec.copy()\n pair_spec = p._pair_spec.copy()\n\n for axis in \"xy\":\n if axis in p._shares:\n subplot_spec[f\"share{axis}\"] = p._shares[axis]\n\n for dim in [\"col\", \"row\"]:\n if dim in common.frame and dim not in facet_spec[\"structure\"]:\n order = categorical_order(common.frame[dim])\n facet_spec[\"structure\"][dim] = order\n\n self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec)\n\n # --- Figure initialization\n self._figure = subplots.init_figure(\n pair_spec, self._pyplot, p._figure_spec, p._target,\n )\n\n # --- Figure annotation\n for sub in subplots:\n ax = sub[\"ax\"]\n for axis in \"xy\":\n axis_key = sub[axis]\n\n # ~~ Axis labels\n\n # TODO Should we make it possible to use only one x/y label for\n # all rows/columns in a faceted plot? Maybe using sub{axis}label,\n # although the alignments of the labels from that method leaves\n # something to be desired (in terms of how it defines 'centered').\n names = [\n common.names.get(axis_key),\n *(layer[\"data\"].names.get(axis_key) for layer in layers)\n ]\n auto_label = next((name for name in names if name is not None), None)\n label = self._resolve_label(p, axis_key, auto_label)\n ax.set(**{f\"{axis}label\": label})\n\n # ~~ Decoration visibility\n\n # TODO there should be some override (in Plot.layout?) so that\n # axis / tick labels can be shown on interior shared axes if desired\n\n axis_obj = getattr(ax, f\"{axis}axis\")\n visible_side = {\"x\": \"bottom\", \"y\": \"left\"}.get(axis)\n show_axis_label = (\n sub[visible_side]\n or not p._pair_spec.get(\"cross\", True)\n or (\n axis in p._pair_spec.get(\"structure\", {})\n and bool(p._pair_spec.get(\"wrap\"))\n )\n )\n axis_obj.get_label().set_visible(show_axis_label)\n\n show_tick_labels = (\n show_axis_label\n or subplot_spec.get(f\"share{axis}\") not in (\n True, \"all\", {\"x\": \"col\", \"y\": \"row\"}[axis]\n )\n )\n for group in (\"major\", \"minor\"):\n for t in getattr(axis_obj, f\"get_{group}ticklabels\")():\n t.set_visible(show_tick_labels)\n\n # TODO we want right-side titles for row facets in most cases?\n # Let's have what we currently call \"margin titles\" but properly using the\n # ax.set_title interface (see my gist)\n title_parts = []\n for dim in [\"col\", \"row\"]:\n if sub[dim] is not None:\n val = self._resolve_label(p, \"title\", f\"{sub[dim]}\")\n if dim in p._labels:\n key = self._resolve_label(p, dim, common.names.get(dim))\n val = f\"{key} {val}\"\n title_parts.append(val)\n\n has_col = sub[\"col\"] is not None\n has_row = sub[\"row\"] is not None\n show_title = (\n has_col and has_row\n or (has_col or has_row) and p._facet_spec.get(\"wrap\")\n or (has_col and sub[\"top\"])\n # TODO or has_row and sub[\"right\"] and \n or has_row # TODO and not \n )\n if title_parts:\n title = \" | \".join(title_parts)\n title_text = ax.set_title(title)\n title_text.set_visible(show_title)\n elif not (has_col or has_row):\n title = self._resolve_label(p, \"title\", None)\n title_text = ax.set_title(title)"},{"attributeType":"str","col":4,"comment":"null","endLoc":109,"id":2324,"name":"_","nodeType":"Attribute","startLoc":109,"text":"_"},{"col":4,"comment":"null","endLoc":149,"header":"def test_normal_axes(self)","id":2325,"name":"test_normal_axes","nodeType":"Function","startLoc":119,"text":"def test_normal_axes(self):\n\n null = np.empty(0, object).flat\n\n g = ag.FacetGrid(self.df)\n npt.assert_array_equal(g._bottom_axes, g.axes.flat)\n npt.assert_array_equal(g._not_bottom_axes, null)\n npt.assert_array_equal(g._left_axes, g.axes.flat)\n npt.assert_array_equal(g._not_left_axes, null)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, col=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes.flat)\n npt.assert_array_equal(g._not_bottom_axes, null)\n npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, row=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)\n npt.assert_array_equal(g._left_axes, g.axes.flat)\n npt.assert_array_equal(g._not_left_axes, null)\n npt.assert_array_equal(g._inner_axes, null)\n\n g = ag.FacetGrid(self.df, col=\"a\", row=\"c\")\n npt.assert_array_equal(g._bottom_axes, g.axes[-1, :].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:-1, :].flat)\n npt.assert_array_equal(g._left_axes, g.axes[:, 0].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[:, 1:].flat)\n npt.assert_array_equal(g._inner_axes, g.axes[:-1, 1:].flat)"},{"col":4,"comment":"null","endLoc":202,"header":"def test_unfilled(self, x, y)","id":2326,"name":"test_unfilled","nodeType":"Function","startLoc":194,"text":"def test_unfilled(self, x, y):\n\n p = Plot(x, y).add(Bars(fill=False, edgecolor=\"C4\")).plot()\n ax = p._figure.axes[0]\n fcs = ax.collections[0].get_facecolors()\n ecs = ax.collections[0].get_edgecolors()\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n assert_array_equal(fcs, to_rgba_array([colors[0]] * len(x), 0))\n assert_array_equal(ecs, to_rgba_array([colors[4]] * len(x), 1))"},{"attributeType":"str","col":7,"comment":"null","endLoc":109,"id":2327,"name":"fpath","nodeType":"Attribute","startLoc":109,"text":"fpath"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":2328,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":2329,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"attributeType":"str","col":14,"comment":"null","endLoc":109,"id":2330,"name":"outdir","nodeType":"Attribute","startLoc":109,"text":"outdir"},{"attributeType":"str","col":4,"comment":"null","endLoc":110,"id":2331,"name":"basedir","nodeType":"Attribute","startLoc":110,"text":"basedir"},{"col":4,"comment":"null","endLoc":1180,"header":"@pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable)","id":2332,"name":"test_long_vectors","nodeType":"Function","startLoc":1162,"text":"@pytest.mark.parametrize(\n \"variable\", [\"x\", \"y\"],\n )\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, axs = plt.subplots(3)\n for vector, ax in zip(vectors, axs):\n histplot(data=long_df, ax=ax, **{variable: vector})\n\n bars = [ax.patches for ax in axs]\n for a_bars, b_bars in itertools.product(bars, bars):\n for a, b in zip(a_bars, b_bars):\n assert_array_equal(a.get_height(), b.get_height())\n assert_array_equal(a.get_xy(), b.get_xy())"},{"col":0,"comment":"null","endLoc":349,"header":"def aesthetics()","id":2333,"name":"aesthetics","nodeType":"Function","startLoc":340,"text":"def aesthetics():\n\n f = mpl.figure.Figure(figsize=(5, 5))\n for i, style in enumerate([\"darkgrid\", \"white\", \"ticks\", \"whitegrid\"], 1):\n with sns.axes_style(style):\n ax = f.add_subplot(2, 2, i)\n ax.set(xticks=[0, .25, .5, .75, 1], yticks=[0, .25, .5, .75, 1])\n sns.despine(ax=f.axes[1])\n sns.despine(ax=f.axes[2])\n return f"},{"attributeType":"str","col":13,"comment":"null","endLoc":110,"id":2334,"name":"fname","nodeType":"Attribute","startLoc":110,"text":"fname"},{"attributeType":"str","col":4,"comment":"null","endLoc":111,"id":2335,"name":"fstem","nodeType":"Attribute","startLoc":111,"text":"fstem"},{"attributeType":"TextIO","col":24,"comment":"null","endLoc":114,"id":2336,"name":"f","nodeType":"Attribute","startLoc":114,"text":"f"},{"col":0,"comment":"null","endLoc":362,"header":"def color_palettes()","id":2337,"name":"color_palettes","nodeType":"Function","startLoc":352,"text":"def color_palettes():\n\n f = mpl.figure.Figure(figsize=(5, 5))\n palettes = [\"deep\", \"husl\", \"gray\", \"ch:\", \"mako\", \"vlag\", \"icefire\"]\n axs = f.subplots(len(palettes))\n x = np.arange(10)\n for ax, name in zip(axs, palettes):\n cmap = mpl.colors.ListedColormap(sns.color_palette(name, x.size))\n ax.pcolormesh(x[None, :], linewidth=.5, edgecolor=\"w\", alpha=.8, cmap=cmap)\n ax.set_axis_off()\n return f"},{"col":4,"comment":"null","endLoc":161,"header":"def test_wrapped_axes(self)","id":2338,"name":"test_wrapped_axes","nodeType":"Function","startLoc":151,"text":"def test_wrapped_axes(self):\n\n null = np.empty(0, object).flat\n\n g = ag.FacetGrid(self.df, col=\"a\", col_wrap=2)\n npt.assert_array_equal(g._bottom_axes,\n g.axes[np.array([1, 2])].flat)\n npt.assert_array_equal(g._not_bottom_axes, g.axes[:1].flat)\n npt.assert_array_equal(g._left_axes, g.axes[np.array([0, 2])].flat)\n npt.assert_array_equal(g._not_left_axes, g.axes[np.array([1])].flat)\n npt.assert_array_equal(g._inner_axes, null)"},{"col":4,"comment":"null","endLoc":188,"header":"def test_axes_dict(self)","id":2339,"name":"test_axes_dict","nodeType":"Function","startLoc":163,"text":"def test_axes_dict(self):\n\n g = ag.FacetGrid(self.df)\n assert isinstance(g.axes_dict, dict)\n assert not g.axes_dict\n\n g = ag.FacetGrid(self.df, row=\"c\")\n assert list(g.axes_dict.keys()) == g.row_names\n for (name, ax) in zip(g.row_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, col=\"c\")\n assert list(g.axes_dict.keys()) == g.col_names\n for (name, ax) in zip(g.col_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, col=\"a\", col_wrap=2)\n assert list(g.axes_dict.keys()) == g.col_names\n for (name, ax) in zip(g.col_names, g.axes.flat):\n assert g.axes_dict[name] is ax\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"c\")\n for (row_var, col_var), ax in g.axes_dict.items():\n i = g.row_names.index(row_var)\n j = g.col_names.index(col_var)\n assert g.axes[i, j] is ax"},{"col":0,"comment":"null","endLoc":366,"header":"def setup(app)","id":2340,"name":"setup","nodeType":"Function","startLoc":365,"text":"def setup(app):\n app.connect(\"builder-inited\", main)"},{"attributeType":"null","col":16,"comment":"null","endLoc":7,"id":2341,"name":"np","nodeType":"Attribute","startLoc":7,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":8,"id":2342,"name":"mpl","nodeType":"Attribute","startLoc":8,"text":"mpl"},{"attributeType":"null","col":18,"comment":"null","endLoc":9,"id":2343,"name":"sns","nodeType":"Attribute","startLoc":9,"text":"sns"},{"attributeType":"null","col":26,"comment":"null","endLoc":10,"id":2344,"name":"so","nodeType":"Attribute","startLoc":10,"text":"so"},{"attributeType":"str","col":0,"comment":"null","endLoc":13,"id":2345,"name":"TEMPLATE","nodeType":"Attribute","startLoc":13,"text":"TEMPLATE"},{"col":0,"comment":"","endLoc":1,"header":"tutorial_builder.py#","id":2346,"name":"","nodeType":"Function","startLoc":1,"text":"TEMPLATE = \"\"\"\n:notoc:\n\n.. _tutorial:\n\nUser guide and tutorial\n=======================\n{% for section in sections %}\n{{ section.header }}\n{% for page in section.pages %}\n.. grid:: 1\n :gutter: 2\n\n .. grid-item-card::\n\n .. grid:: 2\n\n .. grid-item::\n :columns: 3\n\n .. image:: ./tutorial/{{ page }}.svg\n :target: ./tutorial/{{ page }}.html\n\n .. grid-item::\n :columns: 9\n :margin: auto\n\n .. toctree::\n :maxdepth: 2\n\n tutorial/{{ page }}\n{% endfor %}\n{% endfor %}\n\"\"\""},{"col":4,"comment":"Provide one cycle where palette= implies hue= when not provided","endLoc":180,"header":"def _palette_without_hue_backcompat(self, palette, hue_order)","id":2347,"name":"_palette_without_hue_backcompat","nodeType":"Function","startLoc":170,"text":"def _palette_without_hue_backcompat(self, palette, hue_order):\n \"\"\"Provide one cycle where palette= implies hue= when not provided\"\"\"\n if \"hue\" not in self.variables and palette is not None:\n msg = \"Passing `palette` without assigning `hue` is deprecated.\"\n warnings.warn(msg, FutureWarning, stacklevel=3)\n self.legend = False\n self.plot_data[\"hue\"] = self.plot_data[self.cat_axis]\n self.variables[\"hue\"] = self.variables.get(self.cat_axis)\n self.var_types[\"hue\"] = self.var_types.get(self.cat_axis)\n hue_order = self.var_levels.get(self.cat_axis)\n return hue_order"},{"col":4,"comment":"null","endLoc":184,"header":"@property\n def cat_axis(self)","id":2348,"name":"cat_axis","nodeType":"Function","startLoc":182,"text":"@property\n def cat_axis(self):\n return {\"v\": \"x\", \"h\": \"y\"}[self.orient]"},{"col":4,"comment":"Get a grayscale value that looks good with color.","endLoc":193,"header":"def _get_gray(self, colors)","id":2349,"name":"_get_gray","nodeType":"Function","startLoc":186,"text":"def _get_gray(self, colors):\n \"\"\"Get a grayscale value that looks good with color.\"\"\"\n if not len(colors):\n return None\n unique_colors = np.unique(colors, axis=0)\n light_vals = [rgb_to_hls(*rgb[:3])[1] for rgb in unique_colors]\n lum = min(light_vals) * .6\n return (lum, lum, lum)"},{"col":4,"comment":"Set ticks and limits for a categorical variable.","endLoc":224,"header":"def _adjust_cat_axis(self, ax, axis)","id":2350,"name":"_adjust_cat_axis","nodeType":"Function","startLoc":195,"text":"def _adjust_cat_axis(self, ax, axis):\n \"\"\"Set ticks and limits for a categorical variable.\"\"\"\n # Note: in theory, this could happen in _attach for all categorical axes\n # But two reasons not to do that:\n # - If it happens before plotting, autoscaling messes up the plot limits\n # - It would change existing plots from other seaborn functions\n if self.var_types[axis] != \"categorical\":\n return\n\n # If both x/y data are empty, the correct way to set up the plot is\n # somewhat undefined; because we don't add null category data to the plot in\n # this case we don't *have* a categorical axis (yet), so best to just bail.\n if self.plot_data[axis].empty:\n return\n\n # We can infer the total number of categories (including those from previous\n # plots that are not part of the plot we are currently making) from the number\n # of ticks, which matplotlib sets up while doing unit conversion. This feels\n # slightly risky, as if we are relying on something that may be a matplotlib\n # implementation detail. But I cannot think of a better way to keep track of\n # the state from previous categorical calls (see GH2516 for context)\n n = len(getattr(ax, f\"get_{axis}ticks\")())\n\n if axis == \"x\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, n - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n # Note limits that correspond to previously-inverted y axis\n ax.set_ylim(n - .5, -.5, auto=None)"},{"id":2351,"name":"logo-mark-darkbg.svg","nodeType":"TextFile","path":"doc/_static","text":"\n\n\n\n \n \n \n \n 2020-09-07T14:13:59.975140\n image/svg+xml\n \n \n Matplotlib v3.3.1, https://matplotlib.org/\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"id":2352,"name":"color_palettes.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {\n \"raw_mimetype\": \"text/restructuredtext\"\n },\n \"source\": [\n \".. _palette_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Choosing color palettes\\n\",\n \"=======================\\n\",\n \"\\n\",\n \"Seaborn makes it easy to use colors that are well-suited to the characteristics of your data and your visualization goals. This chapter discusses both the general principles that should guide your choices and the tools in seaborn that help you quickly find the best solution for a given application.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import matplotlib as mpl\\n\",\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"sns.set_theme(style=\\\"white\\\", rc={\\\"xtick.major.pad\\\": 1, \\\"ytick.major.pad\\\": 1})\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"%matplotlib inline\\n\",\n \"np.random.seed(sum(map(ord, \\\"palettes\\\")))\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"# Add colormap display methods to matplotlib colormaps.\\n\",\n \"# These are forthcoming in matplotlib 3.4, but, the matplotlib display\\n\",\n \"# method includes the colormap name, which is redundant.\\n\",\n \"def _repr_png_(self):\\n\",\n \" \\\"\\\"\\\"Generate a PNG representation of the Colormap.\\\"\\\"\\\"\\n\",\n \" import io\\n\",\n \" from PIL import Image\\n\",\n \" import numpy as np\\n\",\n \" IMAGE_SIZE = (400, 50)\\n\",\n \" X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1))\\n\",\n \" pixels = self(X, bytes=True)\\n\",\n \" png_bytes = io.BytesIO()\\n\",\n \" Image.fromarray(pixels).save(png_bytes, format='png')\\n\",\n \" return png_bytes.getvalue()\\n\",\n \" \\n\",\n \"def _repr_html_(self):\\n\",\n \" \\\"\\\"\\\"Generate an HTML representation of the Colormap.\\\"\\\"\\\"\\n\",\n \" import base64\\n\",\n \" png_bytes = self._repr_png_()\\n\",\n \" png_base64 = base64.b64encode(png_bytes).decode('ascii')\\n\",\n \" return ('')\\n\",\n \" \\n\",\n \"import matplotlib as mpl\\n\",\n \"mpl.colors.Colormap._repr_png_ = _repr_png_\\n\",\n \"mpl.colors.Colormap._repr_html_ = _repr_html_\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"General principles for using color in plots\\n\",\n \"-------------------------------------------\\n\",\n \"\\n\",\n \"Components of color\\n\",\n \"~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Because of the way our eyes work, a particular color can be defined using three components. We usually program colors in a computer by specifying their RGB values, which set the intensity of the red, green, and blue channels in a display. But for analyzing the perceptual attributes of a color, it's better to think in terms of *hue*, *saturation*, and *luminance* channels.\\n\",\n \"\\n\",\n \"Hue is the component that distinguishes \\\"different colors\\\" in a non-technical sense. It's property of color that leads to first-order names like \\\"red\\\" and \\\"blue\\\":\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette(8, s=.7)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Saturation (or chroma) is the *colorfulness*. Two colors with different hues will look more distinct when they have more saturation:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"c = sns.color_palette(\\\"muted\\\")[0]\\n\",\n \"sns.blend_palette([sns.desaturate(c, 0), c], 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"And lightness corresponds to how much light is emitted (or reflected, for printed colors), ranging from black to white:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"sns.blend_palette([\\\".1\\\", c, \\\".95\\\"], 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Vary hue to distinguish categories\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"When you want to represent multiple categories in a plot, you typically should vary the color of the elements. Consider this simple example: in which of these two plots is it easier to count the number of triangular points?\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"n = 45\\n\",\n \"rng = np.random.default_rng(200)\\n\",\n \"x = rng.uniform(0, 1, n * 2)\\n\",\n \"y = rng.uniform(0, 1, n * 2)\\n\",\n \"a = np.concatenate([np.zeros(n * 2 - 10), np.ones(10)])\\n\",\n \"\\n\",\n \"f, axs = plt.subplots(1, 2, figsize=(7, 3.5), sharey=True, sharex=True)\\n\",\n \"\\n\",\n \"sns.scatterplot(\\n\",\n \" x=x[::2], y=y[::2], style=a[::2], size=a[::2], legend=False,\\n\",\n \" markers=[\\\"o\\\", (3, 1, 1)], sizes=[70, 140], ax=axs[0],\\n\",\n \")\\n\",\n \"\\n\",\n \"sns.scatterplot(\\n\",\n \" x=x[1::2], y=y[1::2], style=a[1::2], size=a[1::2], hue=a[1::2], legend=False,\\n\",\n \" markers=[\\\"o\\\", (3, 1, 1)], sizes=[70, 140], ax=axs[1],\\n\",\n \")\\n\",\n \"\\n\",\n \"f.tight_layout(w_pad=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In the plot on the right, the orange triangles \\\"pop out\\\", making it easy to distinguish them from the circles. This pop-out effect happens because our visual system prioritizes color differences.\\n\",\n \"\\n\",\n \"The blue and orange colors differ mostly in terms of their hue. Hue is useful for representing categories: most people can distinguish a moderate number of hues relatively easily, and points that have different hues but similar brightness or intensity seem equally important. It also makes plots easier to talk about. Consider this example:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"b = np.tile(np.arange(10), n // 5)\\n\",\n \"\\n\",\n \"f, axs = plt.subplots(1, 2, figsize=(7, 3.5), sharey=True, sharex=True)\\n\",\n \"\\n\",\n \"sns.scatterplot(\\n\",\n \" x=x[::2], y=y[::2], hue=b[::2],\\n\",\n \" legend=False, palette=\\\"muted\\\", s=70, ax=axs[0],\\n\",\n \")\\n\",\n \"\\n\",\n \"sns.scatterplot(\\n\",\n \" x=x[1::2], y=y[1::2], hue=b[1::2],\\n\",\n \" legend=False, palette=\\\"blend:.75,C0\\\", s=70, ax=axs[1],\\n\",\n \")\\n\",\n \"\\n\",\n \"f.tight_layout(w_pad=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Most people would be able to quickly ascertain that there are five distinct categories in the plot on the left and, if asked to characterize the \\\"blue\\\" points, would be able to do so.\\n\",\n \"\\n\",\n \"With the plot on the right, where the points are all blue but vary in their luminance and saturation, it's harder to say how many unique categories are present. And how would we talk about a particular category? \\\"The fairly-but-not-too-blue points?\\\" What's more, the gray dots seem to fade into the background, de-emphasizing them relative to the more intense blue dots. If the categories are equally important, this is a poor representation.\\n\",\n \"\\n\",\n \"So as a general rule, use hue variation to represent categories. With that said, here are few notes of caution. If you have more than a handful of colors in your plot, it can become difficult to keep in mind what each one means, unless there are pre-existing associations between the categories and the colors used to represent them. This makes your plot harder to interpret: rather than focusing on the data, a viewer will have to continually refer to the legend to make sense of what is shown. So you should strive not to make plots that are too complex. And be mindful that not everyone sees colors the same way. Varying both shape (or some other attribute) and color can help people with anomalous color vision understand your plots, and it can keep them (somewhat) interpretable if they are printed to black-and-white.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Vary luminance to represent numbers\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"On the other hand, hue variations are not well suited to representing numeric data. Consider this example, where we need colors to represent the counts in a bivariate histogram. On the left, we use a circular colormap, where gradual changes in the number of observation within each bin correspond to gradual changes in hue. On the right, we use a palette that uses brighter colors to represent bins with larger counts:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"\\n\",\n \"f, axs = plt.subplots(1, 2, figsize=(7, 4.25), sharey=True, sharex=True)\\n\",\n \"\\n\",\n \"sns.histplot(\\n\",\n \" data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n \" binwidth=(3, .75), cmap=\\\"hls\\\", ax=axs[0],\\n\",\n \" cbar=True, cbar_kws=dict(orientation=\\\"horizontal\\\", pad=.1),\\n\",\n \")\\n\",\n \"axs[0].set(xlabel=\\\"\\\", ylabel=\\\"\\\")\\n\",\n \"\\n\",\n \"\\n\",\n \"sns.histplot(\\n\",\n \" data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n \" binwidth=(3, .75), cmap=\\\"flare_r\\\", ax=axs[1],\\n\",\n \" cbar=True, cbar_kws=dict(orientation=\\\"horizontal\\\", pad=.1),\\n\",\n \")\\n\",\n \"axs[1].set(xlabel=\\\"\\\", ylabel=\\\"\\\")\\n\",\n \"\\n\",\n \"f.tight_layout(w_pad=3)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"With the hue-based palette, it's quite difficult to ascertain the shape of the bivariate distribution. In contrast, the luminance palette makes it much more clear that there are two prominent peaks.\\n\",\n \"\\n\",\n \"Varying luminance helps you see structure in data, and changes in luminance are more intuitively processed as changes in importance. But the plot on the right does not use a grayscale colormap. Its colorfulness makes it more interesting, and the subtle hue variation increases the perceptual distance between two values. As a result, small differences slightly easier to resolve.\\n\",\n \"\\n\",\n \"These examples show that color palette choices are about more than aesthetics: the colors you choose can reveal patterns in your data if used effectively or hide them if used poorly. There is not one optimal palette, but there are palettes that are better or worse for particular datasets and visualization approaches.\\n\",\n \"\\n\",\n \"And aesthetics do matter: the more that people want to look at your figures, the greater the chance that they will learn something from them. This is true even when you are making plots for yourself. During exploratory data analysis, you may generate many similar figures. Varying the color palettes will add a sense of novelty, which keeps you engaged and prepared to notice interesting features of your data.\\n\",\n \"\\n\",\n \"So how can you choose color palettes that both represent your data well and look attractive?\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {\n \"raw_mimetype\": \"text/restructuredtext\"\n },\n \"source\": [\n \"Tools for choosing color palettes\\n\",\n \"---------------------------------\\n\",\n \"\\n\",\n \"The most important function for working with color palettes is, aptly, :func:`color_palette`. This function provides an interface to most of the possible ways that one can generate color palettes in seaborn. And it's used internally by any function that has a ``palette`` argument.\\n\",\n \"\\n\",\n \"The primary argument to :func:`color_palette` is usually a string: either the name of a specific palette or the name of a family and additional arguments to select a specific member. In the latter case, :func:`color_palette` will delegate to more specific function, such as :func:`cubehelix_palette`. It's also possible to pass a list of colors specified any way that matplotlib accepts (an RGB tuple, a hex code, or a name in the X11 table). The return value is an object that wraps a list of RGB tuples with a few useful methods, such as conversion to hex codes and a rich HTML representation.\\n\",\n \"\\n\",\n \"Calling :func:`color_palette` with no arguments will return the current default color palette that matplotlib (and most seaborn functions) will use if colors are not otherwise specified. This default palette can be set with the corresponding :func:`set_palette` function, which calls :func:`color_palette` internally and accepts the same arguments.\\n\",\n \"\\n\",\n \"To motivate the different options that :func:`color_palette` provides, it will be useful to introduce a classification scheme for color palettes. Broadly, palettes fall into one of three categories:\\n\",\n \"\\n\",\n \"- qualitative palettes, good for representing categorical data\\n\",\n \"- sequential palettes, good for representing numeric data\\n\",\n \"- diverging palettes, good for representing numeric data with a categorical boundary\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _qualitative_palettes:\\n\",\n \"\\n\",\n \"Qualitative color palettes\\n\",\n \"--------------------------\\n\",\n \"\\n\",\n \"Qualitative palettes are well-suited to representing categorical data because most of their variation is in the hue component. The default color palette in seaborn is a qualitative palette with ten distinct hues:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"These colors have the same ordering as the default matplotlib color palette, ``\\\"tab10\\\"``, but they are a bit less intense. Compare:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"tab10\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Seaborn in fact has six variations of matplotlib's palette, called ``deep``, ``muted``, ``pastel``, ``bright``, ``dark``, and ``colorblind``. These span a range of average luminance and saturation values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide-input\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import io\\n\",\n \"from IPython.display import SVG\\n\",\n \"f = mpl.figure.Figure(figsize=(6, 6))\\n\",\n \"\\n\",\n \"ax_locs = dict(\\n\",\n \" deep=(.4, .4),\\n\",\n \" bright=(.8, .8),\\n\",\n \" muted=(.49, .71),\\n\",\n \" dark=(.8, .2),\\n\",\n \" pastel=(.2, .8),\\n\",\n \" colorblind=(.71, .49),\\n\",\n \")\\n\",\n \"\\n\",\n \"s = .35\\n\",\n \"\\n\",\n \"for pal, (x, y) in ax_locs.items():\\n\",\n \" ax = f.add_axes([x - s / 2, y - s / 2, s, s])\\n\",\n \" ax.pie(np.ones(10),\\n\",\n \" colors=sns.color_palette(pal, 10),\\n\",\n \" counterclock=False, startangle=180,\\n\",\n \" wedgeprops=dict(linewidth=1, edgecolor=\\\"w\\\"))\\n\",\n \" f.text(x, y, pal, ha=\\\"center\\\", va=\\\"center\\\", size=14,\\n\",\n \" bbox=dict(facecolor=\\\"white\\\", alpha=0.85, boxstyle=\\\"round,pad=0.2\\\"))\\n\",\n \"\\n\",\n \"f.text(.1, .05, \\\"Saturation\\\", size=18, ha=\\\"left\\\", va=\\\"center\\\",\\n\",\n \" bbox=dict(facecolor=\\\"white\\\", edgecolor=\\\"w\\\"))\\n\",\n \"f.text(.05, .1, \\\"Luminance\\\", size=18, ha=\\\"center\\\", va=\\\"bottom\\\", rotation=90,\\n\",\n \" bbox=dict(facecolor=\\\"white\\\", edgecolor=\\\"w\\\"))\\n\",\n \"\\n\",\n \"ax = f.add_axes([0, 0, 1, 1])\\n\",\n \"ax.set_axis_off()\\n\",\n \"ax.arrow(.15, .05, .4, 0, width=.002, head_width=.015, color=\\\".15\\\")\\n\",\n \"ax.arrow(.05, .15, 0, .4, width=.002, head_width=.015, color=\\\".15\\\")\\n\",\n \"ax.set(xlim=(0, 1), ylim=(0, 1))\\n\",\n \"f.savefig(svg:=io.StringIO(), format=\\\"svg\\\")\\n\",\n \"SVG(svg.getvalue())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Many people find the moderated hues of the default ``\\\"deep\\\"`` palette to be aesthetically pleasing, but they are also less distinct. As a result, they may be more difficult to discriminate in some contexts, which is something to keep in mind when making publication graphics. `This comparison `_ can be helpful for estimating how the seaborn color palettes perform when simulating different forms of colorblindess.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Using circular color systems\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"When you have an arbitrary number of categories, the easiest approach to finding unique hues is to draw evenly-spaced colors in a circular color space (one where the hue changes while keeping the brightness and saturation constant). This is what most seaborn functions default to when they need to use more colors than are currently set in the default color cycle.\\n\",\n \"\\n\",\n \"The most common way to do this uses the ``hls`` color space, which is a simple transformation of RGB values. We saw this color palette before as a counterexample for how to plot a histogram:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"hls\\\", 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {\n \"raw_mimetype\": \"text/restructuredtext\"\n },\n \"source\": [\n \"Because of the way the human visual system works, colors that have the same luminance and saturation in terms of their RGB values won't necessarily look equally intense To remedy this, seaborn provides an interface to the `husl `_ system (since renamed to HSLuv), which achieves less intensity variation as you rotate around the color wheel:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"husl\\\", 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When seaborn needs a categorical palette with more colors than are available in the current default, it will use this approach.\\n\",\n \"\\n\",\n \"Using categorical Color Brewer palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Another source of visually pleasing categorical palettes comes from the `Color Brewer `_ tool (which also has sequential and diverging palettes, as we'll see below).\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"Set2\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Be aware that the qualitative Color Brewer palettes have different lengths, and the default behavior of :func:`color_palette` is to give you the full list:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"Paired\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _sequential_palettes:\\n\",\n \"\\n\",\n \"Sequential color palettes\\n\",\n \"-------------------------\\n\",\n \"\\n\",\n \"The second major class of color palettes is called \\\"sequential\\\". This kind of mapping is appropriate when data range from relatively low or uninteresting values to relatively high or interesting values (or vice versa). As we saw above, the primary dimension of variation in a sequential palette is luminance. Some seaborn functions will default to a sequential palette when you are mapping numeric data. (For historical reasons, both categorical and numeric mappings are specified with the ``hue`` parameter in functions like :func:`relplot` or :func:`displot`, even though numeric mappings use color palettes with relatively little hue variation).\\n\",\n \"\\n\",\n \"Perceptually uniform palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Because they are intended to represent numeric values, the best sequential palettes will be *perceptually uniform*, meaning that the relative discriminability of two colors is proportional to the difference between the corresponding data values. Seaborn includes four perceptually uniform sequential colormaps: ``\\\"rocket\\\"``, ``\\\"mako\\\"``, ``\\\"flare\\\"``, and ``\\\"crest\\\"``. The first two have a very wide luminance range and are well suited for applications such as heatmaps, where colors fill the space they are plotted into:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"rocket\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"mako\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Because the extreme values of these colormaps approach white, they are not well-suited for coloring elements such as lines or points: it will be difficult to discriminate important values against a white or gray background. The \\\"flare\\\" and \\\"crest\\\" colormaps are a better choice for such plots. They have a more restricted range of luminance variations, which they compensate for with a slightly more pronounced variation in hue. The default direction of the luminance ramp is also reversed, so that smaller values have lighter colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"flare\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"crest\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It is also possible to use the perceptually uniform colormaps provided by matplotlib, such as ``\\\"magma\\\"`` and ``\\\"viridis\\\"``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"magma\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"viridis\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As with the convention in matplotlib, every continuous colormap has a reversed version, which has the suffix ``\\\"_r\\\"``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"rocket_r\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Discrete vs. continuous mapping\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"One thing to be aware of is that seaborn can generate discrete values from sequential colormaps and, when doing so, it will not use the most extreme values. Compare the discrete version of ``\\\"rocket\\\"`` against the continuous version shown above:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"rocket\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Internally, seaborn uses the discrete version for categorical data and the continuous version when in numeric mapping mode. Discrete sequential colormaps can be well-suited for visualizing categorical data with an intrinsic ordering, especially if there is some hue variation.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {\n \"raw_mimetype\": \"text/restructuredtext\"\n },\n \"source\": [\n \".. _cubehelix_palettes:\\n\",\n \"\\n\",\n \"Sequential \\\"cubehelix\\\" palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The perceptually uniform colormaps are difficult to programmatically generate, because they are not based on the RGB color space. The `cubehelix `_ system offers an RGB-based compromise: it generates sequential palettes with a linear increase or decrease in brightness and some continuous variation in hue. While not perfectly perceptually uniform, the resulting colormaps have many good properties. Importantly, many aspects of the design process are parameterizable.\\n\",\n \"\\n\",\n \"Matplotlib has the default cubehelix version built into it:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"cubehelix\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The default palette returned by the seaborn :func:`cubehelix_palette` function is a bit different from the matplotlib default in that it does not rotate as far around the hue wheel or cover as wide a range of intensities. It also reverses the luminance ramp:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Other arguments to :func:`cubehelix_palette` control how the palette looks. The two main things you'll change are the ``start`` (a value between 0 and 3) and ``rot``, or number of rotations (an arbitrary value, but usually between -1 and 1)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(start=.5, rot=-.5, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The more you rotate, the more hue variation you will see:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(start=.5, rot=-.75, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can control both how dark and light the endpoints are and their order:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.cubehelix_palette(start=2, rot=0, dark=0, light=.95, reverse=True, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The :func:`color_palette` accepts a string code, starting with ``\\\"ch:\\\"``, for generating an arbitrary cubehelix palette. You can passs the names of parameters in the string:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"ch:start=.2,rot=-.3\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"And for compactness, each parameter can be specified with its first letter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"ch:s=-.2,r=.6\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Custom sequential palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"For a simpler interface to custom sequential palettes, you can use :func:`light_palette` or :func:`dark_palette`, which are both seeded with a single color and produce a palette that ramps either from light or dark desaturated values to that color:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.light_palette(\\\"seagreen\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.dark_palette(\\\"#69d\\\", reverse=True, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As with cubehelix palettes, you can also specify light or dark palettes through :func:`color_palette` or anywhere ``palette`` is accepted:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"light:b\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Reverse the colormap by adding ``\\\"_r\\\"``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"dark:salmon_r\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Sequential Color Brewer palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The Color Brewer library also has some good options for sequential palettes. They include palettes with one primary hue:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"Blues\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Along with multi-hue options:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"YlOrBr\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _diverging_palettes:\\n\",\n \"\\n\",\n \"Diverging color palettes\\n\",\n \"------------------------\\n\",\n \"\\n\",\n \"The third class of color palettes is called \\\"diverging\\\". These are used for data where both large low and high values are interesting and span a midpoint value (often 0) that should be demphasized. The rules for choosing good diverging palettes are similar to good sequential palettes, except now there should be two dominant hues in the colormap, one at (or near) each pole. It's also important that the starting values are of similar brightness and saturation.\\n\",\n \"\\n\",\n \"Perceptually uniform diverging palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Seaborn includes two perceptually uniform diverging palettes: ``\\\"vlag\\\"`` and ``\\\"icefire\\\"``. They both use blue and red at their poles, which many intuitively processes as \\\"cold\\\" and \\\"hot\\\":\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"vlag\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"icefire\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Custom diverging palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"You can also use the seaborn function :func:`diverging_palette` to create a custom colormap for diverging data. This function makes diverging palettes using the ``husl`` color system. You pass it two hues (in degrees) and, optionally, the lightness and saturation values for the extremes. Using ``husl`` means that the extreme values, and the resulting ramps to the midpoint, while not perfectly perceptually uniform, will be well-balanced:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(220, 20, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"This is convenient when you want to stray from the boring confines of cold-hot approaches:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(145, 300, s=60, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to make a palette where the midpoint is dark rather than light:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(250, 30, l=65, center=\\\"dark\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's important to emphasize here that using red and green, while intuitive, `should be avoided `_.\\n\",\n \"\\n\",\n \"Other diverging palettes\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"There are a few other good diverging palettes built into matplotlib, including Color Brewer palettes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"Spectral\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"And the ``coolwarm`` palette, which has less contrast between the middle values and the extremes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.color_palette(\\\"coolwarm\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As you can see, there are many options for using color in your visualizations. Seaborn tries both to use good defaults and to offer a lot of flexibility.\\n\",\n \"\\n\",\n \"This discussion is only the beginning, and there are a number of good resources for learning more about techniques for using color in visualizations. One great example is this `series of blog posts `_ from the NASA Earth Observatory. The matplotlib docs also have a `nice tutorial `_ that illustrates some of the perceptual properties of their colormaps.\"\n ]\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"fileName":"test_algorithms.py","filePath":"tests","id":2353,"nodeType":"File","text":"import numpy as np\nimport numpy.random as npr\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn import algorithms as algo\nfrom seaborn.external.version import Version\n\n\n@pytest.fixture\ndef random():\n np.random.seed(sum(map(ord, \"test_algorithms\")))\n\n\ndef test_bootstrap(random):\n \"\"\"Test that bootstrapping gives the right answer in dumb cases.\"\"\"\n a_ones = np.ones(10)\n n_boot = 5\n out1 = algo.bootstrap(a_ones, n_boot=n_boot)\n assert_array_equal(out1, np.ones(n_boot))\n out2 = algo.bootstrap(a_ones, n_boot=n_boot, func=np.median)\n assert_array_equal(out2, np.ones(n_boot))\n\n\ndef test_bootstrap_length(random):\n \"\"\"Test that we get a bootstrap array of the right shape.\"\"\"\n a_norm = np.random.randn(1000)\n out = algo.bootstrap(a_norm)\n assert len(out) == 10000\n\n n_boot = 100\n out = algo.bootstrap(a_norm, n_boot=n_boot)\n assert len(out) == n_boot\n\n\ndef test_bootstrap_range(random):\n \"\"\"Test that bootstrapping a random array stays within the right range.\"\"\"\n a_norm = np.random.randn(1000)\n amin, amax = a_norm.min(), a_norm.max()\n out = algo.bootstrap(a_norm)\n assert amin <= out.min()\n assert amax >= out.max()\n\n\ndef test_bootstrap_multiarg(random):\n \"\"\"Test that bootstrap works with multiple input arrays.\"\"\"\n x = np.vstack([[1, 10] for i in range(10)])\n y = np.vstack([[5, 5] for i in range(10)])\n\n def f(x, y):\n return np.vstack((x, y)).max(axis=0)\n\n out_actual = algo.bootstrap(x, y, n_boot=2, func=f)\n out_wanted = np.array([[5, 10], [5, 10]])\n assert_array_equal(out_actual, out_wanted)\n\n\ndef test_bootstrap_axis(random):\n \"\"\"Test axis kwarg to bootstrap function.\"\"\"\n x = np.random.randn(10, 20)\n n_boot = 100\n\n out_default = algo.bootstrap(x, n_boot=n_boot)\n assert out_default.shape == (n_boot,)\n\n out_axis = algo.bootstrap(x, n_boot=n_boot, axis=0)\n assert out_axis.shape, (n_boot, x.shape[1])\n\n\ndef test_bootstrap_seed(random):\n \"\"\"Test that we can get reproducible resamples by seeding the RNG.\"\"\"\n data = np.random.randn(50)\n seed = 42\n boots1 = algo.bootstrap(data, seed=seed)\n boots2 = algo.bootstrap(data, seed=seed)\n assert_array_equal(boots1, boots2)\n\n\ndef test_bootstrap_ols(random):\n \"\"\"Test bootstrap of OLS model fit.\"\"\"\n def ols_fit(X, y):\n XtXinv = np.linalg.inv(np.dot(X.T, X))\n return XtXinv.dot(X.T).dot(y)\n\n X = np.column_stack((np.random.randn(50, 4), np.ones(50)))\n w = [2, 4, 0, 3, 5]\n y_noisy = np.dot(X, w) + np.random.randn(50) * 20\n y_lownoise = np.dot(X, w) + np.random.randn(50)\n\n n_boot = 500\n w_boot_noisy = algo.bootstrap(X, y_noisy,\n n_boot=n_boot,\n func=ols_fit)\n w_boot_lownoise = algo.bootstrap(X, y_lownoise,\n n_boot=n_boot,\n func=ols_fit)\n\n assert w_boot_noisy.shape == (n_boot, 5)\n assert w_boot_lownoise.shape == (n_boot, 5)\n assert w_boot_noisy.std() > w_boot_lownoise.std()\n\n\ndef test_bootstrap_units(random):\n \"\"\"Test that results make sense when passing unit IDs to bootstrap.\"\"\"\n data = np.random.randn(50)\n ids = np.repeat(range(10), 5)\n bwerr = np.random.normal(0, 2, 10)\n bwerr = bwerr[ids]\n data_rm = data + bwerr\n seed = 77\n\n boots_orig = algo.bootstrap(data_rm, seed=seed)\n boots_rm = algo.bootstrap(data_rm, units=ids, seed=seed)\n assert boots_rm.std() > boots_orig.std()\n\n\ndef test_bootstrap_arglength():\n \"\"\"Test that different length args raise ValueError.\"\"\"\n with pytest.raises(ValueError):\n algo.bootstrap(np.arange(5), np.arange(10))\n\n\ndef test_bootstrap_string_func():\n \"\"\"Test that named numpy methods are the same as the numpy function.\"\"\"\n x = np.random.randn(100)\n\n res_a = algo.bootstrap(x, func=\"mean\", seed=0)\n res_b = algo.bootstrap(x, func=np.mean, seed=0)\n assert np.array_equal(res_a, res_b)\n\n res_a = algo.bootstrap(x, func=\"std\", seed=0)\n res_b = algo.bootstrap(x, func=np.std, seed=0)\n assert np.array_equal(res_a, res_b)\n\n with pytest.raises(AttributeError):\n algo.bootstrap(x, func=\"not_a_method_name\")\n\n\ndef test_bootstrap_reproducibility(random):\n \"\"\"Test that bootstrapping uses the internal random state.\"\"\"\n data = np.random.randn(50)\n boots1 = algo.bootstrap(data, seed=100)\n boots2 = algo.bootstrap(data, seed=100)\n assert_array_equal(boots1, boots2)\n\n with pytest.warns(UserWarning):\n # Deprecatd, remove when removing random_seed\n boots1 = algo.bootstrap(data, random_seed=100)\n boots2 = algo.bootstrap(data, random_seed=100)\n assert_array_equal(boots1, boots2)\n\n\n@pytest.mark.skipif(Version(np.__version__) < Version(\"1.17\"),\n reason=\"Tests new numpy random functionality\")\ndef test_seed_new():\n\n # Can't use pytest parametrize because tests will fail where the new\n # Generator object and related function are not defined\n\n test_bank = [\n (None, None, npr.Generator, False),\n (npr.RandomState(0), npr.RandomState(0), npr.RandomState, True),\n (npr.RandomState(0), npr.RandomState(1), npr.RandomState, False),\n (npr.default_rng(1), npr.default_rng(1), npr.Generator, True),\n (npr.default_rng(1), npr.default_rng(2), npr.Generator, False),\n (npr.SeedSequence(10), npr.SeedSequence(10), npr.Generator, True),\n (npr.SeedSequence(10), npr.SeedSequence(20), npr.Generator, False),\n (100, 100, npr.Generator, True),\n (100, 200, npr.Generator, False),\n ]\n for seed1, seed2, rng_class, match in test_bank:\n rng1 = algo._handle_random_seed(seed1)\n rng2 = algo._handle_random_seed(seed2)\n assert isinstance(rng1, rng_class)\n assert isinstance(rng2, rng_class)\n assert (rng1.uniform() == rng2.uniform()) == match\n\n\n@pytest.mark.skipif(Version(np.__version__) >= Version(\"1.17\"),\n reason=\"Tests old numpy random functionality\")\n@pytest.mark.parametrize(\"seed1, seed2, match\", [\n (None, None, False),\n (npr.RandomState(0), npr.RandomState(0), True),\n (npr.RandomState(0), npr.RandomState(1), False),\n (100, 100, True),\n (100, 200, False),\n])\ndef test_seed_old(seed1, seed2, match):\n rng1 = algo._handle_random_seed(seed1)\n rng2 = algo._handle_random_seed(seed2)\n assert isinstance(rng1, np.random.RandomState)\n assert isinstance(rng2, np.random.RandomState)\n assert (rng1.uniform() == rng2.uniform()) == match\n\n\n@pytest.mark.skipif(Version(np.__version__) >= Version(\"1.17\"),\n reason=\"Tests old numpy random functionality\")\ndef test_bad_seed_old():\n\n with pytest.raises(ValueError):\n algo._handle_random_seed(\"not_a_random_seed\")\n\n\ndef test_nanaware_func_auto(random):\n\n x = np.random.normal(size=10)\n x[0] = np.nan\n boots = algo.bootstrap(x, func=\"mean\")\n assert not np.isnan(boots).any()\n\n\ndef test_nanaware_func_warning(random):\n\n x = np.random.normal(size=10)\n x[0] = np.nan\n with pytest.warns(UserWarning, match=\"Data contain nans but\"):\n boots = algo.bootstrap(x, func=\"ptp\")\n assert np.isnan(boots).any()\n"},{"id":2354,"name":"objects.Plot.on.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"id\": \"fb8e120d-5dcf-483b-a0d1-74857d09ce7d\",\n \"metadata\": {},\n \"source\": [\n \".. currentmodule:: seaborn.objects\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"%config InlineBackend.figure_format = \\\"retina\\\"\\n\",\n \"import seaborn as sns\\n\",\n \"import seaborn.objects as so\\n\",\n \"import matplotlib as mpl\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"from seaborn import load_dataset\\n\",\n \"diamonds = load_dataset(\\\"diamonds\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3445ed22-7a6a-4f91-8914-49bb1af023cb\",\n \"metadata\": {},\n \"source\": [\n \"Passing a :class:`matplotlib.axes.Axes` object provides functionality closest to seaborn's axes-level plotting functions. Notice how the resulting image looks different from others created with :class:`Plot`. This is because the plot theme uses the global rcParams at the time the axes were created, rather than :class:`Plot` defaults:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b816b0b1-b861-404e-bec6-9b2b0844ea5a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(diamonds, \\\"carat\\\", \\\"price\\\").add(so.Dots())\\n\",\n \"f, ax = plt.subplots()\\n\",\n \"p.on(ax).show()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"ce3aa102-50fe-44ce-9e06-e25d14b410f1\",\n \"metadata\": {},\n \"source\": [\n \"Alternatively, calling :func:`matplotlib.pyplot.figure` will defer axes creation to :class:`Plot`, which will apply the default theme (and any customizations specified with :meth:`Plot.theme`):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"52eefae9-d08e-48fb-a15b-27920609d53b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f = plt.figure()\\n\",\n \"p.on(f).show()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"171fa466-1f7a-4c5e-8a12-61edb3f11e4a\",\n \"metadata\": {},\n \"source\": [\n \"Creating a :class:`matplotlib.figure.Figure` object will bypass `pyplot` altogether. This may be useful for embedding :class:`Plot` figures in a GUI application:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"bba83103-ab74-4e3c-b16e-77644f4c0431\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f = mpl.figure.Figure()\\n\",\n \"p.on(f).plot()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"4cce3d40-acea-4f5c-87c4-56666480d2fe\",\n \"metadata\": {},\n \"source\": [\n \"Using :class:`Plot.on` also provides access to the underlying matplotlib objects, which may be useful for deep customization. But it requires a careful attention to the order of operations by which the :class:`Plot` is specified, compiled, customized, and displayed:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"91823d24-8269-4b72-abeb-38201eb2db3f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f = mpl.figure.Figure()\\n\",\n \"res = p.on(f).plot()\\n\",\n \"\\n\",\n \"ax = f.axes[0]\\n\",\n \"rect = mpl.patches.Rectangle(\\n\",\n \" xy=(0, 1), width=.4, height=.1,\\n\",\n \" color=\\\"C1\\\", alpha=.2,\\n\",\n \" transform=ax.transAxes, clip_on=False,\\n\",\n \")\\n\",\n \"ax.add_artist(rect)\\n\",\n \"ax.text(\\n\",\n \" x=rect.get_width() / 2, y=1 + rect.get_height() / 2,\\n\",\n \" s=\\\"Diamonds: very sparkly!\\\", size=12,\\n\",\n \" ha=\\\"center\\\", va=\\\"center\\\", transform=ax.transAxes,\\n\",\n \")\\n\",\n \"\\n\",\n \"res\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"61286891-25b3-4db5-8ebe-af080d5c5f31\",\n \"metadata\": {},\n \"source\": [\n \"Matplotlib 3.4 introduced the concept of :meth:`matplotlib.figure.Figure.subfigures`, which make it easier to composite multiple arrangements of subplots. These can also be passed to :meth:`Plot.on`, \"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ca19a28e-7a49-46b3-a727-a26f4a1099c3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"f = mpl.figure.Figure(figsize=(7, 4), dpi=100, layout=\\\"constrained\\\")\\n\",\n \"sf1, sf2 = f.subfigures(1, 2)\\n\",\n \"\\n\",\n \"p.on(sf1).plot()\\n\",\n \"(\\n\",\n \" so.Plot(diamonds, x=\\\"price\\\")\\n\",\n \" .add(so.Bars(), so.Hist())\\n\",\n \" .facet(row=\\\"cut\\\")\\n\",\n \" .scale(x=\\\"log\\\")\\n\",\n \" .share(y=False)\\n\",\n \" .on(sf2)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6ecd4166-939d-4925-92be-bf886a16ae94\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2355,"name":"objects.Hist.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"59690096-a0ad-4ff3-b82c-0258d724035a\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"penguins = load_dataset(\\\"penguins\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"c345a35c-bac8-4163-ba40-e7c208df1033\",\n \"metadata\": {},\n \"source\": [\n \"For discrete or categorical variables, this stat is commonly combined with a :class:`Bar` mark:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6a96ac9b-1240-496d-9385-840205945208\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(penguins, \\\"island\\\").add(so.Bar(), so.Hist())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1e5ff9d5-c6a9-4adc-a9be-0f155b1575be\",\n \"metadata\": {},\n \"source\": [\n \"When used to estimate a univariate distribution, it is better to use the :class:`Bars` mark:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"7f3e3144-752a-4d71-9528-85eb1ed0a9a4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(penguins, \\\"flipper_length_mm\\\")\\n\",\n \"p.add(so.Bars(), so.Hist())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"008b9ffe-da74-4406-9756-4f70e333f33b\",\n \"metadata\": {},\n \"source\": [\n \"The granularity of the bins will influence whether the underlying distribution is accurately represented. Adjust it by setting the total number:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"27d221d5-add5-40a8-85d2-05102384dad1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Bars(), so.Hist(bins=20))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fffebb54-0299-45c5-b7fb-6fcad6427239\",\n \"metadata\": {},\n \"source\": [\n \"Alternatively, specify the *width* of the bins:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d036ca65-7dcf-45ac-a2d1-caafb9f922a7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Bars(), so.Hist(binwidth=5))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"bc1e4bd3-2a16-42bd-9c13-a660dd381f66\",\n \"metadata\": {},\n \"source\": [\n \"By default, the transform returns the count of observations in each bin. The counts can be normalized, e.g. to show a proportion:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"dbf23712-2231-4226-8265-0e2a5299c4bb\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Bars(), so.Hist(stat=\\\"proportion\\\"))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"6c6fb23e-78c5-4630-a958-62cb4dee4ec8\",\n \"metadata\": {},\n \"source\": [\n \"When additional variables define groups, the default behavior is to normalize across all groups:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ac3fe4ef-56e3-4ec7-b580-596d2a3d924b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = p.facet(\\\"island\\\")\\n\",\n \"p.add(so.Bars(), so.Hist(stat=\\\"proportion\\\"))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f7afc403-26cc-4325-a28a-913c2291aa35\",\n \"metadata\": {},\n \"source\": [\n \"Pass `common_norm=False` to normalize each distribution independently:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b2029324-069f-4261-a178-1efad2fd0e88\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Bars(), so.Hist(stat=\\\"proportion\\\", common_norm=False))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0f83401a-e456-4a14-af69-f1483c6c03c4\",\n \"metadata\": {},\n \"source\": [\n \"Or, with more than one grouping varible, specify a subset to normalize within:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5c092262-8a8f-4a3e-8cae-9e0f23dd94ba\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Bars(), so.Hist(stat=\\\"proportion\\\", common_norm=[\\\"col\\\"]), color=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"86532133-bf33-4674-9614-86ae3408aa51\",\n \"metadata\": {},\n \"source\": [\n \"When distributions overlap it may be easier to discern their shapes with an :class:`Area` mark:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"00b18ad8-52d4-460a-a012-d87c66b3e71e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Area(), so.Hist(), color=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"2b34d435-abbf-41aa-b219-91883d7d29f3\",\n \"metadata\": {},\n \"source\": [\n \"Or add :class:`Stack` move to represent a part-whole relationship:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"3a7a0c05-d774-4f99-950f-5dc9865027c4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Bars(), so.Hist(), so.Stack(), color=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e247e74b-2c09-40f0-8f45-9fa5f8264d78\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"multiple_regression.py","filePath":"examples","id":2356,"nodeType":"File","text":"\"\"\"\nMultiple linear regression\n==========================\n\n_thumb: .45, .45\n\"\"\"\nimport seaborn as sns\nsns.set_theme()\n\n# Load the penguins dataset\npenguins = sns.load_dataset(\"penguins\")\n\n# Plot sepal width as a function of sepal_length across days\ng = sns.lmplot(\n data=penguins,\n x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\",\n height=5\n)\n\n# Use more informative axis labels than are provided by default\ng.set_axis_labels(\"Snoot length (mm)\", \"Snoot depth (mm)\")\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2357,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":2358,"name":"penguins","nodeType":"Attribute","startLoc":11,"text":"penguins"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":2359,"name":"g","nodeType":"Attribute","startLoc":14,"text":"g"},{"col":4,"comment":"Return unit of width separating categories on native numeric scale.","endLoc":234,"header":"@property\n def _native_width(self)","id":2360,"name":"_native_width","nodeType":"Function","startLoc":226,"text":"@property\n def _native_width(self):\n \"\"\"Return unit of width separating categories on native numeric scale.\"\"\"\n unique_values = np.unique(self.comp_data[self.cat_axis])\n if len(unique_values) > 1:\n native_width = np.nanmin(np.diff(unique_values))\n else:\n native_width = 1\n return native_width"},{"col":0,"comment":"","endLoc":6,"header":"multiple_regression.py#","id":2361,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nMultiple linear regression\n==========================\n\n_thumb: .45, .45\n\"\"\"\n\nsns.set_theme()\n\npenguins = sns.load_dataset(\"penguins\")\n\ng = sns.lmplot(\n data=penguins,\n x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\",\n height=5\n)\n\ng.set_axis_labels(\"Snoot length (mm)\", \"Snoot depth (mm)\")"},{"col":0,"comment":"null","endLoc":13,"header":"@pytest.fixture\ndef random()","id":2362,"name":"random","nodeType":"Function","startLoc":11,"text":"@pytest.fixture\ndef random():\n np.random.seed(sum(map(ord, \"test_algorithms\")))"},{"id":2363,"name":"regression.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _regression_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Estimating regression fits\\n\",\n \"==========================\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Many datasets contain multiple quantitative variables, and the goal of an analysis is often to relate those variables to each other. We :ref:`previously discussed ` functions that can accomplish this by showing the joint distribution of two variables. It can be very helpful, though, to use statistical models to estimate a simple relationship between two noisy sets of observations. The functions discussed in this chapter will do so through the common framework of linear regression.\\n\",\n \"\\n\",\n \"In the spirit of Tukey, the regression plots in seaborn are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. That is to say that seaborn is not itself a package for statistical analysis. To obtain quantitative measures related to the fit of regression models, you should use `statsmodels `_. The goal of seaborn, however, is to make exploring a dataset through visualization quick and easy, as doing so is just as (if not more) important than exploring a dataset through tables of statistics.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"sns.set_theme(color_codes=True)\\n\",\n \"np.random.seed(sum(map(ord, \\\"regression\\\")))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Functions for drawing linear regression models\\n\",\n \"----------------------------------------------\\n\",\n \"\\n\",\n \"The two functions that can be used to visualize a linear fit are :func:`regplot` and :func:`lmplot`.\\n\",\n \"\\n\",\n \"In the simplest invocation, both functions draw a scatterplot of two variables, ``x`` and ``y``, and then fit the regression model ``y ~ x`` and plot the resulting regression line and a 95% confidence interval for that regression:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.regplot(x=\\\"total_bill\\\", y=\\\"tip\\\", data=tips);\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"tip\\\", data=tips);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"These functions draw similar plots, but :func:regplot` is an :doc:`axes-level function `, and :func:`lmplot` is a figure-level function. Additionally, :func:`regplot` accepts the ``x`` and ``y`` variables in a variety of formats including simple numpy arrays, :class:`pandas.Series` objects, or as references to variables in a :class:`pandas.DataFrame` object passed to `data`. In contrast, :func:`lmplot` has `data` as a required parameter and the `x` and `y` variables must be specified as strings. Finally, only :func:`lmplot` has `hue` as a parameter.\\n\",\n \"\\n\",\n \"The core functionality is otherwise similar, though, so this tutorial will focus on :func:`lmplot`:.\\n\",\n \"\\n\",\n \"It's possible to fit a linear regression when one of the variables takes discrete values, however, the simple scatterplot produced by this kind of dataset is often not optimal:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"size\\\", y=\\\"tip\\\", data=tips);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"One option is to add some random noise (\\\"jitter\\\") to the discrete values to make the distribution of those values more clear. Note that jitter is applied only to the scatterplot data and does not influence the regression line fit itself:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"size\\\", y=\\\"tip\\\", data=tips, x_jitter=.05);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A second option is to collapse over the observations in each discrete bin to plot an estimate of central tendency along with a confidence interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"size\\\", y=\\\"tip\\\", data=tips, x_estimator=np.mean);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Fitting different kinds of models\\n\",\n \"---------------------------------\\n\",\n \"\\n\",\n \"The simple linear regression model used above is very simple to fit, however, it is not appropriate for some kinds of datasets. The `Anscombe's quartet `_ dataset shows a few examples where simple linear regression provides an identical estimate of a relationship where simple visual inspection clearly shows differences. For example, in the first case, the linear regression is a good model:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"anscombe = sns.load_dataset(\\\"anscombe\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'I'\\\"),\\n\",\n \" ci=None, scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The linear relationship in the second dataset is the same, but the plot clearly shows that this is not a good model:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'II'\\\"),\\n\",\n \" ci=None, scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In the presence of these kind of higher-order relationships, :func:`lmplot` and :func:`regplot` can fit a polynomial regression model to explore simple kinds of nonlinear trends in the dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'II'\\\"),\\n\",\n \" order=2, ci=None, scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"A different problem is posed by \\\"outlier\\\" observations that deviate for some reason other than the main relationship under study:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'III'\\\"),\\n\",\n \" ci=None, scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In the presence of outliers, it can be useful to fit a robust regression, which uses a different loss function to downweight relatively large residuals:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'III'\\\"),\\n\",\n \" robust=True, ci=None, scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When the ``y`` variable is binary, simple linear regression also \\\"works\\\" but provides implausible predictions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips[\\\"big_tip\\\"] = (tips.tip / tips.total_bill) > .15\\n\",\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"big_tip\\\", data=tips,\\n\",\n \" y_jitter=.03);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The solution in this case is to fit a logistic regression, such that the regression line shows the estimated probability of ``y = 1`` for a given value of ``x``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"big_tip\\\", data=tips,\\n\",\n \" logistic=True, y_jitter=.03);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Note that the logistic regression estimate is considerably more computationally intensive (this is true of robust regression as well). As the confidence interval around the regression line is computed using a bootstrap procedure, you may wish to turn this off for faster iteration (using ``ci=None``).\\n\",\n \"\\n\",\n \"An altogether different approach is to fit a nonparametric regression using a `lowess smoother `_. This approach has the fewest assumptions, although it is computationally intensive and so currently confidence intervals are not computed at all:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"tip\\\", data=tips,\\n\",\n \" lowess=True, line_kws={\\\"color\\\": \\\"C1\\\"});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The :func:`residplot` function can be a useful tool for checking whether the simple regression model is appropriate for a dataset. It fits and removes a simple linear regression and then plots the residual values for each observation. Ideally, these values should be randomly scattered around ``y = 0``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.residplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'I'\\\"),\\n\",\n \" scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If there is structure in the residuals, it suggests that simple linear regression is not appropriate:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.residplot(x=\\\"x\\\", y=\\\"y\\\", data=anscombe.query(\\\"dataset == 'II'\\\"),\\n\",\n \" scatter_kws={\\\"s\\\": 80});\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Conditioning on other variables\\n\",\n \"-------------------------------\\n\",\n \"\\n\",\n \"The plots above show many ways to explore the relationship between a pair of variables. Often, however, a more interesting question is \\\"how does the relationship between these two variables change as a function of a third variable?\\\" This is where the main differences between :func:`regplot` and :func:`lmplot` appear. While :func:`regplot` always shows a single relationship, :func:`lmplot` combines :func:`regplot` with :class:`FacetGrid` to show multiple fits using `hue` mapping or faceting.\\n\",\n \"\\n\",\n \"The best way to separate out a relationship is to plot both levels on the same axes and to use color to distinguish them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\", data=tips);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Unlike :func:`relplot`, it's not possible to map a distinct variable to the style properties of the scatter plot, but you can redundantly code the `hue` variable with marker shape:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\", data=tips,\\n\",\n \" markers=[\\\"o\\\", \\\"x\\\"], palette=\\\"Set1\\\");\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To add another variable, you can draw multiple \\\"facets\\\" with each level of the variable appearing in the rows or columns of the grid:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\", col=\\\"time\\\", data=tips);\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.lmplot(x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\",\\n\",\n \" col=\\\"time\\\", row=\\\"sex\\\", data=tips, height=3);\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Plotting a regression in other contexts\\n\",\n \"---------------------------------------\\n\",\n \"\\n\",\n \"A few other seaborn functions use :func:`regplot` in the context of a larger, more complex plot. The first is the :func:`jointplot` function that we introduced in the :ref:`distributions tutorial `. In addition to the plot styles previously discussed, :func:`jointplot` can use :func:`regplot` to show the linear regression fit on the joint axes by passing ``kind=\\\"reg\\\"``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.jointplot(x=\\\"total_bill\\\", y=\\\"tip\\\", data=tips, kind=\\\"reg\\\");\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Using the :func:`pairplot` function with ``kind=\\\"reg\\\"`` combines :func:`regplot` and :class:`PairGrid` to show the linear relationship between variables in a dataset. Take care to note how this is different from :func:`lmplot`. In the figure below, the two axes don't show the same relationship conditioned on two levels of a third variable; rather, :func:`PairGrid` is used to show multiple relationships between different pairings of the variables in a dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.pairplot(tips, x_vars=[\\\"total_bill\\\", \\\"size\\\"], y_vars=[\\\"tip\\\"],\\n\",\n \" height=5, aspect=.8, kind=\\\"reg\\\");\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Conditioning on an additional categorical variable is built into both of these functions using the ``hue`` parameter:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.pairplot(tips, x_vars=[\\\"total_bill\\\", \\\"size\\\"], y_vars=[\\\"tip\\\"],\\n\",\n \" hue=\\\"smoker\\\", height=5, aspect=.8, kind=\\\"reg\\\");\"\n ]\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"col":4,"comment":"Return offsets for each hue level for dodged plots.","endLoc":247,"header":"def _nested_offsets(self, width, dodge)","id":2364,"name":"_nested_offsets","nodeType":"Function","startLoc":236,"text":"def _nested_offsets(self, width, dodge):\n \"\"\"Return offsets for each hue level for dodged plots.\"\"\"\n offsets = None\n if \"hue\" in self.variables:\n n_levels = len(self._hue_map.levels)\n if dodge:\n each_width = width / n_levels\n offsets = np.linspace(0, width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n return offsets"},{"col":4,"comment":"null","endLoc":319,"header":"def plot_strips(\n self,\n jitter,\n dodge,\n color,\n edgecolor,\n plot_kws,\n )","id":2365,"name":"plot_strips","nodeType":"Function","startLoc":255,"text":"def plot_strips(\n self,\n jitter,\n dodge,\n color,\n edgecolor,\n plot_kws,\n ):\n\n width = .8 * self._native_width\n offsets = self._nested_offsets(width, dodge)\n\n if jitter is True:\n jlim = 0.1\n else:\n jlim = float(jitter)\n if \"hue\" in self.variables and dodge:\n jlim /= len(self._hue_map.levels)\n jlim *= self._native_width\n jitterer = partial(np.random.uniform, low=-jlim, high=+jlim)\n\n iter_vars = [self.cat_axis]\n if dodge:\n iter_vars.append(\"hue\")\n\n ax = self.ax\n dodge_move = jitter_move = 0\n\n for sub_vars, sub_data in self.iter_data(iter_vars,\n from_comp_data=True,\n allow_empty=True):\n if offsets is not None and (offsets != 0).any():\n dodge_move = offsets[sub_data[\"hue\"].map(self._hue_map.levels.index)]\n\n jitter_move = jitterer(size=len(sub_data)) if len(sub_data) > 1 else 0\n\n adjusted_data = sub_data[self.cat_axis] + dodge_move + jitter_move\n sub_data[self.cat_axis] = adjusted_data\n\n for var in \"xy\":\n if self._log_scaled(var):\n sub_data[var] = np.power(10, sub_data[var])\n\n ax = self._get_axes(sub_vars)\n points = ax.scatter(sub_data[\"x\"], sub_data[\"y\"], color=color, **plot_kws)\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(sub_data[\"hue\"]))\n\n if edgecolor == \"gray\": # XXX TODO change to \"auto\"\n points.set_edgecolors(self._get_gray(points.get_facecolors()))\n else:\n points.set_edgecolors(edgecolor)\n\n # Finalize the axes details\n if self.legend == \"auto\":\n show_legend = not self._redundant_hue and self.input_format != \"wide\"\n else:\n show_legend = bool(self.legend)\n\n if show_legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n ax.legend(title=self.legend_title)"},{"id":2366,"name":"dark_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5cd1cbb8-ba1a-460b-8e3a-bc285867f1d1\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b157eb25-015f-4dd6-9785-83ba19cf4f94\",\n \"metadata\": {},\n \"source\": [\n \"Define a sequential ramp from a dark gray to a specified color:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"5b655d28-9855-4528-8b8e-a6c50288fd1b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.dark_palette(\\\"seagreen\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"50053b26-112a-4378-8ef0-9be0fb565ec7\",\n \"metadata\": {},\n \"source\": [\n \"Specify the color with a hex code:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"74ae0d17-f65b-4bcf-ae66-d97d46964d5c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.dark_palette(\\\"#79C\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"eea376a2-fdf5-40e4-a187-3a28af529072\",\n \"metadata\": {},\n \"source\": [\n \"Specify the color from the husl system:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"66e451ee-869a-41ea-8dc5-4240b11e7be5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.dark_palette((20, 60, 50), input=\\\"husl\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e4f44dcd-cf49-4920-ac05-b4db67870363\",\n \"metadata\": {},\n \"source\": [\n \"Increase the number of colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"75985f07-de92-4d8b-89d5-caf445b9375e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.dark_palette(\\\"xkcd:golden\\\", 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"34687ae8-fd6d-427a-a639-208f19e61122\",\n \"metadata\": {},\n \"source\": [\n \"Return a continuous colormap rather than a discrete palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2c342db4-7f97-40f5-934e-9a82201890d1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.dark_palette(\\\"#b285bc\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e7ebe64b-25fa-4c52-9ebe-fdcbba0ee51e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2367,"name":".gitignore","nodeType":"TextFile","path":"","text":"*.pyc\n*.sw*\nbuild/\n.ipynb_checkpoints/\ndist/\nseaborn.egg-info/\n.cache/\n.coverage\ncover/\nhtmlcov/\n.idea/\n.vscode/\n.pytest_cache/\n.DS_Store\nnotes/\nnotebooks/\n"},{"fileName":"__init__.py","filePath":"seaborn/_marks","id":2368,"nodeType":"File","text":""},{"id":2369,"name":"mpl_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1d0d41d3-463c-4c6f-aa65-38131bdf3ddb\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"d2a0ae1e-a01e-49b3-a677-2b05a195990a\",\n \"metadata\": {},\n \"source\": [\n \"Return discrete samples from a continuous matplotlib colormap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2b6a4ce9-6e4e-4b59-ada8-14ef8aef21d7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.mpl_palette(\\\"viridis\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0ccc47b1-c969-46e2-93bb-b9eb5a2e2141\",\n \"metadata\": {},\n \"source\": [\n \"Return the continuous colormap instead; note how the extreme values are more intense:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a8a1bc5d-1d62-45c6-a53b-9fadb58f11c0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.mpl_palette(\\\"viridis\\\", as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"ff0d1a3b-8641-40c0-bb4b-c22b83ec9432\",\n \"metadata\": {},\n \"source\": [\n \"Return more colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"8faef1d8-a1eb-4060-be10-377342c9bd1d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.mpl_palette(\\\"viridis\\\", 8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"612bf052-e888-411d-a2ea-6a742a78bc63\",\n \"metadata\": {},\n \"source\": [\n \"Return values from a qualitative colormap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"74db95a8-4898-4f6c-a57d-c751af1dc7bf\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.mpl_palette(\\\"Set2\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"918494bf-1b8e-4b00-8950-1bd73032dee1\",\n \"metadata\": {},\n \"source\": [\n \"Notice how the palette will only contain distinct colors and can be shorter than requested:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d97efa25-9050-4e28-b758-da6f43c9f963\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.mpl_palette(\\\"Set2\\\", 10)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f64ad118-e213-43cc-a714-98ed13cc3824\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2370,"name":"catplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a8aa6a6a-f6c0-4a6b-9460-2056e58a2e13\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1aef2740-ae6e-4a1b-a588-3ad978e2614d\",\n \"metadata\": {},\n \"source\": [\n \"By default, the visual representation will be a jittered strip plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"75a49e26-4318-4963-897c-dc0081aebfb3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"df = sns.load_dataset(\\\"titanic\\\")\\n\",\n \"sns.catplot(data=df, x=\\\"age\\\", y=\\\"class\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"db1b8f6d-5264-4200-b81a-b0ee64040a1f\",\n \"metadata\": {},\n \"source\": [\n \"Use `kind` to select a different representation:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"75ecd034-8536-4fe4-8852-a3975dba64dc\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=df, x=\\\"age\\\", y=\\\"class\\\", kind=\\\"box\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"8aee79a9-b8b3-4129-b6d7-e9e32ae1e634\",\n \"metadata\": {},\n \"source\": [\n \"One advantage is that the legend will be automatically placed outside the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"3798aac6-1ff6-4e36-ad83-4742fcb04159\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=df, x=\\\"age\\\", y=\\\"class\\\", hue=\\\"sex\\\", kind=\\\"boxen\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"8a3777e1-90b6-4f4d-9e14-247b6dfd64fe\",\n \"metadata\": {},\n \"source\": [\n \"Additional keyword arguments get passed through to the underlying seaborn function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"afcff2fe-db11-4602-af79-68e4a0380f88\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=df, x=\\\"age\\\", y=\\\"class\\\", hue=\\\"sex\\\",\\n\",\n \" kind=\\\"violin\\\", bw=.25, cut=0, split=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"a75bf46f-a3d0-4a5d-abcd-b9e85def65b0\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a variable to `col` or `row` will automatically create subplots. Control figure size with the `height` and `aspect` parameters:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"835afcf2-ecc9-4edb-9ec8-24484c5b08fb\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(\\n\",\n \" data=df, x=\\\"class\\\", y=\\\"survived\\\", col=\\\"sex\\\",\\n\",\n \" kind=\\\"bar\\\", height=4, aspect=.6,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"ecf323fe-1e86-47ff-aa50-e8c297cfa125\",\n \"metadata\": {},\n \"source\": [\n \"For single-subplot figures, it is easy to layer different representations:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"dc5b0fc0-359c-4219-b04e-171d8c7c8051\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=df, x=\\\"age\\\", y=\\\"class\\\", kind=\\\"violin\\\", color=\\\".9\\\", inner=None)\\n\",\n \"sns.swarmplot(data=df, x=\\\"age\\\", y=\\\"class\\\", size=3)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"26e06ba4-0457-4597-b699-cb0fe8b2be32\",\n \"metadata\": {},\n \"source\": [\n \"Use methods on the returned :class:`FacetGrid` to tweak the presentation:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a43f1914-d868-4060-82df-b3d25553d595\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.catplot(\\n\",\n \" data=df, x=\\\"who\\\", y=\\\"survived\\\", col=\\\"class\\\",\\n\",\n \" kind=\\\"bar\\\", height=4, aspect=.6,\\n\",\n \")\\n\",\n \"g.set_axis_labels(\\\"\\\", \\\"Survival Rate\\\")\\n\",\n \"g.set_xticklabels([\\\"Men\\\", \\\"Women\\\", \\\"Children\\\"])\\n\",\n \"g.set_titles(\\\"{col_name} {col_var}\\\")\\n\",\n \"g.set(ylim=(0, 1))\\n\",\n \"g.despine(left=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a529c18c-45bc-4efb-8ae0-c14518349162\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2371,"name":"husl_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a6794650-f28f-40eb-95a7-3f0e5c4b332d\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fab2f86e-45d4-4982-ade7-0a5ea6d762d1\",\n \"metadata\": {},\n \"source\": [\n \"By default, return 6 colors with identical lightness and saturation and evenly-sampled hues:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b220950e-0ca2-4101-b56a-14eebe8ee8d0\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"c5e4a2e3-e6b8-42bf-be19-348ff7ae2798\",\n \"metadata\": {},\n \"source\": [\n \"Increase the number of colors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"7d0af740-cfca-49fb-a472-1daa4ccb3f3a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette(8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1a7189f2-2a26-446a-90e7-cf41dcac4f25\",\n \"metadata\": {},\n \"source\": [\n \"Decrease the lightness:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"43af79c7-f497-41e5-874a-83eed99500f3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette(l=.4)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"6d4099b7-5115-4365-b120-33a345581f5d\",\n \"metadata\": {},\n \"source\": [\n \"Decrease the saturation:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"52c1afc7-d982-4199-b218-222aa94563c5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette(s=.4)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"d26131ac-0d11-48c5-88b1-4e5cf9383000\",\n \"metadata\": {},\n \"source\": [\n \"Change the start-point for hue sampling:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d72f06a0-13e0-47f7-bc70-4c5935eaa130\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette(h=.5)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"7e6c3c19-41d3-4315-b03e-909d201d0e76\",\n \"metadata\": {},\n \"source\": [\n \"Return a continuous colormap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"49c18838-0589-496f-9a61-635195c07f61\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.husl_palette(as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c710a557-8e84-44cb-ab4c-baabcc4fd328\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2372,"name":"objects.Text.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"cd1cdefe-b8c1-40b9-be31-006d52ec9f18\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"glue = (\\n\",\n \" load_dataset(\\\"glue\\\")\\n\",\n \" .pivot(index=[\\\"Model\\\", \\\"Encoder\\\"], columns=\\\"Task\\\", values=\\\"Score\\\")\\n\",\n \" .assign(Average=lambda x: x.mean(axis=1).round(1))\\n\",\n \" .sort_values(\\\"Average\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"3e49ffb1-8778-4cd5-80d6-9d7e1438bc9c\",\n \"metadata\": {},\n \"source\": [\n \"Add text at x/y locations on the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"3bf21068-d39e-436c-8deb-aa1b15aeb2b3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(glue, x=\\\"SST-2\\\", y=\\\"MRPC\\\", text=\\\"Model\\\")\\n\",\n \" .add(so.Text())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a4b9a8b2-6603-46db-9ede-3b3fb45e0e64\",\n \"metadata\": {},\n \"source\": [\n \"Add bar annotations, horizontally-aligned with `halign`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f68501f0-c868-439e-9485-d71cca86ea47\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(glue, x=\\\"Average\\\", y=\\\"Model\\\", text=\\\"Average\\\")\\n\",\n \" .add(so.Bar())\\n\",\n \" .add(so.Text(color=\\\"w\\\", halign=\\\"right\\\"))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a9d39479-0afa-477b-8403-fe92a54643c9\",\n \"metadata\": {},\n \"source\": [\n \"Fine-tune the alignment using `offset`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b5da4a9d-79f3-4c11-bab3-f89da8512ce4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(glue, x=\\\"Average\\\", y=\\\"Model\\\", text=\\\"Average\\\")\\n\",\n \" .add(so.Bar())\\n\",\n \" .add(so.Text(color=\\\"w\\\", halign=\\\"right\\\", offset=6))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e9c43798-70d5-42b5-bd91-b85684d1b671\",\n \"metadata\": {},\n \"source\": [\n \"Add text above dots, mapping the text color with a third variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b2d26ebc-24ac-4531-9ba2-fa03720c58bc\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(glue, x=\\\"SST-2\\\", y=\\\"MRPC\\\", color=\\\"Encoder\\\", text=\\\"Model\\\")\\n\",\n \" .add(so.Dot())\\n\",\n \" .add(so.Text(valign=\\\"bottom\\\"))\\n\",\n \"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f31aaa38-6728-4299-8422-8762c52c9857\",\n \"metadata\": {},\n \"source\": [\n \"Map the text alignment for better use of space:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"cf4bbf0c-0c5f-4c31-b971-720ea8910918\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(glue, x=\\\"RTE\\\", y=\\\"MRPC\\\", color=\\\"Encoder\\\", text=\\\"Model\\\")\\n\",\n \" .add(so.Dot())\\n\",\n \" .add(so.Text(), halign=\\\"Encoder\\\")\\n\",\n \" .scale(halign={\\\"LSTM\\\": \\\"left\\\", \\\"Transformer\\\": \\\"right\\\"})\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a5de35a6-1ccf-4958-8013-edd9ed1cd4b0\",\n \"metadata\": {},\n \"source\": [\n \"Use additional matplotlib parameters to control the appearance of the text:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9c4be188-1614-4c19-9bd7-b07e986f6a23\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(glue, x=\\\"RTE\\\", y=\\\"MRPC\\\", color=\\\"Encoder\\\", text=\\\"Model\\\")\\n\",\n \" .add(so.Dot())\\n\",\n \" .add(so.Text({\\\"fontweight\\\": \\\"bold\\\"}), halign=\\\"Encoder\\\")\\n\",\n \" .scale(halign={\\\"LSTM\\\": \\\"left\\\", \\\"Transformer\\\": \\\"right\\\"})\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"95fb7aee-090a-4415-917c-b5258d2b298b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":2373,"name":"regplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"611aed40-d120-4fbf-b1e6-9712ed8167fc\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"mpg = sns.load_dataset(\\\"mpg\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"61bebade-0c45-4e99-9567-dfe0bc2dc6e1\",\n \"metadata\": {},\n \"source\": [\n \"Plot the relationship between two variables in a DataFrame:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2f4107db-d89b-46ad-a4c6-9ba1181b2122\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"weight\\\", y=\\\"acceleration\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"146225d0-2e38-4b92-8e64-6d7f78311f40\",\n \"metadata\": {},\n \"source\": [\n \"Fit a higher-order polynomial regression to capture nonlinear trends:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"ba29488c-8a45-4387-bfb1-71a584fa1b3d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"weight\\\", y=\\\"mpg\\\", order=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0ad71f54-b362-465e-8780-1d8b99ff2d51\",\n \"metadata\": {},\n \"source\": [\n \"Alternatively, fit a log-linear regression:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"aae2acaa-ed07-4568-97d2-8665603eb7eb\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"displacement\\\", y=\\\"mpg\\\", logx=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"eef37c8a-7190-465c-b963-076ec17e1b3a\",\n \"metadata\": {},\n \"source\": [\n \"Or use a locally-weighted (LOWESS) smoother:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9276c469-72ea-4c36-9b7c-19ecba564376\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"horsepower\\\", y=\\\"mpg\\\", lowess=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"d18f1534-598e-4f08-91dd-0c4020f30b00\",\n \"metadata\": {},\n \"source\": [\n \"Fit a logistic regression when the response variable is binary:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"79ec9180-10c9-4910-9713-dcd1fdd266be\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(x=mpg[\\\"weight\\\"], y=mpg[\\\"origin\\\"].eq(\\\"usa\\\").rename(\\\"from_usa\\\"), logistic=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"2e165783-d505-4acb-a20a-d22a49965c2b\",\n \"metadata\": {},\n \"source\": [\n \"Fit a robust regression to downweight the influence of outliers:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"fd5cf940-de8f-4230-8b04-5c650418f3c4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"horsepower\\\", y=\\\"weight\\\", robust=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e7d43c4e-e819-4634-8269-cbf5de4a2f24\",\n \"metadata\": {},\n \"source\": [\n \"Disable the confidence interval for faster plotting:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b21384ff-6395-4fa9-b7da-63e8a951d8a5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"weight\\\", y=\\\"horsepower\\\", ci=None)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"06e979ac-f418-4ead-bde1-ec684d0545ff\",\n \"metadata\": {},\n \"source\": [\n \"Jitter the scatterplot when the `x` variable is discrete:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"543a8ace-a89e-4af9-bf6d-a8722ebdfac5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"cylinders\\\", y=\\\"weight\\\", x_jitter=.15)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"c3042eb2-0933-4886-9bff-88c276371516\",\n \"metadata\": {},\n \"source\": [\n \"Or aggregate over the distinct `x` values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"158c6e36-8858-415b-b78c-7d8d79879ee5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"cylinders\\\", y=\\\"acceleration\\\", x_estimator=np.mean, order=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"d9cefe7a-7f86-4353-95da-d7e72e65d4fc\",\n \"metadata\": {},\n \"source\": [\n \"With a continuous `x` variable, bin and then aggregate:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1c48829b-2e3b-4e6b-9b1d-5ba69f713617\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(data=mpg, x=\\\"weight\\\", y=\\\"mpg\\\", x_bins=np.arange(2000, 5500, 250), order=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dfe5a36a-20b0-4e69-b986-fede8e1506cc\",\n \"metadata\": {},\n \"source\": [\n \"Customize the appearance of various elements:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"df689a39-c5e1-4f7b-a8f9-8ffb09b95238\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.regplot(\\n\",\n \" data=mpg, x=\\\"weight\\\", y=\\\"horsepower\\\",\\n\",\n \" ci=99, marker=\\\"x\\\", color=\\\".3\\\", line_kws=dict(color=\\\"r\\\"),\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d625745b-3706-447b-9224-88e6cb1eb7f9\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":115,"id":2374,"name":"nb","nodeType":"Attribute","startLoc":115,"text":"nb"},{"col":4,"comment":"null","endLoc":1193,"header":"def test_wide_vs_long_data(self, wide_df)","id":2375,"name":"test_wide_vs_long_data","nodeType":"Function","startLoc":1182,"text":"def test_wide_vs_long_data(self, wide_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=wide_df, ax=ax1, common_bins=False)\n\n for col in wide_df.columns[::-1]:\n histplot(data=wide_df, x=col, ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_height()\n assert a.get_xy() == b.get_xy()"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":118,"id":2376,"name":"kernel","nodeType":"Attribute","startLoc":118,"text":"kernel"},{"col":4,"comment":"null","endLoc":1204,"header":"def test_flat_vector(self, long_df)","id":2377,"name":"test_flat_vector","nodeType":"Function","startLoc":1195,"text":"def test_flat_vector(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=long_df[\"x\"], ax=ax1)\n histplot(data=long_df, x=\"x\", ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_height()\n assert a.get_xy() == b.get_xy()"},{"attributeType":"null","col":8,"comment":"null","endLoc":120,"id":2378,"name":"kernel","nodeType":"Attribute","startLoc":120,"text":"kernel"},{"attributeType":"null","col":4,"comment":"null","endLoc":121,"id":2379,"name":"ep","nodeType":"Attribute","startLoc":121,"text":"ep"},{"attributeType":"null","col":8,"comment":"null","endLoc":129,"id":2380,"name":"cell","nodeType":"Attribute","startLoc":129,"text":"cell"},{"attributeType":"null","col":8,"comment":"null","endLoc":132,"id":2381,"name":"fields","nodeType":"Attribute","startLoc":132,"text":"fields"},{"col":4,"comment":"null","endLoc":199,"header":"def test_figure_size(self)","id":2382,"name":"test_figure_size","nodeType":"Function","startLoc":190,"text":"def test_figure_size(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 9))\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", height=6)\n npt.assert_array_equal(g.figure.get_size_inches(), (12, 18))\n\n g = ag.FacetGrid(self.df, col=\"c\", height=4, aspect=.5)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))"},{"attributeType":"null","col":12,"comment":"null","endLoc":133,"id":2383,"name":"field","nodeType":"Attribute","startLoc":133,"text":"field"},{"attributeType":"null","col":16,"comment":"null","endLoc":135,"id":2384,"name":"data_keys","nodeType":"Attribute","startLoc":135,"text":"data_keys"},{"attributeType":"null","col":20,"comment":"null","endLoc":136,"id":2385,"name":"key","nodeType":"Attribute","startLoc":136,"text":"key"},{"col":4,"comment":"null","endLoc":212,"header":"def test_figure_size_with_legend(self)","id":2386,"name":"test_figure_size_with_legend","nodeType":"Function","startLoc":201,"text":"def test_figure_size_with_legend(self):\n\n g = ag.FacetGrid(self.df, col=\"a\", hue=\"c\", height=4, aspect=.5)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n g.add_legend()\n assert g.figure.get_size_inches()[0] > 6\n\n g = ag.FacetGrid(self.df, col=\"a\", hue=\"c\", height=4, aspect=.5,\n legend_out=False)\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))\n g.add_legend()\n npt.assert_array_equal(g.figure.get_size_inches(), (6, 4))"},{"attributeType":"null","col":4,"comment":"null","endLoc":143,"id":2387,"name":"exp","nodeType":"Attribute","startLoc":143,"text":"exp"},{"attributeType":"null","col":4,"comment":"null","endLoc":145,"id":2388,"name":"c","nodeType":"Attribute","startLoc":145,"text":"c"},{"attributeType":"set","col":4,"comment":"null","endLoc":146,"id":2389,"name":"remove_cell_tags","nodeType":"Attribute","startLoc":146,"text":"c.TagRemovePreprocessor.remove_cell_tags"},{"attributeType":"set","col":4,"comment":"null","endLoc":147,"id":2390,"name":"remove_input_tags","nodeType":"Attribute","startLoc":147,"text":"c.TagRemovePreprocessor.remove_input_tags"},{"attributeType":"set","col":4,"comment":"null","endLoc":148,"id":2391,"name":"remove_all_outputs_tags","nodeType":"Attribute","startLoc":148,"text":"c.TagRemovePreprocessor.remove_all_outputs_tags"},{"attributeType":"str","col":4,"comment":"null","endLoc":149,"id":2392,"name":"output_filename_template","nodeType":"Attribute","startLoc":149,"text":"c.ExtractOutputPreprocessor.output_filename_template"},{"col":4,"comment":"null","endLoc":1209,"header":"def test_empty_data(self)","id":2393,"name":"test_empty_data","nodeType":"Function","startLoc":1206,"text":"def test_empty_data(self):\n\n ax = histplot(x=[])\n assert not ax.patches"},{"col":4,"comment":"null","endLoc":1219,"header":"def test_variable_assignment(self, long_df)","id":2394,"name":"test_variable_assignment","nodeType":"Function","startLoc":1211,"text":"def test_variable_assignment(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(data=long_df, x=\"x\", ax=ax1)\n histplot(data=long_df, y=\"x\", ax=ax2)\n\n for a, b in zip(ax1.patches, ax2.patches):\n assert a.get_height() == b.get_width()"},{"col":4,"comment":"null","endLoc":235,"header":"def test_legend_data(self)","id":2395,"name":"test_legend_data","nodeType":"Function","startLoc":214,"text":"def test_legend_data(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n palette = color_palette(n_colors=3)\n\n assert g._legend.get_title().get_text() == \"a\"\n\n a_levels = sorted(self.df.a.unique())\n\n lines = g._legend.get_lines()\n assert len(lines) == len(a_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == len(a_levels)\n\n for label, level in zip(labels, a_levels):\n assert label.get_text() == level"},{"attributeType":"null","col":4,"comment":"null","endLoc":155,"id":2396,"name":"body","nodeType":"Attribute","startLoc":155,"text":"body"},{"attributeType":"null","col":10,"comment":"null","endLoc":155,"id":2397,"name":"resources","nodeType":"Attribute","startLoc":155,"text":"resources"},{"attributeType":"{metadata, cells}","col":4,"comment":"null","endLoc":158,"id":2398,"name":"nb","nodeType":"Attribute","startLoc":158,"text":"nb"},{"attributeType":"TextIO","col":30,"comment":"null","endLoc":159,"id":2399,"name":"f","nodeType":"Attribute","startLoc":159,"text":"f"},{"attributeType":"str","col":4,"comment":"null","endLoc":163,"id":2400,"name":"rst_path","nodeType":"Attribute","startLoc":163,"text":"rst_path"},{"id":2401,"name":"doc/_templates","nodeType":"Package"},{"id":2402,"name":"version.html","nodeType":"TextFile","path":"doc/_templates","text":"
\n{{ version }}\n
\n"},{"col":4,"comment":"null","endLoc":1245,"header":"@pytest.mark.parametrize(\"element\", [\"bars\", \"step\", \"poly\"])\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\", \"stack\", \"fill\"])\n def test_hue_fill_colors(self, long_df, multiple, element)","id":2403,"name":"test_hue_fill_colors","nodeType":"Function","startLoc":1221,"text":"@pytest.mark.parametrize(\"element\", [\"bars\", \"step\", \"poly\"])\n @pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\", \"stack\", \"fill\"])\n def test_hue_fill_colors(self, long_df, multiple, element):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n multiple=multiple, bins=1,\n fill=True, element=element, legend=False,\n )\n\n palette = color_palette()\n\n if multiple == \"layer\":\n if element == \"bars\":\n a = .5\n else:\n a = .25\n else:\n a = .75\n\n for bar, color in zip(ax.patches[::-1], palette):\n assert_colors_equal(bar.get_facecolor(), to_rgba(color, a))\n\n for poly, color in zip(ax.collections[::-1], palette):\n assert_colors_equal(poly.get_facecolor(), to_rgba(color, a))"},{"fileName":"smooth_bivariate_kde.py","filePath":"examples","id":2404,"nodeType":"File","text":"\"\"\"\nSmooth kernel density with marginal histograms\n==============================================\n\n_thumb: .48, .41\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"white\")\n\ndf = sns.load_dataset(\"penguins\")\n\ng = sns.JointGrid(data=df, x=\"body_mass_g\", y=\"bill_depth_mm\", space=0)\ng.plot_joint(sns.kdeplot,\n fill=True, clip=((2200, 6800), (10, 25)),\n thresh=0, levels=100, cmap=\"rocket\")\ng.plot_marginals(sns.histplot, color=\"#03051A\", alpha=1, bins=25)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2405,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":2406,"name":"df","nodeType":"Attribute","startLoc":10,"text":"df"},{"attributeType":"TextIO","col":32,"comment":"null","endLoc":164,"id":2407,"name":"f","nodeType":"Attribute","startLoc":164,"text":"f"},{"attributeType":"str","col":4,"comment":"null","endLoc":168,"id":2408,"name":"imdir","nodeType":"Attribute","startLoc":168,"text":"imdir"},{"col":4,"comment":"null","endLoc":1266,"header":"def test_hue_stack(self, long_df)","id":2409,"name":"test_hue_stack","nodeType":"Function","startLoc":1247,"text":"def test_hue_stack(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\", bins=n, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"stack\", ax=ax2)\n\n layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))\n stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))\n assert_array_equal(layer_heights, stack_heights)\n\n stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))\n assert_array_equal(\n stack_xys[..., 1] + stack_heights,\n stack_heights.cumsum(axis=0),\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":172,"id":2410,"name":"imname","nodeType":"Attribute","startLoc":172,"text":"imname"},{"attributeType":"JointGrid","col":0,"comment":"null","endLoc":12,"id":2411,"name":"g","nodeType":"Attribute","startLoc":12,"text":"g"},{"attributeType":"null","col":16,"comment":"null","endLoc":172,"id":2412,"name":"imdata","nodeType":"Attribute","startLoc":172,"text":"imdata"},{"attributeType":"str","col":12,"comment":"null","endLoc":174,"id":2413,"name":"impath","nodeType":"Attribute","startLoc":174,"text":"impath"},{"col":0,"comment":"","endLoc":6,"header":"smooth_bivariate_kde.py#","id":2414,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nSmooth kernel density with marginal histograms\n==============================================\n\n_thumb: .48, .41\n\"\"\"\n\nsns.set_theme(style=\"white\")\n\ndf = sns.load_dataset(\"penguins\")\n\ng = sns.JointGrid(data=df, x=\"body_mass_g\", y=\"bill_depth_mm\", space=0)\n\ng.plot_joint(sns.kdeplot,\n fill=True, clip=((2200, 6800), (10, 25)),\n thresh=0, levels=100, cmap=\"rocket\")\n\ng.plot_marginals(sns.histplot, color=\"#03051A\", alpha=1, bins=25)"},{"col":4,"comment":"null","endLoc":1289,"header":"def test_hue_fill(self, long_df)","id":2415,"name":"test_hue_fill","nodeType":"Function","startLoc":1268,"text":"def test_hue_fill(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n\n kws = dict(data=long_df, x=\"x\", hue=\"a\", bins=n, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"fill\", ax=ax2)\n\n layer_heights = np.reshape([b.get_height() for b in ax1.patches], (-1, n))\n stack_heights = np.reshape([b.get_height() for b in ax2.patches], (-1, n))\n assert_array_almost_equal(\n layer_heights / layer_heights.sum(axis=0), stack_heights\n )\n\n stack_xys = np.reshape([b.get_xy() for b in ax2.patches], (-1, n, 2))\n assert_array_almost_equal(\n (stack_xys[..., 1] + stack_heights) / stack_heights.sum(axis=0),\n stack_heights.cumsum(axis=0),\n )"},{"attributeType":"BinaryIO","col":39,"comment":"null","endLoc":175,"id":2416,"name":"f","nodeType":"Attribute","startLoc":175,"text":"f"},{"id":2417,"name":"doc/_templates/autosummary","nodeType":"Package"},{"id":2418,"name":"base.rst","nodeType":"TextFile","path":"doc/_templates/autosummary","text":"{{ fullname | escape | underline}}\n\n.. currentmodule:: {{ module }}\n\n.. auto{{ objtype }}:: {{ objname }}\n"},{"id":2419,"name":"PairGrid.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns; sns.set_theme()\\n\",\n \"import matplotlib.pyplot as plt\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Calling the constructor sets up a blank grid of subplots with each row and one column corresponding to a numeric variable in the dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"g = sns.PairGrid(penguins)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Passing a bivariate function to :meth:`PairGrid.map` will draw a bivariate plot on every axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins)\\n\",\n \"g.map(sns.scatterplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Passing separate functions to :meth:`PairGrid.map_diag` and :meth:`PairGrid.map_offdiag` will show each variable's marginal distribution on the diagonal:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins)\\n\",\n \"g.map_diag(sns.histplot)\\n\",\n \"g.map_offdiag(sns.scatterplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to use different functions on the upper and lower triangles of the plot (which are otherwise redundant):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, diag_sharey=False)\\n\",\n \"g.map_upper(sns.scatterplot)\\n\",\n \"g.map_lower(sns.kdeplot)\\n\",\n \"g.map_diag(sns.kdeplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Or to avoid the redundancy altogether:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, diag_sharey=False, corner=True)\\n\",\n \"g.map_lower(sns.scatterplot)\\n\",\n \"g.map_diag(sns.kdeplot)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The :class:`PairGrid` constructor accepts a ``hue`` variable. This variable is passed directly to functions that understand it:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, hue=\\\"species\\\")\\n\",\n \"g.map_diag(sns.histplot)\\n\",\n \"g.map_offdiag(sns.scatterplot)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"But you can also pass matplotlib functions, in which case a groupby is performed internally and a separate plot is drawn for each level:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, hue=\\\"species\\\")\\n\",\n \"g.map_diag(plt.hist)\\n\",\n \"g.map_offdiag(plt.scatter)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Additional semantic variables can be assigned by passing data vectors directly while mapping the function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, hue=\\\"species\\\")\\n\",\n \"g.map_diag(sns.histplot)\\n\",\n \"g.map_offdiag(sns.scatterplot, size=penguins[\\\"sex\\\"])\\n\",\n \"g.add_legend(title=\\\"\\\", adjust_subtitles=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When using seaborn functions that can implement a numeric hue mapping, you will want to disable mapping of the variable on the diagonal axes. Note that the ``hue`` variable is excluded from the list of variables shown by default:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, hue=\\\"body_mass_g\\\")\\n\",\n \"g.map_diag(sns.histplot, hue=None, color=\\\".3\\\")\\n\",\n \"g.map_offdiag(sns.scatterplot)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The ``vars`` parameter can be used to control exactly which variables are used:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"variables = [\\\"body_mass_g\\\", \\\"bill_length_mm\\\", \\\"flipper_length_mm\\\"]\\n\",\n \"g = sns.PairGrid(penguins, hue=\\\"body_mass_g\\\", vars=variables)\\n\",\n \"g.map_diag(sns.histplot, hue=None, color=\\\".3\\\")\\n\",\n \"g.map_offdiag(sns.scatterplot)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The plot need not be square: separate variables can be used to define the rows and columns:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"x_vars = [\\\"body_mass_g\\\", \\\"bill_length_mm\\\", \\\"bill_depth_mm\\\", \\\"flipper_length_mm\\\"]\\n\",\n \"y_vars = [\\\"body_mass_g\\\"]\\n\",\n \"g = sns.PairGrid(penguins, hue=\\\"species\\\", x_vars=x_vars, y_vars=y_vars)\\n\",\n \"g.map_diag(sns.histplot, color=\\\".3\\\")\\n\",\n \"g.map_offdiag(sns.scatterplot)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It can be useful to explore different approaches to resolving multiple distributions on the diagonal axes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.PairGrid(penguins, hue=\\\"species\\\")\\n\",\n \"g.map_diag(sns.histplot, multiple=\\\"stack\\\", element=\\\"step\\\")\\n\",\n \"g.map_offdiag(sns.scatterplot)\\n\",\n \"g.add_legend()\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"fileName":"many_pairwise_correlations.py","filePath":"examples","id":2420,"nodeType":"File","text":"\"\"\"\nPlotting a diagonal correlation matrix\n======================================\n\n_thumb: .3, .6\n\"\"\"\nfrom string import ascii_letters\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"white\")\n\n# Generate a large random dataset\nrs = np.random.RandomState(33)\nd = pd.DataFrame(data=rs.normal(size=(100, 26)),\n columns=list(ascii_letters[26:]))\n\n# Compute the correlation matrix\ncorr = d.corr()\n\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corr, dtype=bool))\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(11, 9))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n"},{"attributeType":"LiteralString","col":0,"comment":"null","endLoc":23,"id":2421,"name":"ascii_letters","nodeType":"Attribute","startLoc":23,"text":"ascii_letters"},{"attributeType":"null","col":16,"comment":"null","endLoc":8,"id":2422,"name":"np","nodeType":"Attribute","startLoc":8,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":9,"id":2423,"name":"pd","nodeType":"Attribute","startLoc":9,"text":"pd"},{"attributeType":"null","col":18,"comment":"null","endLoc":10,"id":2424,"name":"sns","nodeType":"Attribute","startLoc":10,"text":"sns"},{"attributeType":"null","col":28,"comment":"null","endLoc":11,"id":2425,"name":"plt","nodeType":"Attribute","startLoc":11,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":2426,"name":"rs","nodeType":"Attribute","startLoc":16,"text":"rs"},{"col":0,"comment":"","endLoc":28,"header":"nb_to_doc.py#","id":2427,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"Execute a .ipynb file, write out a processed .rst and clean .ipynb.\n\nSome functions in this script were copied from the nbstripout tool:\n\nCopyright (c) 2015 Min RK, Florian Rathgeber, Michael McNeil Forbes\n2019 Casper da Costa-Luis\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"\n\nif __name__ == \"__main__\":\n\n # Get the desired ipynb file path and parse into components\n _, fpath, outdir = sys.argv\n basedir, fname = os.path.split(fpath)\n fstem = fname[:-6]\n\n # Read the notebook\n with open(fpath) as f:\n nb = nbformat.read(f, as_version=4)\n\n # Run the notebook\n kernel = os.environ.get(\"NB_KERNEL\", None)\n if kernel is None:\n kernel = nb[\"metadata\"][\"kernelspec\"][\"name\"]\n ep = ExecutePreprocessor(\n timeout=600,\n kernel_name=kernel,\n extra_arguments=[\"--InlineBackend.rc=figure.dpi=88\"]\n )\n ep.preprocess(nb, {\"metadata\": {\"path\": basedir}})\n\n # Remove plain text execution result outputs\n for cell in nb.get(\"cells\", {}):\n if \"show-output\" in cell[\"metadata\"].get(\"tags\", []):\n continue\n fields = cell.get(\"outputs\", [])\n for field in fields:\n if field[\"output_type\"] == \"execute_result\":\n data_keys = field[\"data\"].keys()\n for key in list(data_keys):\n if key == \"text/plain\":\n field[\"data\"].pop(key)\n if not field[\"data\"]:\n fields.remove(field)\n\n # Convert to .rst formats\n exp = RSTExporter()\n\n c = Config()\n c.TagRemovePreprocessor.remove_cell_tags = {\"hide\"}\n c.TagRemovePreprocessor.remove_input_tags = {\"hide-input\"}\n c.TagRemovePreprocessor.remove_all_outputs_tags = {\"hide-output\"}\n c.ExtractOutputPreprocessor.output_filename_template = \\\n f\"{fstem}_files/{fstem}_\" + \"{cell_index}_{index}{extension}\"\n\n exp.register_preprocessor(TagRemovePreprocessor(config=c), True)\n exp.register_preprocessor(ExtractOutputPreprocessor(config=c), True)\n\n body, resources = exp.from_notebook_node(nb)\n\n # Clean the output on the notebook and save a .ipynb back to disk\n nb = strip_output(nb)\n with open(fpath, \"wt\") as f:\n nbformat.write(nb, f)\n\n # Write the .rst file\n rst_path = os.path.join(outdir, f\"{fstem}.rst\")\n with open(rst_path, \"w\") as f:\n f.write(body)\n\n # Write the individual image outputs\n imdir = os.path.join(outdir, f\"{fstem}_files\")\n if not os.path.exists(imdir):\n os.mkdir(imdir)\n\n for imname, imdata in resources[\"outputs\"].items():\n if imname.startswith(fstem):\n impath = os.path.join(outdir, f\"{imname}\")\n with open(impath, \"wb\") as f:\n f.write(imdata)"},{"col":4,"comment":"null","endLoc":260,"header":"def test_legend_data_missing_level(self)","id":2429,"name":"test_legend_data_missing_level","nodeType":"Function","startLoc":237,"text":"def test_legend_data_missing_level(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\", hue_order=list(\"azbc\"))\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n\n c1, c2, c3, c4 = color_palette(n_colors=4)\n palette = [c1, c3, c4]\n\n assert g._legend.get_title().get_text() == \"a\"\n\n a_levels = sorted(self.df.a.unique())\n\n lines = g._legend.get_lines()\n assert len(lines) == len(a_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == 4\n\n for label, level in zip(labels, list(\"azbc\")):\n assert label.get_text() == level"},{"col":4,"comment":"Plot with a bivariate function on the upper diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n ","endLoc":1405,"header":"def map_upper(self, func, **kwargs)","id":2431,"name":"map_upper","nodeType":"Function","startLoc":1392,"text":"def map_upper(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the upper diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n indices = zip(*np.triu_indices_from(self.axes, 1))\n self._map_bivariate(func, indices, **kwargs)\n return self"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":2432,"name":"d","nodeType":"Attribute","startLoc":17,"text":"d"},{"col":4,"comment":"null","endLoc":1309,"header":"def test_hue_dodge(self, long_df)","id":2433,"name":"test_hue_dodge","nodeType":"Function","startLoc":1291,"text":"def test_hue_dodge(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n bw = 2\n\n kws = dict(data=long_df, x=\"x\", hue=\"c\", binwidth=bw, element=\"bars\")\n\n histplot(**kws, multiple=\"layer\", ax=ax1)\n histplot(**kws, multiple=\"dodge\", ax=ax2)\n\n layer_heights = [b.get_height() for b in ax1.patches]\n dodge_heights = [b.get_height() for b in ax2.patches]\n assert_array_equal(layer_heights, dodge_heights)\n\n layer_xs = np.reshape([b.get_x() for b in ax1.patches], (2, -1))\n dodge_xs = np.reshape([b.get_x() for b in ax2.patches], (2, -1))\n assert_array_almost_equal(layer_xs[1], dodge_xs[1])\n assert_array_almost_equal(layer_xs[0], dodge_xs[0] - bw / 2)"},{"attributeType":"null","col":0,"comment":"null","endLoc":21,"id":2434,"name":"corr","nodeType":"Attribute","startLoc":21,"text":"corr"},{"col":4,"comment":"Plot with a bivariate function on the off-diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n ","endLoc":1429,"header":"def map_offdiag(self, func, **kwargs)","id":2435,"name":"map_offdiag","nodeType":"Function","startLoc":1407,"text":"def map_offdiag(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the off-diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n if self.square_grid:\n self.map_lower(func, **kwargs)\n if not self._corner:\n self.map_upper(func, **kwargs)\n else:\n indices = []\n for i, (y_var) in enumerate(self.y_vars):\n for j, (x_var) in enumerate(self.x_vars):\n if x_var != y_var:\n indices.append((i, j))\n self._map_bivariate(func, indices, **kwargs)\n return self"},{"col":4,"comment":"null","endLoc":1131,"header":"def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None","id":2436,"name":"_compute_stats","nodeType":"Function","startLoc":1079,"text":"def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None:\n\n grouping_vars = [v for v in PROPERTIES if v not in \"xy\"]\n grouping_vars += [\"col\", \"row\", \"group\"]\n\n pair_vars = spec._pair_spec.get(\"structure\", {})\n\n for layer in layers:\n\n data = layer[\"data\"]\n mark = layer[\"mark\"]\n stat = layer[\"stat\"]\n\n if stat is None:\n continue\n\n iter_axes = itertools.product(*[\n pair_vars.get(axis, [axis]) for axis in \"xy\"\n ])\n\n old = data.frame\n\n if pair_vars:\n data.frames = {}\n data.frame = data.frame.iloc[:0] # TODO to simplify typing\n\n for coord_vars in iter_axes:\n\n pairings = \"xy\", coord_vars\n\n df = old.copy()\n scales = self._scales.copy()\n\n for axis, var in zip(*pairings):\n if axis != var:\n df = df.rename(columns={var: axis})\n drop_cols = [x for x in df if re.match(rf\"{axis}\\d+\", str(x))]\n df = df.drop(drop_cols, axis=1)\n scales[axis] = scales[var]\n\n orient = layer[\"orient\"] or mark._infer_orient(scales)\n\n if stat.group_by_orient:\n grouper = [orient, *grouping_vars]\n else:\n grouper = grouping_vars\n groupby = GroupBy(grouper)\n res = stat(df, groupby, orient, scales)\n\n if pair_vars:\n data.frames[coord_vars] = res\n else:\n data.frame = res"},{"col":4,"comment":"null","endLoc":1320,"header":"def test_hue_as_numpy_dodged(self, long_df)","id":2438,"name":"test_hue_as_numpy_dodged","nodeType":"Function","startLoc":1311,"text":"def test_hue_as_numpy_dodged(self, long_df):\n # https://github.com/mwaskom/seaborn/issues/2452\n\n ax = histplot(\n long_df,\n x=\"y\", hue=long_df[\"a\"].to_numpy(),\n multiple=\"dodge\", bins=1,\n )\n # Note hue order reversal\n assert ax.patches[1].get_x() < ax.patches[0].get_x()"},{"col":4,"comment":"null","endLoc":1325,"header":"def test_multiple_input_check(self, flat_series)","id":2439,"name":"test_multiple_input_check","nodeType":"Function","startLoc":1322,"text":"def test_multiple_input_check(self, flat_series):\n\n with pytest.raises(ValueError, match=\"`multiple` must be\"):\n histplot(flat_series, multiple=\"invalid\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":24,"id":2440,"name":"mask","nodeType":"Attribute","startLoc":24,"text":"mask"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":2441,"name":"f","nodeType":"Attribute","startLoc":27,"text":"f"},{"attributeType":"null","col":3,"comment":"null","endLoc":27,"id":2442,"name":"ax","nodeType":"Attribute","startLoc":27,"text":"ax"},{"col":4,"comment":"null","endLoc":1330,"header":"def test_element_input_check(self, flat_series)","id":2443,"name":"test_element_input_check","nodeType":"Function","startLoc":1327,"text":"def test_element_input_check(self, flat_series):\n\n with pytest.raises(ValueError, match=\"`element` must be\"):\n histplot(flat_series, element=\"invalid\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":30,"id":2444,"name":"cmap","nodeType":"Attribute","startLoc":30,"text":"cmap"},{"col":4,"comment":"null","endLoc":1336,"header":"def test_count_stat(self, flat_series)","id":2445,"name":"test_count_stat","nodeType":"Function","startLoc":1332,"text":"def test_count_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"count\")\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == len(flat_series)"},{"col":0,"comment":"","endLoc":6,"header":"many_pairwise_correlations.py#","id":2446,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPlotting a diagonal correlation matrix\n======================================\n\n_thumb: .3, .6\n\"\"\"\n\nsns.set_theme(style=\"white\")\n\nrs = np.random.RandomState(33)\n\nd = pd.DataFrame(data=rs.normal(size=(100, 26)),\n columns=list(ascii_letters[26:]))\n\ncorr = d.corr()\n\nmask = np.triu(np.ones_like(corr, dtype=bool))\n\nf, ax = plt.subplots(figsize=(11, 9))\n\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\nsns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})"},{"col":0,"comment":"Make a diverging palette between two HUSL colors.\n\n If you are using the IPython notebook, you can also choose this palette\n interactively with the :func:`choose_diverging_palette` function.\n\n Parameters\n ----------\n h_neg, h_pos : float in [0, 359]\n Anchor hues for negative and positive extents of the map.\n s : float in [0, 100], optional\n Anchor saturation for both extents of the map.\n l : float in [0, 100], optional\n Anchor lightness for both extents of the map.\n sep : int, optional\n Size of the intermediate region.\n n : int, optional\n Number of colors in the palette (if not returning a cmap)\n center : {\"light\", \"dark\"}, optional\n Whether the center of the palette is light or dark\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark values.\n light_palette : Create a sequential palette with light values.\n\n Examples\n --------\n .. include: ../docstrings/diverging_palette.rst\n\n ","endLoc":578,"header":"def diverging_palette(h_neg, h_pos, s=75, l=50, sep=1, n=6, # noqa\n center=\"light\", as_cmap=False)","id":2447,"name":"diverging_palette","nodeType":"Function","startLoc":532,"text":"def diverging_palette(h_neg, h_pos, s=75, l=50, sep=1, n=6, # noqa\n center=\"light\", as_cmap=False):\n \"\"\"Make a diverging palette between two HUSL colors.\n\n If you are using the IPython notebook, you can also choose this palette\n interactively with the :func:`choose_diverging_palette` function.\n\n Parameters\n ----------\n h_neg, h_pos : float in [0, 359]\n Anchor hues for negative and positive extents of the map.\n s : float in [0, 100], optional\n Anchor saturation for both extents of the map.\n l : float in [0, 100], optional\n Anchor lightness for both extents of the map.\n sep : int, optional\n Size of the intermediate region.\n n : int, optional\n Number of colors in the palette (if not returning a cmap)\n center : {\"light\", \"dark\"}, optional\n Whether the center of the palette is light or dark\n as_cmap : bool, optional\n If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n Returns\n -------\n palette\n list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark values.\n light_palette : Create a sequential palette with light values.\n\n Examples\n --------\n .. include: ../docstrings/diverging_palette.rst\n\n \"\"\"\n palfunc = dict(dark=dark_palette, light=light_palette)[center]\n n_half = int(128 - (sep // 2))\n neg = palfunc((h_neg, s, l), n_half, reverse=True, input=\"husl\")\n pos = palfunc((h_pos, s, l), n_half, input=\"husl\")\n midpoint = dict(light=[(.95, .95, .95)], dark=[(.133, .133, .133)])[center]\n mid = midpoint * sep\n pal = blend_palette(np.concatenate([neg, mid, pos]), n, as_cmap=as_cmap)\n return pal"},{"col":4,"comment":"null","endLoc":1343,"header":"def test_density_stat(self, flat_series)","id":2448,"name":"test_density_stat","nodeType":"Function","startLoc":1338,"text":"def test_density_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"density\")\n bar_heights = [b.get_height() for b in ax.patches]\n bar_widths = [b.get_width() for b in ax.patches]\n assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":1353,"header":"def test_density_stat_common_norm(self, long_df)","id":2449,"name":"test_density_stat_common_norm","nodeType":"Function","startLoc":1345,"text":"def test_density_stat_common_norm(self, long_df):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=\"density\", common_norm=True, element=\"bars\",\n )\n bar_heights = [b.get_height() for b in ax.patches]\n bar_widths = [b.get_width() for b in ax.patches]\n assert np.multiply(bar_heights, bar_widths).sum() == pytest.approx(1)"},{"col":0,"comment":"Test that bootstrapping gives the right answer in dumb cases.","endLoc":23,"header":"def test_bootstrap(random)","id":2450,"name":"test_bootstrap","nodeType":"Function","startLoc":16,"text":"def test_bootstrap(random):\n \"\"\"Test that bootstrapping gives the right answer in dumb cases.\"\"\"\n a_ones = np.ones(10)\n n_boot = 5\n out1 = algo.bootstrap(a_ones, n_boot=n_boot)\n assert_array_equal(out1, np.ones(n_boot))\n out2 = algo.bootstrap(a_ones, n_boot=n_boot, func=np.median)\n assert_array_equal(out2, np.ones(n_boot))"},{"col":4,"comment":"null","endLoc":1369,"header":"def test_density_stat_unique_norm(self, long_df)","id":2451,"name":"test_density_stat_unique_norm","nodeType":"Function","startLoc":1355,"text":"def test_density_stat_unique_norm(self, long_df):\n\n n = 10\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=\"density\", bins=n, common_norm=False, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for bars in bar_groups:\n bar_heights = [b.get_height() for b in bars]\n bar_widths = [b.get_width() for b in bars]\n bar_areas = np.multiply(bar_heights, bar_widths)\n assert bar_areas.sum() == pytest.approx(1)"},{"col":0,"comment":"Test that we get a bootstrap array of the right shape.","endLoc":34,"header":"def test_bootstrap_length(random)","id":2452,"name":"test_bootstrap_length","nodeType":"Function","startLoc":26,"text":"def test_bootstrap_length(random):\n \"\"\"Test that we get a bootstrap array of the right shape.\"\"\"\n a_norm = np.random.randn(1000)\n out = algo.bootstrap(a_norm)\n assert len(out) == 10000\n\n n_boot = 100\n out = algo.bootstrap(a_norm, n_boot=n_boot)\n assert len(out) == n_boot"},{"col":4,"comment":"null","endLoc":284,"header":"def test_get_boolean_legend_data(self)","id":2453,"name":"test_get_boolean_legend_data","nodeType":"Function","startLoc":262,"text":"def test_get_boolean_legend_data(self):\n\n self.df[\"b_bool\"] = self.df.b == \"m\"\n g = ag.FacetGrid(self.df, hue=\"b_bool\")\n g.map(plt.plot, \"x\", \"y\")\n g.add_legend()\n palette = color_palette(n_colors=2)\n\n assert g._legend.get_title().get_text() == \"b_bool\"\n\n b_levels = list(map(str, categorical_order(self.df.b_bool)))\n\n lines = g._legend.get_lines()\n assert len(lines) == len(b_levels)\n\n for line, hue in zip(lines, palette):\n assert_colors_equal(line.get_color(), hue)\n\n labels = g._legend.get_texts()\n assert len(labels) == len(b_levels)\n\n for label, level in zip(labels, b_levels):\n assert label.get_text() == level"},{"col":4,"comment":"null","endLoc":1373,"header":"@pytest.fixture(params=[\"probability\", \"proportion\"])\n def height_norm_arg(self, request)","id":2454,"name":"height_norm_arg","nodeType":"Function","startLoc":1371,"text":"@pytest.fixture(params=[\"probability\", \"proportion\"])\n def height_norm_arg(self, request):\n return request.param"},{"col":0,"comment":"Test that bootstrapping a random array stays within the right range.","endLoc":43,"header":"def test_bootstrap_range(random)","id":2455,"name":"test_bootstrap_range","nodeType":"Function","startLoc":37,"text":"def test_bootstrap_range(random):\n \"\"\"Test that bootstrapping a random array stays within the right range.\"\"\"\n a_norm = np.random.randn(1000)\n amin, amax = a_norm.min(), a_norm.max()\n out = algo.bootstrap(a_norm)\n assert amin <= out.min()\n assert amax >= out.max()"},{"col":4,"comment":"null","endLoc":1379,"header":"def test_probability_stat(self, flat_series, height_norm_arg)","id":2456,"name":"test_probability_stat","nodeType":"Function","startLoc":1375,"text":"def test_probability_stat(self, flat_series, height_norm_arg):\n\n ax = histplot(flat_series, stat=height_norm_arg)\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":1388,"header":"def test_probability_stat_common_norm(self, long_df, height_norm_arg)","id":2457,"name":"test_probability_stat_common_norm","nodeType":"Function","startLoc":1381,"text":"def test_probability_stat_common_norm(self, long_df, height_norm_arg):\n\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=height_norm_arg, common_norm=True, element=\"bars\",\n )\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":1402,"header":"def test_probability_stat_unique_norm(self, long_df, height_norm_arg)","id":2458,"name":"test_probability_stat_unique_norm","nodeType":"Function","startLoc":1390,"text":"def test_probability_stat_unique_norm(self, long_df, height_norm_arg):\n\n n = 10\n ax = histplot(\n data=long_df, x=\"x\", hue=\"a\",\n stat=height_norm_arg, bins=n, common_norm=False, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for bars in bar_groups:\n bar_heights = [b.get_height() for b in bars]\n assert sum(bar_heights) == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":1408,"header":"def test_percent_stat(self, flat_series)","id":2459,"name":"test_percent_stat","nodeType":"Function","startLoc":1404,"text":"def test_percent_stat(self, flat_series):\n\n ax = histplot(flat_series, stat=\"percent\")\n bar_heights = [b.get_height() for b in ax.patches]\n assert sum(bar_heights) == 100"},{"col":0,"comment":"Test that bootstrap works with multiple input arrays.","endLoc":56,"header":"def test_bootstrap_multiarg(random)","id":2460,"name":"test_bootstrap_multiarg","nodeType":"Function","startLoc":46,"text":"def test_bootstrap_multiarg(random):\n \"\"\"Test that bootstrap works with multiple input arrays.\"\"\"\n x = np.vstack([[1, 10] for i in range(10)])\n y = np.vstack([[5, 5] for i in range(10)])\n\n def f(x, y):\n return np.vstack((x, y)).max(axis=0)\n\n out_actual = algo.bootstrap(x, y, n_boot=2, func=f)\n out_wanted = np.array([[5, 10], [5, 10]])\n assert_array_equal(out_actual, out_wanted)"},{"col":4,"comment":"null","endLoc":1421,"header":"def test_common_bins(self, long_df)","id":2461,"name":"test_common_bins","nodeType":"Function","startLoc":1410,"text":"def test_common_bins(self, long_df):\n\n n = 10\n ax = histplot(\n long_df, x=\"x\", hue=\"a\", common_bins=True, bins=n, element=\"bars\",\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n assert_array_equal(\n [b.get_xy() for b in bar_groups[0]],\n [b.get_xy() for b in bar_groups[1]]\n )"},{"fileName":"jitter_stripplot.py","filePath":"examples","id":2462,"nodeType":"File","text":"\"\"\"\nConditional means with observations\n===================================\n\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"whitegrid\")\niris = sns.load_dataset(\"iris\")\n\n# \"Melt\" the dataset to \"long-form\" or \"tidy\" representation\niris = pd.melt(iris, \"species\", var_name=\"measurement\")\n\n# Initialize the figure\nf, ax = plt.subplots()\nsns.despine(bottom=True, left=True)\n\n# Show each observation with a scatterplot\nsns.stripplot(\n data=iris, x=\"value\", y=\"measurement\", hue=\"species\",\n dodge=True, alpha=.25, zorder=1, legend=False\n)\n\n# Show the conditional means, aligning each pointplot in the\n# center of the strips by adjusting the width allotted to each\n# category (.8 by default) by the number of hue levels\nsns.pointplot(\n data=iris, x=\"value\", y=\"measurement\", hue=\"species\",\n join=False, dodge=.8 - .8 / 3, palette=\"dark\",\n markers=\"d\", scale=.75, errorbar=None\n)\n\n# Improve the legend\nsns.move_legend(\n ax, loc=\"lower right\", ncol=3, frameon=True, columnspacing=1, handletextpad=0\n)\n"},{"attributeType":"null","col":17,"comment":"null","endLoc":6,"id":2463,"name":"pd","nodeType":"Attribute","startLoc":6,"text":"pd"},{"col":4,"comment":"null","endLoc":1434,"header":"def test_unique_bins(self, wide_df)","id":2464,"name":"test_unique_bins","nodeType":"Function","startLoc":1423,"text":"def test_unique_bins(self, wide_df):\n\n ax = histplot(wide_df, common_bins=False, bins=10, element=\"bars\")\n\n bar_groups = np.split(np.array(ax.patches), len(wide_df.columns))\n\n for i, col in enumerate(wide_df.columns[::-1]):\n bars = bar_groups[i]\n start = bars[0].get_x()\n stop = bars[-1].get_x() + bars[-1].get_width()\n assert_array_almost_equal(start, wide_df[col].min())\n assert_array_almost_equal(stop, wide_df[col].max())"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2465,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":2466,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":2467,"name":"iris","nodeType":"Attribute","startLoc":11,"text":"iris"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":2468,"name":"iris","nodeType":"Attribute","startLoc":14,"text":"iris"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":2469,"name":"f","nodeType":"Attribute","startLoc":17,"text":"f"},{"col":0,"comment":"Test axis kwarg to bootstrap function.","endLoc":68,"header":"def test_bootstrap_axis(random)","id":2470,"name":"test_bootstrap_axis","nodeType":"Function","startLoc":59,"text":"def test_bootstrap_axis(random):\n \"\"\"Test axis kwarg to bootstrap function.\"\"\"\n x = np.random.randn(10, 20)\n n_boot = 100\n\n out_default = algo.bootstrap(x, n_boot=n_boot)\n assert out_default.shape == (n_boot,)\n\n out_axis = algo.bootstrap(x, n_boot=n_boot, axis=0)\n assert out_axis.shape, (n_boot, x.shape[1])"},{"attributeType":"null","col":3,"comment":"null","endLoc":17,"id":2471,"name":"ax","nodeType":"Attribute","startLoc":17,"text":"ax"},{"col":0,"comment":"","endLoc":5,"header":"jitter_stripplot.py#","id":2472,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nConditional means with observations\n===================================\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\niris = sns.load_dataset(\"iris\")\n\niris = pd.melt(iris, \"species\", var_name=\"measurement\")\n\nf, ax = plt.subplots()\n\nsns.despine(bottom=True, left=True)\n\nsns.stripplot(\n data=iris, x=\"value\", y=\"measurement\", hue=\"species\",\n dodge=True, alpha=.25, zorder=1, legend=False\n)\n\nsns.pointplot(\n data=iris, x=\"value\", y=\"measurement\", hue=\"species\",\n join=False, dodge=.8 - .8 / 3, palette=\"dark\",\n markers=\"d\", scale=.75, errorbar=None\n)\n\nsns.move_legend(\n ax, loc=\"lower right\", ncol=3, frameon=True, columnspacing=1, handletextpad=0\n)"},{"col":0,"comment":"Test that we can get reproducible resamples by seeding the RNG.","endLoc":77,"header":"def test_bootstrap_seed(random)","id":2473,"name":"test_bootstrap_seed","nodeType":"Function","startLoc":71,"text":"def test_bootstrap_seed(random):\n \"\"\"Test that we can get reproducible resamples by seeding the RNG.\"\"\"\n data = np.random.randn(50)\n seed = 42\n boots1 = algo.bootstrap(data, seed=seed)\n boots2 = algo.bootstrap(data, seed=seed)\n assert_array_equal(boots1, boots2)"},{"col":0,"comment":"Test bootstrap of OLS model fit.","endLoc":101,"header":"def test_bootstrap_ols(random)","id":2474,"name":"test_bootstrap_ols","nodeType":"Function","startLoc":80,"text":"def test_bootstrap_ols(random):\n \"\"\"Test bootstrap of OLS model fit.\"\"\"\n def ols_fit(X, y):\n XtXinv = np.linalg.inv(np.dot(X.T, X))\n return XtXinv.dot(X.T).dot(y)\n\n X = np.column_stack((np.random.randn(50, 4), np.ones(50)))\n w = [2, 4, 0, 3, 5]\n y_noisy = np.dot(X, w) + np.random.randn(50) * 20\n y_lownoise = np.dot(X, w) + np.random.randn(50)\n\n n_boot = 500\n w_boot_noisy = algo.bootstrap(X, y_noisy,\n n_boot=n_boot,\n func=ols_fit)\n w_boot_lownoise = algo.bootstrap(X, y_lownoise,\n n_boot=n_boot,\n func=ols_fit)\n\n assert w_boot_noisy.shape == (n_boot, 5)\n assert w_boot_lownoise.shape == (n_boot, 5)\n assert w_boot_noisy.std() > w_boot_lownoise.std()"},{"col":0,"comment":"\n Recreate a plot's legend at a new location.\n\n The name is a slight misnomer. Matplotlib legends do not expose public\n control over their position parameters. So this function creates a new legend,\n copying over the data from the original object, which is then removed.\n\n Parameters\n ----------\n obj : the object with the plot\n This argument can be either a seaborn or matplotlib object:\n\n - :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`\n - :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`\n\n loc : str or int\n Location argument, as in :meth:`matplotlib.axes.Axes.legend`.\n\n kwargs\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.\n\n Examples\n --------\n\n .. include:: ../docstrings/move_legend.rst\n\n ","endLoc":483,"header":"def move_legend(obj, loc, **kwargs)","id":2475,"name":"move_legend","nodeType":"Function","startLoc":396,"text":"def move_legend(obj, loc, **kwargs):\n \"\"\"\n Recreate a plot's legend at a new location.\n\n The name is a slight misnomer. Matplotlib legends do not expose public\n control over their position parameters. So this function creates a new legend,\n copying over the data from the original object, which is then removed.\n\n Parameters\n ----------\n obj : the object with the plot\n This argument can be either a seaborn or matplotlib object:\n\n - :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`\n - :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`\n\n loc : str or int\n Location argument, as in :meth:`matplotlib.axes.Axes.legend`.\n\n kwargs\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.\n\n Examples\n --------\n\n .. include:: ../docstrings/move_legend.rst\n\n \"\"\"\n # This is a somewhat hackish solution that will hopefully be obviated by\n # upstream improvements to matplotlib legends that make them easier to\n # modify after creation.\n\n from seaborn.axisgrid import Grid # Avoid circular import\n\n # Locate the legend object and a method to recreate the legend\n if isinstance(obj, Grid):\n old_legend = obj.legend\n legend_func = obj.figure.legend\n elif isinstance(obj, mpl.axes.Axes):\n old_legend = obj.legend_\n legend_func = obj.legend\n elif isinstance(obj, mpl.figure.Figure):\n if obj.legends:\n old_legend = obj.legends[-1]\n else:\n old_legend = None\n legend_func = obj.legend\n else:\n err = \"`obj` must be a seaborn Grid or matplotlib Axes or Figure instance.\"\n raise TypeError(err)\n\n if old_legend is None:\n err = f\"{obj} has no legend attached.\"\n raise ValueError(err)\n\n # Extract the components of the legend we need to reuse\n handles = old_legend.legendHandles\n labels = [t.get_text() for t in old_legend.get_texts()]\n\n # Extract legend properties that can be passed to the recreation method\n # (Vexingly, these don't all round-trip)\n legend_kws = inspect.signature(mpl.legend.Legend).parameters\n props = {k: v for k, v in old_legend.properties().items() if k in legend_kws}\n\n # Delegate default bbox_to_anchor rules to matplotlib\n props.pop(\"bbox_to_anchor\")\n\n # Try to propagate the existing title and font properties; respect new ones too\n title = props.pop(\"title\")\n if \"title\" in kwargs:\n title.set_text(kwargs.pop(\"title\"))\n title_kwargs = {k: v for k, v in kwargs.items() if k.startswith(\"title_\")}\n for key, val in title_kwargs.items():\n title.set(**{key[6:]: val})\n kwargs.pop(key)\n\n # Try to respect the frame visibility\n kwargs.setdefault(\"frameon\", old_legend.legendPatch.get_visible())\n\n # Remove the old legend and create the new one\n props.update(kwargs)\n old_legend.remove()\n new_legend = legend_func(handles, labels, loc=loc, **props)\n new_legend.set_title(title.get_text(), title.get_fontproperties())\n\n # Let the Grid object continue to track the correct legend object\n if isinstance(obj, Grid):\n obj._legend = new_legend"},{"col":4,"comment":"Plot with a univariate function on each diagonal subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take an x array as a positional argument and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n ","endLoc":1511,"header":"def map_diag(self, func, **kwargs)","id":2476,"name":"map_diag","nodeType":"Function","startLoc":1431,"text":"def map_diag(self, func, **kwargs):\n \"\"\"Plot with a univariate function on each diagonal subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take an x array as a positional argument and draw onto the\n \"currently active\" matplotlib Axes. Also needs to accept kwargs\n called ``color`` and ``label``.\n\n \"\"\"\n # Add special diagonal axes for the univariate plot\n if self.diag_axes is None:\n diag_vars = []\n diag_axes = []\n for i, y_var in enumerate(self.y_vars):\n for j, x_var in enumerate(self.x_vars):\n if x_var == y_var:\n\n # Make the density axes\n diag_vars.append(x_var)\n ax = self.axes[i, j]\n diag_ax = ax.twinx()\n diag_ax.set_axis_off()\n diag_axes.append(diag_ax)\n\n # Work around matplotlib bug\n # https://github.com/matplotlib/matplotlib/issues/15188\n if not plt.rcParams.get(\"ytick.left\", True):\n for tick in ax.yaxis.majorTicks:\n tick.tick1line.set_visible(False)\n\n # Remove main y axis from density axes in a corner plot\n if self._corner:\n ax.yaxis.set_visible(False)\n if self._despine:\n utils.despine(ax=ax, left=True)\n # TODO add optional density ticks (on the right)\n # when drawing a corner plot?\n\n if self.diag_sharey and diag_axes:\n for ax in diag_axes[1:]:\n share_axis(diag_axes[0], ax, \"y\")\n\n self.diag_vars = np.array(diag_vars, np.object_)\n self.diag_axes = np.array(diag_axes, np.object_)\n\n if \"hue\" not in signature(func).parameters:\n return self._map_diag_iter_hue(func, **kwargs)\n\n # Loop over diagonal variables and axes, making one plot in each\n for var, ax in zip(self.diag_vars, self.diag_axes):\n\n plot_kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n plot_kwargs[\"ax\"] = ax\n else:\n plt.sca(ax)\n\n vector = self.data[var]\n if self._hue_var is not None:\n hue = self.data[self._hue_var]\n else:\n hue = None\n\n if self._dropna:\n not_na = vector.notna()\n if hue is not None:\n not_na &= hue.notna()\n vector = vector[not_na]\n if hue is not None:\n hue = hue[not_na]\n\n plot_kwargs.setdefault(\"hue\", hue)\n plot_kwargs.setdefault(\"hue_order\", self._hue_order)\n plot_kwargs.setdefault(\"palette\", self._orig_palette)\n func(x=vector, **plot_kwargs)\n ax.legend_ = None\n\n self._add_axis_labels()\n return self"},{"col":0,"comment":"Test that results make sense when passing unit IDs to bootstrap.","endLoc":115,"header":"def test_bootstrap_units(random)","id":2477,"name":"test_bootstrap_units","nodeType":"Function","startLoc":104,"text":"def test_bootstrap_units(random):\n \"\"\"Test that results make sense when passing unit IDs to bootstrap.\"\"\"\n data = np.random.randn(50)\n ids = np.repeat(range(10), 5)\n bwerr = np.random.normal(0, 2, 10)\n bwerr = bwerr[ids]\n data_rm = data + bwerr\n seed = 77\n\n boots_orig = algo.bootstrap(data_rm, seed=seed)\n boots_rm = algo.bootstrap(data_rm, units=ids, seed=seed)\n assert boots_rm.std() > boots_orig.std()"},{"col":4,"comment":"null","endLoc":1442,"header":"def test_weights_with_missing(self, missing_df)","id":2478,"name":"test_weights_with_missing","nodeType":"Function","startLoc":1436,"text":"def test_weights_with_missing(self, missing_df):\n\n ax = histplot(missing_df, x=\"x\", weights=\"s\", bins=5)\n\n bar_heights = [bar.get_height() for bar in ax.patches]\n total_weight = missing_df[[\"x\", \"s\"]].dropna()[\"s\"].sum()\n assert sum(bar_heights) == pytest.approx(total_weight)"},{"col":4,"comment":"null","endLoc":1457,"header":"def test_weight_norm(self, rng)","id":2479,"name":"test_weight_norm","nodeType":"Function","startLoc":1444,"text":"def test_weight_norm(self, rng):\n\n vals = rng.normal(0, 1, 50)\n x = np.concatenate([vals, vals])\n w = np.repeat([1, 2], 50)\n ax = histplot(\n x=x, weights=w, hue=w, common_norm=True, stat=\"density\", bins=5\n )\n\n # Recall that artists are added in reverse of hue order\n y1 = [bar.get_height() for bar in ax.patches[:5]]\n y2 = [bar.get_height() for bar in ax.patches[5:]]\n\n assert sum(y1) == 2 * sum(y2)"},{"col":4,"comment":"null","endLoc":1469,"header":"def test_discrete(self, long_df)","id":2480,"name":"test_discrete","nodeType":"Function","startLoc":1459,"text":"def test_discrete(self, long_df):\n\n ax = histplot(long_df, x=\"s\", discrete=True)\n\n data_min = long_df[\"s\"].min()\n data_max = long_df[\"s\"].max()\n assert len(ax.patches) == (data_max - data_min + 1)\n\n for i, bar in enumerate(ax.patches):\n assert bar.get_width() == 1\n assert bar.get_x() == (data_min + i - .5)"},{"id":2481,"name":"seaborn/external","nodeType":"Package"},{"fileName":"kde.py","filePath":"seaborn/external","id":2482,"nodeType":"File","text":"\"\"\"\nThis module was copied from the scipy project.\n\nIn the process of copying, some methods were removed because they depended on\nother parts of scipy (especially on compiled components), allowing seaborn to\nhave a simple and pure Python implementation. These include:\n\n- integrate_gaussian\n- integrate_box\n- integrate_box_1d\n- integrate_kde\n- logpdf\n- resample\n\nAdditionally, the numpy.linalg module was substituted for scipy.linalg,\nand the examples section (with doctests) was removed from the docstring\n\nThe original scipy license is copied below:\n\nCopyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n\n# -------------------------------------------------------------------------------\n#\n# Define classes for (uni/multi)-variate kernel density estimation.\n#\n# Currently, only Gaussian kernels are implemented.\n#\n# Written by: Robert Kern\n#\n# Date: 2004-08-09\n#\n# Modified: 2005-02-10 by Robert Kern.\n# Contributed to SciPy\n# 2005-10-07 by Robert Kern.\n# Some fixes to match the new scipy_core\n#\n# Copyright 2004-2005 by Enthought, Inc.\n#\n# -------------------------------------------------------------------------------\n\nimport numpy as np\nfrom numpy import (asarray, atleast_2d, reshape, zeros, newaxis, dot, exp, pi,\n sqrt, ravel, power, atleast_1d, squeeze, sum, transpose,\n ones, cov)\nfrom numpy import linalg\n\n\n__all__ = ['gaussian_kde']\n\n\nclass gaussian_kde:\n \"\"\"Representation of a kernel-density estimate using Gaussian kernels.\n\n Kernel density estimation is a way to estimate the probability density\n function (PDF) of a random variable in a non-parametric way.\n `gaussian_kde` works for both uni-variate and multi-variate data. It\n includes automatic bandwidth determination. The estimation works best for\n a unimodal distribution; bimodal or multi-modal distributions tend to be\n oversmoothed.\n\n Parameters\n ----------\n dataset : array_like\n Datapoints to estimate from. In case of univariate data this is a 1-D\n array, otherwise a 2-D array with shape (# of dims, # of data).\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a scalar,\n this will be used directly as `kde.factor`. If a callable, it should\n take a `gaussian_kde` instance as only parameter and return a scalar.\n If None (default), 'scott' is used. See Notes for more details.\n weights : array_like, optional\n weights of datapoints. This must be the same shape as dataset.\n If None (default), the samples are assumed to be equally weighted\n\n Attributes\n ----------\n dataset : ndarray\n The dataset with which `gaussian_kde` was initialized.\n d : int\n Number of dimensions.\n n : int\n Number of datapoints.\n neff : int\n Effective number of datapoints.\n\n .. versionadded:: 1.2.0\n factor : float\n The bandwidth factor, obtained from `kde.covariance_factor`, with which\n the covariance matrix is multiplied.\n covariance : ndarray\n The covariance matrix of `dataset`, scaled by the calculated bandwidth\n (`kde.factor`).\n inv_cov : ndarray\n The inverse of `covariance`.\n\n Methods\n -------\n evaluate\n __call__\n integrate_gaussian\n integrate_box_1d\n integrate_box\n integrate_kde\n pdf\n logpdf\n resample\n set_bandwidth\n covariance_factor\n\n Notes\n -----\n Bandwidth selection strongly influences the estimate obtained from the KDE\n (much more so than the actual shape of the kernel). Bandwidth selection\n can be done by a \"rule of thumb\", by cross-validation, by \"plug-in\n methods\" or by other means; see [3]_, [4]_ for reviews. `gaussian_kde`\n uses a rule of thumb, the default is Scott's Rule.\n\n Scott's Rule [1]_, implemented as `scotts_factor`, is::\n\n n**(-1./(d+4)),\n\n with ``n`` the number of data points and ``d`` the number of dimensions.\n In the case of unequally weighted points, `scotts_factor` becomes::\n\n neff**(-1./(d+4)),\n\n with ``neff`` the effective number of datapoints.\n Silverman's Rule [2]_, implemented as `silverman_factor`, is::\n\n (n * (d + 2) / 4.)**(-1. / (d + 4)).\n\n or in the case of unequally weighted points::\n\n (neff * (d + 2) / 4.)**(-1. / (d + 4)).\n\n Good general descriptions of kernel density estimation can be found in [1]_\n and [2]_, the mathematics for this multi-dimensional implementation can be\n found in [1]_.\n\n With a set of weighted samples, the effective number of datapoints ``neff``\n is defined by::\n\n neff = sum(weights)^2 / sum(weights^2)\n\n as detailed in [5]_.\n\n References\n ----------\n .. [1] D.W. Scott, \"Multivariate Density Estimation: Theory, Practice, and\n Visualization\", John Wiley & Sons, New York, Chicester, 1992.\n .. [2] B.W. Silverman, \"Density Estimation for Statistics and Data\n Analysis\", Vol. 26, Monographs on Statistics and Applied Probability,\n Chapman and Hall, London, 1986.\n .. [3] B.A. Turlach, \"Bandwidth Selection in Kernel Density Estimation: A\n Review\", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993.\n .. [4] D.M. Bashtannyk and R.J. Hyndman, \"Bandwidth selection for kernel\n conditional density estimation\", Computational Statistics & Data\n Analysis, Vol. 36, pp. 279-298, 2001.\n .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society.\n Series A (General), 132, 272\n\n \"\"\"\n def __init__(self, dataset, bw_method=None, weights=None):\n self.dataset = atleast_2d(asarray(dataset))\n if not self.dataset.size > 1:\n raise ValueError(\"`dataset` input should have multiple elements.\")\n\n self.d, self.n = self.dataset.shape\n\n if weights is not None:\n self._weights = atleast_1d(weights).astype(float)\n self._weights /= sum(self._weights)\n if self.weights.ndim != 1:\n raise ValueError(\"`weights` input should be one-dimensional.\")\n if len(self._weights) != self.n:\n raise ValueError(\"`weights` input should be of length n\")\n self._neff = 1/sum(self._weights**2)\n\n self.set_bandwidth(bw_method=bw_method)\n\n def evaluate(self, points):\n \"\"\"Evaluate the estimated pdf on a set of points.\n\n Parameters\n ----------\n points : (# of dimensions, # of points)-array\n Alternatively, a (# of dimensions,) vector can be passed in and\n treated as a single point.\n\n Returns\n -------\n values : (# of points,)-array\n The values at each point.\n\n Raises\n ------\n ValueError : if the dimensionality of the input points is different than\n the dimensionality of the KDE.\n\n \"\"\"\n points = atleast_2d(asarray(points))\n\n d, m = points.shape\n if d != self.d:\n if d == 1 and m == self.d:\n # points was passed in as a row vector\n points = reshape(points, (self.d, 1))\n m = 1\n else:\n msg = f\"points have dimension {d}, dataset has dimension {self.d}\"\n raise ValueError(msg)\n\n output_dtype = np.common_type(self.covariance, points)\n result = zeros((m,), dtype=output_dtype)\n\n whitening = linalg.cholesky(self.inv_cov)\n scaled_dataset = dot(whitening, self.dataset)\n scaled_points = dot(whitening, points)\n\n if m >= self.n:\n # there are more points than data, so loop over data\n for i in range(self.n):\n diff = scaled_dataset[:, i, newaxis] - scaled_points\n energy = sum(diff * diff, axis=0) / 2.0\n result += self.weights[i]*exp(-energy)\n else:\n # loop over points\n for i in range(m):\n diff = scaled_dataset - scaled_points[:, i, newaxis]\n energy = sum(diff * diff, axis=0) / 2.0\n result[i] = sum(exp(-energy)*self.weights, axis=0)\n\n result = result / self._norm_factor\n\n return result\n\n __call__ = evaluate\n\n def scotts_factor(self):\n \"\"\"Compute Scott's factor.\n\n Returns\n -------\n s : float\n Scott's factor.\n \"\"\"\n return power(self.neff, -1./(self.d+4))\n\n def silverman_factor(self):\n \"\"\"Compute the Silverman factor.\n\n Returns\n -------\n s : float\n The silverman factor.\n \"\"\"\n return power(self.neff*(self.d+2.0)/4.0, -1./(self.d+4))\n\n # Default method to calculate bandwidth, can be overwritten by subclass\n covariance_factor = scotts_factor\n covariance_factor.__doc__ = \"\"\"Computes the coefficient (`kde.factor`) that\n multiplies the data covariance matrix to obtain the kernel covariance\n matrix. The default is `scotts_factor`. A subclass can overwrite this\n method to provide a different method, or set it through a call to\n `kde.set_bandwidth`.\"\"\"\n\n def set_bandwidth(self, bw_method=None):\n \"\"\"Compute the estimator bandwidth with given method.\n\n The new bandwidth calculated after a call to `set_bandwidth` is used\n for subsequent evaluations of the estimated density.\n\n Parameters\n ----------\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a\n scalar, this will be used directly as `kde.factor`. If a callable,\n it should take a `gaussian_kde` instance as only parameter and\n return a scalar. If None (default), nothing happens; the current\n `kde.covariance_factor` method is kept.\n\n Notes\n -----\n .. versionadded:: 0.11\n\n \"\"\"\n if bw_method is None:\n pass\n elif bw_method == 'scott':\n self.covariance_factor = self.scotts_factor\n elif bw_method == 'silverman':\n self.covariance_factor = self.silverman_factor\n elif np.isscalar(bw_method) and not isinstance(bw_method, str):\n self._bw_method = 'use constant'\n self.covariance_factor = lambda: bw_method\n elif callable(bw_method):\n self._bw_method = bw_method\n self.covariance_factor = lambda: self._bw_method(self)\n else:\n msg = \"`bw_method` should be 'scott', 'silverman', a scalar \" \\\n \"or a callable.\"\n raise ValueError(msg)\n\n self._compute_covariance()\n\n def _compute_covariance(self):\n \"\"\"Computes the covariance matrix for each Gaussian kernel using\n covariance_factor().\n \"\"\"\n self.factor = self.covariance_factor()\n # Cache covariance and inverse covariance of the data\n if not hasattr(self, '_data_inv_cov'):\n self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,\n bias=False,\n aweights=self.weights))\n self._data_inv_cov = linalg.inv(self._data_covariance)\n\n self.covariance = self._data_covariance * self.factor**2\n self.inv_cov = self._data_inv_cov / self.factor**2\n self._norm_factor = sqrt(linalg.det(2*pi*self.covariance))\n\n def pdf(self, x):\n \"\"\"\n Evaluate the estimated pdf on a provided set of points.\n\n Notes\n -----\n This is an alias for `gaussian_kde.evaluate`. See the ``evaluate``\n docstring for more details.\n\n \"\"\"\n return self.evaluate(x)\n\n @property\n def weights(self):\n try:\n return self._weights\n except AttributeError:\n self._weights = ones(self.n)/self.n\n return self._weights\n\n @property\n def neff(self):\n try:\n return self._neff\n except AttributeError:\n self._neff = 1/sum(self.weights**2)\n return self._neff\n"},{"className":"gaussian_kde","col":0,"comment":"Representation of a kernel-density estimate using Gaussian kernels.\n\n Kernel density estimation is a way to estimate the probability density\n function (PDF) of a random variable in a non-parametric way.\n `gaussian_kde` works for both uni-variate and multi-variate data. It\n includes automatic bandwidth determination. The estimation works best for\n a unimodal distribution; bimodal or multi-modal distributions tend to be\n oversmoothed.\n\n Parameters\n ----------\n dataset : array_like\n Datapoints to estimate from. In case of univariate data this is a 1-D\n array, otherwise a 2-D array with shape (# of dims, # of data).\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a scalar,\n this will be used directly as `kde.factor`. If a callable, it should\n take a `gaussian_kde` instance as only parameter and return a scalar.\n If None (default), 'scott' is used. See Notes for more details.\n weights : array_like, optional\n weights of datapoints. This must be the same shape as dataset.\n If None (default), the samples are assumed to be equally weighted\n\n Attributes\n ----------\n dataset : ndarray\n The dataset with which `gaussian_kde` was initialized.\n d : int\n Number of dimensions.\n n : int\n Number of datapoints.\n neff : int\n Effective number of datapoints.\n\n .. versionadded:: 1.2.0\n factor : float\n The bandwidth factor, obtained from `kde.covariance_factor`, with which\n the covariance matrix is multiplied.\n covariance : ndarray\n The covariance matrix of `dataset`, scaled by the calculated bandwidth\n (`kde.factor`).\n inv_cov : ndarray\n The inverse of `covariance`.\n\n Methods\n -------\n evaluate\n __call__\n integrate_gaussian\n integrate_box_1d\n integrate_box\n integrate_kde\n pdf\n logpdf\n resample\n set_bandwidth\n covariance_factor\n\n Notes\n -----\n Bandwidth selection strongly influences the estimate obtained from the KDE\n (much more so than the actual shape of the kernel). Bandwidth selection\n can be done by a \"rule of thumb\", by cross-validation, by \"plug-in\n methods\" or by other means; see [3]_, [4]_ for reviews. `gaussian_kde`\n uses a rule of thumb, the default is Scott's Rule.\n\n Scott's Rule [1]_, implemented as `scotts_factor`, is::\n\n n**(-1./(d+4)),\n\n with ``n`` the number of data points and ``d`` the number of dimensions.\n In the case of unequally weighted points, `scotts_factor` becomes::\n\n neff**(-1./(d+4)),\n\n with ``neff`` the effective number of datapoints.\n Silverman's Rule [2]_, implemented as `silverman_factor`, is::\n\n (n * (d + 2) / 4.)**(-1. / (d + 4)).\n\n or in the case of unequally weighted points::\n\n (neff * (d + 2) / 4.)**(-1. / (d + 4)).\n\n Good general descriptions of kernel density estimation can be found in [1]_\n and [2]_, the mathematics for this multi-dimensional implementation can be\n found in [1]_.\n\n With a set of weighted samples, the effective number of datapoints ``neff``\n is defined by::\n\n neff = sum(weights)^2 / sum(weights^2)\n\n as detailed in [5]_.\n\n References\n ----------\n .. [1] D.W. Scott, \"Multivariate Density Estimation: Theory, Practice, and\n Visualization\", John Wiley & Sons, New York, Chicester, 1992.\n .. [2] B.W. Silverman, \"Density Estimation for Statistics and Data\n Analysis\", Vol. 26, Monographs on Statistics and Applied Probability,\n Chapman and Hall, London, 1986.\n .. [3] B.A. Turlach, \"Bandwidth Selection in Kernel Density Estimation: A\n Review\", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993.\n .. [4] D.M. Bashtannyk and R.J. Hyndman, \"Bandwidth selection for kernel\n conditional density estimation\", Computational Statistics & Data\n Analysis, Vol. 36, pp. 279-298, 2001.\n .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society.\n Series A (General), 132, 272\n\n ","endLoc":381,"id":2483,"nodeType":"Class","startLoc":82,"text":"class gaussian_kde:\n \"\"\"Representation of a kernel-density estimate using Gaussian kernels.\n\n Kernel density estimation is a way to estimate the probability density\n function (PDF) of a random variable in a non-parametric way.\n `gaussian_kde` works for both uni-variate and multi-variate data. It\n includes automatic bandwidth determination. The estimation works best for\n a unimodal distribution; bimodal or multi-modal distributions tend to be\n oversmoothed.\n\n Parameters\n ----------\n dataset : array_like\n Datapoints to estimate from. In case of univariate data this is a 1-D\n array, otherwise a 2-D array with shape (# of dims, # of data).\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a scalar,\n this will be used directly as `kde.factor`. If a callable, it should\n take a `gaussian_kde` instance as only parameter and return a scalar.\n If None (default), 'scott' is used. See Notes for more details.\n weights : array_like, optional\n weights of datapoints. This must be the same shape as dataset.\n If None (default), the samples are assumed to be equally weighted\n\n Attributes\n ----------\n dataset : ndarray\n The dataset with which `gaussian_kde` was initialized.\n d : int\n Number of dimensions.\n n : int\n Number of datapoints.\n neff : int\n Effective number of datapoints.\n\n .. versionadded:: 1.2.0\n factor : float\n The bandwidth factor, obtained from `kde.covariance_factor`, with which\n the covariance matrix is multiplied.\n covariance : ndarray\n The covariance matrix of `dataset`, scaled by the calculated bandwidth\n (`kde.factor`).\n inv_cov : ndarray\n The inverse of `covariance`.\n\n Methods\n -------\n evaluate\n __call__\n integrate_gaussian\n integrate_box_1d\n integrate_box\n integrate_kde\n pdf\n logpdf\n resample\n set_bandwidth\n covariance_factor\n\n Notes\n -----\n Bandwidth selection strongly influences the estimate obtained from the KDE\n (much more so than the actual shape of the kernel). Bandwidth selection\n can be done by a \"rule of thumb\", by cross-validation, by \"plug-in\n methods\" or by other means; see [3]_, [4]_ for reviews. `gaussian_kde`\n uses a rule of thumb, the default is Scott's Rule.\n\n Scott's Rule [1]_, implemented as `scotts_factor`, is::\n\n n**(-1./(d+4)),\n\n with ``n`` the number of data points and ``d`` the number of dimensions.\n In the case of unequally weighted points, `scotts_factor` becomes::\n\n neff**(-1./(d+4)),\n\n with ``neff`` the effective number of datapoints.\n Silverman's Rule [2]_, implemented as `silverman_factor`, is::\n\n (n * (d + 2) / 4.)**(-1. / (d + 4)).\n\n or in the case of unequally weighted points::\n\n (neff * (d + 2) / 4.)**(-1. / (d + 4)).\n\n Good general descriptions of kernel density estimation can be found in [1]_\n and [2]_, the mathematics for this multi-dimensional implementation can be\n found in [1]_.\n\n With a set of weighted samples, the effective number of datapoints ``neff``\n is defined by::\n\n neff = sum(weights)^2 / sum(weights^2)\n\n as detailed in [5]_.\n\n References\n ----------\n .. [1] D.W. Scott, \"Multivariate Density Estimation: Theory, Practice, and\n Visualization\", John Wiley & Sons, New York, Chicester, 1992.\n .. [2] B.W. Silverman, \"Density Estimation for Statistics and Data\n Analysis\", Vol. 26, Monographs on Statistics and Applied Probability,\n Chapman and Hall, London, 1986.\n .. [3] B.A. Turlach, \"Bandwidth Selection in Kernel Density Estimation: A\n Review\", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993.\n .. [4] D.M. Bashtannyk and R.J. Hyndman, \"Bandwidth selection for kernel\n conditional density estimation\", Computational Statistics & Data\n Analysis, Vol. 36, pp. 279-298, 2001.\n .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society.\n Series A (General), 132, 272\n\n \"\"\"\n def __init__(self, dataset, bw_method=None, weights=None):\n self.dataset = atleast_2d(asarray(dataset))\n if not self.dataset.size > 1:\n raise ValueError(\"`dataset` input should have multiple elements.\")\n\n self.d, self.n = self.dataset.shape\n\n if weights is not None:\n self._weights = atleast_1d(weights).astype(float)\n self._weights /= sum(self._weights)\n if self.weights.ndim != 1:\n raise ValueError(\"`weights` input should be one-dimensional.\")\n if len(self._weights) != self.n:\n raise ValueError(\"`weights` input should be of length n\")\n self._neff = 1/sum(self._weights**2)\n\n self.set_bandwidth(bw_method=bw_method)\n\n def evaluate(self, points):\n \"\"\"Evaluate the estimated pdf on a set of points.\n\n Parameters\n ----------\n points : (# of dimensions, # of points)-array\n Alternatively, a (# of dimensions,) vector can be passed in and\n treated as a single point.\n\n Returns\n -------\n values : (# of points,)-array\n The values at each point.\n\n Raises\n ------\n ValueError : if the dimensionality of the input points is different than\n the dimensionality of the KDE.\n\n \"\"\"\n points = atleast_2d(asarray(points))\n\n d, m = points.shape\n if d != self.d:\n if d == 1 and m == self.d:\n # points was passed in as a row vector\n points = reshape(points, (self.d, 1))\n m = 1\n else:\n msg = f\"points have dimension {d}, dataset has dimension {self.d}\"\n raise ValueError(msg)\n\n output_dtype = np.common_type(self.covariance, points)\n result = zeros((m,), dtype=output_dtype)\n\n whitening = linalg.cholesky(self.inv_cov)\n scaled_dataset = dot(whitening, self.dataset)\n scaled_points = dot(whitening, points)\n\n if m >= self.n:\n # there are more points than data, so loop over data\n for i in range(self.n):\n diff = scaled_dataset[:, i, newaxis] - scaled_points\n energy = sum(diff * diff, axis=0) / 2.0\n result += self.weights[i]*exp(-energy)\n else:\n # loop over points\n for i in range(m):\n diff = scaled_dataset - scaled_points[:, i, newaxis]\n energy = sum(diff * diff, axis=0) / 2.0\n result[i] = sum(exp(-energy)*self.weights, axis=0)\n\n result = result / self._norm_factor\n\n return result\n\n __call__ = evaluate\n\n def scotts_factor(self):\n \"\"\"Compute Scott's factor.\n\n Returns\n -------\n s : float\n Scott's factor.\n \"\"\"\n return power(self.neff, -1./(self.d+4))\n\n def silverman_factor(self):\n \"\"\"Compute the Silverman factor.\n\n Returns\n -------\n s : float\n The silverman factor.\n \"\"\"\n return power(self.neff*(self.d+2.0)/4.0, -1./(self.d+4))\n\n # Default method to calculate bandwidth, can be overwritten by subclass\n covariance_factor = scotts_factor\n covariance_factor.__doc__ = \"\"\"Computes the coefficient (`kde.factor`) that\n multiplies the data covariance matrix to obtain the kernel covariance\n matrix. The default is `scotts_factor`. A subclass can overwrite this\n method to provide a different method, or set it through a call to\n `kde.set_bandwidth`.\"\"\"\n\n def set_bandwidth(self, bw_method=None):\n \"\"\"Compute the estimator bandwidth with given method.\n\n The new bandwidth calculated after a call to `set_bandwidth` is used\n for subsequent evaluations of the estimated density.\n\n Parameters\n ----------\n bw_method : str, scalar or callable, optional\n The method used to calculate the estimator bandwidth. This can be\n 'scott', 'silverman', a scalar constant or a callable. If a\n scalar, this will be used directly as `kde.factor`. If a callable,\n it should take a `gaussian_kde` instance as only parameter and\n return a scalar. If None (default), nothing happens; the current\n `kde.covariance_factor` method is kept.\n\n Notes\n -----\n .. versionadded:: 0.11\n\n \"\"\"\n if bw_method is None:\n pass\n elif bw_method == 'scott':\n self.covariance_factor = self.scotts_factor\n elif bw_method == 'silverman':\n self.covariance_factor = self.silverman_factor\n elif np.isscalar(bw_method) and not isinstance(bw_method, str):\n self._bw_method = 'use constant'\n self.covariance_factor = lambda: bw_method\n elif callable(bw_method):\n self._bw_method = bw_method\n self.covariance_factor = lambda: self._bw_method(self)\n else:\n msg = \"`bw_method` should be 'scott', 'silverman', a scalar \" \\\n \"or a callable.\"\n raise ValueError(msg)\n\n self._compute_covariance()\n\n def _compute_covariance(self):\n \"\"\"Computes the covariance matrix for each Gaussian kernel using\n covariance_factor().\n \"\"\"\n self.factor = self.covariance_factor()\n # Cache covariance and inverse covariance of the data\n if not hasattr(self, '_data_inv_cov'):\n self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,\n bias=False,\n aweights=self.weights))\n self._data_inv_cov = linalg.inv(self._data_covariance)\n\n self.covariance = self._data_covariance * self.factor**2\n self.inv_cov = self._data_inv_cov / self.factor**2\n self._norm_factor = sqrt(linalg.det(2*pi*self.covariance))\n\n def pdf(self, x):\n \"\"\"\n Evaluate the estimated pdf on a provided set of points.\n\n Notes\n -----\n This is an alias for `gaussian_kde.evaluate`. See the ``evaluate``\n docstring for more details.\n\n \"\"\"\n return self.evaluate(x)\n\n @property\n def weights(self):\n try:\n return self._weights\n except AttributeError:\n self._weights = ones(self.n)/self.n\n return self._weights\n\n @property\n def neff(self):\n try:\n return self._neff\n except AttributeError:\n self._neff = 1/sum(self.weights**2)\n return self._neff"},{"col":4,"comment":"Evaluate the estimated pdf on a set of points.\n\n Parameters\n ----------\n points : (# of dimensions, # of points)-array\n Alternatively, a (# of dimensions,) vector can be passed in and\n treated as a single point.\n\n Returns\n -------\n values : (# of points,)-array\n The values at each point.\n\n Raises\n ------\n ValueError : if the dimensionality of the input points is different than\n the dimensionality of the KDE.\n\n ","endLoc":267,"header":"def evaluate(self, points)","id":2484,"name":"evaluate","nodeType":"Function","startLoc":213,"text":"def evaluate(self, points):\n \"\"\"Evaluate the estimated pdf on a set of points.\n\n Parameters\n ----------\n points : (# of dimensions, # of points)-array\n Alternatively, a (# of dimensions,) vector can be passed in and\n treated as a single point.\n\n Returns\n -------\n values : (# of points,)-array\n The values at each point.\n\n Raises\n ------\n ValueError : if the dimensionality of the input points is different than\n the dimensionality of the KDE.\n\n \"\"\"\n points = atleast_2d(asarray(points))\n\n d, m = points.shape\n if d != self.d:\n if d == 1 and m == self.d:\n # points was passed in as a row vector\n points = reshape(points, (self.d, 1))\n m = 1\n else:\n msg = f\"points have dimension {d}, dataset has dimension {self.d}\"\n raise ValueError(msg)\n\n output_dtype = np.common_type(self.covariance, points)\n result = zeros((m,), dtype=output_dtype)\n\n whitening = linalg.cholesky(self.inv_cov)\n scaled_dataset = dot(whitening, self.dataset)\n scaled_points = dot(whitening, points)\n\n if m >= self.n:\n # there are more points than data, so loop over data\n for i in range(self.n):\n diff = scaled_dataset[:, i, newaxis] - scaled_points\n energy = sum(diff * diff, axis=0) / 2.0\n result += self.weights[i]*exp(-energy)\n else:\n # loop over points\n for i in range(m):\n diff = scaled_dataset - scaled_points[:, i, newaxis]\n energy = sum(diff * diff, axis=0) / 2.0\n result[i] = sum(exp(-energy)*self.weights, axis=0)\n\n result = result / self._norm_factor\n\n return result"},{"col":4,"comment":"null","endLoc":1475,"header":"def test_discrete_categorical_default(self, long_df)","id":2485,"name":"test_discrete_categorical_default","nodeType":"Function","startLoc":1471,"text":"def test_discrete_categorical_default(self, long_df):\n\n ax = histplot(long_df, x=\"a\")\n for i, bar in enumerate(ax.patches):\n assert bar.get_width() == 1"},{"col":0,"comment":"Test that different length args raise ValueError.","endLoc":121,"header":"def test_bootstrap_arglength()","id":2486,"name":"test_bootstrap_arglength","nodeType":"Function","startLoc":118,"text":"def test_bootstrap_arglength():\n \"\"\"Test that different length args raise ValueError.\"\"\"\n with pytest.raises(ValueError):\n algo.bootstrap(np.arange(5), np.arange(10))"},{"col":0,"comment":"Test that named numpy methods are the same as the numpy function.","endLoc":137,"header":"def test_bootstrap_string_func()","id":2487,"name":"test_bootstrap_string_func","nodeType":"Function","startLoc":124,"text":"def test_bootstrap_string_func():\n \"\"\"Test that named numpy methods are the same as the numpy function.\"\"\"\n x = np.random.randn(100)\n\n res_a = algo.bootstrap(x, func=\"mean\", seed=0)\n res_b = algo.bootstrap(x, func=np.mean, seed=0)\n assert np.array_equal(res_a, res_b)\n\n res_a = algo.bootstrap(x, func=\"std\", seed=0)\n res_b = algo.bootstrap(x, func=np.std, seed=0)\n assert np.array_equal(res_a, res_b)\n\n with pytest.raises(AttributeError):\n algo.bootstrap(x, func=\"not_a_method_name\")"},{"fileName":"test_palettes.py","filePath":"tests","id":2488,"nodeType":"File","text":"import colorsys\nimport numpy as np\nimport matplotlib as mpl\n\nimport pytest\nimport numpy.testing as npt\n\nfrom seaborn import palettes, utils, rcmod\nfrom seaborn.external import husl\nfrom seaborn._compat import get_colormap\nfrom seaborn.colors import xkcd_rgb, crayons\n\n\nclass TestColorPalettes:\n\n def test_current_palette(self):\n\n pal = palettes.color_palette([\"red\", \"blue\", \"green\"])\n rcmod.set_palette(pal)\n assert pal == utils.get_color_cycle()\n rcmod.set()\n\n def test_palette_context(self):\n\n default_pal = palettes.color_palette()\n context_pal = palettes.color_palette(\"muted\")\n\n with palettes.color_palette(context_pal):\n assert utils.get_color_cycle() == context_pal\n\n assert utils.get_color_cycle() == default_pal\n\n def test_big_palette_context(self):\n\n original_pal = palettes.color_palette(\"deep\", n_colors=8)\n context_pal = palettes.color_palette(\"husl\", 10)\n\n rcmod.set_palette(original_pal)\n with palettes.color_palette(context_pal, 10):\n assert utils.get_color_cycle() == context_pal\n\n assert utils.get_color_cycle() == original_pal\n\n # Reset default\n rcmod.set()\n\n def test_palette_size(self):\n\n pal = palettes.color_palette(\"deep\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"deep\"]\n\n pal = palettes.color_palette(\"pastel6\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"pastel6\"]\n\n pal = palettes.color_palette(\"Set3\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"Set3\"]\n\n pal = palettes.color_palette(\"husl\")\n assert len(pal) == 6\n\n pal = palettes.color_palette(\"Greens\")\n assert len(pal) == 6\n\n def test_seaborn_palettes(self):\n\n pals = \"deep\", \"muted\", \"pastel\", \"bright\", \"dark\", \"colorblind\"\n for name in pals:\n full = palettes.color_palette(name, 10).as_hex()\n short = palettes.color_palette(name + \"6\", 6).as_hex()\n b, _, g, r, m, _, _, _, y, c = full\n assert [b, g, r, m, y, c] == list(short)\n\n def test_hls_palette(self):\n\n pal1 = palettes.hls_palette()\n pal2 = palettes.color_palette(\"hls\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = palettes.hls_palette(as_cmap=True)\n cmap2 = palettes.color_palette(\"hls\", as_cmap=True)\n npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))\n\n def test_husl_palette(self):\n\n pal1 = palettes.husl_palette()\n pal2 = palettes.color_palette(\"husl\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = palettes.husl_palette(as_cmap=True)\n cmap2 = palettes.color_palette(\"husl\", as_cmap=True)\n npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))\n\n def test_mpl_palette(self):\n\n pal1 = palettes.mpl_palette(\"Reds\")\n pal2 = palettes.color_palette(\"Reds\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = get_colormap(\"Reds\")\n cmap2 = palettes.mpl_palette(\"Reds\", as_cmap=True)\n cmap3 = palettes.color_palette(\"Reds\", as_cmap=True)\n npt.assert_array_equal(cmap1, cmap2)\n npt.assert_array_equal(cmap1, cmap3)\n\n def test_mpl_dark_palette(self):\n\n mpl_pal1 = palettes.mpl_palette(\"Blues_d\")\n mpl_pal2 = palettes.color_palette(\"Blues_d\")\n npt.assert_array_equal(mpl_pal1, mpl_pal2)\n\n mpl_pal1 = palettes.mpl_palette(\"Blues_r_d\")\n mpl_pal2 = palettes.color_palette(\"Blues_r_d\")\n npt.assert_array_equal(mpl_pal1, mpl_pal2)\n\n def test_bad_palette_name(self):\n\n with pytest.raises(ValueError):\n palettes.color_palette(\"IAmNotAPalette\")\n\n def test_terrible_palette_name(self):\n\n with pytest.raises(ValueError):\n palettes.color_palette(\"jet\")\n\n def test_bad_palette_colors(self):\n\n pal = [\"red\", \"blue\", \"iamnotacolor\"]\n with pytest.raises(ValueError):\n palettes.color_palette(pal)\n\n def test_palette_desat(self):\n\n pal1 = palettes.husl_palette(6)\n pal1 = [utils.desaturate(c, .5) for c in pal1]\n pal2 = palettes.color_palette(\"husl\", desat=.5)\n npt.assert_array_equal(pal1, pal2)\n\n def test_palette_is_list_of_tuples(self):\n\n pal_in = np.array([\"red\", \"blue\", \"green\"])\n pal_out = palettes.color_palette(pal_in, 3)\n\n assert isinstance(pal_out, list)\n assert isinstance(pal_out[0], tuple)\n assert isinstance(pal_out[0][0], float)\n assert len(pal_out[0]) == 3\n\n def test_palette_cycles(self):\n\n deep = palettes.color_palette(\"deep6\")\n double_deep = palettes.color_palette(\"deep6\", 12)\n assert double_deep == deep + deep\n\n def test_hls_values(self):\n\n pal1 = palettes.hls_palette(6, h=0)\n pal2 = palettes.hls_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.hls_palette(5, l=.2) # noqa\n pal_bright = palettes.hls_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.hls_palette(5, s=.1)\n pal_bold = palettes.hls_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))\n\n def test_husl_values(self):\n\n pal1 = palettes.husl_palette(6, h=0)\n pal2 = palettes.husl_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.husl_palette(5, l=.2) # noqa\n pal_bright = palettes.husl_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.husl_palette(5, s=.1)\n pal_bold = palettes.husl_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))\n\n def test_cbrewer_qual(self):\n\n pal_short = palettes.mpl_palette(\"Set1\", 4)\n pal_long = palettes.mpl_palette(\"Set1\", 6)\n assert pal_short == pal_long[:4]\n\n pal_full = palettes.mpl_palette(\"Set2\", 8)\n pal_long = palettes.mpl_palette(\"Set2\", 10)\n assert pal_full == pal_long[:8]\n\n def test_mpl_reversal(self):\n\n pal_forward = palettes.mpl_palette(\"BuPu\", 6)\n pal_reverse = palettes.mpl_palette(\"BuPu_r\", 6)\n npt.assert_array_almost_equal(pal_forward, pal_reverse[::-1])\n\n def test_rgb_from_hls(self):\n\n color = .5, .8, .4\n rgb_got = palettes._color_to_rgb(color, \"hls\")\n rgb_want = colorsys.hls_to_rgb(*color)\n assert rgb_got == rgb_want\n\n def test_rgb_from_husl(self):\n\n color = 120, 50, 40\n rgb_got = palettes._color_to_rgb(color, \"husl\")\n rgb_want = tuple(husl.husl_to_rgb(*color))\n assert rgb_got == rgb_want\n\n for h in range(0, 360):\n color = h, 100, 100\n rgb = palettes._color_to_rgb(color, \"husl\")\n assert min(rgb) >= 0\n assert max(rgb) <= 1\n\n def test_rgb_from_xkcd(self):\n\n color = \"dull red\"\n rgb_got = palettes._color_to_rgb(color, \"xkcd\")\n rgb_want = mpl.colors.to_rgb(xkcd_rgb[color])\n assert rgb_got == rgb_want\n\n def test_light_palette(self):\n\n n = 4\n pal_forward = palettes.light_palette(\"red\", n)\n pal_reverse = palettes.light_palette(\"red\", n, reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_f_from_string = palettes.color_palette(\"light:red\", n)\n assert pal_forward[3] == pal_f_from_string[3]\n\n pal_r_from_string = palettes.color_palette(\"light:red_r\", n)\n assert pal_reverse[3] == pal_r_from_string[3]\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"light:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"light:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n def test_dark_palette(self):\n\n n = 4\n pal_forward = palettes.dark_palette(\"red\", n)\n pal_reverse = palettes.dark_palette(\"red\", n, reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_f_from_string = palettes.color_palette(\"dark:red\", n)\n assert pal_forward[3] == pal_f_from_string[3]\n\n pal_r_from_string = palettes.color_palette(\"dark:red_r\", n)\n assert pal_reverse[3] == pal_r_from_string[3]\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"dark:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"dark:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n def test_diverging_palette(self):\n\n h_neg, h_pos = 100, 200\n sat, lum = 70, 50\n args = h_neg, h_pos, sat, lum\n\n n = 12\n pal = palettes.diverging_palette(*args, n=n)\n neg_pal = palettes.light_palette((h_neg, sat, lum), int(n // 2),\n input=\"husl\")\n pos_pal = palettes.light_palette((h_pos, sat, lum), int(n // 2),\n input=\"husl\")\n assert len(pal) == n\n assert pal[0] == neg_pal[-1]\n assert pal[-1] == pos_pal[-1]\n\n pal_dark = palettes.diverging_palette(*args, n=n, center=\"dark\")\n assert np.mean(pal[int(n / 2)]) > np.mean(pal_dark[int(n / 2)])\n\n pal_cmap = palettes.diverging_palette(*args, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n def test_blend_palette(self):\n\n colors = [\"red\", \"yellow\", \"white\"]\n pal_cmap = palettes.blend_palette(colors, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n colors = [\"red\", \"blue\"]\n pal = palettes.blend_palette(colors)\n pal_str = \"blend:\" + \",\".join(colors)\n pal_from_str = palettes.color_palette(pal_str)\n assert pal == pal_from_str\n\n def test_cubehelix_against_matplotlib(self):\n\n x = np.linspace(0, 1, 8)\n mpl_pal = mpl.cm.cubehelix(x)[:, :3].tolist()\n\n sns_pal = palettes.cubehelix_palette(8, start=0.5, rot=-1.5, hue=1,\n dark=0, light=1, reverse=True)\n\n assert sns_pal == mpl_pal\n\n def test_cubehelix_n_colors(self):\n\n for n in [3, 5, 8]:\n pal = palettes.cubehelix_palette(n)\n assert len(pal) == n\n\n def test_cubehelix_reverse(self):\n\n pal_forward = palettes.cubehelix_palette()\n pal_reverse = palettes.cubehelix_palette(reverse=True)\n assert pal_forward == pal_reverse[::-1]\n\n def test_cubehelix_cmap(self):\n\n cmap = palettes.cubehelix_palette(as_cmap=True)\n assert isinstance(cmap, mpl.colors.ListedColormap)\n pal = palettes.cubehelix_palette()\n x = np.linspace(0, 1, 6)\n npt.assert_array_equal(cmap(x)[:, :3], pal)\n\n cmap_rev = palettes.cubehelix_palette(as_cmap=True, reverse=True)\n x = np.linspace(0, 1, 6)\n pal_forward = cmap(x).tolist()\n pal_reverse = cmap_rev(x[::-1]).tolist()\n assert pal_forward == pal_reverse\n\n def test_cubehelix_code(self):\n\n color_palette = palettes.color_palette\n cubehelix_palette = palettes.cubehelix_palette\n\n pal1 = color_palette(\"ch:\", 8)\n pal2 = color_palette(cubehelix_palette(8))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:.5, -.25,hue = .5,light=.75\", 8)\n pal2 = color_palette(cubehelix_palette(8, .5, -.25, hue=.5, light=.75))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:h=1,r=.5\", 9)\n pal2 = color_palette(cubehelix_palette(9, hue=1, rot=.5))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", 6)\n pal2 = color_palette(cubehelix_palette(6, reverse=True))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", as_cmap=True)\n pal2 = cubehelix_palette(6, reverse=True, as_cmap=True)\n assert pal1(.5) == pal2(.5)\n\n def test_xkcd_palette(self):\n\n names = list(xkcd_rgb.keys())[10:15]\n colors = palettes.xkcd_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n assert as_hex == xkcd_rgb[name]\n\n def test_crayon_palette(self):\n\n names = list(crayons.keys())[10:15]\n colors = palettes.crayon_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n assert as_hex == crayons[name].lower()\n\n def test_color_codes(self):\n\n palettes.set_color_codes(\"deep\")\n colors = palettes.color_palette(\"deep6\") + [\".1\"]\n for code, color in zip(\"bgrmyck\", colors):\n rgb_want = mpl.colors.colorConverter.to_rgb(color)\n rgb_got = mpl.colors.colorConverter.to_rgb(code)\n assert rgb_want == rgb_got\n palettes.set_color_codes(\"reset\")\n\n with pytest.raises(ValueError):\n palettes.set_color_codes(\"Set1\")\n\n def test_as_hex(self):\n\n pal = palettes.color_palette(\"deep\")\n for rgb, hex in zip(pal, pal.as_hex()):\n assert mpl.colors.rgb2hex(rgb) == hex\n\n def test_preserved_palette_length(self):\n\n pal_in = palettes.color_palette(\"Set1\", 10)\n pal_out = palettes.color_palette(pal_in)\n assert pal_in == pal_out\n\n def test_html_repr(self):\n\n pal = palettes.color_palette()\n html = pal._repr_html_()\n for color in pal.as_hex():\n assert color in html\n\n def test_colormap_display_patch(self):\n\n orig_repr_png = getattr(mpl.colors.Colormap, \"_repr_png_\", None)\n orig_repr_html = getattr(mpl.colors.Colormap, \"_repr_html_\", None)\n\n try:\n palettes._patch_colormap_display()\n cmap = mpl.cm.Reds\n assert cmap._repr_html_().startswith('\"Reds')\n ymin"},{"col":0,"comment":"null","endLoc":177,"header":"@pytest.mark.skipif(Version(np.__version__) < Version(\"1.17\"),\n reason=\"Tests new numpy random functionality\")\ndef test_seed_new()","id":2491,"name":"test_seed_new","nodeType":"Function","startLoc":154,"text":"@pytest.mark.skipif(Version(np.__version__) < Version(\"1.17\"),\n reason=\"Tests new numpy random functionality\")\ndef test_seed_new():\n\n # Can't use pytest parametrize because tests will fail where the new\n # Generator object and related function are not defined\n\n test_bank = [\n (None, None, npr.Generator, False),\n (npr.RandomState(0), npr.RandomState(0), npr.RandomState, True),\n (npr.RandomState(0), npr.RandomState(1), npr.RandomState, False),\n (npr.default_rng(1), npr.default_rng(1), npr.Generator, True),\n (npr.default_rng(1), npr.default_rng(2), npr.Generator, False),\n (npr.SeedSequence(10), npr.SeedSequence(10), npr.Generator, True),\n (npr.SeedSequence(10), npr.SeedSequence(20), npr.Generator, False),\n (100, 100, npr.Generator, True),\n (100, 200, npr.Generator, False),\n ]\n for seed1, seed2, rng_class, match in test_bank:\n rng1 = algo._handle_random_seed(seed1)\n rng2 = algo._handle_random_seed(seed2)\n assert isinstance(rng1, rng_class)\n assert isinstance(rng2, rng_class)\n assert (rng1.uniform() == rng2.uniform()) == match"},{"col":4,"comment":"null","endLoc":296,"header":"def test_legend_tuples(self)","id":2492,"name":"test_legend_tuples","nodeType":"Function","startLoc":286,"text":"def test_legend_tuples(self):\n\n g = ag.FacetGrid(self.df, hue=\"a\")\n g.map(plt.plot, \"x\", \"y\")\n\n handles, labels = g.ax.get_legend_handles_labels()\n label_tuples = [(\"\", l) for l in labels]\n legend_data = dict(zip(label_tuples, handles))\n g.add_legend(legend_data, label_tuples)\n for entry, label in zip(g._legend.get_texts(), labels):\n assert entry.get_text() == label"},{"col":4,"comment":"null","endLoc":1492,"header":"@pytest.mark.skipif(\n Version(np.__version__) < Version(\"1.17\"),\n reason=\"Histogram over datetime64 requires numpy >= 1.17\",\n )\n def test_datetime_scale(self, long_df)","id":2493,"name":"test_datetime_scale","nodeType":"Function","startLoc":1483,"text":"@pytest.mark.skipif(\n Version(np.__version__) < Version(\"1.17\"),\n reason=\"Histogram over datetime64 requires numpy >= 1.17\",\n )\n def test_datetime_scale(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(x=long_df[\"t\"], fill=True, ax=ax1)\n histplot(x=long_df[\"t\"], fill=False, ax=ax2)\n assert ax1.get_xlim() == ax2.get_xlim()"},{"col":4,"comment":"null","endLoc":411,"header":"def plot_swarms(\n self,\n dodge,\n color,\n edgecolor,\n warn_thresh,\n plot_kws,\n )","id":2494,"name":"plot_swarms","nodeType":"Function","startLoc":321,"text":"def plot_swarms(\n self,\n dodge,\n color,\n edgecolor,\n warn_thresh,\n plot_kws,\n ):\n\n width = .8 * self._native_width\n offsets = self._nested_offsets(width, dodge)\n\n iter_vars = [self.cat_axis]\n if dodge:\n iter_vars.append(\"hue\")\n\n ax = self.ax\n point_collections = {}\n dodge_move = 0\n\n for sub_vars, sub_data in self.iter_data(iter_vars,\n from_comp_data=True,\n allow_empty=True):\n\n if offsets is not None:\n dodge_move = offsets[sub_data[\"hue\"].map(self._hue_map.levels.index)]\n\n if not sub_data.empty:\n sub_data[self.cat_axis] = sub_data[self.cat_axis] + dodge_move\n\n for var in \"xy\":\n if self._log_scaled(var):\n sub_data[var] = np.power(10, sub_data[var])\n\n ax = self._get_axes(sub_vars)\n points = ax.scatter(sub_data[\"x\"], sub_data[\"y\"], color=color, **plot_kws)\n\n if \"hue\" in self.variables:\n points.set_facecolors(self._hue_map(sub_data[\"hue\"]))\n\n if edgecolor == \"gray\": # XXX TODO change to \"auto\"\n points.set_edgecolors(self._get_gray(points.get_facecolors()))\n else:\n points.set_edgecolors(edgecolor)\n\n if not sub_data.empty:\n point_collections[(ax, sub_data[self.cat_axis].iloc[0])] = points\n\n beeswarm = Beeswarm(\n width=width, orient=self.orient, warn_thresh=warn_thresh,\n )\n for (ax, center), points in point_collections.items():\n if points.get_offsets().shape[0] > 1:\n\n def draw(points, renderer, *, center=center):\n\n beeswarm(points, center)\n\n if self.orient == \"h\":\n scalex = False\n scaley = ax.get_autoscaley_on()\n else:\n scalex = ax.get_autoscalex_on()\n scaley = False\n\n # This prevents us from undoing the nice categorical axis limits\n # set in _adjust_cat_axis, because that method currently leave\n # the autoscale flag in its original setting. It may be better\n # to disable autoscaling there to avoid needing to do this.\n fixed_scale = self.var_types[self.cat_axis] == \"categorical\"\n ax.update_datalim(points.get_datalim(ax.transData))\n if not fixed_scale and (scalex or scaley):\n ax.autoscale_view(scalex=scalex, scaley=scaley)\n\n super(points.__class__, points).draw(renderer)\n\n points.draw = draw.__get__(points)\n\n _draw_figure(ax.figure)\n\n # Finalize the axes details\n if self.legend == \"auto\":\n show_legend = not self._redundant_hue and self.input_format != \"wide\"\n else:\n show_legend = bool(self.legend)\n\n if show_legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n ax.legend(title=self.legend_title)"},{"attributeType":"null","col":0,"comment":"null","endLoc":1,"id":2495,"name":"xkcd_rgb","nodeType":"Attribute","startLoc":1,"text":"xkcd_rgb"},{"col":4,"comment":"null","endLoc":1508,"header":"@pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde(self, flat_series, stat)","id":2496,"name":"test_kde","nodeType":"Function","startLoc":1494,"text":"@pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde(self, flat_series, stat):\n\n ax = histplot(\n flat_series, kde=True, stat=stat, kde_kws={\"cut\": 10}\n )\n\n bar_widths = [b.get_width() for b in ax.patches]\n bar_heights = [b.get_height() for b in ax.patches]\n hist_area = np.multiply(bar_widths, bar_heights).sum()\n\n density, = ax.lines\n kde_area = integrate(density.get_ydata(), density.get_xdata())\n\n assert kde_area == pytest.approx(hist_area)"},{"col":0,"comment":"\"Simple numerical integration for testing KDE code.","endLoc":2456,"header":"def integrate(y, x)","id":2497,"name":"integrate","nodeType":"Function","startLoc":2451,"text":"def integrate(y, x):\n \"\"\"\"Simple numerical integration for testing KDE code.\"\"\"\n y = np.asarray(y)\n x = np.asarray(x)\n dx = np.diff(x)\n return (dx * y[:-1] + dx * y[1:]).sum() / 2"},{"col":4,"comment":"null","endLoc":1534,"header":"@pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\"])\n @pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde_with_hue(self, long_df, stat, multiple)","id":2498,"name":"test_kde_with_hue","nodeType":"Function","startLoc":1510,"text":"@pytest.mark.parametrize(\"multiple\", [\"layer\", \"dodge\"])\n @pytest.mark.parametrize(\"stat\", [\"count\", \"density\", \"probability\"])\n def test_kde_with_hue(self, long_df, stat, multiple):\n\n n = 10\n ax = histplot(\n long_df, x=\"x\", hue=\"c\", multiple=multiple,\n kde=True, stat=stat, element=\"bars\",\n kde_kws={\"cut\": 10}, bins=n,\n )\n\n bar_groups = ax.patches[:n], ax.patches[-n:]\n\n for i, bars in enumerate(bar_groups):\n bar_widths = [b.get_width() for b in bars]\n bar_heights = [b.get_height() for b in bars]\n hist_area = np.multiply(bar_widths, bar_heights).sum()\n\n x, y = ax.lines[i].get_xydata().T\n kde_area = integrate(y, x)\n\n if multiple == \"layer\":\n assert kde_area == pytest.approx(hist_area)\n elif multiple == \"dodge\":\n assert kde_area == pytest.approx(hist_area * 2)"},{"col":4,"comment":"null","endLoc":3356,"header":"def __init__(self, orient=\"v\", width=0.8, warn_thresh=.05)","id":2499,"name":"__init__","nodeType":"Function","startLoc":3350,"text":"def __init__(self, orient=\"v\", width=0.8, warn_thresh=.05):\n\n # XXX should we keep the orient parameterization or specify the swarm axis?\n\n self.orient = orient\n self.width = width\n self.warn_thresh = warn_thresh"},{"col":0,"comment":"null","endLoc":194,"header":"@pytest.mark.skipif(Version(np.__version__) >= Version(\"1.17\"),\n reason=\"Tests old numpy random functionality\")\n@pytest.mark.parametrize(\"seed1, seed2, match\", [\n (None, None, False),\n (npr.RandomState(0), npr.RandomState(0), True),\n (npr.RandomState(0), npr.RandomState(1), False),\n (100, 100, True),\n (100, 200, False),\n])\ndef test_seed_old(seed1, seed2, match)","id":2500,"name":"test_seed_old","nodeType":"Function","startLoc":180,"text":"@pytest.mark.skipif(Version(np.__version__) >= Version(\"1.17\"),\n reason=\"Tests old numpy random functionality\")\n@pytest.mark.parametrize(\"seed1, seed2, match\", [\n (None, None, False),\n (npr.RandomState(0), npr.RandomState(0), True),\n (npr.RandomState(0), npr.RandomState(1), False),\n (100, 100, True),\n (100, 200, False),\n])\ndef test_seed_old(seed1, seed2, match):\n rng1 = algo._handle_random_seed(seed1)\n rng2 = algo._handle_random_seed(seed2)\n assert isinstance(rng1, np.random.RandomState)\n assert isinstance(rng2, np.random.RandomState)\n assert (rng1.uniform() == rng2.uniform()) == match"},{"col":0,"comment":"null","endLoc":202,"header":"@pytest.mark.skipif(Version(np.__version__) >= Version(\"1.17\"),\n reason=\"Tests old numpy random functionality\")\ndef test_bad_seed_old()","id":2501,"name":"test_bad_seed_old","nodeType":"Function","startLoc":197,"text":"@pytest.mark.skipif(Version(np.__version__) >= Version(\"1.17\"),\n reason=\"Tests old numpy random functionality\")\ndef test_bad_seed_old():\n\n with pytest.raises(ValueError):\n algo._handle_random_seed(\"not_a_random_seed\")"},{"col":4,"comment":"null","endLoc":1541,"header":"def test_kde_default_cut(self, flat_series)","id":2502,"name":"test_kde_default_cut","nodeType":"Function","startLoc":1536,"text":"def test_kde_default_cut(self, flat_series):\n\n ax = histplot(flat_series, kde=True)\n support = ax.lines[0].get_xdata()\n assert support.min() == flat_series.min()\n assert support.max() == flat_series.max()"},{"col":0,"comment":"null","endLoc":210,"header":"def test_nanaware_func_auto(random)","id":2503,"name":"test_nanaware_func_auto","nodeType":"Function","startLoc":205,"text":"def test_nanaware_func_auto(random):\n\n x = np.random.normal(size=10)\n x[0] = np.nan\n boots = algo.bootstrap(x, func=\"mean\")\n assert not np.isnan(boots).any()"},{"col":0,"comment":"null","endLoc":219,"header":"def test_nanaware_func_warning(random)","id":2504,"name":"test_nanaware_func_warning","nodeType":"Function","startLoc":213,"text":"def test_nanaware_func_warning(random):\n\n x = np.random.normal(size=10)\n x[0] = np.nan\n with pytest.warns(UserWarning, match=\"Data contain nans but\"):\n boots = algo.bootstrap(x, func=\"ptp\")\n assert np.isnan(boots).any()"},{"attributeType":"null","col":16,"comment":"null","endLoc":1,"id":2505,"name":"np","nodeType":"Attribute","startLoc":1,"text":"np"},{"attributeType":"null","col":23,"comment":"null","endLoc":2,"id":2506,"name":"npr","nodeType":"Attribute","startLoc":2,"text":"npr"},{"attributeType":"null","col":34,"comment":"null","endLoc":7,"id":2507,"name":"algo","nodeType":"Attribute","startLoc":7,"text":"algo"},{"attributeType":"null","col":0,"comment":"null","endLoc":1,"id":2508,"name":"crayons","nodeType":"Attribute","startLoc":1,"text":"crayons"},{"id":2509,"name":"tutorial.yaml","nodeType":"TextFile","path":"doc","text":"- title:\n pages:\n - introduction\n- title: API Overview\n pages:\n - function_overview\n - data_structure\n- title: Objects interface\n pages:\n - objects_interface\n - properties\n- title: Plotting functions\n pages:\n - relational\n - distributions\n - categorical\n- title: Statistical operations\n pages:\n - error_bars\n - regression\n- title: Multi-plot grids\n pages:\n - axis_grids\n- title: Figure aesthetics\n pages:\n - aesthetics\n - color_palettes\n"},{"col":4,"comment":"null","endLoc":1551,"header":"def test_kde_hue(self, long_df)","id":2510,"name":"test_kde_hue","nodeType":"Function","startLoc":1543,"text":"def test_kde_hue(self, long_df):\n\n n = 10\n ax = histplot(data=long_df, x=\"x\", hue=\"a\", kde=True, bins=n)\n\n for bar, line in zip(ax.patches[::n], ax.lines):\n assert_colors_equal(\n bar.get_facecolor(), line.get_color(), check_alpha=False\n )"},{"className":"TestColorPalettes","col":0,"comment":"null","endLoc":439,"id":2511,"nodeType":"Class","startLoc":14,"text":"class TestColorPalettes:\n\n def test_current_palette(self):\n\n pal = palettes.color_palette([\"red\", \"blue\", \"green\"])\n rcmod.set_palette(pal)\n assert pal == utils.get_color_cycle()\n rcmod.set()\n\n def test_palette_context(self):\n\n default_pal = palettes.color_palette()\n context_pal = palettes.color_palette(\"muted\")\n\n with palettes.color_palette(context_pal):\n assert utils.get_color_cycle() == context_pal\n\n assert utils.get_color_cycle() == default_pal\n\n def test_big_palette_context(self):\n\n original_pal = palettes.color_palette(\"deep\", n_colors=8)\n context_pal = palettes.color_palette(\"husl\", 10)\n\n rcmod.set_palette(original_pal)\n with palettes.color_palette(context_pal, 10):\n assert utils.get_color_cycle() == context_pal\n\n assert utils.get_color_cycle() == original_pal\n\n # Reset default\n rcmod.set()\n\n def test_palette_size(self):\n\n pal = palettes.color_palette(\"deep\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"deep\"]\n\n pal = palettes.color_palette(\"pastel6\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"pastel6\"]\n\n pal = palettes.color_palette(\"Set3\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"Set3\"]\n\n pal = palettes.color_palette(\"husl\")\n assert len(pal) == 6\n\n pal = palettes.color_palette(\"Greens\")\n assert len(pal) == 6\n\n def test_seaborn_palettes(self):\n\n pals = \"deep\", \"muted\", \"pastel\", \"bright\", \"dark\", \"colorblind\"\n for name in pals:\n full = palettes.color_palette(name, 10).as_hex()\n short = palettes.color_palette(name + \"6\", 6).as_hex()\n b, _, g, r, m, _, _, _, y, c = full\n assert [b, g, r, m, y, c] == list(short)\n\n def test_hls_palette(self):\n\n pal1 = palettes.hls_palette()\n pal2 = palettes.color_palette(\"hls\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = palettes.hls_palette(as_cmap=True)\n cmap2 = palettes.color_palette(\"hls\", as_cmap=True)\n npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))\n\n def test_husl_palette(self):\n\n pal1 = palettes.husl_palette()\n pal2 = palettes.color_palette(\"husl\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = palettes.husl_palette(as_cmap=True)\n cmap2 = palettes.color_palette(\"husl\", as_cmap=True)\n npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))\n\n def test_mpl_palette(self):\n\n pal1 = palettes.mpl_palette(\"Reds\")\n pal2 = palettes.color_palette(\"Reds\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = get_colormap(\"Reds\")\n cmap2 = palettes.mpl_palette(\"Reds\", as_cmap=True)\n cmap3 = palettes.color_palette(\"Reds\", as_cmap=True)\n npt.assert_array_equal(cmap1, cmap2)\n npt.assert_array_equal(cmap1, cmap3)\n\n def test_mpl_dark_palette(self):\n\n mpl_pal1 = palettes.mpl_palette(\"Blues_d\")\n mpl_pal2 = palettes.color_palette(\"Blues_d\")\n npt.assert_array_equal(mpl_pal1, mpl_pal2)\n\n mpl_pal1 = palettes.mpl_palette(\"Blues_r_d\")\n mpl_pal2 = palettes.color_palette(\"Blues_r_d\")\n npt.assert_array_equal(mpl_pal1, mpl_pal2)\n\n def test_bad_palette_name(self):\n\n with pytest.raises(ValueError):\n palettes.color_palette(\"IAmNotAPalette\")\n\n def test_terrible_palette_name(self):\n\n with pytest.raises(ValueError):\n palettes.color_palette(\"jet\")\n\n def test_bad_palette_colors(self):\n\n pal = [\"red\", \"blue\", \"iamnotacolor\"]\n with pytest.raises(ValueError):\n palettes.color_palette(pal)\n\n def test_palette_desat(self):\n\n pal1 = palettes.husl_palette(6)\n pal1 = [utils.desaturate(c, .5) for c in pal1]\n pal2 = palettes.color_palette(\"husl\", desat=.5)\n npt.assert_array_equal(pal1, pal2)\n\n def test_palette_is_list_of_tuples(self):\n\n pal_in = np.array([\"red\", \"blue\", \"green\"])\n pal_out = palettes.color_palette(pal_in, 3)\n\n assert isinstance(pal_out, list)\n assert isinstance(pal_out[0], tuple)\n assert isinstance(pal_out[0][0], float)\n assert len(pal_out[0]) == 3\n\n def test_palette_cycles(self):\n\n deep = palettes.color_palette(\"deep6\")\n double_deep = palettes.color_palette(\"deep6\", 12)\n assert double_deep == deep + deep\n\n def test_hls_values(self):\n\n pal1 = palettes.hls_palette(6, h=0)\n pal2 = palettes.hls_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.hls_palette(5, l=.2) # noqa\n pal_bright = palettes.hls_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.hls_palette(5, s=.1)\n pal_bold = palettes.hls_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))\n\n def test_husl_values(self):\n\n pal1 = palettes.husl_palette(6, h=0)\n pal2 = palettes.husl_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.husl_palette(5, l=.2) # noqa\n pal_bright = palettes.husl_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.husl_palette(5, s=.1)\n pal_bold = palettes.husl_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))\n\n def test_cbrewer_qual(self):\n\n pal_short = palettes.mpl_palette(\"Set1\", 4)\n pal_long = palettes.mpl_palette(\"Set1\", 6)\n assert pal_short == pal_long[:4]\n\n pal_full = palettes.mpl_palette(\"Set2\", 8)\n pal_long = palettes.mpl_palette(\"Set2\", 10)\n assert pal_full == pal_long[:8]\n\n def test_mpl_reversal(self):\n\n pal_forward = palettes.mpl_palette(\"BuPu\", 6)\n pal_reverse = palettes.mpl_palette(\"BuPu_r\", 6)\n npt.assert_array_almost_equal(pal_forward, pal_reverse[::-1])\n\n def test_rgb_from_hls(self):\n\n color = .5, .8, .4\n rgb_got = palettes._color_to_rgb(color, \"hls\")\n rgb_want = colorsys.hls_to_rgb(*color)\n assert rgb_got == rgb_want\n\n def test_rgb_from_husl(self):\n\n color = 120, 50, 40\n rgb_got = palettes._color_to_rgb(color, \"husl\")\n rgb_want = tuple(husl.husl_to_rgb(*color))\n assert rgb_got == rgb_want\n\n for h in range(0, 360):\n color = h, 100, 100\n rgb = palettes._color_to_rgb(color, \"husl\")\n assert min(rgb) >= 0\n assert max(rgb) <= 1\n\n def test_rgb_from_xkcd(self):\n\n color = \"dull red\"\n rgb_got = palettes._color_to_rgb(color, \"xkcd\")\n rgb_want = mpl.colors.to_rgb(xkcd_rgb[color])\n assert rgb_got == rgb_want\n\n def test_light_palette(self):\n\n n = 4\n pal_forward = palettes.light_palette(\"red\", n)\n pal_reverse = palettes.light_palette(\"red\", n, reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_f_from_string = palettes.color_palette(\"light:red\", n)\n assert pal_forward[3] == pal_f_from_string[3]\n\n pal_r_from_string = palettes.color_palette(\"light:red_r\", n)\n assert pal_reverse[3] == pal_r_from_string[3]\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"light:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"light:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n def test_dark_palette(self):\n\n n = 4\n pal_forward = palettes.dark_palette(\"red\", n)\n pal_reverse = palettes.dark_palette(\"red\", n, reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_f_from_string = palettes.color_palette(\"dark:red\", n)\n assert pal_forward[3] == pal_f_from_string[3]\n\n pal_r_from_string = palettes.color_palette(\"dark:red_r\", n)\n assert pal_reverse[3] == pal_r_from_string[3]\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"dark:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"dark:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n def test_diverging_palette(self):\n\n h_neg, h_pos = 100, 200\n sat, lum = 70, 50\n args = h_neg, h_pos, sat, lum\n\n n = 12\n pal = palettes.diverging_palette(*args, n=n)\n neg_pal = palettes.light_palette((h_neg, sat, lum), int(n // 2),\n input=\"husl\")\n pos_pal = palettes.light_palette((h_pos, sat, lum), int(n // 2),\n input=\"husl\")\n assert len(pal) == n\n assert pal[0] == neg_pal[-1]\n assert pal[-1] == pos_pal[-1]\n\n pal_dark = palettes.diverging_palette(*args, n=n, center=\"dark\")\n assert np.mean(pal[int(n / 2)]) > np.mean(pal_dark[int(n / 2)])\n\n pal_cmap = palettes.diverging_palette(*args, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n def test_blend_palette(self):\n\n colors = [\"red\", \"yellow\", \"white\"]\n pal_cmap = palettes.blend_palette(colors, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n colors = [\"red\", \"blue\"]\n pal = palettes.blend_palette(colors)\n pal_str = \"blend:\" + \",\".join(colors)\n pal_from_str = palettes.color_palette(pal_str)\n assert pal == pal_from_str\n\n def test_cubehelix_against_matplotlib(self):\n\n x = np.linspace(0, 1, 8)\n mpl_pal = mpl.cm.cubehelix(x)[:, :3].tolist()\n\n sns_pal = palettes.cubehelix_palette(8, start=0.5, rot=-1.5, hue=1,\n dark=0, light=1, reverse=True)\n\n assert sns_pal == mpl_pal\n\n def test_cubehelix_n_colors(self):\n\n for n in [3, 5, 8]:\n pal = palettes.cubehelix_palette(n)\n assert len(pal) == n\n\n def test_cubehelix_reverse(self):\n\n pal_forward = palettes.cubehelix_palette()\n pal_reverse = palettes.cubehelix_palette(reverse=True)\n assert pal_forward == pal_reverse[::-1]\n\n def test_cubehelix_cmap(self):\n\n cmap = palettes.cubehelix_palette(as_cmap=True)\n assert isinstance(cmap, mpl.colors.ListedColormap)\n pal = palettes.cubehelix_palette()\n x = np.linspace(0, 1, 6)\n npt.assert_array_equal(cmap(x)[:, :3], pal)\n\n cmap_rev = palettes.cubehelix_palette(as_cmap=True, reverse=True)\n x = np.linspace(0, 1, 6)\n pal_forward = cmap(x).tolist()\n pal_reverse = cmap_rev(x[::-1]).tolist()\n assert pal_forward == pal_reverse\n\n def test_cubehelix_code(self):\n\n color_palette = palettes.color_palette\n cubehelix_palette = palettes.cubehelix_palette\n\n pal1 = color_palette(\"ch:\", 8)\n pal2 = color_palette(cubehelix_palette(8))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:.5, -.25,hue = .5,light=.75\", 8)\n pal2 = color_palette(cubehelix_palette(8, .5, -.25, hue=.5, light=.75))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:h=1,r=.5\", 9)\n pal2 = color_palette(cubehelix_palette(9, hue=1, rot=.5))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", 6)\n pal2 = color_palette(cubehelix_palette(6, reverse=True))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", as_cmap=True)\n pal2 = cubehelix_palette(6, reverse=True, as_cmap=True)\n assert pal1(.5) == pal2(.5)\n\n def test_xkcd_palette(self):\n\n names = list(xkcd_rgb.keys())[10:15]\n colors = palettes.xkcd_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n assert as_hex == xkcd_rgb[name]\n\n def test_crayon_palette(self):\n\n names = list(crayons.keys())[10:15]\n colors = palettes.crayon_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n assert as_hex == crayons[name].lower()\n\n def test_color_codes(self):\n\n palettes.set_color_codes(\"deep\")\n colors = palettes.color_palette(\"deep6\") + [\".1\"]\n for code, color in zip(\"bgrmyck\", colors):\n rgb_want = mpl.colors.colorConverter.to_rgb(color)\n rgb_got = mpl.colors.colorConverter.to_rgb(code)\n assert rgb_want == rgb_got\n palettes.set_color_codes(\"reset\")\n\n with pytest.raises(ValueError):\n palettes.set_color_codes(\"Set1\")\n\n def test_as_hex(self):\n\n pal = palettes.color_palette(\"deep\")\n for rgb, hex in zip(pal, pal.as_hex()):\n assert mpl.colors.rgb2hex(rgb) == hex\n\n def test_preserved_palette_length(self):\n\n pal_in = palettes.color_palette(\"Set1\", 10)\n pal_out = palettes.color_palette(pal_in)\n assert pal_in == pal_out\n\n def test_html_repr(self):\n\n pal = palettes.color_palette()\n html = pal._repr_html_()\n for color in pal.as_hex():\n assert color in html\n\n def test_colormap_display_patch(self):\n\n orig_repr_png = getattr(mpl.colors.Colormap, \"_repr_png_\", None)\n orig_repr_html = getattr(mpl.colors.Colormap, \"_repr_html_\", None)\n\n try:\n palettes._patch_colormap_display()\n cmap = mpl.cm.Reds\n assert cmap._repr_html_().startswith('\"Reds')\n","id":2559,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nThis module was copied from the scipy project.\n\nIn the process of copying, some methods were removed because they depended on\nother parts of scipy (especially on compiled components), allowing seaborn to\nhave a simple and pure Python implementation. These include:\n\n- integrate_gaussian\n- integrate_box\n- integrate_box_1d\n- integrate_kde\n- logpdf\n- resample\n\nAdditionally, the numpy.linalg module was substituted for scipy.linalg,\nand the examples section (with doctests) was removed from the docstring\n\nThe original scipy license is copied below:\n\nCopyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n\n__all__ = ['gaussian_kde']"},{"id":2560,"name":"matplotlibrc","nodeType":"TextFile","path":"doc","text":"savefig.bbox : tight\n"},{"col":4,"comment":"Adjust x position of points to avoid overlaps.","endLoc":3450,"header":"def beeswarm(self, orig_xyr)","id":2561,"name":"beeswarm","nodeType":"Function","startLoc":3420,"text":"def beeswarm(self, orig_xyr):\n \"\"\"Adjust x position of points to avoid overlaps.\"\"\"\n # In this method, `x` is always the categorical axis\n # Center of the swarm, in point coordinates\n midline = orig_xyr[0, 0]\n\n # Start the swarm with the first point\n swarm = np.atleast_2d(orig_xyr[0])\n\n # Loop over the remaining points\n for xyr_i in orig_xyr[1:]:\n\n # Find the points in the swarm that could possibly\n # overlap with the point we are currently placing\n neighbors = self.could_overlap(xyr_i, swarm)\n\n # Find positions that would be valid individually\n # with respect to each of the swarm neighbors\n candidates = self.position_candidates(xyr_i, neighbors)\n\n # Sort candidates by their centrality\n offsets = np.abs(candidates[:, 0] - midline)\n candidates = candidates[np.argsort(offsets)]\n\n # Find the first candidate that does not overlap any neighbors\n new_xyr_i = self.first_non_overlapping_candidate(candidates, neighbors)\n\n # Place it into the swarm\n swarm = np.vstack([swarm, new_xyr_i])\n\n return swarm"},{"col":4,"comment":"Return a list of all swarm points that could overlap with target.","endLoc":3464,"header":"def could_overlap(self, xyr_i, swarm)","id":2562,"name":"could_overlap","nodeType":"Function","startLoc":3452,"text":"def could_overlap(self, xyr_i, swarm):\n \"\"\"Return a list of all swarm points that could overlap with target.\"\"\"\n # Because we work backwards through the swarm and can short-circuit,\n # the for-loop is faster than vectorization\n _, y_i, r_i = xyr_i\n neighbors = []\n for xyr_j in reversed(swarm):\n _, y_j, r_j = xyr_j\n if (y_i - y_j) < (r_i + r_j):\n neighbors.append(xyr_j)\n else:\n break\n return np.array(neighbors)[::-1]"},{"col":4,"comment":"Return a list of coordinates that might be valid by adjusting x.","endLoc":3481,"header":"def position_candidates(self, xyr_i, neighbors)","id":2563,"name":"position_candidates","nodeType":"Function","startLoc":3466,"text":"def position_candidates(self, xyr_i, neighbors):\n \"\"\"Return a list of coordinates that might be valid by adjusting x.\"\"\"\n candidates = [xyr_i]\n x_i, y_i, r_i = xyr_i\n left_first = True\n for x_j, y_j, r_j in neighbors:\n dy = y_i - y_j\n dx = np.sqrt(max((r_i + r_j) ** 2 - dy ** 2, 0)) * 1.05\n cl, cr = (x_j - dx, y_i, r_i), (x_j + dx, y_i, r_i)\n if left_first:\n new_candidates = [cl, cr]\n else:\n new_candidates = [cr, cl]\n candidates.extend(new_candidates)\n left_first = not left_first\n return np.array(candidates)"},{"col":4,"comment":"Find the first candidate that does not overlap with the swarm.","endLoc":3514,"header":"def first_non_overlapping_candidate(self, candidates, neighbors)","id":2564,"name":"first_non_overlapping_candidate","nodeType":"Function","startLoc":3483,"text":"def first_non_overlapping_candidate(self, candidates, neighbors):\n \"\"\"Find the first candidate that does not overlap with the swarm.\"\"\"\n\n # If we have no neighbors, all candidates are good.\n if len(neighbors) == 0:\n return candidates[0]\n\n neighbors_x = neighbors[:, 0]\n neighbors_y = neighbors[:, 1]\n neighbors_r = neighbors[:, 2]\n\n for xyr_i in candidates:\n\n x_i, y_i, r_i = xyr_i\n\n dx = neighbors_x - x_i\n dy = neighbors_y - y_i\n sq_distances = np.square(dx) + np.square(dy)\n\n sep_needed = np.square(neighbors_r + r_i)\n\n # Good candidate does not overlap any of neighbors which means that\n # squared distance between candidate and any of the neighbors has\n # to be at least square of the summed radii\n good_candidate = np.all(sq_distances >= sep_needed)\n\n if good_candidate:\n return xyr_i\n\n raise RuntimeError(\n \"No non-overlapping candidates found. This should not happen.\"\n )"},{"fileName":"conf.py","filePath":"doc","id":2565,"nodeType":"File","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\nimport time\nimport seaborn\nfrom seaborn._core.properties import PROPERTIES\n\nsys.path.insert(0, os.path.abspath('sphinxext'))\n\n\n# -- Project information -----------------------------------------------------\n\nproject = 'seaborn'\ncopyright = f'2012-{time.strftime(\"%Y\")}'\nauthor = 'Michael Waskom'\nversion = release = seaborn.__version__\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (amed 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.intersphinx',\n 'matplotlib.sphinxext.plot_directive',\n 'gallery_generator',\n 'tutorial_builder',\n 'numpydoc',\n 'sphinx_copybutton',\n 'sphinx_issues',\n 'sphinx_design',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The root document.\nroot_doc = 'index'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = ['_build', 'docstrings', 'nextgen', 'Thumbs.db', '.DS_Store']\n\n# The reST default role (used for this markup: `text`) to use for all documents.\ndefault_role = 'literal'\n\n# Generate the API documentation when building\nautosummary_generate = True\nnumpydoc_show_class_members = False\n\n# Sphinx-issues configuration\nissues_github_path = 'mwaskom/seaborn'\n\n# Include the example source for plots in API docs\nplot_include_source = True\nplot_formats = [('png', 90)]\nplot_html_show_formats = False\nplot_html_show_source_link = False\n\n# Don't add a source link in the sidebar\nhtml_show_sourcelink = False\n\n# Control the appearance of type hints\nautodoc_typehints = \"none\"\nautodoc_typehints_format = \"short\"\n\n# Allow shorthand references for main function interface\nrst_prolog = \"\"\"\n.. currentmodule:: seaborn\n\"\"\"\n\n# Define replacements (used in whatsnew bullets)\nrst_epilog = \"\"\"\n\n.. role:: raw-html(raw)\n :format: html\n\n.. role:: raw-latex(raw)\n :format: latex\n\n.. |API| replace:: :raw-html:`API` :raw-latex:`{\\small\\sc [API]}`\n.. |Defaults| replace:: :raw-html:`Defaults` :raw-latex:`{\\small\\sc [Defaults]}`\n.. |Docs| replace:: :raw-html:`Docs` :raw-latex:`{\\small\\sc [Docs]}`\n.. |Feature| replace:: :raw-html:`Feature` :raw-latex:`{\\small\\sc [Feature]}`\n.. |Enhancement| replace:: :raw-html:`Enhancement` :raw-latex:`{\\small\\sc [Enhancement]}`\n.. |Fix| replace:: :raw-html:`Fix` :raw-latex:`{\\small\\sc [Fix]}`\n.. |Build| replace:: :raw-html:`Build` :raw-latex:`{\\small\\sc [Deps]}`\n\n\"\"\" # noqa\n\nrst_epilog += \"\\n\".join([\n f\".. |{key}| replace:: :ref:`{key} <{val.__class__.__name__.lower()}_property>`\"\n for key, val in PROPERTIES.items()\n])\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'pydata_sphinx_theme'\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named 'default.css' will overwrite the builtin 'default.css'.\nhtml_static_path = ['_static', 'example_thumbs']\nfor path in html_static_path:\n if not os.path.exists(path):\n os.makedirs(path)\n\nhtml_css_files = [f'css/custom.css?v={seaborn.__version__}']\n\nhtml_logo = \"_static/logo-wide-lightbg.svg\"\nhtml_favicon = \"_static/favicon.ico\"\n\nhtml_theme_options = {\n \"icon_links\": [\n {\n \"name\": \"GitHub\",\n \"url\": \"https://github.com/mwaskom/seaborn\",\n \"icon\": \"fab fa-github\",\n \"type\": \"fontawesome\",\n },\n {\n \"name\": \"StackOverflow\",\n \"url\": \"https://stackoverflow.com/tags/seaborn\",\n \"icon\": \"fab fa-stack-overflow\",\n \"type\": \"fontawesome\",\n },\n {\n \"name\": \"Twitter\",\n \"url\": \"https://twitter.com/michaelwaskom\",\n \"icon\": \"fab fa-twitter\",\n \"type\": \"fontawesome\",\n },\n ],\n \"show_prev_next\": False,\n \"navbar_start\": [\"navbar-logo\"],\n \"navbar_end\": [\"navbar-icon-links\"],\n \"header_links_before_dropdown\": 8,\n}\n\nhtml_context = {\n \"default_mode\": \"light\",\n}\n\nhtml_sidebars = {\n \"index\": [],\n \"examples/index\": [],\n \"**\": [\"sidebar-nav-bs.html\"],\n}\n\n# -- Intersphinx ------------------------------------------------\n\nintersphinx_mapping = {\n 'numpy': ('https://numpy.org/doc/stable/', None),\n 'scipy': ('https://docs.scipy.org/doc/scipy/', None),\n 'matplotlib': ('https://matplotlib.org/stable', None),\n 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None),\n 'statsmodels': ('https://www.statsmodels.org/stable/', None)\n}\n"},{"attributeType":"str","col":0,"comment":"null","endLoc":24,"id":2566,"name":"project","nodeType":"Attribute","startLoc":24,"text":"project"},{"attributeType":"str","col":0,"comment":"null","endLoc":25,"id":2567,"name":"copyright","nodeType":"Attribute","startLoc":25,"text":"copyright"},{"attributeType":"str","col":0,"comment":"null","endLoc":26,"id":2568,"name":"author","nodeType":"Attribute","startLoc":26,"text":"author"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":2569,"name":"version","nodeType":"Attribute","startLoc":27,"text":"version"},{"col":4,"comment":"null","endLoc":350,"header":"def test_gridspec_kws(self)","id":2570,"name":"test_gridspec_kws","nodeType":"Function","startLoc":336,"text":"def test_gridspec_kws(self):\n ratios = [3, 1, 2]\n\n gskws = dict(width_ratios=ratios)\n g = ag.FacetGrid(self.df, col='c', row='a', gridspec_kws=gskws)\n\n for ax in g.axes.flat:\n ax.set_xticks([])\n ax.set_yticks([])\n\n g.figure.tight_layout()\n\n for (l, m, r) in g.axes:\n assert l.get_position().width > m.get_position().width\n assert r.get_position().width > m.get_position().width"},{"col":4,"comment":"null","endLoc":357,"header":"def test_gridspec_kws_col_wrap(self)","id":2571,"name":"test_gridspec_kws_col_wrap","nodeType":"Function","startLoc":352,"text":"def test_gridspec_kws_col_wrap(self):\n ratios = [3, 1, 2, 1, 1]\n\n gskws = dict(width_ratios=ratios)\n with pytest.warns(UserWarning):\n ag.FacetGrid(self.df, col='d', col_wrap=5, gridspec_kws=gskws)"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":1334,"id":2572,"name":"_legend_data","nodeType":"Attribute","startLoc":1334,"text":"self._legend_data"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1355,"id":2573,"name":"_despine","nodeType":"Attribute","startLoc":1355,"text":"self._despine"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1263,"id":2574,"name":"square_grid","nodeType":"Attribute","startLoc":1263,"text":"self.square_grid"},{"attributeType":"list","col":8,"comment":"null","endLoc":1261,"id":2575,"name":"x_vars","nodeType":"Attribute","startLoc":1261,"text":"self.x_vars"},{"attributeType":"null","col":8,"comment":"null","endLoc":1294,"id":2576,"name":"data","nodeType":"Attribute","startLoc":1294,"text":"self.data"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1285,"id":2577,"name":"_corner","nodeType":"Attribute","startLoc":1285,"text":"self._corner"},{"attributeType":"list | list","col":12,"comment":"null","endLoc":1325,"id":2578,"name":"hue_names","nodeType":"Attribute","startLoc":1325,"text":"self.hue_names"},{"attributeType":"null","col":10,"comment":"null","endLoc":27,"id":2579,"name":"release","nodeType":"Attribute","startLoc":27,"text":"release"},{"attributeType":"list","col":0,"comment":"null","endLoc":35,"id":2580,"name":"extensions","nodeType":"Attribute","startLoc":35,"text":"extensions"},{"attributeType":"list","col":0,"comment":"null","endLoc":52,"id":2581,"name":"templates_path","nodeType":"Attribute","startLoc":52,"text":"templates_path"},{"attributeType":"str","col":0,"comment":"null","endLoc":55,"id":2582,"name":"root_doc","nodeType":"Attribute","startLoc":55,"text":"root_doc"},{"attributeType":"list","col":0,"comment":"null","endLoc":60,"id":2583,"name":"exclude_patterns","nodeType":"Attribute","startLoc":60,"text":"exclude_patterns"},{"attributeType":"str","col":0,"comment":"null","endLoc":63,"id":2584,"name":"default_role","nodeType":"Attribute","startLoc":63,"text":"default_role"},{"attributeType":"bool","col":0,"comment":"null","endLoc":66,"id":2585,"name":"autosummary_generate","nodeType":"Attribute","startLoc":66,"text":"autosummary_generate"},{"attributeType":"bool","col":0,"comment":"null","endLoc":67,"id":2586,"name":"numpydoc_show_class_members","nodeType":"Attribute","startLoc":67,"text":"numpydoc_show_class_members"},{"attributeType":"str","col":0,"comment":"null","endLoc":70,"id":2587,"name":"issues_github_path","nodeType":"Attribute","startLoc":70,"text":"issues_github_path"},{"attributeType":"bool","col":0,"comment":"null","endLoc":73,"id":2588,"name":"plot_include_source","nodeType":"Attribute","startLoc":73,"text":"plot_include_source"},{"attributeType":"list","col":0,"comment":"null","endLoc":74,"id":2589,"name":"plot_formats","nodeType":"Attribute","startLoc":74,"text":"plot_formats"},{"attributeType":"bool","col":0,"comment":"null","endLoc":75,"id":2590,"name":"plot_html_show_formats","nodeType":"Attribute","startLoc":75,"text":"plot_html_show_formats"},{"attributeType":"bool","col":0,"comment":"null","endLoc":76,"id":2591,"name":"plot_html_show_source_link","nodeType":"Attribute","startLoc":76,"text":"plot_html_show_source_link"},{"attributeType":"bool","col":0,"comment":"null","endLoc":79,"id":2592,"name":"html_show_sourcelink","nodeType":"Attribute","startLoc":79,"text":"html_show_sourcelink"},{"attributeType":"str","col":0,"comment":"null","endLoc":82,"id":2593,"name":"autodoc_typehints","nodeType":"Attribute","startLoc":82,"text":"autodoc_typehints"},{"attributeType":"str","col":0,"comment":"null","endLoc":83,"id":2594,"name":"autodoc_typehints_format","nodeType":"Attribute","startLoc":83,"text":"autodoc_typehints_format"},{"attributeType":"str","col":0,"comment":"null","endLoc":86,"id":2595,"name":"rst_prolog","nodeType":"Attribute","startLoc":86,"text":"rst_prolog"},{"attributeType":"str","col":0,"comment":"null","endLoc":91,"id":2596,"name":"rst_epilog","nodeType":"Attribute","startLoc":91,"text":"rst_epilog"},{"attributeType":"null","col":8,"comment":"null","endLoc":111,"id":2597,"name":"key","nodeType":"Attribute","startLoc":111,"text":"key"},{"attributeType":"null","col":13,"comment":"null","endLoc":111,"id":2598,"name":"val","nodeType":"Attribute","startLoc":111,"text":"val"},{"attributeType":"str","col":0,"comment":"null","endLoc":119,"id":2599,"name":"html_theme","nodeType":"Attribute","startLoc":119,"text":"html_theme"},{"attributeType":"list","col":0,"comment":"null","endLoc":124,"id":2600,"name":"html_static_path","nodeType":"Attribute","startLoc":124,"text":"html_static_path"},{"attributeType":"str","col":4,"comment":"null","endLoc":125,"id":2601,"name":"path","nodeType":"Attribute","startLoc":125,"text":"path"},{"col":4,"comment":"null","endLoc":397,"header":"def test_data_generator(self)","id":2602,"name":"test_data_generator","nodeType":"Function","startLoc":359,"text":"def test_data_generator(self):\n\n g = ag.FacetGrid(self.df, row=\"a\")\n d = list(g.facet_data())\n assert len(d) == 3\n\n tup, data = d[0]\n assert tup == (0, 0, 0)\n assert (data[\"a\"] == \"a\").all()\n\n tup, data = d[1]\n assert tup == (1, 0, 0)\n assert (data[\"a\"] == \"b\").all()\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n d = list(g.facet_data())\n assert len(d) == 6\n\n tup, data = d[0]\n assert tup == (0, 0, 0)\n assert (data[\"a\"] == \"a\").all()\n assert (data[\"b\"] == \"m\").all()\n\n tup, data = d[1]\n assert tup == (0, 1, 0)\n assert (data[\"a\"] == \"a\").all()\n assert (data[\"b\"] == \"n\").all()\n\n tup, data = d[2]\n assert tup == (1, 0, 0)\n assert (data[\"a\"] == \"b\").all()\n assert (data[\"b\"] == \"m\").all()\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n d = list(g.facet_data())\n assert len(d) == 3\n tup, data = d[1]\n assert tup == (0, 0, 1)\n assert (data[\"c\"] == \"u\").all()"},{"attributeType":"list","col":0,"comment":"null","endLoc":129,"id":2603,"name":"html_css_files","nodeType":"Attribute","startLoc":129,"text":"html_css_files"},{"attributeType":"str","col":0,"comment":"null","endLoc":131,"id":2604,"name":"html_logo","nodeType":"Attribute","startLoc":131,"text":"html_logo"},{"attributeType":"str","col":0,"comment":"null","endLoc":132,"id":2605,"name":"html_favicon","nodeType":"Attribute","startLoc":132,"text":"html_favicon"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":134,"id":2606,"name":"html_theme_options","nodeType":"Attribute","startLoc":134,"text":"html_theme_options"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":161,"id":2607,"name":"html_context","nodeType":"Attribute","startLoc":161,"text":"html_context"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":165,"id":2608,"name":"html_sidebars","nodeType":"Attribute","startLoc":165,"text":"html_sidebars"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":173,"id":2609,"name":"intersphinx_mapping","nodeType":"Attribute","startLoc":173,"text":"intersphinx_mapping"},{"col":0,"comment":"","endLoc":13,"header":"conf.py#","id":2610,"name":"","nodeType":"Function","startLoc":13,"text":"sys.path.insert(0, os.path.abspath('sphinxext'))\n\nproject = 'seaborn'\n\ncopyright = f'2012-{time.strftime(\"%Y\")}'\n\nauthor = 'Michael Waskom'\n\nversion = release = seaborn.__version__\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.intersphinx',\n 'matplotlib.sphinxext.plot_directive',\n 'gallery_generator',\n 'tutorial_builder',\n 'numpydoc',\n 'sphinx_copybutton',\n 'sphinx_issues',\n 'sphinx_design',\n]\n\ntemplates_path = ['_templates']\n\nroot_doc = 'index'\n\nexclude_patterns = ['_build', 'docstrings', 'nextgen', 'Thumbs.db', '.DS_Store']\n\ndefault_role = 'literal'\n\nautosummary_generate = True\n\nnumpydoc_show_class_members = False\n\nissues_github_path = 'mwaskom/seaborn'\n\nplot_include_source = True\n\nplot_formats = [('png', 90)]\n\nplot_html_show_formats = False\n\nplot_html_show_source_link = False\n\nhtml_show_sourcelink = False\n\nautodoc_typehints = \"none\"\n\nautodoc_typehints_format = \"short\"\n\nrst_prolog = \"\"\"\n.. currentmodule:: seaborn\n\"\"\"\n\nrst_epilog = \"\"\"\n\n.. role:: raw-html(raw)\n :format: html\n\n.. role:: raw-latex(raw)\n :format: latex\n\n.. |API| replace:: :raw-html:`API` :raw-latex:`{\\small\\sc [API]}`\n.. |Defaults| replace:: :raw-html:`Defaults` :raw-latex:`{\\small\\sc [Defaults]}`\n.. |Docs| replace:: :raw-html:`Docs` :raw-latex:`{\\small\\sc [Docs]}`\n.. |Feature| replace:: :raw-html:`Feature` :raw-latex:`{\\small\\sc [Feature]}`\n.. |Enhancement| replace:: :raw-html:`Enhancement` :raw-latex:`{\\small\\sc [Enhancement]}`\n.. |Fix| replace:: :raw-html:`Fix` :raw-latex:`{\\small\\sc [Fix]}`\n.. |Build| replace:: :raw-html:`Build` :raw-latex:`{\\small\\sc [Deps]}`\n\n\"\"\" # noqa\n\nrst_epilog += \"\\n\".join([\n f\".. |{key}| replace:: :ref:`{key} <{val.__class__.__name__.lower()}_property>`\"\n for key, val in PROPERTIES.items()\n])\n\nhtml_theme = 'pydata_sphinx_theme'\n\nhtml_static_path = ['_static', 'example_thumbs']\n\nfor path in html_static_path:\n if not os.path.exists(path):\n os.makedirs(path)\n\nhtml_css_files = [f'css/custom.css?v={seaborn.__version__}']\n\nhtml_logo = \"_static/logo-wide-lightbg.svg\"\n\nhtml_favicon = \"_static/favicon.ico\"\n\nhtml_theme_options = {\n \"icon_links\": [\n {\n \"name\": \"GitHub\",\n \"url\": \"https://github.com/mwaskom/seaborn\",\n \"icon\": \"fab fa-github\",\n \"type\": \"fontawesome\",\n },\n {\n \"name\": \"StackOverflow\",\n \"url\": \"https://stackoverflow.com/tags/seaborn\",\n \"icon\": \"fab fa-stack-overflow\",\n \"type\": \"fontawesome\",\n },\n {\n \"name\": \"Twitter\",\n \"url\": \"https://twitter.com/michaelwaskom\",\n \"icon\": \"fab fa-twitter\",\n \"type\": \"fontawesome\",\n },\n ],\n \"show_prev_next\": False,\n \"navbar_start\": [\"navbar-logo\"],\n \"navbar_end\": [\"navbar-icon-links\"],\n \"header_links_before_dropdown\": 8,\n}\n\nhtml_context = {\n \"default_mode\": \"light\",\n}\n\nhtml_sidebars = {\n \"index\": [],\n \"examples/index\": [],\n \"**\": [\"sidebar-nav-bs.html\"],\n}\n\nintersphinx_mapping = {\n 'numpy': ('https://numpy.org/doc/stable/', None),\n 'scipy': ('https://docs.scipy.org/doc/scipy/', None),\n 'matplotlib': ('https://matplotlib.org/stable', None),\n 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None),\n 'statsmodels': ('https://www.statsmodels.org/stable/', None)\n}"},{"attributeType":"None","col":8,"comment":"null","endLoc":1299,"id":2612,"name":"diag_axes","nodeType":"Attribute","startLoc":1299,"text":"self.diag_axes"},{"attributeType":"null","col":12,"comment":"null","endLoc":1326,"id":2613,"name":"hue_vals","nodeType":"Attribute","startLoc":1326,"text":"self.hue_vals"},{"col":4,"comment":"null","endLoc":1021,"header":"def insert(self, __index: SupportsIndex, __object: _T) -> None","id":2614,"name":"insert","nodeType":"Function","startLoc":1021,"text":"def insert(self, __index: SupportsIndex, __object: _T) -> None: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":1293,"id":2616,"name":"axes","nodeType":"Attribute","startLoc":1293,"text":"self.axes"},{"attributeType":"None","col":8,"comment":"null","endLoc":1298,"id":2617,"name":"diag_vars","nodeType":"Attribute","startLoc":1298,"text":"self.diag_vars"},{"attributeType":"null","col":8,"comment":"null","endLoc":1354,"id":2618,"name":"_tight_layout_pad","nodeType":"Attribute","startLoc":1354,"text":"self._tight_layout_pad"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":1329,"id":2619,"name":"hue_kws","nodeType":"Attribute","startLoc":1329,"text":"self.hue_kws"},{"attributeType":"null","col":8,"comment":"null","endLoc":1331,"id":2620,"name":"_orig_palette","nodeType":"Attribute","startLoc":1331,"text":"self._orig_palette"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1301,"id":2621,"name":"_dropna","nodeType":"Attribute","startLoc":1301,"text":"self._dropna"},{"attributeType":"list | list","col":8,"comment":"null","endLoc":1332,"id":2622,"name":"_hue_order","nodeType":"Attribute","startLoc":1332,"text":"self._hue_order"},{"attributeType":"null","col":8,"comment":"null","endLoc":1292,"id":2623,"name":"_figure","nodeType":"Attribute","startLoc":1292,"text":"self._figure"},{"attributeType":"list","col":8,"comment":"null","endLoc":1353,"id":2624,"name":"_tight_layout_rect","nodeType":"Attribute","startLoc":1353,"text":"self._tight_layout_rect"},{"col":4,"comment":"null","endLoc":186,"header":"def test_husl_values(self)","id":2625,"name":"test_husl_values","nodeType":"Function","startLoc":171,"text":"def test_husl_values(self):\n\n pal1 = palettes.husl_palette(6, h=0)\n pal2 = palettes.husl_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.husl_palette(5, l=.2) # noqa\n pal_bright = palettes.husl_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.husl_palette(5, s=.1)\n pal_bold = palettes.husl_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))"},{"attributeType":"null","col":8,"comment":"null","endLoc":1333,"id":2626,"name":"palette","nodeType":"Attribute","startLoc":1333,"text":"self.palette"},{"attributeType":"null","col":8,"comment":"null","endLoc":1307,"id":2627,"name":"_hue_var","nodeType":"Attribute","startLoc":1307,"text":"self._hue_var"},{"attributeType":"bool","col":12,"comment":"null","endLoc":1559,"id":2628,"name":"_extract_legend_handles","nodeType":"Attribute","startLoc":1559,"text":"self._extract_legend_handles"},{"attributeType":"list","col":8,"comment":"null","endLoc":1262,"id":2629,"name":"y_vars","nodeType":"Attribute","startLoc":1262,"text":"self.y_vars"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1297,"id":2630,"name":"diag_sharey","nodeType":"Attribute","startLoc":1297,"text":"self.diag_sharey"},{"className":"JointGrid","col":0,"comment":"Grid for drawing a bivariate plot with marginal univariate plots.\n\n Many plots can be drawn by using the figure-level interface :func:`jointplot`.\n Use this class directly when you need more flexibility.\n\n ","endLoc":1958,"id":2631,"nodeType":"Class","startLoc":1673,"text":"class JointGrid(_BaseGrid):\n \"\"\"Grid for drawing a bivariate plot with marginal univariate plots.\n\n Many plots can be drawn by using the figure-level interface :func:`jointplot`.\n Use this class directly when you need more flexibility.\n\n \"\"\"\n\n def __init__(\n self, data=None, *,\n x=None, y=None, hue=None,\n height=6, ratio=5, space=.2,\n palette=None, hue_order=None, hue_norm=None,\n dropna=False, xlim=None, ylim=None, marginal_ticks=False,\n ):\n\n # Set up the subplot grid\n f = plt.figure(figsize=(height, height))\n gs = plt.GridSpec(ratio + 1, ratio + 1)\n\n ax_joint = f.add_subplot(gs[1:, :-1])\n ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint)\n ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint)\n\n self._figure = f\n self.ax_joint = ax_joint\n self.ax_marg_x = ax_marg_x\n self.ax_marg_y = ax_marg_y\n\n # Turn off tick visibility for the measure axis on the marginal plots\n plt.setp(ax_marg_x.get_xticklabels(), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(), visible=False)\n plt.setp(ax_marg_x.get_xticklabels(minor=True), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(minor=True), visible=False)\n\n # Turn off the ticks on the density axis for the marginal plots\n if not marginal_ticks:\n plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(minor=True), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(minor=True), visible=False)\n ax_marg_x.yaxis.grid(False)\n ax_marg_y.xaxis.grid(False)\n\n # Process the input variables\n p = VectorPlotter(data=data, variables=dict(x=x, y=y, hue=hue))\n plot_data = p.plot_data.loc[:, p.plot_data.notna().any()]\n\n # Possibly drop NA\n if dropna:\n plot_data = plot_data.dropna()\n\n def get_var(var):\n vector = plot_data.get(var, None)\n if vector is not None:\n vector = vector.rename(p.variables.get(var, None))\n return vector\n\n self.x = get_var(\"x\")\n self.y = get_var(\"y\")\n self.hue = get_var(\"hue\")\n\n for axis in \"xy\":\n name = p.variables.get(axis, None)\n if name is not None:\n getattr(ax_joint, f\"set_{axis}label\")(name)\n\n if xlim is not None:\n ax_joint.set_xlim(xlim)\n if ylim is not None:\n ax_joint.set_ylim(ylim)\n\n # Store the semantic mapping parameters for axes-level functions\n self._hue_params = dict(palette=palette, hue_order=hue_order, hue_norm=hue_norm)\n\n # Make the grid look nice\n utils.despine(f)\n if not marginal_ticks:\n utils.despine(ax=ax_marg_x, left=True)\n utils.despine(ax=ax_marg_y, bottom=True)\n for axes in [ax_marg_x, ax_marg_y]:\n for axis in [axes.xaxis, axes.yaxis]:\n axis.label.set_visible(False)\n f.tight_layout()\n f.subplots_adjust(hspace=space, wspace=space)\n\n def _inject_kwargs(self, func, kws, params):\n \"\"\"Add params to kws if they are accepted by func.\"\"\"\n func_params = signature(func).parameters\n for key, val in params.items():\n if key in func_params:\n kws.setdefault(key, val)\n\n def plot(self, joint_func, marginal_func, **kwargs):\n \"\"\"Draw the plot by passing functions for joint and marginal axes.\n\n This method passes the ``kwargs`` dictionary to both functions. If you\n need more control, call :meth:`JointGrid.plot_joint` and\n :meth:`JointGrid.plot_marginals` directly with specific parameters.\n\n Parameters\n ----------\n joint_func, marginal_func : callables\n Functions to draw the bivariate and univariate plots. See methods\n referenced above for information about the required characteristics\n of these functions.\n kwargs\n Additional keyword arguments are passed to both functions.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n self.plot_marginals(marginal_func, **kwargs)\n self.plot_joint(joint_func, **kwargs)\n return self\n\n def plot_joint(self, func, **kwargs):\n \"\"\"Draw a bivariate plot on the joint axes of the grid.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y``. Otherwise,\n it must accept ``x`` and ``y`` vectors of data as the first two\n positional arguments, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, the function must\n accept ``hue`` as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n kwargs = kwargs.copy()\n if str(func.__module__).startswith(\"seaborn\"):\n kwargs[\"ax\"] = self.ax_joint\n else:\n plt.sca(self.ax_joint)\n if self.hue is not None:\n kwargs[\"hue\"] = self.hue\n self._inject_kwargs(func, kwargs, self._hue_params)\n\n if str(func.__module__).startswith(\"seaborn\"):\n func(x=self.x, y=self.y, **kwargs)\n else:\n func(self.x, self.y, **kwargs)\n\n return self\n\n def plot_marginals(self, func, **kwargs):\n \"\"\"Draw univariate plots on each marginal axes.\n\n Parameters\n ----------\n func : plotting callable\n If a seaborn function, it should accept ``x`` and ``y`` and plot\n when only one of them is defined. Otherwise, it must accept a vector\n of data as the first positional argument and determine its orientation\n using the ``vertical`` parameter, and it must plot on the \"current\" axes.\n If ``hue`` was defined in the class constructor, it must accept ``hue``\n as a parameter.\n kwargs\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n seaborn_func = (\n str(func.__module__).startswith(\"seaborn\")\n # deprecated distplot has a legacy API, special case it\n and not func.__name__ == \"distplot\"\n )\n func_params = signature(func).parameters\n kwargs = kwargs.copy()\n if self.hue is not None:\n kwargs[\"hue\"] = self.hue\n self._inject_kwargs(func, kwargs, self._hue_params)\n\n if \"legend\" in func_params:\n kwargs.setdefault(\"legend\", False)\n\n if \"orientation\" in func_params:\n # e.g. plt.hist\n orient_kw_x = {\"orientation\": \"vertical\"}\n orient_kw_y = {\"orientation\": \"horizontal\"}\n elif \"vertical\" in func_params:\n # e.g. sns.distplot (also how did this get backwards?)\n orient_kw_x = {\"vertical\": False}\n orient_kw_y = {\"vertical\": True}\n\n if seaborn_func:\n func(x=self.x, ax=self.ax_marg_x, **kwargs)\n else:\n plt.sca(self.ax_marg_x)\n func(self.x, **orient_kw_x, **kwargs)\n\n if seaborn_func:\n func(y=self.y, ax=self.ax_marg_y, **kwargs)\n else:\n plt.sca(self.ax_marg_y)\n func(self.y, **orient_kw_y, **kwargs)\n\n self.ax_marg_x.yaxis.get_label().set_visible(False)\n self.ax_marg_y.xaxis.get_label().set_visible(False)\n\n return self\n\n def refline(\n self, *, x=None, y=None, joint=True, marginal=True,\n color='.5', linestyle='--', **line_kws\n ):\n \"\"\"Add a reference line(s) to joint and/or marginal axes.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n joint, marginal : bools\n Whether to add the reference line(s) to the joint/marginal axes.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s).\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n line_kws['color'] = color\n line_kws['linestyle'] = linestyle\n\n if x is not None:\n if joint:\n self.ax_joint.axvline(x, **line_kws)\n if marginal:\n self.ax_marg_x.axvline(x, **line_kws)\n\n if y is not None:\n if joint:\n self.ax_joint.axhline(y, **line_kws)\n if marginal:\n self.ax_marg_y.axhline(y, **line_kws)\n\n return self\n\n def set_axis_labels(self, xlabel=\"\", ylabel=\"\", **kwargs):\n \"\"\"Set axis labels on the bivariate axes.\n\n Parameters\n ----------\n xlabel, ylabel : strings\n Label names for the x and y variables.\n kwargs : key, value mappings\n Other keyword arguments are passed to the following functions:\n\n - :meth:`matplotlib.axes.Axes.set_xlabel`\n - :meth:`matplotlib.axes.Axes.set_ylabel`\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n self.ax_joint.set_xlabel(xlabel, **kwargs)\n self.ax_joint.set_ylabel(ylabel, **kwargs)\n return self"},{"col":4,"comment":"Draw the plot by passing functions for joint and marginal axes.\n\n This method passes the ``kwargs`` dictionary to both functions. If you\n need more control, call :meth:`JointGrid.plot_joint` and\n :meth:`JointGrid.plot_marginals` directly with specific parameters.\n\n Parameters\n ----------\n joint_func, marginal_func : callables\n Functions to draw the bivariate and univariate plots. See methods\n referenced above for information about the required characteristics\n of these functions.\n kwargs\n Additional keyword arguments are passed to both functions.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n ","endLoc":1794,"header":"def plot(self, joint_func, marginal_func, **kwargs)","id":2632,"name":"plot","nodeType":"Function","startLoc":1770,"text":"def plot(self, joint_func, marginal_func, **kwargs):\n \"\"\"Draw the plot by passing functions for joint and marginal axes.\n\n This method passes the ``kwargs`` dictionary to both functions. If you\n need more control, call :meth:`JointGrid.plot_joint` and\n :meth:`JointGrid.plot_marginals` directly with specific parameters.\n\n Parameters\n ----------\n joint_func, marginal_func : callables\n Functions to draw the bivariate and univariate plots. See methods\n referenced above for information about the required characteristics\n of these functions.\n kwargs\n Additional keyword arguments are passed to both functions.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n self.plot_marginals(marginal_func, **kwargs)\n self.plot_joint(joint_func, **kwargs)\n return self"},{"col":4,"comment":"null","endLoc":412,"header":"def test_map(self)","id":2633,"name":"test_map","nodeType":"Function","startLoc":399,"text":"def test_map(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n g.map(plt.plot, \"x\", \"y\", linewidth=3)\n\n lines = g.axes[0, 0].lines\n assert len(lines) == 3\n\n line1, _, _ = lines\n assert line1.get_linewidth() == 3\n x, y = line1.get_data()\n mask = (self.df.a == \"a\") & (self.df.b == \"m\") & (self.df.c == \"t\")\n npt.assert_array_equal(x, self.df.x[mask])\n npt.assert_array_equal(y, self.df.y[mask])"},{"col":4,"comment":"Add a reference line(s) to joint and/or marginal axes.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n joint, marginal : bools\n Whether to add the reference line(s) to the joint/marginal axes.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s).\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n ","endLoc":1935,"header":"def refline(\n self, *, x=None, y=None, joint=True, marginal=True,\n color='.5', linestyle='--', **line_kws\n )","id":2634,"name":"refline","nodeType":"Function","startLoc":1893,"text":"def refline(\n self, *, x=None, y=None, joint=True, marginal=True,\n color='.5', linestyle='--', **line_kws\n ):\n \"\"\"Add a reference line(s) to joint and/or marginal axes.\n\n Parameters\n ----------\n x, y : numeric\n Value(s) to draw the line(s) at.\n joint, marginal : bools\n Whether to add the reference line(s) to the joint/marginal axes.\n color : :mod:`matplotlib color `\n Specifies the color of the reference line(s).\n linestyle : str\n Specifies the style of the reference line(s).\n line_kws : key, value mappings\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline`\n when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y``\n is not None.\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n line_kws['color'] = color\n line_kws['linestyle'] = linestyle\n\n if x is not None:\n if joint:\n self.ax_joint.axvline(x, **line_kws)\n if marginal:\n self.ax_marg_x.axvline(x, **line_kws)\n\n if y is not None:\n if joint:\n self.ax_joint.axhline(y, **line_kws)\n if marginal:\n self.ax_marg_y.axhline(y, **line_kws)\n\n return self"},{"col":4,"comment":"null","endLoc":433,"header":"def test_map_dataframe(self)","id":2635,"name":"test_map_dataframe","nodeType":"Function","startLoc":414,"text":"def test_map_dataframe(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n\n def plot(x, y, data=None, **kws):\n plt.plot(data[x], data[y], **kws)\n # Modify __module__ so this doesn't look like a seaborn function\n plot.__module__ = \"test\"\n\n g.map_dataframe(plot, \"x\", \"y\", linestyle=\"--\")\n\n lines = g.axes[0, 0].lines\n assert len(g.axes[0, 0].lines) == 3\n\n line1, _, _ = lines\n assert line1.get_linestyle() == \"--\"\n x, y = line1.get_data()\n mask = (self.df.a == \"a\") & (self.df.b == \"m\") & (self.df.c == \"t\")\n npt.assert_array_equal(x, self.df.x[mask])\n npt.assert_array_equal(y, self.df.y[mask])"},{"col":4,"comment":"null","endLoc":447,"header":"def test_set(self)","id":2636,"name":"test_set","nodeType":"Function","startLoc":435,"text":"def test_set(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n xlim = (-2, 5)\n ylim = (3, 6)\n xticks = [-2, 0, 3, 5]\n yticks = [3, 4.5, 6]\n g.set(xlim=xlim, ylim=ylim, xticks=xticks, yticks=yticks)\n for ax in g.axes.flat:\n npt.assert_array_equal(ax.get_xlim(), xlim)\n npt.assert_array_equal(ax.get_ylim(), ylim)\n npt.assert_array_equal(ax.get_xticks(), xticks)\n npt.assert_array_equal(ax.get_yticks(), yticks)"},{"col":4,"comment":"null","endLoc":475,"header":"def test_set_titles(self)","id":2637,"name":"test_set_titles","nodeType":"Function","startLoc":449,"text":"def test_set_titles(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"a = a | b = m\"\n assert g.axes[0, 1].get_title() == \"a = a | b = n\"\n assert g.axes[1, 0].get_title() == \"a = b | b = m\"\n\n # Test a provided title\n g.set_titles(\"{row_var} == {row_name} \\\\/ {col_var} == {col_name}\")\n assert g.axes[0, 0].get_title() == \"a == a \\\\/ b == m\"\n assert g.axes[0, 1].get_title() == \"a == a \\\\/ b == n\"\n assert g.axes[1, 0].get_title() == \"a == b \\\\/ b == m\"\n\n # Test a single row\n g = ag.FacetGrid(self.df, col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"b = m\"\n assert g.axes[0, 1].get_title() == \"b = n\"\n\n # test with dropna=False\n g = ag.FacetGrid(self.df, col=\"b\", hue=\"b\", dropna=False)\n g.map(plt.plot, 'x', 'y')"},{"col":4,"comment":"Set axis labels on the bivariate axes.\n\n Parameters\n ----------\n xlabel, ylabel : strings\n Label names for the x and y variables.\n kwargs : key, value mappings\n Other keyword arguments are passed to the following functions:\n\n - :meth:`matplotlib.axes.Axes.set_xlabel`\n - :meth:`matplotlib.axes.Axes.set_ylabel`\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n ","endLoc":1958,"header":"def set_axis_labels(self, xlabel=\"\", ylabel=\"\", **kwargs)","id":2638,"name":"set_axis_labels","nodeType":"Function","startLoc":1937,"text":"def set_axis_labels(self, xlabel=\"\", ylabel=\"\", **kwargs):\n \"\"\"Set axis labels on the bivariate axes.\n\n Parameters\n ----------\n xlabel, ylabel : strings\n Label names for the x and y variables.\n kwargs : key, value mappings\n Other keyword arguments are passed to the following functions:\n\n - :meth:`matplotlib.axes.Axes.set_xlabel`\n - :meth:`matplotlib.axes.Axes.set_ylabel`\n\n Returns\n -------\n :class:`JointGrid` instance\n Returns ``self`` for easy method chaining.\n\n \"\"\"\n self.ax_joint.set_xlabel(xlabel, **kwargs)\n self.ax_joint.set_ylabel(ylabel, **kwargs)\n return self"},{"fileName":"faceted_lineplot.py","filePath":"examples","id":2639,"nodeType":"File","text":"\"\"\"\nLine plots on multiple facets\n=============================\n\n_thumb: .48, .42\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\n\ndots = sns.load_dataset(\"dots\")\n\n# Define the palette as a list to specify exact values\npalette = sns.color_palette(\"rocket_r\")\n\n# Plot the lines on two facets\nsns.relplot(\n data=dots,\n x=\"time\", y=\"firing_rate\",\n hue=\"coherence\", size=\"choice\", col=\"align\",\n kind=\"line\", size_order=[\"T1\", \"T2\"], palette=palette,\n height=5, aspect=.75, facet_kws=dict(sharex=False),\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":2640,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":1750,"id":2641,"name":"_hue_params","nodeType":"Attribute","startLoc":1750,"text":"self._hue_params"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":2642,"name":"dots","nodeType":"Attribute","startLoc":11,"text":"dots"},{"col":4,"comment":"null","endLoc":1146,"header":"def _get_scale(\n self, spec: Plot, var: str, prop: Property, values: Series\n ) -> Scale","id":2643,"name":"_get_scale","nodeType":"Function","startLoc":1133,"text":"def _get_scale(\n self, spec: Plot, var: str, prop: Property, values: Series\n ) -> Scale:\n\n if var in spec._scales:\n arg = spec._scales[var]\n if arg is None or isinstance(arg, Scale):\n scale = arg\n else:\n scale = prop.infer_scale(arg, values)\n else:\n scale = prop.default_scale(values)\n\n return scale"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":2644,"name":"palette","nodeType":"Attribute","startLoc":14,"text":"palette"},{"col":0,"comment":"","endLoc":7,"header":"faceted_lineplot.py#","id":2645,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nLine plots on multiple facets\n=============================\n\n_thumb: .48, .42\n\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\ndots = sns.load_dataset(\"dots\")\n\npalette = sns.color_palette(\"rocket_r\")\n\nsns.relplot(\n data=dots,\n x=\"time\", y=\"firing_rate\",\n hue=\"coherence\", size=\"choice\", col=\"align\",\n kind=\"line\", size_order=[\"T1\", \"T2\"], palette=palette,\n height=5, aspect=.75, facet_kws=dict(sharex=False),\n)"},{"fileName":"test_data.py","filePath":"tests/_core","id":2646,"nodeType":"File","text":"import functools\nimport numpy as np\nimport pandas as pd\n\nimport pytest\nfrom numpy.testing import assert_array_equal\nfrom pandas.testing import assert_series_equal\n\nfrom seaborn._core.data import PlotData\n\n\nassert_vector_equal = functools.partial(assert_series_equal, check_names=False)\n\n\nclass TestPlotData:\n\n @pytest.fixture\n def long_variables(self):\n variables = dict(x=\"x\", y=\"y\", color=\"a\", size=\"z\", style=\"s_cat\")\n return variables\n\n def test_named_vectors(self, long_df, long_variables):\n\n p = PlotData(long_df, long_variables)\n assert p.source_data is long_df\n assert p.source_vars is long_variables\n for key, val in long_variables.items():\n assert p.names[key] == val\n assert_vector_equal(p.frame[key], long_df[val])\n\n def test_named_and_given_vectors(self, long_df, long_variables):\n\n long_variables[\"y\"] = long_df[\"b\"]\n long_variables[\"size\"] = long_df[\"z\"].to_numpy()\n\n p = PlotData(long_df, long_variables)\n\n assert_vector_equal(p.frame[\"color\"], long_df[long_variables[\"color\"]])\n assert_vector_equal(p.frame[\"y\"], long_df[\"b\"])\n assert_vector_equal(p.frame[\"size\"], long_df[\"z\"])\n\n assert p.names[\"color\"] == long_variables[\"color\"]\n assert p.names[\"y\"] == \"b\"\n assert p.names[\"size\"] is None\n\n assert p.ids[\"color\"] == long_variables[\"color\"]\n assert p.ids[\"y\"] == \"b\"\n assert p.ids[\"size\"] == id(long_variables[\"size\"])\n\n def test_index_as_variable(self, long_df, long_variables):\n\n index = pd.Index(np.arange(len(long_df)) * 2 + 10, name=\"i\", dtype=int)\n long_variables[\"x\"] = \"i\"\n p = PlotData(long_df.set_index(index), long_variables)\n\n assert p.names[\"x\"] == p.ids[\"x\"] == \"i\"\n assert_vector_equal(p.frame[\"x\"], pd.Series(index, index))\n\n def test_multiindex_as_variables(self, long_df, long_variables):\n\n index_i = pd.Index(np.arange(len(long_df)) * 2 + 10, name=\"i\", dtype=int)\n index_j = pd.Index(np.arange(len(long_df)) * 3 + 5, name=\"j\", dtype=int)\n index = pd.MultiIndex.from_arrays([index_i, index_j])\n long_variables.update({\"x\": \"i\", \"y\": \"j\"})\n\n p = PlotData(long_df.set_index(index), long_variables)\n assert_vector_equal(p.frame[\"x\"], pd.Series(index_i, index))\n assert_vector_equal(p.frame[\"y\"], pd.Series(index_j, index))\n\n def test_int_as_variable_key(self, rng):\n\n df = pd.DataFrame(rng.uniform(size=(10, 3)))\n\n var = \"x\"\n key = 2\n\n p = PlotData(df, {var: key})\n assert_vector_equal(p.frame[var], df[key])\n assert p.names[var] == p.ids[var] == str(key)\n\n def test_int_as_variable_value(self, long_df):\n\n p = PlotData(long_df, {\"x\": 0, \"y\": \"y\"})\n assert (p.frame[\"x\"] == 0).all()\n assert p.names[\"x\"] is None\n assert p.ids[\"x\"] == id(0)\n\n def test_tuple_as_variable_key(self, rng):\n\n cols = pd.MultiIndex.from_product([(\"a\", \"b\", \"c\"), (\"x\", \"y\")])\n df = pd.DataFrame(rng.uniform(size=(10, 6)), columns=cols)\n\n var = \"color\"\n key = (\"b\", \"y\")\n p = PlotData(df, {var: key})\n assert_vector_equal(p.frame[var], df[key])\n assert p.names[var] == p.ids[var] == str(key)\n\n def test_dict_as_data(self, long_dict, long_variables):\n\n p = PlotData(long_dict, long_variables)\n assert p.source_data is long_dict\n for key, val in long_variables.items():\n assert_vector_equal(p.frame[key], pd.Series(long_dict[val]))\n\n @pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_vectors_various_types(self, long_df, long_variables, vector_type):\n\n variables = {key: long_df[val] for key, val in long_variables.items()}\n if vector_type == \"numpy\":\n variables = {key: val.to_numpy() for key, val in variables.items()}\n elif vector_type == \"list\":\n variables = {key: val.to_list() for key, val in variables.items()}\n\n p = PlotData(None, variables)\n\n assert list(p.names) == list(long_variables)\n if vector_type == \"series\":\n assert p.source_vars is variables\n assert p.names == p.ids == {key: val.name for key, val in variables.items()}\n else:\n assert p.names == {key: None for key in variables}\n assert p.ids == {key: id(val) for key, val in variables.items()}\n\n for key, val in long_variables.items():\n if vector_type == \"series\":\n assert_vector_equal(p.frame[key], long_df[val])\n else:\n assert_array_equal(p.frame[key], long_df[val])\n\n def test_none_as_variable_value(self, long_df):\n\n p = PlotData(long_df, {\"x\": \"z\", \"y\": None})\n assert list(p.frame.columns) == [\"x\"]\n assert p.names == p.ids == {\"x\": \"z\"}\n\n def test_frame_and_vector_mismatched_lengths(self, long_df):\n\n vector = np.arange(len(long_df) * 2)\n with pytest.raises(ValueError):\n PlotData(long_df, {\"x\": \"x\", \"y\": vector})\n\n @pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg):\n\n p = PlotData(arg, {})\n assert p.frame.empty\n assert not p.names\n\n if not isinstance(arg, pd.DataFrame):\n p = PlotData(None, dict(x=arg, y=arg))\n assert p.frame.empty\n assert not p.names\n\n def test_index_alignment_series_to_dataframe(self):\n\n x = [1, 2, 3]\n x_index = pd.Index(x, dtype=int)\n\n y_values = [3, 4, 5]\n y_index = pd.Index(y_values, dtype=int)\n y = pd.Series(y_values, y_index, name=\"y\")\n\n data = pd.DataFrame(dict(x=x), index=x_index)\n\n p = PlotData(data, {\"x\": \"x\", \"y\": y})\n\n x_col_expected = pd.Series([1, 2, 3, np.nan, np.nan], np.arange(1, 6))\n y_col_expected = pd.Series([np.nan, np.nan, 3, 4, 5], np.arange(1, 6))\n assert_vector_equal(p.frame[\"x\"], x_col_expected)\n assert_vector_equal(p.frame[\"y\"], y_col_expected)\n\n def test_index_alignment_between_series(self):\n\n x_index = [1, 2, 3]\n x_values = [10, 20, 30]\n x = pd.Series(x_values, x_index, name=\"x\")\n\n y_index = [3, 4, 5]\n y_values = [300, 400, 500]\n y = pd.Series(y_values, y_index, name=\"y\")\n\n p = PlotData(None, {\"x\": x, \"y\": y})\n\n x_col_expected = pd.Series([10, 20, 30, np.nan, np.nan], np.arange(1, 6))\n y_col_expected = pd.Series([np.nan, np.nan, 300, 400, 500], np.arange(1, 6))\n assert_vector_equal(p.frame[\"x\"], x_col_expected)\n assert_vector_equal(p.frame[\"y\"], y_col_expected)\n\n def test_key_not_in_data_raises(self, long_df):\n\n var = \"x\"\n key = \"what\"\n msg = f\"Could not interpret value `{key}` for `{var}`. An entry with this name\"\n with pytest.raises(ValueError, match=msg):\n PlotData(long_df, {var: key})\n\n def test_key_with_no_data_raises(self):\n\n var = \"x\"\n key = \"what\"\n msg = f\"Could not interpret value `{key}` for `{var}`. Value is a string,\"\n with pytest.raises(ValueError, match=msg):\n PlotData(None, {var: key})\n\n def test_data_vector_different_lengths_raises(self, long_df):\n\n vector = np.arange(len(long_df) - 5)\n msg = \"Length of ndarray vectors must match length of `data`\"\n with pytest.raises(ValueError, match=msg):\n PlotData(long_df, {\"y\": vector})\n\n def test_undefined_variables_raise(self, long_df):\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"not_in_df\"))\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"x\", y=\"not_in_df\"))\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"x\", y=\"y\", color=\"not_in_df\"))\n\n def test_contains_operation(self, long_df):\n\n p = PlotData(long_df, {\"x\": \"y\", \"color\": long_df[\"a\"]})\n assert \"x\" in p\n assert \"y\" not in p\n assert \"color\" in p\n\n def test_join_add_variable(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"f\"}\n v2 = {\"color\": \"a\"}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n for var, key in dict(**v1, **v2).items():\n assert var in p2\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_replace_variable(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"y\": \"s\"}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n variables = v1.copy()\n variables.update(v2)\n\n for var, key in variables.items():\n assert var in p2\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_remove_variable(self, long_df):\n\n variables = {\"x\": \"x\", \"y\": \"f\"}\n drop_var = \"y\"\n\n p1 = PlotData(long_df, variables)\n p2 = p1.join(None, {drop_var: None})\n\n assert drop_var in p1\n assert drop_var not in p2\n assert drop_var not in p2.frame\n assert drop_var not in p2.names\n\n def test_join_all_operations(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\", \"color\": \"a\"}\n v2 = {\"y\": \"s\", \"size\": \"s\", \"color\": None}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n for var, key in v2.items():\n if key is None:\n assert var not in p2\n else:\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_all_operations_same_data(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\", \"color\": \"a\"}\n v2 = {\"y\": \"s\", \"size\": \"s\", \"color\": None}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(long_df, v2)\n\n for var, key in v2.items():\n if key is None:\n assert var not in p2\n else:\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_add_variable_new_data(self, long_df):\n\n d1 = long_df[[\"x\", \"y\"]]\n d2 = long_df[[\"a\", \"s\"]]\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"color\": \"a\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n for var, key in dict(**v1, **v2).items():\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_replace_variable_new_data(self, long_df):\n\n d1 = long_df[[\"x\", \"y\"]]\n d2 = long_df[[\"a\", \"s\"]]\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"x\": \"a\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n variables = v1.copy()\n variables.update(v2)\n\n for var, key in variables.items():\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_add_variable_different_index(self, long_df):\n\n d1 = long_df.iloc[:70]\n d2 = long_df.iloc[30:]\n\n v1 = {\"x\": \"a\"}\n v2 = {\"y\": \"z\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n (var1, key1), = v1.items()\n (var2, key2), = v2.items()\n\n assert_vector_equal(p2.frame.loc[d1.index, var1], d1[key1])\n assert_vector_equal(p2.frame.loc[d2.index, var2], d2[key2])\n\n assert p2.frame.loc[d2.index.difference(d1.index), var1].isna().all()\n assert p2.frame.loc[d1.index.difference(d2.index), var2].isna().all()\n\n def test_join_replace_variable_different_index(self, long_df):\n\n d1 = long_df.iloc[:70]\n d2 = long_df.iloc[30:]\n\n var = \"x\"\n k1, k2 = \"a\", \"z\"\n v1 = {var: k1}\n v2 = {var: k2}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n (var1, key1), = v1.items()\n (var2, key2), = v2.items()\n\n assert_vector_equal(p2.frame.loc[d2.index, var], d2[k2])\n assert p2.frame.loc[d1.index.difference(d2.index), var].isna().all()\n\n def test_join_subset_data_inherit_variables(self, long_df):\n\n sub_df = long_df[long_df[\"a\"] == \"b\"]\n\n var = \"y\"\n p1 = PlotData(long_df, {var: var})\n p2 = p1.join(sub_df, None)\n\n assert_vector_equal(p2.frame.loc[sub_df.index, var], sub_df[var])\n assert p2.frame.loc[long_df.index.difference(sub_df.index), var].isna().all()\n\n def test_join_multiple_inherits_from_orig(self, rng):\n\n d1 = pd.DataFrame(dict(a=rng.normal(0, 1, 100), b=rng.normal(0, 1, 100)))\n d2 = pd.DataFrame(dict(a=rng.normal(0, 1, 100)))\n\n p = PlotData(d1, {\"x\": \"a\"}).join(d2, {\"y\": \"a\"}).join(None, {\"y\": \"a\"})\n assert_vector_equal(p.frame[\"x\"], d1[\"a\"])\n assert_vector_equal(p.frame[\"y\"], d1[\"a\"])\n"},{"className":"TestPlotData","col":0,"comment":"null","endLoc":398,"id":2647,"nodeType":"Class","startLoc":15,"text":"class TestPlotData:\n\n @pytest.fixture\n def long_variables(self):\n variables = dict(x=\"x\", y=\"y\", color=\"a\", size=\"z\", style=\"s_cat\")\n return variables\n\n def test_named_vectors(self, long_df, long_variables):\n\n p = PlotData(long_df, long_variables)\n assert p.source_data is long_df\n assert p.source_vars is long_variables\n for key, val in long_variables.items():\n assert p.names[key] == val\n assert_vector_equal(p.frame[key], long_df[val])\n\n def test_named_and_given_vectors(self, long_df, long_variables):\n\n long_variables[\"y\"] = long_df[\"b\"]\n long_variables[\"size\"] = long_df[\"z\"].to_numpy()\n\n p = PlotData(long_df, long_variables)\n\n assert_vector_equal(p.frame[\"color\"], long_df[long_variables[\"color\"]])\n assert_vector_equal(p.frame[\"y\"], long_df[\"b\"])\n assert_vector_equal(p.frame[\"size\"], long_df[\"z\"])\n\n assert p.names[\"color\"] == long_variables[\"color\"]\n assert p.names[\"y\"] == \"b\"\n assert p.names[\"size\"] is None\n\n assert p.ids[\"color\"] == long_variables[\"color\"]\n assert p.ids[\"y\"] == \"b\"\n assert p.ids[\"size\"] == id(long_variables[\"size\"])\n\n def test_index_as_variable(self, long_df, long_variables):\n\n index = pd.Index(np.arange(len(long_df)) * 2 + 10, name=\"i\", dtype=int)\n long_variables[\"x\"] = \"i\"\n p = PlotData(long_df.set_index(index), long_variables)\n\n assert p.names[\"x\"] == p.ids[\"x\"] == \"i\"\n assert_vector_equal(p.frame[\"x\"], pd.Series(index, index))\n\n def test_multiindex_as_variables(self, long_df, long_variables):\n\n index_i = pd.Index(np.arange(len(long_df)) * 2 + 10, name=\"i\", dtype=int)\n index_j = pd.Index(np.arange(len(long_df)) * 3 + 5, name=\"j\", dtype=int)\n index = pd.MultiIndex.from_arrays([index_i, index_j])\n long_variables.update({\"x\": \"i\", \"y\": \"j\"})\n\n p = PlotData(long_df.set_index(index), long_variables)\n assert_vector_equal(p.frame[\"x\"], pd.Series(index_i, index))\n assert_vector_equal(p.frame[\"y\"], pd.Series(index_j, index))\n\n def test_int_as_variable_key(self, rng):\n\n df = pd.DataFrame(rng.uniform(size=(10, 3)))\n\n var = \"x\"\n key = 2\n\n p = PlotData(df, {var: key})\n assert_vector_equal(p.frame[var], df[key])\n assert p.names[var] == p.ids[var] == str(key)\n\n def test_int_as_variable_value(self, long_df):\n\n p = PlotData(long_df, {\"x\": 0, \"y\": \"y\"})\n assert (p.frame[\"x\"] == 0).all()\n assert p.names[\"x\"] is None\n assert p.ids[\"x\"] == id(0)\n\n def test_tuple_as_variable_key(self, rng):\n\n cols = pd.MultiIndex.from_product([(\"a\", \"b\", \"c\"), (\"x\", \"y\")])\n df = pd.DataFrame(rng.uniform(size=(10, 6)), columns=cols)\n\n var = \"color\"\n key = (\"b\", \"y\")\n p = PlotData(df, {var: key})\n assert_vector_equal(p.frame[var], df[key])\n assert p.names[var] == p.ids[var] == str(key)\n\n def test_dict_as_data(self, long_dict, long_variables):\n\n p = PlotData(long_dict, long_variables)\n assert p.source_data is long_dict\n for key, val in long_variables.items():\n assert_vector_equal(p.frame[key], pd.Series(long_dict[val]))\n\n @pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_vectors_various_types(self, long_df, long_variables, vector_type):\n\n variables = {key: long_df[val] for key, val in long_variables.items()}\n if vector_type == \"numpy\":\n variables = {key: val.to_numpy() for key, val in variables.items()}\n elif vector_type == \"list\":\n variables = {key: val.to_list() for key, val in variables.items()}\n\n p = PlotData(None, variables)\n\n assert list(p.names) == list(long_variables)\n if vector_type == \"series\":\n assert p.source_vars is variables\n assert p.names == p.ids == {key: val.name for key, val in variables.items()}\n else:\n assert p.names == {key: None for key in variables}\n assert p.ids == {key: id(val) for key, val in variables.items()}\n\n for key, val in long_variables.items():\n if vector_type == \"series\":\n assert_vector_equal(p.frame[key], long_df[val])\n else:\n assert_array_equal(p.frame[key], long_df[val])\n\n def test_none_as_variable_value(self, long_df):\n\n p = PlotData(long_df, {\"x\": \"z\", \"y\": None})\n assert list(p.frame.columns) == [\"x\"]\n assert p.names == p.ids == {\"x\": \"z\"}\n\n def test_frame_and_vector_mismatched_lengths(self, long_df):\n\n vector = np.arange(len(long_df) * 2)\n with pytest.raises(ValueError):\n PlotData(long_df, {\"x\": \"x\", \"y\": vector})\n\n @pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg):\n\n p = PlotData(arg, {})\n assert p.frame.empty\n assert not p.names\n\n if not isinstance(arg, pd.DataFrame):\n p = PlotData(None, dict(x=arg, y=arg))\n assert p.frame.empty\n assert not p.names\n\n def test_index_alignment_series_to_dataframe(self):\n\n x = [1, 2, 3]\n x_index = pd.Index(x, dtype=int)\n\n y_values = [3, 4, 5]\n y_index = pd.Index(y_values, dtype=int)\n y = pd.Series(y_values, y_index, name=\"y\")\n\n data = pd.DataFrame(dict(x=x), index=x_index)\n\n p = PlotData(data, {\"x\": \"x\", \"y\": y})\n\n x_col_expected = pd.Series([1, 2, 3, np.nan, np.nan], np.arange(1, 6))\n y_col_expected = pd.Series([np.nan, np.nan, 3, 4, 5], np.arange(1, 6))\n assert_vector_equal(p.frame[\"x\"], x_col_expected)\n assert_vector_equal(p.frame[\"y\"], y_col_expected)\n\n def test_index_alignment_between_series(self):\n\n x_index = [1, 2, 3]\n x_values = [10, 20, 30]\n x = pd.Series(x_values, x_index, name=\"x\")\n\n y_index = [3, 4, 5]\n y_values = [300, 400, 500]\n y = pd.Series(y_values, y_index, name=\"y\")\n\n p = PlotData(None, {\"x\": x, \"y\": y})\n\n x_col_expected = pd.Series([10, 20, 30, np.nan, np.nan], np.arange(1, 6))\n y_col_expected = pd.Series([np.nan, np.nan, 300, 400, 500], np.arange(1, 6))\n assert_vector_equal(p.frame[\"x\"], x_col_expected)\n assert_vector_equal(p.frame[\"y\"], y_col_expected)\n\n def test_key_not_in_data_raises(self, long_df):\n\n var = \"x\"\n key = \"what\"\n msg = f\"Could not interpret value `{key}` for `{var}`. An entry with this name\"\n with pytest.raises(ValueError, match=msg):\n PlotData(long_df, {var: key})\n\n def test_key_with_no_data_raises(self):\n\n var = \"x\"\n key = \"what\"\n msg = f\"Could not interpret value `{key}` for `{var}`. Value is a string,\"\n with pytest.raises(ValueError, match=msg):\n PlotData(None, {var: key})\n\n def test_data_vector_different_lengths_raises(self, long_df):\n\n vector = np.arange(len(long_df) - 5)\n msg = \"Length of ndarray vectors must match length of `data`\"\n with pytest.raises(ValueError, match=msg):\n PlotData(long_df, {\"y\": vector})\n\n def test_undefined_variables_raise(self, long_df):\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"not_in_df\"))\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"x\", y=\"not_in_df\"))\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"x\", y=\"y\", color=\"not_in_df\"))\n\n def test_contains_operation(self, long_df):\n\n p = PlotData(long_df, {\"x\": \"y\", \"color\": long_df[\"a\"]})\n assert \"x\" in p\n assert \"y\" not in p\n assert \"color\" in p\n\n def test_join_add_variable(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"f\"}\n v2 = {\"color\": \"a\"}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n for var, key in dict(**v1, **v2).items():\n assert var in p2\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_replace_variable(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"y\": \"s\"}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n variables = v1.copy()\n variables.update(v2)\n\n for var, key in variables.items():\n assert var in p2\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_remove_variable(self, long_df):\n\n variables = {\"x\": \"x\", \"y\": \"f\"}\n drop_var = \"y\"\n\n p1 = PlotData(long_df, variables)\n p2 = p1.join(None, {drop_var: None})\n\n assert drop_var in p1\n assert drop_var not in p2\n assert drop_var not in p2.frame\n assert drop_var not in p2.names\n\n def test_join_all_operations(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\", \"color\": \"a\"}\n v2 = {\"y\": \"s\", \"size\": \"s\", \"color\": None}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n for var, key in v2.items():\n if key is None:\n assert var not in p2\n else:\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_all_operations_same_data(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\", \"color\": \"a\"}\n v2 = {\"y\": \"s\", \"size\": \"s\", \"color\": None}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(long_df, v2)\n\n for var, key in v2.items():\n if key is None:\n assert var not in p2\n else:\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_add_variable_new_data(self, long_df):\n\n d1 = long_df[[\"x\", \"y\"]]\n d2 = long_df[[\"a\", \"s\"]]\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"color\": \"a\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n for var, key in dict(**v1, **v2).items():\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_replace_variable_new_data(self, long_df):\n\n d1 = long_df[[\"x\", \"y\"]]\n d2 = long_df[[\"a\", \"s\"]]\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"x\": \"a\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n variables = v1.copy()\n variables.update(v2)\n\n for var, key in variables.items():\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])\n\n def test_join_add_variable_different_index(self, long_df):\n\n d1 = long_df.iloc[:70]\n d2 = long_df.iloc[30:]\n\n v1 = {\"x\": \"a\"}\n v2 = {\"y\": \"z\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n (var1, key1), = v1.items()\n (var2, key2), = v2.items()\n\n assert_vector_equal(p2.frame.loc[d1.index, var1], d1[key1])\n assert_vector_equal(p2.frame.loc[d2.index, var2], d2[key2])\n\n assert p2.frame.loc[d2.index.difference(d1.index), var1].isna().all()\n assert p2.frame.loc[d1.index.difference(d2.index), var2].isna().all()\n\n def test_join_replace_variable_different_index(self, long_df):\n\n d1 = long_df.iloc[:70]\n d2 = long_df.iloc[30:]\n\n var = \"x\"\n k1, k2 = \"a\", \"z\"\n v1 = {var: k1}\n v2 = {var: k2}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n (var1, key1), = v1.items()\n (var2, key2), = v2.items()\n\n assert_vector_equal(p2.frame.loc[d2.index, var], d2[k2])\n assert p2.frame.loc[d1.index.difference(d2.index), var].isna().all()\n\n def test_join_subset_data_inherit_variables(self, long_df):\n\n sub_df = long_df[long_df[\"a\"] == \"b\"]\n\n var = \"y\"\n p1 = PlotData(long_df, {var: var})\n p2 = p1.join(sub_df, None)\n\n assert_vector_equal(p2.frame.loc[sub_df.index, var], sub_df[var])\n assert p2.frame.loc[long_df.index.difference(sub_df.index), var].isna().all()\n\n def test_join_multiple_inherits_from_orig(self, rng):\n\n d1 = pd.DataFrame(dict(a=rng.normal(0, 1, 100), b=rng.normal(0, 1, 100)))\n d2 = pd.DataFrame(dict(a=rng.normal(0, 1, 100)))\n\n p = PlotData(d1, {\"x\": \"a\"}).join(d2, {\"y\": \"a\"}).join(None, {\"y\": \"a\"})\n assert_vector_equal(p.frame[\"x\"], d1[\"a\"])\n assert_vector_equal(p.frame[\"y\"], d1[\"a\"])"},{"col":4,"comment":"null","endLoc":20,"header":"@pytest.fixture\n def long_variables(self)","id":2648,"name":"long_variables","nodeType":"Function","startLoc":17,"text":"@pytest.fixture\n def long_variables(self):\n variables = dict(x=\"x\", y=\"y\", color=\"a\", size=\"z\", style=\"s_cat\")\n return variables"},{"col":4,"comment":"null","endLoc":29,"header":"def test_named_vectors(self, long_df, long_variables)","id":2649,"name":"test_named_vectors","nodeType":"Function","startLoc":22,"text":"def test_named_vectors(self, long_df, long_variables):\n\n p = PlotData(long_df, long_variables)\n assert p.source_data is long_df\n assert p.source_vars is long_variables\n for key, val in long_variables.items():\n assert p.names[key] == val\n assert_vector_equal(p.frame[key], long_df[val])"},{"col":4,"comment":"null","endLoc":1168,"header":"def _get_subplot_data(self, df, var, view, share_state)","id":2650,"name":"_get_subplot_data","nodeType":"Function","startLoc":1148,"text":"def _get_subplot_data(self, df, var, view, share_state):\n\n if share_state in [True, \"all\"]:\n # The all-shared case is easiest, every subplot sees all the data\n seed_values = df[var]\n else:\n # Otherwise, we need to setup separate scales for different subplots\n if share_state in [False, \"none\"]:\n # Fully independent axes are also easy: use each subplot's data\n idx = self._get_subplot_index(df, view)\n elif share_state in df:\n # Sharing within row/col is more complicated\n use_rows = df[share_state] == view[share_state]\n idx = df.index[use_rows]\n else:\n # This configuration doesn't make much sense, but it's fine\n idx = df.index\n\n seed_values = df.loc[idx, var]\n\n return seed_values"},{"col":4,"comment":"null","endLoc":1591,"header":"def test_element_default(self, long_df)","id":2651,"name":"test_element_default","nodeType":"Function","startLoc":1581,"text":"def test_element_default(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(long_df, x=\"x\", ax=ax1)\n histplot(long_df, x=\"x\", ax=ax2, element=\"bars\")\n assert len(ax1.patches) == len(ax2.patches)\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(long_df, x=\"x\", hue=\"a\", ax=ax1)\n histplot(long_df, x=\"x\", hue=\"a\", ax=ax2, element=\"bars\")\n assert len(ax1.patches) == len(ax2.patches)"},{"col":4,"comment":"null","endLoc":499,"header":"def test_set_titles_margin_titles(self)","id":2652,"name":"test_set_titles_margin_titles","nodeType":"Function","startLoc":477,"text":"def test_set_titles_margin_titles(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", margin_titles=True)\n g.map(plt.plot, \"x\", \"y\")\n\n # Test the default titles\n assert g.axes[0, 0].get_title() == \"b = m\"\n assert g.axes[0, 1].get_title() == \"b = n\"\n assert g.axes[1, 0].get_title() == \"\"\n\n # Test the row \"titles\"\n assert g.axes[0, 1].texts[0].get_text() == \"a = a\"\n assert g.axes[1, 1].texts[0].get_text() == \"a = b\"\n assert g.axes[0, 1].texts[0] is g._margin_titles_texts[0]\n\n # Test provided titles\n g.set_titles(col_template=\"{col_name}\", row_template=\"{row_name}\")\n assert g.axes[0, 0].get_title() == \"m\"\n assert g.axes[0, 1].get_title() == \"n\"\n assert g.axes[1, 0].get_title() == \"\"\n\n assert len(g.axes[1, 1].texts) == 1\n assert g.axes[1, 1].texts[0].get_text() == \"b\""},{"col":4,"comment":"null","endLoc":1599,"header":"def test_bars_no_fill(self, flat_series)","id":2653,"name":"test_bars_no_fill","nodeType":"Function","startLoc":1593,"text":"def test_bars_no_fill(self, flat_series):\n\n alpha = .5\n ax = histplot(flat_series, element=\"bars\", fill=False, alpha=alpha)\n for bar in ax.patches:\n assert bar.get_facecolor() == (0, 0, 0, 0)\n assert bar.get_edgecolor()[-1] == alpha"},{"col":4,"comment":"null","endLoc":1620,"header":"def test_step_fill(self, flat_series)","id":2654,"name":"test_step_fill","nodeType":"Function","startLoc":1601,"text":"def test_step_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=True, bins=n, ax=ax1)\n histplot(flat_series, element=\"step\", fill=True, bins=n, ax=ax2)\n\n bar_heights = [b.get_height() for b in ax1.patches]\n bar_widths = [b.get_width() for b in ax1.patches]\n bar_edges = [b.get_x() for b in ax1.patches]\n\n fill = ax2.collections[0]\n x, y = fill.get_paths()[0].vertices[::-1].T\n\n assert_array_equal(x[1:2 * n:2], bar_edges)\n assert_array_equal(y[1:2 * n:2], bar_heights)\n\n assert x[n * 2] == bar_edges[-1] + bar_widths[-1]\n assert y[n * 2] == bar_heights[-1]"},{"col":4,"comment":"null","endLoc":1443,"header":"def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index","id":2655,"name":"_get_subplot_index","nodeType":"Function","startLoc":1434,"text":"def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index:\n\n dims = df.columns.intersection([\"col\", \"row\"])\n if dims.empty:\n return df.index\n\n keep_rows = pd.Series(True, df.index, dtype=bool)\n for dim in dims:\n keep_rows &= df[dim] == subplot[dim]\n return df.index[keep_rows]"},{"col":4,"comment":"null","endLoc":1288,"header":"def _setup_scales(\n self, p: Plot,\n common: PlotData,\n layers: list[Layer],\n variables: list[str] | None = None,\n ) -> None","id":2656,"name":"_setup_scales","nodeType":"Function","startLoc":1170,"text":"def _setup_scales(\n self, p: Plot,\n common: PlotData,\n layers: list[Layer],\n variables: list[str] | None = None,\n ) -> None:\n\n if variables is None:\n # Add variables that have data but not a scale, which happens\n # because this method can be called multiple time, to handle\n # variables added during the Stat transform.\n variables = []\n for layer in layers:\n variables.extend(layer[\"data\"].frame.columns)\n for df in layer[\"data\"].frames.values():\n variables.extend(str(v) for v in df if v not in variables)\n variables = [v for v in variables if v not in self._scales]\n\n for var in variables:\n\n # Determine whether this is a coordinate variable\n # (i.e., x/y, paired x/y, or derivative such as xmax)\n m = re.match(r\"^(?P(?Px|y)\\d*).*\", var)\n if m is None:\n coord = axis = None\n else:\n coord = m[\"coord\"]\n axis = m[\"axis\"]\n\n # Get keys that handle things like x0, xmax, properly where relevant\n prop_key = var if axis is None else axis\n scale_key = var if coord is None else coord\n\n if prop_key not in PROPERTIES:\n continue\n\n # Concatenate layers, using only the relevant coordinate and faceting vars,\n # This is unnecessarily wasteful, as layer data will often be redundant.\n # But figuring out the minimal amount we need is more complicated.\n cols = [var, \"col\", \"row\"]\n parts = [common.frame.filter(cols)]\n for layer in layers:\n parts.append(layer[\"data\"].frame.filter(cols))\n for df in layer[\"data\"].frames.values():\n parts.append(df.filter(cols))\n var_df = pd.concat(parts, ignore_index=True)\n\n prop = PROPERTIES[prop_key]\n scale = self._get_scale(p, scale_key, prop, var_df[var])\n\n if scale_key not in p._variables:\n # TODO this implies that the variable was added by the stat\n # It allows downstream orientation inference to work properly.\n # But it feels rather hacky, so ideally revisit.\n scale._priority = 0 # type: ignore\n\n if axis is None:\n # We could think about having a broader concept of (un)shared properties\n # In general, not something you want to do (different scales in facets)\n # But could make sense e.g. with paired plots. Build later.\n share_state = None\n subplots = []\n else:\n share_state = self._subplots.subplot_spec[f\"share{axis}\"]\n subplots = [view for view in self._subplots if view[axis] == coord]\n\n # Shared categorical axes are broken on matplotlib<3.4.0.\n # https://github.com/matplotlib/matplotlib/pull/18308\n # This only affects us when sharing *paired* axes. This is a novel/niche\n # behavior, so we will raise rather than hack together a workaround.\n if axis is not None and Version(mpl.__version__) < Version(\"3.4.0\"):\n from seaborn._core.scales import Nominal\n paired_axis = axis in p._pair_spec.get(\"structure\", {})\n cat_scale = isinstance(scale, Nominal)\n ok_dim = {\"x\": \"col\", \"y\": \"row\"}[axis]\n shared_axes = share_state not in [False, \"none\", ok_dim]\n if paired_axis and cat_scale and shared_axes:\n err = \"Sharing paired categorical axes requires matplotlib>=3.4.0\"\n raise RuntimeError(err)\n\n if scale is None:\n self._scales[var] = Scale._identity()\n else:\n self._scales[var] = scale._setup(var_df[var], prop)\n\n # Everything below here applies only to coordinate variables\n # We additionally skip it when we're working with a value\n # that is derived from a coordinate we've already processed.\n # e.g., the Stat consumed y and added ymin/ymax. In that case,\n # we've already setup the y scale and ymin/max are in scale space.\n if axis is None or (var != coord and coord in p._variables):\n continue\n\n # Set up an empty series to receive the transformed values.\n # We need this to handle piecemeal transforms of categories -> floats.\n transformed_data = []\n for layer in layers:\n index = layer[\"data\"].frame.index\n empty_series = pd.Series(dtype=float, index=index, name=var)\n transformed_data.append(empty_series)\n\n for view in subplots:\n\n axis_obj = getattr(view[\"ax\"], f\"{axis}axis\")\n seed_values = self._get_subplot_data(var_df, var, view, share_state)\n view_scale = scale._setup(seed_values, prop, axis=axis_obj)\n set_scale_obj(view[\"ax\"], axis, view_scale._matplotlib_scale)\n\n for layer, new_series in zip(layers, transformed_data):\n layer_df = layer[\"data\"].frame\n if var in layer_df:\n idx = self._get_subplot_index(layer_df, view)\n new_series.loc[idx] = view_scale(layer_df.loc[idx, var])\n\n # Now the transformed data series are complete, set update the layer data\n for layer, new_series in zip(layers, transformed_data):\n layer_df = layer[\"data\"].frame\n if var in layer_df:\n layer_df[var] = new_series"},{"col":4,"comment":"null","endLoc":533,"header":"def test_set_ticklabels(self)","id":2657,"name":"test_set_ticklabels","nodeType":"Function","startLoc":501,"text":"def test_set_ticklabels(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n\n ax = g.axes[-1, 0]\n xlab = [l.get_text() + \"h\" for l in ax.get_xticklabels()]\n ylab = [l.get_text() + \"i\" for l in ax.get_yticklabels()]\n\n g.set_xticklabels(xlab)\n g.set_yticklabels(ylab)\n got_x = [l.get_text() for l in g.axes[-1, 1].get_xticklabels()]\n got_y = [l.get_text() for l in g.axes[0, 0].get_yticklabels()]\n npt.assert_array_equal(got_x, xlab)\n npt.assert_array_equal(got_y, ylab)\n\n x, y = np.arange(10), np.arange(10)\n df = pd.DataFrame(np.c_[x, y], columns=[\"x\", \"y\"])\n g = ag.FacetGrid(df).map_dataframe(pointplot, x=\"x\", y=\"y\", order=x)\n g.set_xticklabels(step=2)\n got_x = [int(l.get_text()) for l in g.axes[0, 0].get_xticklabels()]\n npt.assert_array_equal(x[::2], got_x)\n\n g = ag.FacetGrid(self.df, col=\"d\", col_wrap=5)\n g.map(plt.plot, \"x\", \"y\")\n g.set_xticklabels(rotation=45)\n g.set_yticklabels(rotation=75)\n for ax in g._bottom_axes:\n for l in ax.get_xticklabels():\n assert l.get_rotation() == 45\n for ax in g._left_axes:\n for l in ax.get_yticklabels():\n assert l.get_rotation() == 75"},{"col":4,"comment":"null","endLoc":1638,"header":"def test_poly_fill(self, flat_series)","id":2658,"name":"test_poly_fill","nodeType":"Function","startLoc":1622,"text":"def test_poly_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=True, bins=n, ax=ax1)\n histplot(flat_series, element=\"poly\", fill=True, bins=n, ax=ax2)\n\n bar_heights = np.array([b.get_height() for b in ax1.patches])\n bar_widths = np.array([b.get_width() for b in ax1.patches])\n bar_edges = np.array([b.get_x() for b in ax1.patches])\n\n fill = ax2.collections[0]\n x, y = fill.get_paths()[0].vertices[::-1].T\n\n assert_array_equal(x[1:n + 1], bar_edges + bar_widths / 2)\n assert_array_equal(y[1:n + 1], bar_heights)"},{"col":4,"comment":"null","endLoc":1655,"header":"def test_poly_no_fill(self, flat_series)","id":2659,"name":"test_poly_no_fill","nodeType":"Function","startLoc":1640,"text":"def test_poly_no_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n n = 10\n histplot(flat_series, element=\"bars\", fill=False, bins=n, ax=ax1)\n histplot(flat_series, element=\"poly\", fill=False, bins=n, ax=ax2)\n\n bar_heights = np.array([b.get_height() for b in ax1.patches])\n bar_widths = np.array([b.get_width() for b in ax1.patches])\n bar_edges = np.array([b.get_x() for b in ax1.patches])\n\n x, y = ax2.lines[0].get_xydata().T\n\n assert_array_equal(x, bar_edges + bar_widths / 2)\n assert_array_equal(y, bar_heights)"},{"col":4,"comment":"null","endLoc":1673,"header":"def test_step_no_fill(self, flat_series)","id":2660,"name":"test_step_no_fill","nodeType":"Function","startLoc":1657,"text":"def test_step_no_fill(self, flat_series):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n histplot(flat_series, element=\"bars\", fill=False, ax=ax1)\n histplot(flat_series, element=\"step\", fill=False, ax=ax2)\n\n bar_heights = [b.get_height() for b in ax1.patches]\n bar_widths = [b.get_width() for b in ax1.patches]\n bar_edges = [b.get_x() for b in ax1.patches]\n\n x, y = ax2.lines[0].get_xydata().T\n\n assert_array_equal(x[:-1], bar_edges)\n assert_array_equal(y[:-1], bar_heights)\n assert x[-1] == bar_edges[-1] + bar_widths[-1]\n assert y[-1] == y[-2]"},{"col":4,"comment":"Stop points from extending beyond their territory.","endLoc":3542,"header":"def add_gutters(self, points, center, log_scale=False)","id":2661,"name":"add_gutters","nodeType":"Function","startLoc":3516,"text":"def add_gutters(self, points, center, log_scale=False):\n \"\"\"Stop points from extending beyond their territory.\"\"\"\n half_width = self.width / 2\n if log_scale:\n low_gutter = 10 ** (np.log10(center) - half_width)\n else:\n low_gutter = center - half_width\n off_low = points < low_gutter\n if off_low.any():\n points[off_low] = low_gutter\n if log_scale:\n high_gutter = 10 ** (np.log10(center) + half_width)\n else:\n high_gutter = center + half_width\n off_high = points > high_gutter\n if off_high.any():\n points[off_high] = high_gutter\n\n gutter_prop = (off_high + off_low).sum() / len(points)\n if gutter_prop > self.warn_thresh:\n msg = (\n \"{:.1%} of the points cannot be placed; you may want \"\n \"to decrease the size of the markers or use stripplot.\"\n ).format(gutter_prop)\n warnings.warn(msg, UserWarning)\n\n return points"},{"col":4,"comment":"null","endLoc":1685,"header":"def test_step_fill_xy(self, flat_series)","id":2662,"name":"test_step_fill_xy","nodeType":"Function","startLoc":1675,"text":"def test_step_fill_xy(self, flat_series):\n\n f, ax = plt.subplots()\n\n histplot(x=flat_series, element=\"step\", fill=True)\n histplot(y=flat_series, element=\"step\", fill=True)\n\n xverts = ax.collections[0].get_paths()[0].vertices\n yverts = ax.collections[1].get_paths()[0].vertices\n\n assert_array_equal(xverts, yverts[:, ::-1])"},{"col":4,"comment":"null","endLoc":1697,"header":"def test_step_no_fill_xy(self, flat_series)","id":2663,"name":"test_step_no_fill_xy","nodeType":"Function","startLoc":1687,"text":"def test_step_no_fill_xy(self, flat_series):\n\n f, ax = plt.subplots()\n\n histplot(x=flat_series, element=\"step\", fill=False)\n histplot(y=flat_series, element=\"step\", fill=False)\n\n xline, yline = ax.lines\n\n assert_array_equal(xline.get_xdata(), yline.get_ydata())\n assert_array_equal(xline.get_ydata(), yline.get_xdata())"},{"col":4,"comment":"null","endLoc":48,"header":"def test_named_and_given_vectors(self, long_df, long_variables)","id":2664,"name":"test_named_and_given_vectors","nodeType":"Function","startLoc":31,"text":"def test_named_and_given_vectors(self, long_df, long_variables):\n\n long_variables[\"y\"] = long_df[\"b\"]\n long_variables[\"size\"] = long_df[\"z\"].to_numpy()\n\n p = PlotData(long_df, long_variables)\n\n assert_vector_equal(p.frame[\"color\"], long_df[long_variables[\"color\"]])\n assert_vector_equal(p.frame[\"y\"], long_df[\"b\"])\n assert_vector_equal(p.frame[\"size\"], long_df[\"z\"])\n\n assert p.names[\"color\"] == long_variables[\"color\"]\n assert p.names[\"y\"] == \"b\"\n assert p.names[\"size\"] is None\n\n assert p.ids[\"color\"] == long_variables[\"color\"]\n assert p.ids[\"y\"] == \"b\"\n assert p.ids[\"size\"] == id(long_variables[\"size\"])"},{"col":4,"comment":"null","endLoc":57,"header":"def test_index_as_variable(self, long_df, long_variables)","id":2665,"name":"test_index_as_variable","nodeType":"Function","startLoc":50,"text":"def test_index_as_variable(self, long_df, long_variables):\n\n index = pd.Index(np.arange(len(long_df)) * 2 + 10, name=\"i\", dtype=int)\n long_variables[\"x\"] = \"i\"\n p = PlotData(long_df.set_index(index), long_variables)\n\n assert p.names[\"x\"] == p.ids[\"x\"] == \"i\"\n assert_vector_equal(p.frame[\"x\"], pd.Series(index, index))"},{"col":4,"comment":"null","endLoc":68,"header":"def test_multiindex_as_variables(self, long_df, long_variables)","id":2666,"name":"test_multiindex_as_variables","nodeType":"Function","startLoc":59,"text":"def test_multiindex_as_variables(self, long_df, long_variables):\n\n index_i = pd.Index(np.arange(len(long_df)) * 2 + 10, name=\"i\", dtype=int)\n index_j = pd.Index(np.arange(len(long_df)) * 3 + 5, name=\"j\", dtype=int)\n index = pd.MultiIndex.from_arrays([index_i, index_j])\n long_variables.update({\"x\": \"i\", \"y\": \"j\"})\n\n p = PlotData(long_df.set_index(index), long_variables)\n assert_vector_equal(p.frame[\"x\"], pd.Series(index_i, index))\n assert_vector_equal(p.frame[\"y\"], pd.Series(index_j, index))"},{"col":4,"comment":"null","endLoc":79,"header":"def test_int_as_variable_key(self, rng)","id":2667,"name":"test_int_as_variable_key","nodeType":"Function","startLoc":70,"text":"def test_int_as_variable_key(self, rng):\n\n df = pd.DataFrame(rng.uniform(size=(10, 3)))\n\n var = \"x\"\n key = 2\n\n p = PlotData(df, {var: key})\n assert_vector_equal(p.frame[var], df[key])\n assert p.names[var] == p.ids[var] == str(key)"},{"col":4,"comment":"null","endLoc":1704,"header":"def test_weighted_histogram(self)","id":2668,"name":"test_weighted_histogram","nodeType":"Function","startLoc":1699,"text":"def test_weighted_histogram(self):\n\n ax = histplot(x=[0, 1, 2], weights=[1, 2, 3], discrete=True)\n\n bar_heights = [b.get_height() for b in ax.patches]\n assert bar_heights == [1, 2, 3]"},{"col":4,"comment":"null","endLoc":1710,"header":"def test_weights_with_auto_bins(self, long_df)","id":2669,"name":"test_weights_with_auto_bins","nodeType":"Function","startLoc":1706,"text":"def test_weights_with_auto_bins(self, long_df):\n\n with pytest.warns(UserWarning):\n ax = histplot(long_df, x=\"x\", weights=\"f\")\n assert len(ax.patches) == 10"},{"col":4,"comment":"null","endLoc":1728,"header":"def test_shrink(self, long_df)","id":2670,"name":"test_shrink","nodeType":"Function","startLoc":1712,"text":"def test_shrink(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(2)\n\n bw = 2\n shrink = .4\n\n histplot(long_df, x=\"x\", binwidth=bw, ax=ax1)\n histplot(long_df, x=\"x\", binwidth=bw, shrink=shrink, ax=ax2)\n\n for p1, p2 in zip(ax1.patches, ax2.patches):\n\n w1, w2 = p1.get_width(), p2.get_width()\n assert w2 == pytest.approx(shrink * w1)\n\n x1, x2 = p1.get_x(), p2.get_x()\n assert (x2 + w2 / 2) == pytest.approx(x1 + w1 / 2)"},{"col":4,"comment":"null","endLoc":86,"header":"def test_int_as_variable_value(self, long_df)","id":2671,"name":"test_int_as_variable_value","nodeType":"Function","startLoc":81,"text":"def test_int_as_variable_value(self, long_df):\n\n p = PlotData(long_df, {\"x\": 0, \"y\": \"y\"})\n assert (p.frame[\"x\"] == 0).all()\n assert p.names[\"x\"] is None\n assert p.ids[\"x\"] == id(0)"},{"col":4,"comment":"null","endLoc":97,"header":"def test_tuple_as_variable_key(self, rng)","id":2672,"name":"test_tuple_as_variable_key","nodeType":"Function","startLoc":88,"text":"def test_tuple_as_variable_key(self, rng):\n\n cols = pd.MultiIndex.from_product([(\"a\", \"b\", \"c\"), (\"x\", \"y\")])\n df = pd.DataFrame(rng.uniform(size=(10, 6)), columns=cols)\n\n var = \"color\"\n key = (\"b\", \"y\")\n p = PlotData(df, {var: key})\n assert_vector_equal(p.frame[var], df[key])\n assert p.names[var] == p.ids[var] == str(key)"},{"col":4,"comment":"null","endLoc":196,"header":"def test_cbrewer_qual(self)","id":2673,"name":"test_cbrewer_qual","nodeType":"Function","startLoc":188,"text":"def test_cbrewer_qual(self):\n\n pal_short = palettes.mpl_palette(\"Set1\", 4)\n pal_long = palettes.mpl_palette(\"Set1\", 6)\n assert pal_short == pal_long[:4]\n\n pal_full = palettes.mpl_palette(\"Set2\", 8)\n pal_long = palettes.mpl_palette(\"Set2\", 10)\n assert pal_full == pal_long[:8]"},{"col":4,"comment":"null","endLoc":202,"header":"def test_mpl_reversal(self)","id":2674,"name":"test_mpl_reversal","nodeType":"Function","startLoc":198,"text":"def test_mpl_reversal(self):\n\n pal_forward = palettes.mpl_palette(\"BuPu\", 6)\n pal_reverse = palettes.mpl_palette(\"BuPu_r\", 6)\n npt.assert_array_almost_equal(pal_forward, pal_reverse[::-1])"},{"col":4,"comment":"null","endLoc":209,"header":"def test_rgb_from_hls(self)","id":2675,"name":"test_rgb_from_hls","nodeType":"Function","startLoc":204,"text":"def test_rgb_from_hls(self):\n\n color = .5, .8, .4\n rgb_got = palettes._color_to_rgb(color, \"hls\")\n rgb_want = colorsys.hls_to_rgb(*color)\n assert rgb_got == rgb_want"},{"col":4,"comment":"null","endLoc":556,"header":"def test_set_axis_labels(self)","id":2676,"name":"test_set_axis_labels","nodeType":"Function","startLoc":535,"text":"def test_set_axis_labels(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.map(plt.plot, \"x\", \"y\")\n xlab = 'xx'\n ylab = 'yy'\n\n g.set_axis_labels(xlab, ylab)\n\n got_x = [ax.get_xlabel() for ax in g.axes[-1, :]]\n got_y = [ax.get_ylabel() for ax in g.axes[:, 0]]\n npt.assert_array_equal(got_x, xlab)\n npt.assert_array_equal(got_y, ylab)\n\n for ax in g.axes.flat:\n ax.set(xlabel=\"x\", ylabel=\"y\")\n\n g.set_axis_labels(xlab, ylab)\n for ax in g._not_bottom_axes:\n assert not ax.get_xlabel()\n for ax in g._not_left_axes:\n assert not ax.get_ylabel()"},{"col":4,"comment":"null","endLoc":222,"header":"def test_rgb_from_husl(self)","id":2677,"name":"test_rgb_from_husl","nodeType":"Function","startLoc":211,"text":"def test_rgb_from_husl(self):\n\n color = 120, 50, 40\n rgb_got = palettes._color_to_rgb(color, \"husl\")\n rgb_want = tuple(husl.husl_to_rgb(*color))\n assert rgb_got == rgb_want\n\n for h in range(0, 360):\n color = h, 100, 100\n rgb = palettes._color_to_rgb(color, \"husl\")\n assert min(rgb) >= 0\n assert max(rgb) <= 1"},{"col":4,"comment":"null","endLoc":104,"header":"def test_dict_as_data(self, long_dict, long_variables)","id":2678,"name":"test_dict_as_data","nodeType":"Function","startLoc":99,"text":"def test_dict_as_data(self, long_dict, long_variables):\n\n p = PlotData(long_dict, long_variables)\n assert p.source_data is long_dict\n for key, val in long_variables.items():\n assert_vector_equal(p.frame[key], pd.Series(long_dict[val]))"},{"col":4,"comment":"null","endLoc":132,"header":"@pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_vectors_various_types(self, long_df, long_variables, vector_type)","id":2679,"name":"test_vectors_various_types","nodeType":"Function","startLoc":106,"text":"@pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_vectors_various_types(self, long_df, long_variables, vector_type):\n\n variables = {key: long_df[val] for key, val in long_variables.items()}\n if vector_type == \"numpy\":\n variables = {key: val.to_numpy() for key, val in variables.items()}\n elif vector_type == \"list\":\n variables = {key: val.to_list() for key, val in variables.items()}\n\n p = PlotData(None, variables)\n\n assert list(p.names) == list(long_variables)\n if vector_type == \"series\":\n assert p.source_vars is variables\n assert p.names == p.ids == {key: val.name for key, val in variables.items()}\n else:\n assert p.names == {key: None for key in variables}\n assert p.ids == {key: id(val) for key, val in variables.items()}\n\n for key, val in long_variables.items():\n if vector_type == \"series\":\n assert_vector_equal(p.frame[key], long_df[val])\n else:\n assert_array_equal(p.frame[key], long_df[val])"},{"col":4,"comment":"null","endLoc":1737,"header":"def test_log_scale_explicit(self, rng)","id":2680,"name":"test_log_scale_explicit","nodeType":"Function","startLoc":1730,"text":"def test_log_scale_explicit(self, rng):\n\n x = rng.lognormal(0, 2, 1000)\n ax = histplot(x, log_scale=True, binwidth=1)\n\n bar_widths = [b.get_width() for b in ax.patches]\n steps = np.divide(bar_widths[1:], bar_widths[:-1])\n assert np.allclose(steps, 10)"},{"col":4,"comment":"null","endLoc":1749,"header":"def test_log_scale_implicit(self, rng)","id":2681,"name":"test_log_scale_implicit","nodeType":"Function","startLoc":1739,"text":"def test_log_scale_implicit(self, rng):\n\n x = rng.lognormal(0, 2, 1000)\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n histplot(x, binwidth=1, ax=ax)\n\n bar_widths = [b.get_width() for b in ax.patches]\n steps = np.divide(bar_widths[1:], bar_widths[:-1])\n assert np.allclose(steps, 10)"},{"col":4,"comment":"null","endLoc":1758,"header":"def test_log_scale_dodge(self, rng)","id":2682,"name":"test_log_scale_dodge","nodeType":"Function","startLoc":1751,"text":"def test_log_scale_dodge(self, rng):\n\n x = rng.lognormal(0, 2, 100)\n hue = np.repeat([\"a\", \"b\"], 50)\n ax = histplot(x=x, hue=hue, bins=5, log_scale=True, multiple=\"dodge\")\n x_min = np.log([b.get_x() for b in ax.patches])\n x_max = np.log([b.get_x() + b.get_width() for b in ax.patches])\n assert np.unique(np.round(x_max - x_min, 10)).size == 1"},{"col":4,"comment":"null","endLoc":1096,"header":"def test_orient(self, long_df)","id":2683,"name":"test_orient","nodeType":"Function","startLoc":1073,"text":"def test_orient(self, long_df):\n\n long_df = long_df.drop(\"x\", axis=1).rename(columns={\"s\": \"y\", \"y\": \"x\"})\n\n ax1 = plt.figure().subplots()\n lineplot(data=long_df, x=\"x\", y=\"y\", orient=\"y\", errorbar=\"sd\")\n assert len(ax1.lines) == len(ax1.collections)\n line, = ax1.lines\n expected = long_df.groupby(\"y\").agg({\"x\": \"mean\"}).reset_index()\n assert_array_almost_equal(line.get_xdata(), expected[\"x\"])\n assert_array_almost_equal(line.get_ydata(), expected[\"y\"])\n ribbon_y = ax1.collections[0].get_paths()[0].vertices[:, 1]\n assert_array_equal(np.unique(ribbon_y), long_df[\"y\"].sort_values().unique())\n\n ax2 = plt.figure().subplots()\n lineplot(\n data=long_df, x=\"x\", y=\"y\", orient=\"y\", errorbar=\"sd\", err_style=\"bars\"\n )\n segments = ax2.collections[0].get_segments()\n for i, val in enumerate(sorted(long_df[\"y\"].unique())):\n assert (segments[i][:, 1] == val).all()\n\n with pytest.raises(ValueError, match=\"`orient` must be either 'x' or 'y'\"):\n lineplot(long_df, x=\"y\", y=\"x\", orient=\"bad\")"},{"col":4,"comment":"null","endLoc":1790,"header":"@pytest.mark.parametrize(\n \"fill\", [True, False],\n )\n def test_auto_linewidth(self, flat_series, fill)","id":2685,"name":"test_auto_linewidth","nodeType":"Function","startLoc":1760,"text":"@pytest.mark.parametrize(\n \"fill\", [True, False],\n )\n def test_auto_linewidth(self, flat_series, fill):\n\n get_lw = lambda ax: ax.patches[0].get_linewidth() # noqa: E731\n\n kws = dict(element=\"bars\", fill=fill)\n\n f, (ax1, ax2) = plt.subplots(2)\n histplot(flat_series, **kws, bins=10, ax=ax1)\n histplot(flat_series, **kws, bins=100, ax=ax2)\n assert get_lw(ax1) > get_lw(ax2)\n\n f, ax1 = plt.subplots(figsize=(10, 5))\n f, ax2 = plt.subplots(figsize=(2, 5))\n histplot(flat_series, **kws, bins=30, ax=ax1)\n histplot(flat_series, **kws, bins=30, ax=ax2)\n assert get_lw(ax1) > get_lw(ax2)\n\n f, ax1 = plt.subplots(figsize=(4, 5))\n f, ax2 = plt.subplots(figsize=(4, 5))\n histplot(flat_series, **kws, bins=30, ax=ax1)\n histplot(10 ** flat_series, **kws, bins=30, log_scale=True, ax=ax2)\n assert get_lw(ax1) == pytest.approx(get_lw(ax2))\n\n f, ax1 = plt.subplots(figsize=(4, 5))\n f, ax2 = plt.subplots(figsize=(4, 5))\n histplot(y=[0, 1, 1], **kws, discrete=True, ax=ax1)\n histplot(y=[\"a\", \"b\", \"b\"], **kws, ax=ax2)\n assert get_lw(ax1) == pytest.approx(get_lw(ax2))"},{"col":17,"endLoc":1765,"id":2686,"nodeType":"Lambda","startLoc":1765,"text":"lambda ax: ax.patches[0].get_linewidth()"},{"col":4,"comment":"null","endLoc":562,"header":"def test_axis_lims(self)","id":2687,"name":"test_axis_lims","nodeType":"Function","startLoc":558,"text":"def test_axis_lims(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", xlim=(0, 4), ylim=(-2, 3))\n assert g.axes[0, 0].get_xlim() == (0, 4)\n assert g.axes[0, 0].get_ylim() == (-2, 3)"},{"col":4,"comment":"null","endLoc":591,"header":"def test_data_orders(self)","id":2688,"name":"test_data_orders","nodeType":"Function","startLoc":564,"text":"def test_data_orders(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\")\n\n assert g.row_names == list(\"abc\")\n assert g.col_names == list(\"mn\")\n assert g.hue_names == list(\"tuv\")\n assert g.axes.shape == (3, 2)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\",\n row_order=list(\"bca\"),\n col_order=list(\"nm\"),\n hue_order=list(\"vtu\"))\n\n assert g.row_names == list(\"bca\")\n assert g.col_names == list(\"nm\")\n assert g.hue_names == list(\"vtu\")\n assert g.axes.shape == (3, 2)\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\", hue=\"c\",\n row_order=list(\"bcda\"),\n col_order=list(\"nom\"),\n hue_order=list(\"qvtu\"))\n\n assert g.row_names == list(\"bcda\")\n assert g.col_names == list(\"nom\")\n assert g.hue_names == list(\"qvtu\")\n assert g.axes.shape == (4, 3)"},{"col":4,"comment":"null","endLoc":1799,"header":"def test_bar_kwargs(self, flat_series)","id":2689,"name":"test_bar_kwargs","nodeType":"Function","startLoc":1792,"text":"def test_bar_kwargs(self, flat_series):\n\n lw = 2\n ec = (1, .2, .9, .5)\n ax = histplot(flat_series, binwidth=1, ec=ec, lw=lw)\n for bar in ax.patches:\n assert_colors_equal(bar.get_edgecolor(), ec)\n assert bar.get_linewidth() == lw"},{"col":4,"comment":"null","endLoc":1808,"header":"def test_step_fill_kwargs(self, flat_series)","id":2691,"name":"test_step_fill_kwargs","nodeType":"Function","startLoc":1801,"text":"def test_step_fill_kwargs(self, flat_series):\n\n lw = 2\n ec = (1, .2, .9, .5)\n ax = histplot(flat_series, element=\"step\", ec=ec, lw=lw)\n poly = ax.collections[0]\n assert_colors_equal(poly.get_edgecolor(), ec)\n assert poly.get_linewidth() == lw"},{"col":4,"comment":"null","endLoc":229,"header":"def test_rgb_from_xkcd(self)","id":2692,"name":"test_rgb_from_xkcd","nodeType":"Function","startLoc":224,"text":"def test_rgb_from_xkcd(self):\n\n color = \"dull red\"\n rgb_got = palettes._color_to_rgb(color, \"xkcd\")\n rgb_want = mpl.colors.to_rgb(xkcd_rgb[color])\n assert rgb_got == rgb_want"},{"col":4,"comment":"null","endLoc":255,"header":"def test_light_palette(self)","id":2693,"name":"test_light_palette","nodeType":"Function","startLoc":231,"text":"def test_light_palette(self):\n\n n = 4\n pal_forward = palettes.light_palette(\"red\", n)\n pal_reverse = palettes.light_palette(\"red\", n, reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_f_from_string = palettes.color_palette(\"light:red\", n)\n assert pal_forward[3] == pal_f_from_string[3]\n\n pal_r_from_string = palettes.color_palette(\"light:red_r\", n)\n assert pal_reverse[3] == pal_r_from_string[3]\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"light:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"light:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)"},{"col":4,"comment":"null","endLoc":1817,"header":"def test_step_line_kwargs(self, flat_series)","id":2694,"name":"test_step_line_kwargs","nodeType":"Function","startLoc":1810,"text":"def test_step_line_kwargs(self, flat_series):\n\n lw = 2\n ls = \"--\"\n ax = histplot(flat_series, element=\"step\", fill=False, lw=lw, ls=ls)\n line = ax.lines[0]\n assert line.get_linewidth() == lw\n assert line.get_linestyle() == ls"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":1135,"id":2695,"name":"func","nodeType":"Attribute","startLoc":1135,"text":"func"},{"attributeType":"null","col":8,"comment":"null","endLoc":1698,"id":2696,"name":"ax_joint","nodeType":"Attribute","startLoc":1698,"text":"self.ax_joint"},{"attributeType":"null","col":8,"comment":"null","endLoc":1697,"id":2697,"name":"_figure","nodeType":"Attribute","startLoc":1697,"text":"self._figure"},{"attributeType":"None","col":8,"comment":"null","endLoc":1735,"id":2698,"name":"x","nodeType":"Attribute","startLoc":1735,"text":"self.x"},{"className":"TestHistPlotBivariate","col":0,"comment":"null","endLoc":2104,"id":2699,"nodeType":"Class","startLoc":1820,"text":"class TestHistPlotBivariate:\n\n def test_mesh(self, long_df):\n\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(long_df[\"x\"], long_df[\"y\"])\n\n ax = histplot(long_df, x=\"x\", y=\"y\")\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_with_hue(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", hue=\"c\")\n\n hist = Histogram()\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_with_hue_unique_bins(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", hue=\"c\", common_bins=False)\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n hist = Histogram()\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_with_col_unique_bins(self, long_df):\n\n g = displot(long_df, x=\"x\", y=\"y\", col=\"c\", common_bins=False)\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n hist = Histogram()\n\n mesh = g.axes.flat[i].collections[0]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y\n\n def test_mesh_log_scale(self, rng):\n\n x, y = rng.lognormal(0, 1, (2, 1000))\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(np.log10(x), np.log10(y))\n\n ax = histplot(x=x, y=y, log_scale=True)\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y_i, x_i) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == 10 ** x_i\n assert path.vertices[0, 1] == 10 ** y_i\n\n def test_mesh_thresh(self, long_df):\n\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(long_df[\"x\"], long_df[\"y\"])\n\n thresh = 5\n ax = histplot(long_df, x=\"x\", y=\"y\", thresh=thresh)\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, (counts <= thresh).T.flat)\n\n def test_mesh_sticky_edges(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", thresh=None)\n mesh = ax.collections[0]\n assert mesh.sticky_edges.x == [long_df[\"x\"].min(), long_df[\"x\"].max()]\n assert mesh.sticky_edges.y == [long_df[\"y\"].min(), long_df[\"y\"].max()]\n\n ax.clear()\n ax = histplot(long_df, x=\"x\", y=\"y\")\n mesh = ax.collections[0]\n assert not mesh.sticky_edges.x\n assert not mesh.sticky_edges.y\n\n def test_mesh_common_norm(self, long_df):\n\n stat = \"density\"\n ax = histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\", common_norm=True, stat=stat,\n )\n\n hist = Histogram(stat=\"density\")\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n density, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n scale = len(sub_df) / len(long_df)\n assert_array_equal(mesh_data.data, (density * scale).T.flat)\n\n def test_mesh_unique_norm(self, long_df):\n\n stat = \"density\"\n ax = histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\", common_norm=False, stat=stat,\n )\n\n hist = Histogram()\n bin_kws = hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n sub_hist = Histogram(bins=bin_kws[\"bins\"], stat=stat)\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n density, (x_edges, y_edges) = sub_hist(sub_df[\"x\"], sub_df[\"y\"])\n assert_array_equal(mesh_data.data, density.T.flat)\n\n @pytest.mark.parametrize(\"stat\", [\"probability\", \"proportion\", \"percent\"])\n def test_mesh_normalization(self, long_df, stat):\n\n ax = histplot(\n long_df, x=\"x\", y=\"y\", stat=stat,\n )\n\n mesh_data = ax.collections[0].get_array()\n expected_sum = {\"percent\": 100}.get(stat, 1)\n assert mesh_data.data.sum() == expected_sum\n\n def test_mesh_colors(self, long_df):\n\n color = \"r\"\n f, ax = plt.subplots()\n histplot(\n long_df, x=\"x\", y=\"y\", color=color,\n )\n mesh = ax.collections[0]\n assert_array_equal(\n mesh.get_cmap().colors,\n _DistributionPlotter()._cmap_from_color(color).colors,\n )\n\n f, ax = plt.subplots()\n histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\",\n )\n colors = color_palette()\n for i, mesh in enumerate(ax.collections):\n assert_array_equal(\n mesh.get_cmap().colors,\n _DistributionPlotter()._cmap_from_color(colors[i]).colors,\n )\n\n def test_color_limits(self, long_df):\n\n f, (ax1, ax2, ax3) = plt.subplots(3)\n kws = dict(data=long_df, x=\"x\", y=\"y\")\n hist = Histogram()\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n\n histplot(**kws, ax=ax1)\n assert ax1.collections[0].get_clim() == (0, counts.max())\n\n vmax = 10\n histplot(**kws, vmax=vmax, ax=ax2)\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n assert ax2.collections[0].get_clim() == (0, vmax)\n\n pmax = .8\n pthresh = .1\n f = _DistributionPlotter()._quantile_to_level\n\n histplot(**kws, pmax=pmax, pthresh=pthresh, ax=ax3)\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n mesh = ax3.collections[0]\n assert mesh.get_clim() == (0, f(counts, pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (counts <= f(counts, pthresh)).T.flat,\n )\n\n def test_hue_color_limits(self, long_df):\n\n _, (ax1, ax2, ax3, ax4) = plt.subplots(4)\n kws = dict(data=long_df, x=\"x\", y=\"y\", hue=\"c\", bins=4)\n\n hist = Histogram(bins=kws[\"bins\"])\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n full_counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n\n sub_counts = []\n for _, sub_df in long_df.groupby(kws[\"hue\"]):\n c, _ = hist(sub_df[\"x\"], sub_df[\"y\"])\n sub_counts.append(c)\n\n pmax = .8\n pthresh = .05\n f = _DistributionPlotter()._quantile_to_level\n\n histplot(**kws, common_norm=True, ax=ax1)\n for i, mesh in enumerate(ax1.collections):\n assert mesh.get_clim() == (0, full_counts.max())\n\n histplot(**kws, common_norm=False, ax=ax2)\n for i, mesh in enumerate(ax2.collections):\n assert mesh.get_clim() == (0, sub_counts[i].max())\n\n histplot(**kws, common_norm=True, pmax=pmax, pthresh=pthresh, ax=ax3)\n for i, mesh in enumerate(ax3.collections):\n assert mesh.get_clim() == (0, f(full_counts, pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (sub_counts[i] <= f(full_counts, pthresh)).T.flat,\n )\n\n histplot(**kws, common_norm=False, pmax=pmax, pthresh=pthresh, ax=ax4)\n for i, mesh in enumerate(ax4.collections):\n assert mesh.get_clim() == (0, f(sub_counts[i], pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (sub_counts[i] <= f(sub_counts[i], pthresh)).T.flat,\n )\n\n def test_colorbar(self, long_df):\n\n f, ax = plt.subplots()\n histplot(long_df, x=\"x\", y=\"y\", cbar=True, ax=ax)\n assert len(ax.figure.axes) == 2\n\n f, (ax, cax) = plt.subplots(2)\n histplot(long_df, x=\"x\", y=\"y\", cbar=True, cbar_ax=cax, ax=ax)\n assert len(ax.figure.axes) == 2"},{"attributeType":"(str, str, str, str)","col":4,"comment":"null","endLoc":46,"id":2700,"name":"semantics","nodeType":"Attribute","startLoc":46,"text":"semantics"},{"col":4,"comment":"null","endLoc":1838,"header":"def test_mesh(self, long_df)","id":2701,"name":"test_mesh","nodeType":"Function","startLoc":1822,"text":"def test_mesh(self, long_df):\n\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(long_df[\"x\"], long_df[\"y\"])\n\n ax = histplot(long_df, x=\"x\", y=\"y\")\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":48,"id":2702,"name":"wide_structure","nodeType":"Attribute","startLoc":48,"text":"wide_structure"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":51,"id":2703,"name":"flat_structure","nodeType":"Attribute","startLoc":51,"text":"flat_structure"},{"attributeType":"str","col":4,"comment":"null","endLoc":53,"id":2704,"name":"_legend_func","nodeType":"Attribute","startLoc":53,"text":"_legend_func"},{"attributeType":"list","col":4,"comment":"null","endLoc":54,"id":2705,"name":"_legend_attributes","nodeType":"Attribute","startLoc":54,"text":"_legend_attributes"},{"attributeType":"null","col":8,"comment":"null","endLoc":96,"id":2706,"name":"orient","nodeType":"Attribute","startLoc":96,"text":"self.orient"},{"attributeType":"str","col":8,"comment":"null","endLoc":103,"id":2707,"name":"legend","nodeType":"Attribute","startLoc":103,"text":"self.legend"},{"attributeType":"bool","col":12,"comment":"null","endLoc":141,"id":2708,"name":"_redundant_hue","nodeType":"Attribute","startLoc":141,"text":"self._redundant_hue"},{"attributeType":"null","col":12,"comment":"null","endLoc":78,"id":2709,"name":"plot_data","nodeType":"Attribute","startLoc":78,"text":"self.plot_data"},{"className":"_CategoricalFacetPlotter","col":0,"comment":"null","endLoc":416,"id":2710,"nodeType":"Class","startLoc":414,"text":"class _CategoricalFacetPlotter(_CategoricalPlotterNew):\n\n semantics = _CategoricalPlotterNew.semantics + (\"col\", \"row\")"},{"attributeType":"(str, str, str, str, str, str)","col":4,"comment":"null","endLoc":416,"id":2711,"name":"semantics","nodeType":"Attribute","startLoc":416,"text":"semantics"},{"attributeType":"None","col":8,"comment":"null","endLoc":1736,"id":2712,"name":"y","nodeType":"Attribute","startLoc":1736,"text":"self.y"},{"col":4,"comment":"null","endLoc":1861,"header":"def test_mesh_with_hue(self, long_df)","id":2713,"name":"test_mesh_with_hue","nodeType":"Function","startLoc":1840,"text":"def test_mesh_with_hue(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", hue=\"c\")\n\n hist = Histogram()\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y"},{"col":4,"comment":"null","endLoc":281,"header":"def test_dark_palette(self)","id":2714,"name":"test_dark_palette","nodeType":"Function","startLoc":257,"text":"def test_dark_palette(self):\n\n n = 4\n pal_forward = palettes.dark_palette(\"red\", n)\n pal_reverse = palettes.dark_palette(\"red\", n, reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_f_from_string = palettes.color_palette(\"dark:red\", n)\n assert pal_forward[3] == pal_f_from_string[3]\n\n pal_r_from_string = palettes.color_palette(\"dark:red_r\", n)\n assert pal_reverse[3] == pal_r_from_string[3]\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"dark:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"dark:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)"},{"fileName":"test_rcmod.py","filePath":"tests","id":2715,"nodeType":"File","text":"import pytest\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy.testing as npt\n\nfrom seaborn import rcmod, palettes, utils\n\n\ndef has_verdana():\n \"\"\"Helper to verify if Verdana font is present\"\"\"\n # This import is relatively lengthy, so to prevent its import for\n # testing other tests in this module not requiring this knowledge,\n # import font_manager here\n import matplotlib.font_manager as mplfm\n try:\n verdana_font = mplfm.findfont('Verdana', fallback_to_default=False)\n except: # noqa\n # if https://github.com/matplotlib/matplotlib/pull/3435\n # gets accepted\n return False\n # otherwise check if not matching the logic for a 'default' one\n try:\n unlikely_font = mplfm.findfont(\"very_unlikely_to_exist1234\",\n fallback_to_default=False)\n except: # noqa\n # if matched verdana but not unlikely, Verdana must exist\n return True\n # otherwise -- if they match, must be the same default\n return verdana_font != unlikely_font\n\n\nclass RCParamFixtures:\n\n @pytest.fixture(autouse=True)\n def reset_params(self):\n yield\n rcmod.reset_orig()\n\n def flatten_list(self, orig_list):\n\n iter_list = map(np.atleast_1d, orig_list)\n flat_list = [item for sublist in iter_list for item in sublist]\n return flat_list\n\n def assert_rc_params(self, params):\n\n for k, v in params.items():\n # Various subtle issues in matplotlib lead to unexpected\n # values for the backend rcParam, which isn't relevant here\n if k == \"backend\":\n continue\n if isinstance(v, np.ndarray):\n npt.assert_array_equal(mpl.rcParams[k], v)\n else:\n assert mpl.rcParams[k] == v\n\n def assert_rc_params_equal(self, params1, params2):\n\n for key, v1 in params1.items():\n # Various subtle issues in matplotlib lead to unexpected\n # values for the backend rcParam, which isn't relevant here\n if key == \"backend\":\n continue\n\n v2 = params2[key]\n if isinstance(v1, np.ndarray):\n npt.assert_array_equal(v1, v2)\n else:\n assert v1 == v2\n\n\nclass TestAxesStyle(RCParamFixtures):\n\n styles = [\"white\", \"dark\", \"whitegrid\", \"darkgrid\", \"ticks\"]\n\n def test_default_return(self):\n\n current = rcmod.axes_style()\n self.assert_rc_params(current)\n\n def test_key_usage(self):\n\n _style_keys = set(rcmod._style_keys)\n for style in self.styles:\n assert not set(rcmod.axes_style(style)) ^ _style_keys\n\n def test_bad_style(self):\n\n with pytest.raises(ValueError):\n rcmod.axes_style(\"i_am_not_a_style\")\n\n def test_rc_override(self):\n\n rc = {\"axes.facecolor\": \"blue\", \"foo.notaparam\": \"bar\"}\n out = rcmod.axes_style(\"darkgrid\", rc)\n assert out[\"axes.facecolor\"] == \"blue\"\n assert \"foo.notaparam\" not in out\n\n def test_set_style(self):\n\n for style in self.styles:\n\n style_dict = rcmod.axes_style(style)\n rcmod.set_style(style)\n self.assert_rc_params(style_dict)\n\n def test_style_context_manager(self):\n\n rcmod.set_style(\"darkgrid\")\n orig_params = rcmod.axes_style()\n context_params = rcmod.axes_style(\"whitegrid\")\n\n with rcmod.axes_style(\"whitegrid\"):\n self.assert_rc_params(context_params)\n self.assert_rc_params(orig_params)\n\n @rcmod.axes_style(\"whitegrid\")\n def func():\n self.assert_rc_params(context_params)\n func()\n self.assert_rc_params(orig_params)\n\n def test_style_context_independence(self):\n\n assert set(rcmod._style_keys) ^ set(rcmod._context_keys)\n\n def test_set_rc(self):\n\n rcmod.set_theme(rc={\"lines.linewidth\": 4})\n assert mpl.rcParams[\"lines.linewidth\"] == 4\n rcmod.set_theme()\n\n def test_set_with_palette(self):\n\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=\"deep\")\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=\"deep\", color_codes=False)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n pal = palettes.color_palette(\"deep\")\n rcmod.set_theme(palette=pal)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=pal, color_codes=False)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme()\n\n def test_reset_defaults(self):\n\n rcmod.reset_defaults()\n self.assert_rc_params(mpl.rcParamsDefault)\n rcmod.set_theme()\n\n def test_reset_orig(self):\n\n rcmod.reset_orig()\n self.assert_rc_params(mpl.rcParamsOrig)\n rcmod.set_theme()\n\n def test_set_is_alias(self):\n\n rcmod.set_theme(context=\"paper\", style=\"white\")\n params1 = mpl.rcParams.copy()\n rcmod.reset_orig()\n\n rcmod.set_theme(context=\"paper\", style=\"white\")\n params2 = mpl.rcParams.copy()\n\n self.assert_rc_params_equal(params1, params2)\n\n rcmod.set_theme()\n\n\nclass TestPlottingContext(RCParamFixtures):\n\n contexts = [\"paper\", \"notebook\", \"talk\", \"poster\"]\n\n def test_default_return(self):\n\n current = rcmod.plotting_context()\n self.assert_rc_params(current)\n\n def test_key_usage(self):\n\n _context_keys = set(rcmod._context_keys)\n for context in self.contexts:\n missing = set(rcmod.plotting_context(context)) ^ _context_keys\n assert not missing\n\n def test_bad_context(self):\n\n with pytest.raises(ValueError):\n rcmod.plotting_context(\"i_am_not_a_context\")\n\n def test_font_scale(self):\n\n notebook_ref = rcmod.plotting_context(\"notebook\")\n notebook_big = rcmod.plotting_context(\"notebook\", 2)\n\n font_keys = [\n \"font.size\",\n \"axes.labelsize\", \"axes.titlesize\",\n \"xtick.labelsize\", \"ytick.labelsize\",\n \"legend.fontsize\", \"legend.title_fontsize\",\n ]\n\n for k in font_keys:\n assert notebook_ref[k] * 2 == notebook_big[k]\n\n def test_rc_override(self):\n\n key, val = \"grid.linewidth\", 5\n rc = {key: val, \"foo\": \"bar\"}\n out = rcmod.plotting_context(\"talk\", rc=rc)\n assert out[key] == val\n assert \"foo\" not in out\n\n def test_set_context(self):\n\n for context in self.contexts:\n\n context_dict = rcmod.plotting_context(context)\n rcmod.set_context(context)\n self.assert_rc_params(context_dict)\n\n def test_context_context_manager(self):\n\n rcmod.set_context(\"notebook\")\n orig_params = rcmod.plotting_context()\n context_params = rcmod.plotting_context(\"paper\")\n\n with rcmod.plotting_context(\"paper\"):\n self.assert_rc_params(context_params)\n self.assert_rc_params(orig_params)\n\n @rcmod.plotting_context(\"paper\")\n def func():\n self.assert_rc_params(context_params)\n func()\n self.assert_rc_params(orig_params)\n\n\nclass TestPalette(RCParamFixtures):\n\n def test_set_palette(self):\n\n rcmod.set_palette(\"deep\")\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n\n rcmod.set_palette(\"pastel6\")\n assert utils.get_color_cycle() == palettes.color_palette(\"pastel6\", 6)\n\n rcmod.set_palette(\"dark\", 4)\n assert utils.get_color_cycle() == palettes.color_palette(\"dark\", 4)\n\n rcmod.set_palette(\"Set2\", color_codes=True)\n assert utils.get_color_cycle() == palettes.color_palette(\"Set2\", 8)\n\n assert mpl.colors.same_color(\n mpl.rcParams[\"patch.facecolor\"], palettes.color_palette()[0]\n )\n\n\nclass TestFonts(RCParamFixtures):\n\n _no_verdana = not has_verdana()\n\n @pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_set_font(self):\n\n rcmod.set_theme(font=\"Verdana\")\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() == \"Verdana\"\n\n rcmod.set_theme()\n\n def test_set_serif_font(self):\n\n rcmod.set_theme(font=\"serif\")\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() in mpl.rcParams[\"font.serif\"]\n\n rcmod.set_theme()\n\n @pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_different_sans_serif(self):\n\n rcmod.set_theme()\n rcmod.set_style(rc={\"font.sans-serif\": [\"Verdana\"]})\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() == \"Verdana\"\n\n rcmod.set_theme()\n"},{"className":"RCParamFixtures","col":0,"comment":"null","endLoc":70,"id":2716,"nodeType":"Class","startLoc":33,"text":"class RCParamFixtures:\n\n @pytest.fixture(autouse=True)\n def reset_params(self):\n yield\n rcmod.reset_orig()\n\n def flatten_list(self, orig_list):\n\n iter_list = map(np.atleast_1d, orig_list)\n flat_list = [item for sublist in iter_list for item in sublist]\n return flat_list\n\n def assert_rc_params(self, params):\n\n for k, v in params.items():\n # Various subtle issues in matplotlib lead to unexpected\n # values for the backend rcParam, which isn't relevant here\n if k == \"backend\":\n continue\n if isinstance(v, np.ndarray):\n npt.assert_array_equal(mpl.rcParams[k], v)\n else:\n assert mpl.rcParams[k] == v\n\n def assert_rc_params_equal(self, params1, params2):\n\n for key, v1 in params1.items():\n # Various subtle issues in matplotlib lead to unexpected\n # values for the backend rcParam, which isn't relevant here\n if key == \"backend\":\n continue\n\n v2 = params2[key]\n if isinstance(v1, np.ndarray):\n npt.assert_array_equal(v1, v2)\n else:\n assert v1 == v2"},{"col":4,"comment":"null","endLoc":38,"header":"@pytest.fixture(autouse=True)\n def reset_params(self)","id":2717,"name":"reset_params","nodeType":"Function","startLoc":35,"text":"@pytest.fixture(autouse=True)\n def reset_params(self):\n yield\n rcmod.reset_orig()"},{"col":0,"comment":"Restore all RC params to original settings (respects custom rc).","endLoc":143,"header":"def reset_orig()","id":2718,"name":"reset_orig","nodeType":"Function","startLoc":140,"text":"def reset_orig():\n \"\"\"Restore all RC params to original settings (respects custom rc).\"\"\"\n from . import _orig_rc_params\n mpl.rcParams.update(_orig_rc_params)"},{"col":4,"comment":"null","endLoc":44,"header":"def flatten_list(self, orig_list)","id":2719,"name":"flatten_list","nodeType":"Function","startLoc":40,"text":"def flatten_list(self, orig_list):\n\n iter_list = map(np.atleast_1d, orig_list)\n flat_list = [item for sublist in iter_list for item in sublist]\n return flat_list"},{"col":4,"comment":"null","endLoc":1124,"header":"def test_log_scale(self)","id":2720,"name":"test_log_scale","nodeType":"Function","startLoc":1098,"text":"def test_log_scale(self):\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n\n x = [1, 10, 100]\n y = [1, 2, 3]\n\n lineplot(x=x, y=y)\n line = ax.lines[0]\n assert_array_equal(line.get_xdata(), x)\n assert_array_equal(line.get_ydata(), y)\n\n f, ax = plt.subplots()\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n\n x = [1, 1, 2, 2]\n y = [1, 10, 1, 100]\n\n lineplot(x=x, y=y, err_style=\"bars\", errorbar=(\"pi\", 100))\n line = ax.lines[0]\n assert line.get_ydata()[1] == 10\n\n ebars = ax.collections[0].get_segments()\n assert_array_equal(ebars[0][:, 1], y[:2])\n assert_array_equal(ebars[1][:, 1], y[2:])"},{"attributeType":"None","col":8,"comment":"null","endLoc":1737,"id":2721,"name":"hue","nodeType":"Attribute","startLoc":1737,"text":"self.hue"},{"attributeType":"null","col":8,"comment":"null","endLoc":1700,"id":2722,"name":"ax_marg_y","nodeType":"Attribute","startLoc":1700,"text":"self.ax_marg_y"},{"attributeType":"null","col":8,"comment":"null","endLoc":1699,"id":2723,"name":"ax_marg_x","nodeType":"Attribute","startLoc":1699,"text":"self.ax_marg_x"},{"attributeType":"null","col":0,"comment":"null","endLoc":24,"id":2724,"name":"__all__","nodeType":"Attribute","startLoc":24,"text":"__all__"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":2725,"name":"_param_docs","nodeType":"Attribute","startLoc":27,"text":"_param_docs"},{"col":4,"comment":"null","endLoc":614,"header":"def test_palette(self)","id":2726,"name":"test_palette","nodeType":"Function","startLoc":593,"text":"def test_palette(self):\n\n rcmod.set()\n\n g = ag.FacetGrid(self.df, hue=\"c\")\n assert g._colors == color_palette(n_colors=len(self.df.c.unique()))\n\n g = ag.FacetGrid(self.df, hue=\"d\")\n assert g._colors == color_palette(\"husl\", len(self.df.d.unique()))\n\n g = ag.FacetGrid(self.df, hue=\"c\", palette=\"Set2\")\n assert g._colors == color_palette(\"Set2\", len(self.df.c.unique()))\n\n dict_pal = dict(t=\"red\", u=\"green\", v=\"blue\")\n list_pal = color_palette([\"red\", \"green\", \"blue\"], 3)\n g = ag.FacetGrid(self.df, hue=\"c\", palette=dict_pal)\n assert g._colors == list_pal\n\n list_pal = color_palette([\"green\", \"blue\", \"red\"], 3)\n g = ag.FacetGrid(self.df, hue=\"c\", hue_order=list(\"uvt\"),\n palette=dict_pal)\n assert g._colors == list_pal"},{"col":0,"comment":"","endLoc":1,"header":"axisgrid.py#","id":2727,"name":"","nodeType":"Function","startLoc":1,"text":"__all__ = [\"FacetGrid\", \"PairGrid\", \"JointGrid\", \"pairplot\", \"jointplot\"]\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n)\n\n_facet_docs = dict(\n\n data=dedent(\"\"\"\\\n data : DataFrame\n Tidy (\"long-form\") dataframe where each column is a variable and each\n row is an observation.\\\n \"\"\"),\n rowcol=dedent(\"\"\"\\\n row, col : vectors or keys in ``data``\n Variables that define subsets to plot on different facets.\\\n \"\"\"),\n rowcol_order=dedent(\"\"\"\\\n {row,col}_order : vector of strings\n Specify the order in which levels of the ``row`` and/or ``col`` variables\n appear in the grid of subplots.\\\n \"\"\"),\n col_wrap=dedent(\"\"\"\\\n col_wrap : int\n \"Wrap\" the column variable at this width, so that the column facets\n span multiple rows. Incompatible with a ``row`` facet.\\\n \"\"\"),\n share_xy=dedent(\"\"\"\\\n share{x,y} : bool, 'col', or 'row' optional\n If true, the facets will share y axes across columns and/or x axes\n across rows.\\\n \"\"\"),\n height=dedent(\"\"\"\\\n height : scalar\n Height (in inches) of each facet. See also: ``aspect``.\\\n \"\"\"),\n aspect=dedent(\"\"\"\\\n aspect : scalar\n Aspect ratio of each facet, so that ``aspect * height`` gives the width\n of each facet in inches.\\\n \"\"\"),\n palette=dedent(\"\"\"\\\n palette : palette name, list, or dict\n Colors to use for the different levels of the ``hue`` variable. Should\n be something that can be interpreted by :func:`color_palette`, or a\n dictionary mapping hue levels to matplotlib colors.\\\n \"\"\"),\n legend_out=dedent(\"\"\"\\\n legend_out : bool\n If ``True``, the figure size will be extended, and the legend will be\n drawn outside the plot on the center right.\\\n \"\"\"),\n margin_titles=dedent(\"\"\"\\\n margin_titles : bool\n If ``True``, the titles for the row variable are drawn to the right of\n the last column. This option is experimental and may not work in all\n cases.\\\n \"\"\"),\n facet_kws=dedent(\"\"\"\\\n facet_kws : dict\n Additional parameters passed to :class:`FacetGrid`.\n \"\"\"),\n)\n\nJointGrid.__init__.__doc__ = \"\"\"\\\nSet up the grid of subplots and store data internally for easy plotting.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\nheight : number\n Size of each side of the figure in inches (it will be square).\nratio : number\n Ratio of joint axes height to marginal axes height.\nspace : number\n Space between the joint and marginal axes\ndropna : bool\n If True, remove missing observations before plotting.\n{{x, y}}lim : pairs of numbers\n Set axis limits to these values before plotting.\nmarginal_ticks : bool\n If False, suppress ticks on the count/density axis of the marginal plots.\n{params.core.hue}\n Note: unlike in :class:`FacetGrid` or :class:`PairGrid`, the axes-level\n functions must support ``hue`` to use it in :class:`JointGrid`.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n\nSee Also\n--------\n{seealso.jointplot}\n{seealso.pairgrid}\n{seealso.pairplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/JointGrid.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\njointplot.__doc__ = \"\"\"\\\nDraw a plot of two variables with bivariate and univariate graphs.\n\nThis function provides a convenient interface to the :class:`JointGrid`\nclass, with several canned plot kinds. This is intended to be a fairly\nlightweight wrapper; if you need more flexibility, you should use\n:class:`JointGrid` directly.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\n Semantic variable that is mapped to determine the color of plot elements.\nkind : {{ \"scatter\" | \"kde\" | \"hist\" | \"hex\" | \"reg\" | \"resid\" }}\n Kind of plot to draw. See the examples for references to the underlying functions.\nheight : numeric\n Size of the figure (it will be square).\nratio : numeric\n Ratio of joint axes height to marginal axes height.\nspace : numeric\n Space between the joint and marginal axes\ndropna : bool\n If True, remove observations that are missing from ``x`` and ``y``.\n{{x, y}}lim : pairs of numbers\n Axis limits to set before plotting.\n{params.core.color}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\nmarginal_ticks : bool\n If False, suppress ticks on the count/density axis of the marginal plots.\n{{joint, marginal}}_kws : dicts\n Additional keyword arguments for the plot components.\nkwargs\n Additional keyword arguments are passed to the function used to\n draw the plot on the joint Axes, superseding items in the\n ``joint_kws`` dictionary.\n\nReturns\n-------\n{returns.jointgrid}\n\nSee Also\n--------\n{seealso.jointgrid}\n{seealso.pairgrid}\n{seealso.pairplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/jointplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)"},{"col":4,"comment":"null","endLoc":303,"header":"def test_diverging_palette(self)","id":2728,"name":"test_diverging_palette","nodeType":"Function","startLoc":283,"text":"def test_diverging_palette(self):\n\n h_neg, h_pos = 100, 200\n sat, lum = 70, 50\n args = h_neg, h_pos, sat, lum\n\n n = 12\n pal = palettes.diverging_palette(*args, n=n)\n neg_pal = palettes.light_palette((h_neg, sat, lum), int(n // 2),\n input=\"husl\")\n pos_pal = palettes.light_palette((h_pos, sat, lum), int(n // 2),\n input=\"husl\")\n assert len(pal) == n\n assert pal[0] == neg_pal[-1]\n assert pal[-1] == pos_pal[-1]\n\n pal_dark = palettes.diverging_palette(*args, n=n, center=\"dark\")\n assert np.mean(pal[int(n / 2)]) > np.mean(pal_dark[int(n / 2)])\n\n pal_cmap = palettes.diverging_palette(*args, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)"},{"col":4,"comment":"null","endLoc":1142,"header":"def test_axis_labels(self, long_df)","id":2729,"name":"test_axis_labels","nodeType":"Function","startLoc":1126,"text":"def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n p = _LinePlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n\n p.plot(ax1, {})\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n\n p.plot(ax2, {})\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()"},{"className":"_CategoricalPlotter","col":0,"comment":"null","endLoc":776,"id":2730,"nodeType":"Class","startLoc":419,"text":"class _CategoricalPlotter:\n\n width = .8\n default_palette = \"light\"\n require_numeric = True\n\n def establish_variables(self, x=None, y=None, hue=None, data=None,\n orient=None, order=None, hue_order=None,\n units=None):\n \"\"\"Convert input specification into a common representation.\"\"\"\n # Option 1:\n # We are plotting a wide-form dataset\n # -----------------------------------\n if x is None and y is None:\n\n # Do a sanity check on the inputs\n if hue is not None:\n error = \"Cannot use `hue` without `x` and `y`\"\n raise ValueError(error)\n\n # No hue grouping with wide inputs\n plot_hues = None\n hue_title = None\n hue_names = None\n\n # No statistical units with wide inputs\n plot_units = None\n\n # We also won't get a axes labels here\n value_label = None\n group_label = None\n\n # Option 1a:\n # The input data is a Pandas DataFrame\n # ------------------------------------\n\n if isinstance(data, pd.DataFrame):\n\n # Order the data correctly\n if order is None:\n order = []\n # Reduce to just numeric columns\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n order.append(col)\n plot_data = data[order]\n group_names = order\n group_label = data.columns.name\n\n # Convert to a list of arrays, the common representation\n iter_data = plot_data.items()\n plot_data = [np.asarray(s, float) for k, s in iter_data]\n\n # Option 1b:\n # The input data is an array or list\n # ----------------------------------\n\n else:\n\n # We can't reorder the data\n if order is not None:\n error = \"Input data must be a pandas object to reorder\"\n raise ValueError(error)\n\n # The input data is an array\n if hasattr(data, \"shape\"):\n if len(data.shape) == 1:\n if np.isscalar(data[0]):\n plot_data = [data]\n else:\n plot_data = list(data)\n elif len(data.shape) == 2:\n nr, nc = data.shape\n if nr == 1 or nc == 1:\n plot_data = [data.ravel()]\n else:\n plot_data = [data[:, i] for i in range(nc)]\n else:\n error = (\"Input `data` can have no \"\n \"more than 2 dimensions\")\n raise ValueError(error)\n\n # Check if `data` is None to let us bail out here (for testing)\n elif data is None:\n plot_data = [[]]\n\n # The input data is a flat list\n elif np.isscalar(data[0]):\n plot_data = [data]\n\n # The input data is a nested list\n # This will catch some things that might fail later\n # but exhaustive checks are hard\n else:\n plot_data = data\n\n # Convert to a list of arrays, the common representation\n plot_data = [np.asarray(d, float) for d in plot_data]\n\n # The group names will just be numeric indices\n group_names = list(range(len(plot_data)))\n\n # Figure out the plotting orientation\n orient = \"h\" if str(orient).startswith(\"h\") else \"v\"\n\n # Option 2:\n # We are plotting a long-form dataset\n # -----------------------------------\n\n else:\n\n # See if we need to get variables from `data`\n if data is not None:\n x = data.get(x, x)\n y = data.get(y, y)\n hue = data.get(hue, hue)\n units = data.get(units, units)\n\n # Validate the inputs\n for var in [x, y, hue, units]:\n if isinstance(var, str):\n err = f\"Could not interpret input '{var}'\"\n raise ValueError(err)\n\n # Figure out the plotting orientation\n orient = infer_orient(\n x, y, orient, require_numeric=self.require_numeric\n )\n\n # Option 2a:\n # We are plotting a single set of data\n # ------------------------------------\n if x is None or y is None:\n\n # Determine where the data are\n vals = y if x is None else x\n\n # Put them into the common representation\n plot_data = [np.asarray(vals)]\n\n # Get a label for the value axis\n if hasattr(vals, \"name\"):\n value_label = vals.name\n else:\n value_label = None\n\n # This plot will not have group labels or hue nesting\n groups = None\n group_label = None\n group_names = []\n plot_hues = None\n hue_names = None\n hue_title = None\n plot_units = None\n\n # Option 2b:\n # We are grouping the data values by another variable\n # ---------------------------------------------------\n else:\n\n # Determine which role each variable will play\n if orient == \"v\":\n vals, groups = y, x\n else:\n vals, groups = x, y\n\n # Get the categorical axis label\n group_label = None\n if hasattr(groups, \"name\"):\n group_label = groups.name\n\n # Get the order on the categorical axis\n group_names = categorical_order(groups, order)\n\n # Group the numeric data\n plot_data, value_label = self._group_longform(vals, groups,\n group_names)\n\n # Now handle the hue levels for nested ordering\n if hue is None:\n plot_hues = None\n hue_title = None\n hue_names = None\n else:\n\n # Get the order of the hue levels\n hue_names = categorical_order(hue, hue_order)\n\n # Group the hue data\n plot_hues, hue_title = self._group_longform(hue, groups,\n group_names)\n\n # Now handle the units for nested observations\n if units is None:\n plot_units = None\n else:\n plot_units, _ = self._group_longform(units, groups,\n group_names)\n\n # Assign object attributes\n # ------------------------\n self.orient = orient\n self.plot_data = plot_data\n self.group_label = group_label\n self.value_label = value_label\n self.group_names = group_names\n self.plot_hues = plot_hues\n self.hue_title = hue_title\n self.hue_names = hue_names\n self.plot_units = plot_units\n\n def _group_longform(self, vals, grouper, order):\n \"\"\"Group a long-form variable by another with correct order.\"\"\"\n # Ensure that the groupby will work\n if not isinstance(vals, pd.Series):\n if isinstance(grouper, pd.Series):\n index = grouper.index\n else:\n index = None\n vals = pd.Series(vals, index=index)\n\n # Group the val data\n grouped_vals = vals.groupby(grouper)\n out_data = []\n for g in order:\n try:\n g_vals = grouped_vals.get_group(g)\n except KeyError:\n g_vals = np.array([])\n out_data.append(g_vals)\n\n # Get the vals axis label\n label = vals.name\n\n return out_data, label\n\n def establish_colors(self, color, palette, saturation):\n \"\"\"Get a list of colors for the main component of the plots.\"\"\"\n if self.hue_names is None:\n n_colors = len(self.plot_data)\n else:\n n_colors = len(self.hue_names)\n\n # Determine the main colors\n if color is None and palette is None:\n # Determine whether the current palette will have enough values\n # If not, we'll default to the husl palette so each is distinct\n current_palette = utils.get_color_cycle()\n if n_colors <= len(current_palette):\n colors = color_palette(n_colors=n_colors)\n else:\n colors = husl_palette(n_colors, l=.7) # noqa\n\n elif palette is None:\n # When passing a specific color, the interpretation depends\n # on whether there is a hue variable or not.\n # If so, we will make a blend palette so that the different\n # levels have some amount of variation.\n if self.hue_names is None:\n colors = [color] * n_colors\n else:\n if self.default_palette == \"light\":\n colors = light_palette(color, n_colors)\n elif self.default_palette == \"dark\":\n colors = dark_palette(color, n_colors)\n else:\n raise RuntimeError(\"No default palette specified\")\n else:\n\n # Let `palette` be a dict mapping level to color\n if isinstance(palette, dict):\n if self.hue_names is None:\n levels = self.group_names\n else:\n levels = self.hue_names\n palette = [palette[l] for l in levels]\n\n colors = color_palette(palette, n_colors)\n\n # Desaturate a bit because these are patches\n if saturation < 1:\n colors = color_palette(colors, desat=saturation)\n\n # Convert the colors to a common representations\n rgb_colors = color_palette(colors)\n\n # Determine the gray color to use for the lines framing the plot\n light_vals = [rgb_to_hls(*c)[1] for c in rgb_colors]\n lum = min(light_vals) * .6\n gray = mpl.colors.rgb2hex((lum, lum, lum))\n\n # Assign object attributes\n self.colors = rgb_colors\n self.gray = gray\n\n @property\n def hue_offsets(self):\n \"\"\"A list of center positions for plots when hue nesting is used.\"\"\"\n n_levels = len(self.hue_names)\n if self.dodge:\n each_width = self.width / n_levels\n offsets = np.linspace(0, self.width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n\n return offsets\n\n @property\n def nested_width(self):\n \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n if self.dodge:\n width = self.width / len(self.hue_names) * .98\n else:\n width = self.width\n return width\n\n def annotate_axes(self, ax):\n \"\"\"Add descriptive labels to an Axes object.\"\"\"\n if self.orient == \"v\":\n xlabel, ylabel = self.group_label, self.value_label\n else:\n xlabel, ylabel = self.value_label, self.group_label\n\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n group_names = self.group_names\n if not group_names:\n group_names = [\"\" for _ in range(len(self.plot_data))]\n\n if self.orient == \"v\":\n ax.set_xticks(np.arange(len(self.plot_data)))\n ax.set_xticklabels(group_names)\n else:\n ax.set_yticks(np.arange(len(self.plot_data)))\n ax.set_yticklabels(group_names)\n\n if self.orient == \"v\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, len(self.plot_data) - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n ax.set_ylim(-.5, len(self.plot_data) - .5, auto=None)\n\n if self.hue_names is not None:\n ax.legend(loc=\"best\", title=self.hue_title)\n\n def add_legend_data(self, ax, color, label):\n \"\"\"Add a dummy patch object so we can get legend data.\"\"\"\n rect = plt.Rectangle([0, 0], 0, 0,\n linewidth=self.linewidth / 2,\n edgecolor=self.gray,\n facecolor=color,\n label=label)\n ax.add_patch(rect)"},{"col":4,"comment":"A list of center positions for plots when hue nesting is used.","endLoc":725,"header":"@property\n def hue_offsets(self)","id":2731,"name":"hue_offsets","nodeType":"Function","startLoc":714,"text":"@property\n def hue_offsets(self):\n \"\"\"A list of center positions for plots when hue nesting is used.\"\"\"\n n_levels = len(self.hue_names)\n if self.dodge:\n each_width = self.width / n_levels\n offsets = np.linspace(0, self.width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n\n return offsets"},{"col":4,"comment":"A float with the width of plot elements when hue nesting is used.","endLoc":734,"header":"@property\n def nested_width(self)","id":2732,"name":"nested_width","nodeType":"Function","startLoc":727,"text":"@property\n def nested_width(self):\n \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n if self.dodge:\n width = self.width / len(self.hue_names) * .98\n else:\n width = self.width\n return width"},{"col":4,"comment":"Add descriptive labels to an Axes object.","endLoc":767,"header":"def annotate_axes(self, ax)","id":2733,"name":"annotate_axes","nodeType":"Function","startLoc":736,"text":"def annotate_axes(self, ax):\n \"\"\"Add descriptive labels to an Axes object.\"\"\"\n if self.orient == \"v\":\n xlabel, ylabel = self.group_label, self.value_label\n else:\n xlabel, ylabel = self.value_label, self.group_label\n\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n group_names = self.group_names\n if not group_names:\n group_names = [\"\" for _ in range(len(self.plot_data))]\n\n if self.orient == \"v\":\n ax.set_xticks(np.arange(len(self.plot_data)))\n ax.set_xticklabels(group_names)\n else:\n ax.set_yticks(np.arange(len(self.plot_data)))\n ax.set_yticklabels(group_names)\n\n if self.orient == \"v\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, len(self.plot_data) - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n ax.set_ylim(-.5, len(self.plot_data) - .5, auto=None)\n\n if self.hue_names is not None:\n ax.legend(loc=\"best\", title=self.hue_title)"},{"col":4,"comment":"null","endLoc":1158,"header":"def test_matplotlib_kwargs(self, long_df)","id":2734,"name":"test_matplotlib_kwargs","nodeType":"Function","startLoc":1144,"text":"def test_matplotlib_kwargs(self, long_df):\n\n kws = {\n \"linestyle\": \"--\",\n \"linewidth\": 3,\n \"color\": (1, .5, .2),\n \"markeredgecolor\": (.2, .5, .2),\n \"markeredgewidth\": 1,\n }\n ax = lineplot(data=long_df, x=\"x\", y=\"y\", **kws)\n\n line, *_ = ax.lines\n for key, val in kws.items():\n plot_val = getattr(line, f\"get_{key}\")()\n assert plot_val == val"},{"fileName":"husl.py","filePath":"seaborn/external","id":2735,"nodeType":"File","text":"import operator\nimport math\n\n__version__ = \"2.1.0\"\n\n\nm = [\n [3.2406, -1.5372, -0.4986],\n [-0.9689, 1.8758, 0.0415],\n [0.0557, -0.2040, 1.0570]\n]\n\nm_inv = [\n [0.4124, 0.3576, 0.1805],\n [0.2126, 0.7152, 0.0722],\n [0.0193, 0.1192, 0.9505]\n]\n\n# Hard-coded D65 illuminant\nrefX = 0.95047\nrefY = 1.00000\nrefZ = 1.08883\nrefU = 0.19784\nrefV = 0.46834\nlab_e = 0.008856\nlab_k = 903.3\n\n\n# Public API\n\ndef husl_to_rgb(h, s, l):\n return lch_to_rgb(*husl_to_lch([h, s, l]))\n\n\ndef husl_to_hex(h, s, l):\n return rgb_to_hex(husl_to_rgb(h, s, l))\n\n\ndef rgb_to_husl(r, g, b):\n return lch_to_husl(rgb_to_lch(r, g, b))\n\n\ndef hex_to_husl(hex):\n return rgb_to_husl(*hex_to_rgb(hex))\n\n\ndef huslp_to_rgb(h, s, l):\n return lch_to_rgb(*huslp_to_lch([h, s, l]))\n\n\ndef huslp_to_hex(h, s, l):\n return rgb_to_hex(huslp_to_rgb(h, s, l))\n\n\ndef rgb_to_huslp(r, g, b):\n return lch_to_huslp(rgb_to_lch(r, g, b))\n\n\ndef hex_to_huslp(hex):\n return rgb_to_huslp(*hex_to_rgb(hex))\n\n\ndef lch_to_rgb(l, c, h):\n return xyz_to_rgb(luv_to_xyz(lch_to_luv([l, c, h])))\n\n\ndef rgb_to_lch(r, g, b):\n return luv_to_lch(xyz_to_luv(rgb_to_xyz([r, g, b])))\n\n\ndef max_chroma(L, H):\n hrad = math.radians(H)\n sinH = (math.sin(hrad))\n cosH = (math.cos(hrad))\n sub1 = (math.pow(L + 16, 3.0) / 1560896.0)\n sub2 = sub1 if sub1 > 0.008856 else (L / 903.3)\n result = float(\"inf\")\n for row in m:\n m1 = row[0]\n m2 = row[1]\n m3 = row[2]\n top = ((0.99915 * m1 + 1.05122 * m2 + 1.14460 * m3) * sub2)\n rbottom = (0.86330 * m3 - 0.17266 * m2)\n lbottom = (0.12949 * m3 - 0.38848 * m1)\n bottom = (rbottom * sinH + lbottom * cosH) * sub2\n\n for t in (0.0, 1.0):\n C = (L * (top - 1.05122 * t) / (bottom + 0.17266 * sinH * t))\n if C > 0.0 and C < result:\n result = C\n return result\n\n\ndef _hrad_extremum(L):\n lhs = (math.pow(L, 3.0) + 48.0 * math.pow(L, 2.0) + 768.0 * L + 4096.0) / 1560896.0\n rhs = 1107.0 / 125000.0\n sub = lhs if lhs > rhs else 10.0 * L / 9033.0\n chroma = float(\"inf\")\n result = None\n for row in m:\n for limit in (0.0, 1.0):\n [m1, m2, m3] = row\n top = -3015466475.0 * m3 * sub + 603093295.0 * m2 * sub - 603093295.0 * limit\n bottom = 1356959916.0 * m1 * sub - 452319972.0 * m3 * sub\n hrad = math.atan2(top, bottom)\n # This is a math hack to deal with tan quadrants, I'm too lazy to figure\n # out how to do this properly\n if limit == 0.0:\n hrad += math.pi\n test = max_chroma(L, math.degrees(hrad))\n if test < chroma:\n chroma = test\n result = hrad\n return result\n\n\ndef max_chroma_pastel(L):\n H = math.degrees(_hrad_extremum(L))\n return max_chroma(L, H)\n\n\ndef dot_product(a, b):\n return sum(map(operator.mul, a, b))\n\n\ndef f(t):\n if t > lab_e:\n return (math.pow(t, 1.0 / 3.0))\n else:\n return (7.787 * t + 16.0 / 116.0)\n\n\ndef f_inv(t):\n if math.pow(t, 3.0) > lab_e:\n return (math.pow(t, 3.0))\n else:\n return (116.0 * t - 16.0) / lab_k\n\n\ndef from_linear(c):\n if c <= 0.0031308:\n return 12.92 * c\n else:\n return (1.055 * math.pow(c, 1.0 / 2.4) - 0.055)\n\n\ndef to_linear(c):\n a = 0.055\n\n if c > 0.04045:\n return (math.pow((c + a) / (1.0 + a), 2.4))\n else:\n return (c / 12.92)\n\n\ndef rgb_prepare(triple):\n ret = []\n for ch in triple:\n ch = round(ch, 3)\n\n if ch < -0.0001 or ch > 1.0001:\n raise Exception(f\"Illegal RGB value {ch:f}\")\n\n if ch < 0:\n ch = 0\n if ch > 1:\n ch = 1\n\n # Fix for Python 3 which by default rounds 4.5 down to 4.0\n # instead of Python 2 which is rounded to 5.0 which caused\n # a couple off by one errors in the tests. Tests now all pass\n # in Python 2 and Python 3\n ret.append(int(round(ch * 255 + 0.001, 0)))\n\n return ret\n\n\ndef hex_to_rgb(hex):\n if hex.startswith('#'):\n hex = hex[1:]\n r = int(hex[0:2], 16) / 255.0\n g = int(hex[2:4], 16) / 255.0\n b = int(hex[4:6], 16) / 255.0\n return [r, g, b]\n\n\ndef rgb_to_hex(triple):\n [r, g, b] = triple\n return '#%02x%02x%02x' % tuple(rgb_prepare([r, g, b]))\n\n\ndef xyz_to_rgb(triple):\n xyz = map(lambda row: dot_product(row, triple), m)\n return list(map(from_linear, xyz))\n\n\ndef rgb_to_xyz(triple):\n rgbl = list(map(to_linear, triple))\n return list(map(lambda row: dot_product(row, rgbl), m_inv))\n\n\ndef xyz_to_luv(triple):\n X, Y, Z = triple\n\n if X == Y == Z == 0.0:\n return [0.0, 0.0, 0.0]\n\n varU = (4.0 * X) / (X + (15.0 * Y) + (3.0 * Z))\n varV = (9.0 * Y) / (X + (15.0 * Y) + (3.0 * Z))\n L = 116.0 * f(Y / refY) - 16.0\n\n # Black will create a divide-by-zero error\n if L == 0.0:\n return [0.0, 0.0, 0.0]\n\n U = 13.0 * L * (varU - refU)\n V = 13.0 * L * (varV - refV)\n\n return [L, U, V]\n\n\ndef luv_to_xyz(triple):\n L, U, V = triple\n\n if L == 0:\n return [0.0, 0.0, 0.0]\n\n varY = f_inv((L + 16.0) / 116.0)\n varU = U / (13.0 * L) + refU\n varV = V / (13.0 * L) + refV\n Y = varY * refY\n X = 0.0 - (9.0 * Y * varU) / ((varU - 4.0) * varV - varU * varV)\n Z = (9.0 * Y - (15.0 * varV * Y) - (varV * X)) / (3.0 * varV)\n\n return [X, Y, Z]\n\n\ndef luv_to_lch(triple):\n L, U, V = triple\n\n C = (math.pow(math.pow(U, 2) + math.pow(V, 2), (1.0 / 2.0)))\n hrad = (math.atan2(V, U))\n H = math.degrees(hrad)\n if H < 0.0:\n H = 360.0 + H\n\n return [L, C, H]\n\n\ndef lch_to_luv(triple):\n L, C, H = triple\n\n Hrad = math.radians(H)\n U = (math.cos(Hrad) * C)\n V = (math.sin(Hrad) * C)\n\n return [L, U, V]\n\n\ndef husl_to_lch(triple):\n H, S, L = triple\n\n if L > 99.9999999:\n return [100, 0.0, H]\n if L < 0.00000001:\n return [0.0, 0.0, H]\n\n mx = max_chroma(L, H)\n C = mx / 100.0 * S\n\n return [L, C, H]\n\n\ndef lch_to_husl(triple):\n L, C, H = triple\n\n if L > 99.9999999:\n return [H, 0.0, 100.0]\n if L < 0.00000001:\n return [H, 0.0, 0.0]\n\n mx = max_chroma(L, H)\n S = C / mx * 100.0\n\n return [H, S, L]\n\n\ndef huslp_to_lch(triple):\n H, S, L = triple\n\n if L > 99.9999999:\n return [100, 0.0, H]\n if L < 0.00000001:\n return [0.0, 0.0, H]\n\n mx = max_chroma_pastel(L)\n C = mx / 100.0 * S\n\n return [L, C, H]\n\n\ndef lch_to_huslp(triple):\n L, C, H = triple\n\n if L > 99.9999999:\n return [H, 0.0, 100.0]\n if L < 0.00000001:\n return [H, 0.0, 0.0]\n\n mx = max_chroma_pastel(L)\n S = C / mx * 100.0\n\n return [H, S, L]\n"},{"col":0,"comment":"null","endLoc":36,"header":"def husl_to_hex(h, s, l)","id":2736,"name":"husl_to_hex","nodeType":"Function","startLoc":35,"text":"def husl_to_hex(h, s, l):\n return rgb_to_hex(husl_to_rgb(h, s, l))"},{"col":4,"comment":"null","endLoc":623,"header":"def test_hue_kws(self)","id":2737,"name":"test_hue_kws","nodeType":"Function","startLoc":616,"text":"def test_hue_kws(self):\n\n kws = dict(marker=[\"o\", \"s\", \"D\"])\n g = ag.FacetGrid(self.df, hue=\"c\", hue_kws=kws)\n g.map(plt.plot, \"x\", \"y\")\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker"},{"col":0,"comment":"null","endLoc":189,"header":"def rgb_to_hex(triple)","id":2738,"name":"rgb_to_hex","nodeType":"Function","startLoc":187,"text":"def rgb_to_hex(triple):\n [r, g, b] = triple\n return '#%02x%02x%02x' % tuple(rgb_prepare([r, g, b]))"},{"col":4,"comment":"null","endLoc":138,"header":"def test_none_as_variable_value(self, long_df)","id":2739,"name":"test_none_as_variable_value","nodeType":"Function","startLoc":134,"text":"def test_none_as_variable_value(self, long_df):\n\n p = PlotData(long_df, {\"x\": \"z\", \"y\": None})\n assert list(p.frame.columns) == [\"x\"]\n assert p.names == p.ids == {\"x\": \"z\"}"},{"col":4,"comment":"null","endLoc":144,"header":"def test_frame_and_vector_mismatched_lengths(self, long_df)","id":2740,"name":"test_frame_and_vector_mismatched_lengths","nodeType":"Function","startLoc":140,"text":"def test_frame_and_vector_mismatched_lengths(self, long_df):\n\n vector = np.arange(len(long_df) * 2)\n with pytest.raises(ValueError):\n PlotData(long_df, {\"x\": \"x\", \"y\": vector})"},{"col":4,"comment":"null","endLoc":158,"header":"@pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg)","id":2741,"name":"test_empty_data_input","nodeType":"Function","startLoc":146,"text":"@pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg):\n\n p = PlotData(arg, {})\n assert p.frame.empty\n assert not p.names\n\n if not isinstance(arg, pd.DataFrame):\n p = PlotData(None, dict(x=arg, y=arg))\n assert p.frame.empty\n assert not p.names"},{"col":0,"comment":"null","endLoc":175,"header":"def rgb_prepare(triple)","id":2742,"name":"rgb_prepare","nodeType":"Function","startLoc":156,"text":"def rgb_prepare(triple):\n ret = []\n for ch in triple:\n ch = round(ch, 3)\n\n if ch < -0.0001 or ch > 1.0001:\n raise Exception(f\"Illegal RGB value {ch:f}\")\n\n if ch < 0:\n ch = 0\n if ch > 1:\n ch = 1\n\n # Fix for Python 3 which by default rounds 4.5 down to 4.0\n # instead of Python 2 which is rounded to 5.0 which caused\n # a couple off by one errors in the tests. Tests now all pass\n # in Python 2 and Python 3\n ret.append(int(round(ch * 255 + 0.001, 0)))\n\n return ret"},{"col":4,"comment":"null","endLoc":1165,"header":"def test_nonmapped_dashes(self)","id":2743,"name":"test_nonmapped_dashes","nodeType":"Function","startLoc":1160,"text":"def test_nonmapped_dashes(self):\n\n ax = lineplot(x=[1, 2], y=[1, 2], dashes=(2, 1))\n line = ax.lines[0]\n # Not a great test, but lines don't expose the dash style publicly\n assert line.get_linestyle() == \"--\""},{"col":4,"comment":"null","endLoc":176,"header":"def test_index_alignment_series_to_dataframe(self)","id":2746,"name":"test_index_alignment_series_to_dataframe","nodeType":"Function","startLoc":160,"text":"def test_index_alignment_series_to_dataframe(self):\n\n x = [1, 2, 3]\n x_index = pd.Index(x, dtype=int)\n\n y_values = [3, 4, 5]\n y_index = pd.Index(y_values, dtype=int)\n y = pd.Series(y_values, y_index, name=\"y\")\n\n data = pd.DataFrame(dict(x=x), index=x_index)\n\n p = PlotData(data, {\"x\": \"x\", \"y\": y})\n\n x_col_expected = pd.Series([1, 2, 3, np.nan, np.nan], np.arange(1, 6))\n y_col_expected = pd.Series([np.nan, np.nan, 3, 4, 5], np.arange(1, 6))\n assert_vector_equal(p.frame[\"x\"], x_col_expected)\n assert_vector_equal(p.frame[\"y\"], y_col_expected)"},{"col":4,"comment":"null","endLoc":193,"header":"def test_index_alignment_between_series(self)","id":2747,"name":"test_index_alignment_between_series","nodeType":"Function","startLoc":178,"text":"def test_index_alignment_between_series(self):\n\n x_index = [1, 2, 3]\n x_values = [10, 20, 30]\n x = pd.Series(x_values, x_index, name=\"x\")\n\n y_index = [3, 4, 5]\n y_values = [300, 400, 500]\n y = pd.Series(y_values, y_index, name=\"y\")\n\n p = PlotData(None, {\"x\": x, \"y\": y})\n\n x_col_expected = pd.Series([10, 20, 30, np.nan, np.nan], np.arange(1, 6))\n y_col_expected = pd.Series([np.nan, np.nan, 300, 400, 500], np.arange(1, 6))\n assert_vector_equal(p.frame[\"x\"], x_col_expected)\n assert_vector_equal(p.frame[\"y\"], y_col_expected)"},{"col":4,"comment":"null","endLoc":1883,"header":"def test_mesh_with_hue_unique_bins(self, long_df)","id":2748,"name":"test_mesh_with_hue_unique_bins","nodeType":"Function","startLoc":1863,"text":"def test_mesh_with_hue_unique_bins(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", hue=\"c\", common_bins=False)\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n hist = Histogram()\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y"},{"col":4,"comment":"null","endLoc":201,"header":"def test_key_not_in_data_raises(self, long_df)","id":2749,"name":"test_key_not_in_data_raises","nodeType":"Function","startLoc":195,"text":"def test_key_not_in_data_raises(self, long_df):\n\n var = \"x\"\n key = \"what\"\n msg = f\"Could not interpret value `{key}` for `{var}`. An entry with this name\"\n with pytest.raises(ValueError, match=msg):\n PlotData(long_df, {var: key})"},{"col":4,"comment":"null","endLoc":1176,"header":"def test_lineplot_axes(self, wide_df)","id":2750,"name":"test_lineplot_axes","nodeType":"Function","startLoc":1167,"text":"def test_lineplot_axes(self, wide_df):\n\n f1, ax1 = plt.subplots()\n f2, ax2 = plt.subplots()\n\n ax = lineplot(data=wide_df)\n assert ax is ax2\n\n ax = lineplot(data=wide_df, ax=ax1)\n assert ax is ax1"},{"col":4,"comment":"null","endLoc":209,"header":"def test_key_with_no_data_raises(self)","id":2751,"name":"test_key_with_no_data_raises","nodeType":"Function","startLoc":203,"text":"def test_key_with_no_data_raises(self):\n\n var = \"x\"\n key = \"what\"\n msg = f\"Could not interpret value `{key}` for `{var}`. Value is a string,\"\n with pytest.raises(ValueError, match=msg):\n PlotData(None, {var: key})"},{"col":4,"comment":"null","endLoc":216,"header":"def test_data_vector_different_lengths_raises(self, long_df)","id":2752,"name":"test_data_vector_different_lengths_raises","nodeType":"Function","startLoc":211,"text":"def test_data_vector_different_lengths_raises(self, long_df):\n\n vector = np.arange(len(long_df) - 5)\n msg = \"Length of ndarray vectors must match length of `data`\"\n with pytest.raises(ValueError, match=msg):\n PlotData(long_df, {\"y\": vector})"},{"col":4,"comment":"null","endLoc":227,"header":"def test_undefined_variables_raise(self, long_df)","id":2753,"name":"test_undefined_variables_raise","nodeType":"Function","startLoc":218,"text":"def test_undefined_variables_raise(self, long_df):\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"not_in_df\"))\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"x\", y=\"not_in_df\"))\n\n with pytest.raises(ValueError):\n PlotData(long_df, dict(x=\"x\", y=\"y\", color=\"not_in_df\"))"},{"col":4,"comment":"null","endLoc":1190,"header":"def test_lineplot_vs_relplot(self, long_df, long_semantics)","id":2754,"name":"test_lineplot_vs_relplot","nodeType":"Function","startLoc":1178,"text":"def test_lineplot_vs_relplot(self, long_df, long_semantics):\n\n ax = lineplot(data=long_df, **long_semantics)\n g = relplot(data=long_df, kind=\"line\", **long_semantics)\n\n lin_lines = ax.lines\n rel_lines = g.ax.lines\n\n for l1, l2 in zip(lin_lines, rel_lines):\n assert_array_equal(l1.get_xydata(), l2.get_xydata())\n assert same_color(l1.get_color(), l2.get_color())\n assert l1.get_linewidth() == l2.get_linewidth()\n assert l1.get_linestyle() == l2.get_linestyle()"},{"col":4,"comment":"null","endLoc":1905,"header":"def test_mesh_with_col_unique_bins(self, long_df)","id":2755,"name":"test_mesh_with_col_unique_bins","nodeType":"Function","startLoc":1885,"text":"def test_mesh_with_col_unique_bins(self, long_df):\n\n g = displot(long_df, x=\"x\", y=\"y\", col=\"c\", common_bins=False)\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n hist = Histogram()\n\n mesh = g.axes.flat[i].collections[0]\n mesh_data = mesh.get_array()\n\n counts, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, counts.T.flat == 0)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y, x) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == x\n assert path.vertices[0, 1] == y"},{"col":4,"comment":"null","endLoc":1278,"header":"def test_lineplot_smoke(\n self,\n wide_df, wide_array,\n wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n flat_array, flat_series, flat_list,\n long_df, missing_df, object_df\n )","id":2756,"name":"test_lineplot_smoke","nodeType":"Function","startLoc":1192,"text":"def test_lineplot_smoke(\n self,\n wide_df, wide_array,\n wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n flat_array, flat_series, flat_list,\n long_df, missing_df, object_df\n ):\n\n f, ax = plt.subplots()\n\n lineplot(x=[], y=[])\n ax.clear()\n\n lineplot(data=wide_df)\n ax.clear()\n\n lineplot(data=wide_array)\n ax.clear()\n\n lineplot(data=wide_list_of_series)\n ax.clear()\n\n lineplot(data=wide_list_of_arrays)\n ax.clear()\n\n lineplot(data=wide_list_of_lists)\n ax.clear()\n\n lineplot(data=flat_series)\n ax.clear()\n\n lineplot(data=flat_array)\n ax.clear()\n\n lineplot(data=flat_list)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", data=long_df)\n ax.clear()\n\n lineplot(x=long_df.x, y=long_df.y)\n ax.clear()\n\n lineplot(x=long_df.x, y=\"y\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=long_df.y.to_numpy(), data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"t\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=long_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=missing_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"f\", data=object_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"c\", size=\"f\", data=object_df)\n ax.clear()\n\n lineplot(x=\"x\", y=\"y\", hue=\"f\", size=\"s\", data=object_df)\n ax.clear()"},{"col":4,"comment":"null","endLoc":635,"header":"def test_dropna(self)","id":2757,"name":"test_dropna","nodeType":"Function","startLoc":625,"text":"def test_dropna(self):\n\n df = self.df.copy()\n hasna = pd.Series(np.tile(np.arange(6), 10), dtype=float)\n hasna[hasna == 5] = np.nan\n df[\"hasna\"] = hasna\n g = ag.FacetGrid(df, dropna=False, row=\"hasna\")\n assert g._not_na.sum() == 60\n\n g = ag.FacetGrid(df, dropna=True, row=\"hasna\")\n assert g._not_na.sum() == 50"},{"col":4,"comment":"null","endLoc":234,"header":"def test_contains_operation(self, long_df)","id":2758,"name":"test_contains_operation","nodeType":"Function","startLoc":229,"text":"def test_contains_operation(self, long_df):\n\n p = PlotData(long_df, {\"x\": \"y\", \"color\": long_df[\"a\"]})\n assert \"x\" in p\n assert \"y\" not in p\n assert \"color\" in p"},{"col":4,"comment":"null","endLoc":644,"header":"def test_categorical_column_missing_categories(self)","id":2759,"name":"test_categorical_column_missing_categories","nodeType":"Function","startLoc":637,"text":"def test_categorical_column_missing_categories(self):\n\n df = self.df.copy()\n df['a'] = df['a'].astype('category')\n\n g = ag.FacetGrid(df[df['a'] == 'a'], col=\"a\", col_wrap=1)\n\n assert g.axes.shape == (len(df['a'].cat.categories),)"},{"col":4,"comment":"null","endLoc":247,"header":"def test_join_add_variable(self, long_df)","id":2760,"name":"test_join_add_variable","nodeType":"Function","startLoc":236,"text":"def test_join_add_variable(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"f\"}\n v2 = {\"color\": \"a\"}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n for var, key in dict(**v1, **v2).items():\n assert var in p2\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])"},{"col":4,"comment":"null","endLoc":650,"header":"def test_categorical_warning(self)","id":2761,"name":"test_categorical_warning","nodeType":"Function","startLoc":646,"text":"def test_categorical_warning(self):\n\n g = ag.FacetGrid(self.df, col=\"b\")\n with pytest.warns(UserWarning):\n g.map(pointplot, \"b\", \"x\")"},{"col":4,"comment":"null","endLoc":674,"header":"def test_refline(self)","id":2762,"name":"test_refline","nodeType":"Function","startLoc":652,"text":"def test_refline(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n g.refline()\n for ax in g.axes.flat:\n assert not ax.lines\n\n refx = refy = 0.5\n hline = np.array([[0, refy], [1, refy]])\n vline = np.array([[refx, 0], [refx, 1]])\n g.refline(x=refx, y=refy)\n for ax in g.axes.flat:\n assert ax.lines[0].get_color() == '.5'\n assert ax.lines[0].get_linestyle() == '--'\n assert len(ax.lines) == 2\n npt.assert_array_equal(ax.lines[0].get_xydata(), vline)\n npt.assert_array_equal(ax.lines[1].get_xydata(), hline)\n\n color, linestyle = 'red', '-'\n g.refline(x=refx, color=color, linestyle=linestyle)\n npt.assert_array_equal(g.axes[0, 0].lines[-1].get_xydata(), vline)\n assert g.axes[0, 0].lines[-1].get_color() == color\n assert g.axes[0, 0].lines[-1].get_linestyle() == linestyle"},{"col":4,"comment":"null","endLoc":315,"header":"def test_blend_palette(self)","id":2763,"name":"test_blend_palette","nodeType":"Function","startLoc":305,"text":"def test_blend_palette(self):\n\n colors = [\"red\", \"yellow\", \"white\"]\n pal_cmap = palettes.blend_palette(colors, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n colors = [\"red\", \"blue\"]\n pal = palettes.blend_palette(colors)\n pal_str = \"blend:\" + \",\".join(colors)\n pal_from_str = palettes.color_palette(pal_str)\n assert pal == pal_from_str"},{"col":4,"comment":"null","endLoc":1923,"header":"def test_mesh_log_scale(self, rng)","id":2764,"name":"test_mesh_log_scale","nodeType":"Function","startLoc":1907,"text":"def test_mesh_log_scale(self, rng):\n\n x, y = rng.lognormal(0, 1, (2, 1000))\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(np.log10(x), np.log10(y))\n\n ax = histplot(x=x, y=y, log_scale=True)\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n\n edges = itertools.product(y_edges[:-1], x_edges[:-1])\n for i, (y_i, x_i) in enumerate(edges):\n path = mesh.get_paths()[i]\n assert path.vertices[0, 0] == 10 ** x_i\n assert path.vertices[0, 1] == 10 ** y_i"},{"col":4,"comment":"null","endLoc":263,"header":"def test_join_replace_variable(self, long_df)","id":2765,"name":"test_join_replace_variable","nodeType":"Function","startLoc":249,"text":"def test_join_replace_variable(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"y\": \"s\"}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n variables = v1.copy()\n variables.update(v2)\n\n for var, key in variables.items():\n assert var in p2\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])"},{"col":4,"comment":"null","endLoc":56,"header":"def assert_rc_params(self, params)","id":2766,"name":"assert_rc_params","nodeType":"Function","startLoc":46,"text":"def assert_rc_params(self, params):\n\n for k, v in params.items():\n # Various subtle issues in matplotlib lead to unexpected\n # values for the backend rcParam, which isn't relevant here\n if k == \"backend\":\n continue\n if isinstance(v, np.ndarray):\n npt.assert_array_equal(mpl.rcParams[k], v)\n else:\n assert mpl.rcParams[k] == v"},{"col":4,"comment":"null","endLoc":1292,"header":"def test_ci_deprecation(self, long_df)","id":2767,"name":"test_ci_deprecation","nodeType":"Function","startLoc":1280,"text":"def test_ci_deprecation(self, long_df):\n\n axs = plt.figure().subplots(2)\n lineplot(data=long_df, x=\"x\", y=\"y\", errorbar=(\"ci\", 95), seed=0, ax=axs[0])\n with pytest.warns(FutureWarning, match=\"\\n\\nThe `ci` parameter is deprecated\"):\n lineplot(data=long_df, x=\"x\", y=\"y\", ci=95, seed=0, ax=axs[1])\n assert_plots_equal(*axs)\n\n axs = plt.figure().subplots(2)\n lineplot(data=long_df, x=\"x\", y=\"y\", errorbar=\"sd\", ax=axs[0])\n with pytest.warns(FutureWarning, match=\"\\n\\nThe `ci` parameter is deprecated\"):\n lineplot(data=long_df, x=\"x\", y=\"y\", ci=\"sd\", ax=axs[1])\n assert_plots_equal(*axs)"},{"col":4,"comment":"null","endLoc":325,"header":"def test_cubehelix_against_matplotlib(self)","id":2768,"name":"test_cubehelix_against_matplotlib","nodeType":"Function","startLoc":317,"text":"def test_cubehelix_against_matplotlib(self):\n\n x = np.linspace(0, 1, 8)\n mpl_pal = mpl.cm.cubehelix(x)[:, :3].tolist()\n\n sns_pal = palettes.cubehelix_palette(8, start=0.5, rot=-1.5, hue=1,\n dark=0, light=1, reverse=True)\n\n assert sns_pal == mpl_pal"},{"col":4,"comment":"null","endLoc":331,"header":"def test_cubehelix_n_colors(self)","id":2769,"name":"test_cubehelix_n_colors","nodeType":"Function","startLoc":327,"text":"def test_cubehelix_n_colors(self):\n\n for n in [3, 5, 8]:\n pal = palettes.cubehelix_palette(n)\n assert len(pal) == n"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":664,"id":2770,"name":"func","nodeType":"Attribute","startLoc":664,"text":"func"},{"col":4,"comment":"null","endLoc":337,"header":"def test_cubehelix_reverse(self)","id":2771,"name":"test_cubehelix_reverse","nodeType":"Function","startLoc":333,"text":"def test_cubehelix_reverse(self):\n\n pal_forward = palettes.cubehelix_palette()\n pal_reverse = palettes.cubehelix_palette(reverse=True)\n assert pal_forward == pal_reverse[::-1]"},{"col":4,"comment":"null","endLoc":351,"header":"def test_cubehelix_cmap(self)","id":2772,"name":"test_cubehelix_cmap","nodeType":"Function","startLoc":339,"text":"def test_cubehelix_cmap(self):\n\n cmap = palettes.cubehelix_palette(as_cmap=True)\n assert isinstance(cmap, mpl.colors.ListedColormap)\n pal = palettes.cubehelix_palette()\n x = np.linspace(0, 1, 6)\n npt.assert_array_equal(cmap(x)[:, :3], pal)\n\n cmap_rev = palettes.cubehelix_palette(as_cmap=True, reverse=True)\n x = np.linspace(0, 1, 6)\n pal_forward = cmap(x).tolist()\n pal_reverse = cmap_rev(x[::-1]).tolist()\n assert pal_forward == pal_reverse"},{"col":4,"comment":"null","endLoc":70,"header":"def assert_rc_params_equal(self, params1, params2)","id":2773,"name":"assert_rc_params_equal","nodeType":"Function","startLoc":58,"text":"def assert_rc_params_equal(self, params1, params2):\n\n for key, v1 in params1.items():\n # Various subtle issues in matplotlib lead to unexpected\n # values for the backend rcParam, which isn't relevant here\n if key == \"backend\":\n continue\n\n v2 = params2[key]\n if isinstance(v1, np.ndarray):\n npt.assert_array_equal(v1, v2)\n else:\n assert v1 == v2"},{"col":4,"comment":"null","endLoc":685,"header":"def test_apply(self, long_df)","id":2774,"name":"test_apply","nodeType":"Function","startLoc":676,"text":"def test_apply(self, long_df):\n\n def f(grid, color):\n grid.figure.set_facecolor(color)\n\n color = (.1, .6, .3, .9)\n g = ag.FacetGrid(long_df)\n res = g.apply(f, color)\n assert res is g\n assert g.figure.get_facecolor() == color"},{"col":4,"comment":"null","endLoc":376,"header":"def test_cubehelix_code(self)","id":2775,"name":"test_cubehelix_code","nodeType":"Function","startLoc":353,"text":"def test_cubehelix_code(self):\n\n color_palette = palettes.color_palette\n cubehelix_palette = palettes.cubehelix_palette\n\n pal1 = color_palette(\"ch:\", 8)\n pal2 = color_palette(cubehelix_palette(8))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:.5, -.25,hue = .5,light=.75\", 8)\n pal2 = color_palette(cubehelix_palette(8, .5, -.25, hue=.5, light=.75))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:h=1,r=.5\", 9)\n pal2 = color_palette(cubehelix_palette(9, hue=1, rot=.5))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", 6)\n pal2 = color_palette(cubehelix_palette(6, reverse=True))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", as_cmap=True)\n pal2 = cubehelix_palette(6, reverse=True, as_cmap=True)\n assert pal1(.5) == pal2(.5)"},{"col":4,"comment":"null","endLoc":697,"header":"def test_pipe(self, long_df)","id":2776,"name":"test_pipe","nodeType":"Function","startLoc":687,"text":"def test_pipe(self, long_df):\n\n def f(grid, color):\n grid.figure.set_facecolor(color)\n return color\n\n color = (.1, .6, .3, .9)\n g = ag.FacetGrid(long_df)\n res = g.pipe(f, color)\n assert res == color\n assert g.figure.get_facecolor() == color"},{"className":"TestAxesStyle","col":0,"comment":"null","endLoc":180,"id":2777,"nodeType":"Class","startLoc":73,"text":"class TestAxesStyle(RCParamFixtures):\n\n styles = [\"white\", \"dark\", \"whitegrid\", \"darkgrid\", \"ticks\"]\n\n def test_default_return(self):\n\n current = rcmod.axes_style()\n self.assert_rc_params(current)\n\n def test_key_usage(self):\n\n _style_keys = set(rcmod._style_keys)\n for style in self.styles:\n assert not set(rcmod.axes_style(style)) ^ _style_keys\n\n def test_bad_style(self):\n\n with pytest.raises(ValueError):\n rcmod.axes_style(\"i_am_not_a_style\")\n\n def test_rc_override(self):\n\n rc = {\"axes.facecolor\": \"blue\", \"foo.notaparam\": \"bar\"}\n out = rcmod.axes_style(\"darkgrid\", rc)\n assert out[\"axes.facecolor\"] == \"blue\"\n assert \"foo.notaparam\" not in out\n\n def test_set_style(self):\n\n for style in self.styles:\n\n style_dict = rcmod.axes_style(style)\n rcmod.set_style(style)\n self.assert_rc_params(style_dict)\n\n def test_style_context_manager(self):\n\n rcmod.set_style(\"darkgrid\")\n orig_params = rcmod.axes_style()\n context_params = rcmod.axes_style(\"whitegrid\")\n\n with rcmod.axes_style(\"whitegrid\"):\n self.assert_rc_params(context_params)\n self.assert_rc_params(orig_params)\n\n @rcmod.axes_style(\"whitegrid\")\n def func():\n self.assert_rc_params(context_params)\n func()\n self.assert_rc_params(orig_params)\n\n def test_style_context_independence(self):\n\n assert set(rcmod._style_keys) ^ set(rcmod._context_keys)\n\n def test_set_rc(self):\n\n rcmod.set_theme(rc={\"lines.linewidth\": 4})\n assert mpl.rcParams[\"lines.linewidth\"] == 4\n rcmod.set_theme()\n\n def test_set_with_palette(self):\n\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=\"deep\")\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=\"deep\", color_codes=False)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n pal = palettes.color_palette(\"deep\")\n rcmod.set_theme(palette=pal)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=pal, color_codes=False)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme()\n\n def test_reset_defaults(self):\n\n rcmod.reset_defaults()\n self.assert_rc_params(mpl.rcParamsDefault)\n rcmod.set_theme()\n\n def test_reset_orig(self):\n\n rcmod.reset_orig()\n self.assert_rc_params(mpl.rcParamsOrig)\n rcmod.set_theme()\n\n def test_set_is_alias(self):\n\n rcmod.set_theme(context=\"paper\", style=\"white\")\n params1 = mpl.rcParams.copy()\n rcmod.reset_orig()\n\n rcmod.set_theme(context=\"paper\", style=\"white\")\n params2 = mpl.rcParams.copy()\n\n self.assert_rc_params_equal(params1, params2)\n\n rcmod.set_theme()"},{"col":4,"comment":"null","endLoc":80,"header":"def test_default_return(self)","id":2778,"name":"test_default_return","nodeType":"Function","startLoc":77,"text":"def test_default_return(self):\n\n current = rcmod.axes_style()\n self.assert_rc_params(current)"},{"col":4,"comment":"null","endLoc":384,"header":"def test_xkcd_palette(self)","id":2779,"name":"test_xkcd_palette","nodeType":"Function","startLoc":378,"text":"def test_xkcd_palette(self):\n\n names = list(xkcd_rgb.keys())[10:15]\n colors = palettes.xkcd_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n assert as_hex == xkcd_rgb[name]"},{"col":4,"comment":"null","endLoc":86,"header":"def test_key_usage(self)","id":2780,"name":"test_key_usage","nodeType":"Function","startLoc":82,"text":"def test_key_usage(self):\n\n _style_keys = set(rcmod._style_keys)\n for style in self.styles:\n assert not set(rcmod.axes_style(style)) ^ _style_keys"},{"col":4,"comment":"null","endLoc":710,"header":"def test_tick_params(self)","id":2781,"name":"test_tick_params","nodeType":"Function","startLoc":699,"text":"def test_tick_params(self):\n\n g = ag.FacetGrid(self.df, row=\"a\", col=\"b\")\n color = \"blue\"\n pad = 3\n g.tick_params(pad=pad, color=color)\n for ax in g.axes.flat:\n for axis in [\"xaxis\", \"yaxis\"]:\n for tick in getattr(ax, axis).get_major_ticks():\n assert mpl.colors.same_color(tick.tick1line.get_color(), color)\n assert mpl.colors.same_color(tick.tick2line.get_color(), color)\n assert tick.get_pad() == pad"},{"col":4,"comment":"null","endLoc":276,"header":"def test_join_remove_variable(self, long_df)","id":2782,"name":"test_join_remove_variable","nodeType":"Function","startLoc":265,"text":"def test_join_remove_variable(self, long_df):\n\n variables = {\"x\": \"x\", \"y\": \"f\"}\n drop_var = \"y\"\n\n p1 = PlotData(long_df, variables)\n p2 = p1.join(None, {drop_var: None})\n\n assert drop_var in p1\n assert drop_var not in p2\n assert drop_var not in p2.frame\n assert drop_var not in p2.names"},{"col":4,"comment":"null","endLoc":291,"header":"def test_join_all_operations(self, long_df)","id":2783,"name":"test_join_all_operations","nodeType":"Function","startLoc":278,"text":"def test_join_all_operations(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\", \"color\": \"a\"}\n v2 = {\"y\": \"s\", \"size\": \"s\", \"color\": None}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(None, v2)\n\n for var, key in v2.items():\n if key is None:\n assert var not in p2\n else:\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])"},{"col":0,"comment":"null","endLoc":44,"header":"def hex_to_husl(hex)","id":2784,"name":"hex_to_husl","nodeType":"Function","startLoc":43,"text":"def hex_to_husl(hex):\n return rgb_to_husl(*hex_to_rgb(hex))"},{"col":0,"comment":"null","endLoc":184,"header":"def hex_to_rgb(hex)","id":2785,"name":"hex_to_rgb","nodeType":"Function","startLoc":178,"text":"def hex_to_rgb(hex):\n if hex.startswith('#'):\n hex = hex[1:]\n r = int(hex[0:2], 16) / 255.0\n g = int(hex[2:4], 16) / 255.0\n b = int(hex[4:6], 16) / 255.0\n return [r, g, b]"},{"col":0,"comment":"Make a palette with color names from the xkcd color survey.\n\n See xkcd for the full list of colors: https://xkcd.com/color/rgb/\n\n This is just a simple wrapper around the `seaborn.xkcd_rgb` dictionary.\n\n Parameters\n ----------\n colors : list of strings\n List of keys in the `seaborn.xkcd_rgb` dictionary.\n\n Returns\n -------\n palette\n A list of colors as RGB tuples.\n\n See Also\n --------\n crayon_palette : Make a palette with Crayola crayon colors.\n\n ","endLoc":635,"header":"def xkcd_palette(colors)","id":2786,"name":"xkcd_palette","nodeType":"Function","startLoc":612,"text":"def xkcd_palette(colors):\n \"\"\"Make a palette with color names from the xkcd color survey.\n\n See xkcd for the full list of colors: https://xkcd.com/color/rgb/\n\n This is just a simple wrapper around the `seaborn.xkcd_rgb` dictionary.\n\n Parameters\n ----------\n colors : list of strings\n List of keys in the `seaborn.xkcd_rgb` dictionary.\n\n Returns\n -------\n palette\n A list of colors as RGB tuples.\n\n See Also\n --------\n crayon_palette : Make a palette with Crayola crayon colors.\n\n \"\"\"\n palette = [xkcd_rgb[name] for name in colors]\n return color_palette(palette, len(palette))"},{"col":4,"comment":"null","endLoc":306,"header":"def test_join_all_operations_same_data(self, long_df)","id":2787,"name":"test_join_all_operations_same_data","nodeType":"Function","startLoc":293,"text":"def test_join_all_operations_same_data(self, long_df):\n\n v1 = {\"x\": \"x\", \"y\": \"y\", \"color\": \"a\"}\n v2 = {\"y\": \"s\", \"size\": \"s\", \"color\": None}\n\n p1 = PlotData(long_df, v1)\n p2 = p1.join(long_df, v2)\n\n for var, key in v2.items():\n if key is None:\n assert var not in p2\n else:\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])"},{"col":4,"comment":"null","endLoc":1936,"header":"def test_mesh_thresh(self, long_df)","id":2788,"name":"test_mesh_thresh","nodeType":"Function","startLoc":1925,"text":"def test_mesh_thresh(self, long_df):\n\n hist = Histogram()\n counts, (x_edges, y_edges) = hist(long_df[\"x\"], long_df[\"y\"])\n\n thresh = 5\n ax = histplot(long_df, x=\"x\", y=\"y\", thresh=thresh)\n mesh = ax.collections[0]\n mesh_data = mesh.get_array()\n\n assert_array_equal(mesh_data.data, counts.T.flat)\n assert_array_equal(mesh_data.mask, (counts <= thresh).T.flat)"},{"col":4,"comment":"null","endLoc":321,"header":"def test_join_add_variable_new_data(self, long_df)","id":2789,"name":"test_join_add_variable_new_data","nodeType":"Function","startLoc":308,"text":"def test_join_add_variable_new_data(self, long_df):\n\n d1 = long_df[[\"x\", \"y\"]]\n d2 = long_df[[\"a\", \"s\"]]\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"color\": \"a\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n for var, key in dict(**v1, **v2).items():\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])"},{"col":0,"comment":"null","endLoc":48,"header":"def huslp_to_rgb(h, s, l)","id":2790,"name":"huslp_to_rgb","nodeType":"Function","startLoc":47,"text":"def huslp_to_rgb(h, s, l):\n return lch_to_rgb(*huslp_to_lch([h, s, l]))"},{"col":0,"comment":"null","endLoc":299,"header":"def huslp_to_lch(triple)","id":2791,"name":"huslp_to_lch","nodeType":"Function","startLoc":288,"text":"def huslp_to_lch(triple):\n H, S, L = triple\n\n if L > 99.9999999:\n return [100, 0.0, H]\n if L < 0.00000001:\n return [0.0, 0.0, H]\n\n mx = max_chroma_pastel(L)\n C = mx / 100.0 * S\n\n return [L, C, H]"},{"col":0,"comment":"null","endLoc":119,"header":"def max_chroma_pastel(L)","id":2792,"name":"max_chroma_pastel","nodeType":"Function","startLoc":117,"text":"def max_chroma_pastel(L):\n H = math.degrees(_hrad_extremum(L))\n return max_chroma(L, H)"},{"col":0,"comment":"null","endLoc":114,"header":"def _hrad_extremum(L)","id":2793,"name":"_hrad_extremum","nodeType":"Function","startLoc":94,"text":"def _hrad_extremum(L):\n lhs = (math.pow(L, 3.0) + 48.0 * math.pow(L, 2.0) + 768.0 * L + 4096.0) / 1560896.0\n rhs = 1107.0 / 125000.0\n sub = lhs if lhs > rhs else 10.0 * L / 9033.0\n chroma = float(\"inf\")\n result = None\n for row in m:\n for limit in (0.0, 1.0):\n [m1, m2, m3] = row\n top = -3015466475.0 * m3 * sub + 603093295.0 * m2 * sub - 603093295.0 * limit\n bottom = 1356959916.0 * m1 * sub - 452319972.0 * m3 * sub\n hrad = math.atan2(top, bottom)\n # This is a math hack to deal with tan quadrants, I'm too lazy to figure\n # out how to do this properly\n if limit == 0.0:\n hrad += math.pi\n test = max_chroma(L, math.degrees(hrad))\n if test < chroma:\n chroma = test\n result = hrad\n return result"},{"col":4,"comment":"null","endLoc":1949,"header":"def test_mesh_sticky_edges(self, long_df)","id":2794,"name":"test_mesh_sticky_edges","nodeType":"Function","startLoc":1938,"text":"def test_mesh_sticky_edges(self, long_df):\n\n ax = histplot(long_df, x=\"x\", y=\"y\", thresh=None)\n mesh = ax.collections[0]\n assert mesh.sticky_edges.x == [long_df[\"x\"].min(), long_df[\"x\"].max()]\n assert mesh.sticky_edges.y == [long_df[\"y\"].min(), long_df[\"y\"].max()]\n\n ax.clear()\n ax = histplot(long_df, x=\"x\", y=\"y\")\n mesh = ax.collections[0]\n assert not mesh.sticky_edges.x\n assert not mesh.sticky_edges.y"},{"col":4,"comment":"Add a dummy patch object so we can get legend data.","endLoc":776,"header":"def add_legend_data(self, ax, color, label)","id":2795,"name":"add_legend_data","nodeType":"Function","startLoc":769,"text":"def add_legend_data(self, ax, color, label):\n \"\"\"Add a dummy patch object so we can get legend data.\"\"\"\n rect = plt.Rectangle([0, 0], 0, 0,\n linewidth=self.linewidth / 2,\n edgecolor=self.gray,\n facecolor=color,\n label=label)\n ax.add_patch(rect)"},{"attributeType":"float","col":4,"comment":"null","endLoc":421,"id":2796,"name":"width","nodeType":"Attribute","startLoc":421,"text":"width"},{"attributeType":"str","col":4,"comment":"null","endLoc":422,"id":2797,"name":"default_palette","nodeType":"Attribute","startLoc":422,"text":"default_palette"},{"col":4,"comment":"null","endLoc":1969,"header":"def test_mesh_common_norm(self, long_df)","id":2798,"name":"test_mesh_common_norm","nodeType":"Function","startLoc":1951,"text":"def test_mesh_common_norm(self, long_df):\n\n stat = \"density\"\n ax = histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\", common_norm=True, stat=stat,\n )\n\n hist = Histogram(stat=\"density\")\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n density, (x_edges, y_edges) = hist(sub_df[\"x\"], sub_df[\"y\"])\n\n scale = len(sub_df) / len(long_df)\n assert_array_equal(mesh_data.data, (density * scale).T.flat)"},{"attributeType":"bool","col":4,"comment":"null","endLoc":423,"id":2799,"name":"require_numeric","nodeType":"Attribute","startLoc":423,"text":"require_numeric"},{"attributeType":"None","col":8,"comment":"null","endLoc":623,"id":2800,"name":"value_label","nodeType":"Attribute","startLoc":623,"text":"self.value_label"},{"col":0,"comment":"null","endLoc":52,"header":"def huslp_to_hex(h, s, l)","id":2801,"name":"huslp_to_hex","nodeType":"Function","startLoc":51,"text":"def huslp_to_hex(h, s, l):\n return rgb_to_hex(huslp_to_rgb(h, s, l))"},{"col":0,"comment":"null","endLoc":56,"header":"def rgb_to_huslp(r, g, b)","id":2802,"name":"rgb_to_huslp","nodeType":"Function","startLoc":55,"text":"def rgb_to_huslp(r, g, b):\n return lch_to_huslp(rgb_to_lch(r, g, b))"},{"className":"TestScatterPlotter","col":0,"comment":"null","endLoc":1839,"id":2803,"nodeType":"Class","startLoc":1295,"text":"class TestScatterPlotter(SharedAxesLevelTests, Helpers):\n\n func = staticmethod(scatterplot)\n\n def get_last_color(self, ax):\n\n colors = ax.collections[-1].get_facecolors()\n unique_colors = np.unique(colors, axis=0)\n assert len(unique_colors) == 1\n return to_rgba(unique_colors.squeeze())\n\n def test_color(self, long_df):\n\n super().test_color(long_df)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", facecolor=\"C5\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C5\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", facecolors=\"C6\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C6\")\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", fc=\"C4\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C4\")\n\n def test_legend_data(self, long_df):\n\n m = mpl.markers.MarkerStyle(\"o\")\n default_mark = m.get_path().transformed(m.get_transform())\n\n m = mpl.markers.MarkerStyle(\"\")\n null = m.get_path().transformed(m.get_transform())\n\n f, ax = plt.subplots()\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert handles == []\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n assert labels == p._hue_map.levels\n assert same_color(colors, expected_colors)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n paths = [h.get_paths()[0] for h in handles]\n expected_paths = p._style_map(p._style_map.levels, \"path\")\n assert labels == p._hue_map.levels\n assert labels == p._style_map.levels\n assert same_color(colors, expected_colors)\n assert self.paths_equal(paths, expected_paths)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n paths = [h.get_paths()[0] for h in handles]\n expected_colors = (\n [\"w\"] + p._hue_map(p._hue_map.levels)\n + [\"w\"] + [\".2\" for _ in p._style_map.levels]\n )\n expected_paths = (\n [null] + [default_mark for _ in p._hue_map.levels]\n + [null] + p._style_map(p._style_map.levels, \"path\")\n )\n assert labels == (\n [\"a\"] + p._hue_map.levels + [\"b\"] + p._style_map.levels\n )\n assert same_color(colors, expected_colors)\n assert self.paths_equal(paths, expected_paths)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"a\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == p._hue_map.levels\n assert labels == p._size_map.levels\n assert same_color(colors, expected_colors)\n assert sizes == expected_sizes\n\n # --\n\n ax.clear()\n sizes_list = [10, 100, 200]\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n legend=\"full\",\n )\n p.map_size(sizes=sizes_list)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == [str(l) for l in p._size_map.levels]\n assert sizes == expected_sizes\n\n # --\n\n ax.clear()\n sizes_dict = {2: 10, 4: 100, 8: 200}\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n legend=\"full\"\n )\n p.map_size(sizes=sizes_dict)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == [str(l) for l in p._size_map.levels]\n assert sizes == expected_sizes\n\n # --\n\n x, y = np.random.randn(2, 40)\n z = np.tile(np.arange(20), 2)\n\n p = _ScatterPlotter(\n variables=dict(x=x, y=y, hue=z),\n )\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._hue_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._hue_map.levels)\n\n p = _ScatterPlotter(\n variables=dict(x=x, y=y, size=z),\n )\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._size_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"bad_value\"\n with pytest.raises(ValueError):\n p.add_legend_data(ax)\n\n def test_plot(self, long_df, repeated_df):\n\n f, ax = plt.subplots()\n\n p = _ScatterPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p.plot(ax, {})\n points = ax.collections[0]\n assert_array_equal(points.get_offsets(), long_df[[\"x\", \"y\"]].to_numpy())\n\n ax.clear()\n p.plot(ax, {\"color\": \"k\", \"label\": \"test\"})\n points = ax.collections[0]\n assert same_color(points.get_facecolor(), \"k\")\n assert points.get_label() == \"test\"\n\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_colors = p._hue_map(p.plot_data[\"hue\"])\n assert same_color(points.get_facecolors(), expected_colors)\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"c\"),\n )\n p.map_style(markers=[\"+\", \"x\"])\n\n ax.clear()\n color = (1, .3, .8)\n p.plot(ax, {\"color\": color})\n points = ax.collections[0]\n assert same_color(points.get_edgecolors(), [color])\n\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_sizes = p._size_map(p.plot_data[\"size\"])\n assert_array_equal(points.get_sizes(), expected_sizes)\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_colors = p._hue_map(p.plot_data[\"hue\"])\n expected_paths = p._style_map(p.plot_data[\"style\"], \"path\")\n assert same_color(points.get_facecolors(), expected_colors)\n assert self.paths_equal(points.get_paths(), expected_paths)\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n )\n p.map_style(markers=True)\n\n ax.clear()\n p.plot(ax, {})\n points = ax.collections[0]\n expected_colors = p._hue_map(p.plot_data[\"hue\"])\n expected_paths = p._style_map(p.plot_data[\"style\"], \"path\")\n assert same_color(points.get_facecolors(), expected_colors)\n assert self.paths_equal(points.get_paths(), expected_paths)\n\n x_str = long_df[\"x\"].astype(str)\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n p = _ScatterPlotter(\n data=long_df, variables=dict(x=\"x\", y=\"y\", size=x_str),\n )\n ax.clear()\n p.plot(ax, {})\n\n def test_axis_labels(self, long_df):\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n p = _ScatterPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p.plot(ax1, {})\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n\n p.plot(ax2, {})\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()\n\n def test_scatterplot_axes(self, wide_df):\n\n f1, ax1 = plt.subplots()\n f2, ax2 = plt.subplots()\n\n ax = scatterplot(data=wide_df)\n assert ax is ax2\n\n ax = scatterplot(data=wide_df, ax=ax1)\n assert ax is ax1\n\n def test_literal_attribute_vectors(self):\n\n f, ax = plt.subplots()\n\n x = y = [1, 2, 3]\n s = [5, 10, 15]\n c = [(1, 1, 0, 1), (1, 0, 1, .5), (.5, 1, 0, 1)]\n\n scatterplot(x=x, y=y, c=c, s=s, ax=ax)\n\n points, = ax.collections\n\n assert_array_equal(points.get_sizes().squeeze(), s)\n assert_array_equal(points.get_facecolors(), c)\n\n def test_supplied_color_array(self, long_df):\n\n cmap = get_colormap(\"Blues\")\n norm = mpl.colors.Normalize()\n colors = cmap(norm(long_df[\"y\"].to_numpy()))\n\n keys = [\"c\", \"facecolor\", \"facecolors\"]\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n keys.append(\"fc\")\n\n for key in keys:\n\n ax = plt.figure().subplots()\n scatterplot(data=long_df, x=\"x\", y=\"y\", **{key: colors})\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n ax = plt.figure().subplots()\n scatterplot(data=long_df, x=\"x\", y=\"y\", c=long_df[\"y\"], cmap=cmap)\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n def test_hue_order(self, long_df):\n\n order = categorical_order(long_df[\"a\"])\n unused = order.pop()\n\n ax = scatterplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", hue_order=order)\n points = ax.collections[0]\n assert (points.get_facecolors()[long_df[\"a\"] == unused] == 0).all()\n assert [t.get_text() for t in ax.legend_.texts] == order\n\n def test_linewidths(self, long_df):\n\n f, ax = plt.subplots()\n\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=10)\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=20)\n points1, points2 = ax.collections\n assert (\n points1.get_linewidths().item() < points2.get_linewidths().item()\n )\n\n ax.clear()\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=long_df[\"x\"])\n scatterplot(data=long_df, x=\"x\", y=\"y\", s=long_df[\"x\"] * 2)\n points1, points2 = ax.collections\n assert (\n points1.get_linewidths().item() < points2.get_linewidths().item()\n )\n\n ax.clear()\n scatterplot(data=long_df, x=\"x\", y=\"y\", size=long_df[\"x\"])\n scatterplot(data=long_df, x=\"x\", y=\"y\", size=long_df[\"x\"] * 2)\n points1, points2, *_ = ax.collections\n assert (\n points1.get_linewidths().item() < points2.get_linewidths().item()\n )\n\n ax.clear()\n lw = 2\n scatterplot(data=long_df, x=\"x\", y=\"y\", linewidth=lw)\n assert ax.collections[0].get_linewidths().item() == lw\n\n def test_size_norm_extrapolation(self):\n\n # https://github.com/mwaskom/seaborn/issues/2539\n x = np.arange(0, 20, 2)\n f, axs = plt.subplots(1, 2, sharex=True, sharey=True)\n\n slc = 5\n kws = dict(sizes=(50, 200), size_norm=(0, x.max()), legend=\"brief\")\n\n scatterplot(x=x, y=x, size=x, ax=axs[0], **kws)\n scatterplot(x=x[:slc], y=x[:slc], size=x[:slc], ax=axs[1], **kws)\n\n assert np.allclose(\n axs[0].collections[0].get_sizes()[:slc],\n axs[1].collections[0].get_sizes()\n )\n\n legends = [ax.legend_ for ax in axs]\n legend_data = [\n {\n label.get_text(): handle.get_sizes().item()\n for label, handle in zip(legend.get_texts(), legend.legendHandles)\n } for legend in legends\n ]\n\n for key in set(legend_data[0]) & set(legend_data[1]):\n if key == \"y\":\n # At some point (circa 3.0) matplotlib auto-added pandas series\n # with a valid name into the legend, which messes up this test.\n # I can't track down when that was added (or removed), so let's\n # just anticipate and ignore it here.\n continue\n assert legend_data[0][key] == legend_data[1][key]\n\n def test_datetime_scale(self, long_df):\n\n ax = scatterplot(data=long_df, x=\"t\", y=\"y\")\n # Check that we avoid weird matplotlib default auto scaling\n # https://github.com/matplotlib/matplotlib/issues/17586\n ax.get_xlim()[0] > ax.xaxis.convert_units(np.datetime64(\"2002-01-01\"))\n\n def test_unfilled_marker_edgecolor_warning(self, long_df): # GH2636\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n scatterplot(data=long_df, x=\"x\", y=\"y\", marker=\"+\")\n\n def test_scatterplot_vs_relplot(self, long_df, long_semantics):\n\n ax = scatterplot(data=long_df, **long_semantics)\n g = relplot(data=long_df, kind=\"scatter\", **long_semantics)\n\n for s_pts, r_pts in zip(ax.collections, g.ax.collections):\n\n assert_array_equal(s_pts.get_offsets(), r_pts.get_offsets())\n assert_array_equal(s_pts.get_sizes(), r_pts.get_sizes())\n assert_array_equal(s_pts.get_facecolors(), r_pts.get_facecolors())\n assert self.paths_equal(s_pts.get_paths(), r_pts.get_paths())\n\n def test_scatterplot_smoke(\n self,\n wide_df, wide_array,\n flat_series, flat_array, flat_list,\n wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n long_df, missing_df, object_df\n ):\n\n f, ax = plt.subplots()\n\n scatterplot(x=[], y=[])\n ax.clear()\n\n scatterplot(data=wide_df)\n ax.clear()\n\n scatterplot(data=wide_array)\n ax.clear()\n\n scatterplot(data=wide_list_of_series)\n ax.clear()\n\n scatterplot(data=wide_list_of_arrays)\n ax.clear()\n\n scatterplot(data=wide_list_of_lists)\n ax.clear()\n\n scatterplot(data=flat_series)\n ax.clear()\n\n scatterplot(data=flat_array)\n ax.clear()\n\n scatterplot(data=flat_list)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", data=long_df)\n ax.clear()\n\n scatterplot(x=long_df.x, y=long_df.y)\n ax.clear()\n\n scatterplot(x=long_df.x, y=\"y\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=long_df.y.to_numpy(), data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=long_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=missing_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"f\", data=object_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"c\", size=\"f\", data=object_df)\n ax.clear()\n\n scatterplot(x=\"x\", y=\"y\", hue=\"f\", size=\"s\", data=object_df)\n ax.clear()"},{"col":0,"comment":"null","endLoc":313,"header":"def lch_to_huslp(triple)","id":2804,"name":"lch_to_huslp","nodeType":"Function","startLoc":302,"text":"def lch_to_huslp(triple):\n L, C, H = triple\n\n if L > 99.9999999:\n return [H, 0.0, 100.0]\n if L < 0.00000001:\n return [H, 0.0, 0.0]\n\n mx = max_chroma_pastel(L)\n S = C / mx * 100.0\n\n return [H, S, L]"},{"attributeType":"null","col":4,"comment":"null","endLoc":31,"id":2805,"name":"df","nodeType":"Attribute","startLoc":31,"text":"df"},{"className":"TestPairGrid","col":0,"comment":"null","endLoc":1458,"id":2806,"nodeType":"Class","startLoc":713,"text":"class TestPairGrid:\n\n rs = np.random.RandomState(sum(map(ord, \"PairGrid\")))\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n y=rs.randint(0, 4, size=(60)),\n z=rs.gamma(3, size=60),\n a=np.repeat(list(\"abc\"), 20),\n b=np.repeat(list(\"abcdefghijkl\"), 5)))\n\n def test_self_data(self):\n\n g = ag.PairGrid(self.df)\n assert g.data is self.df\n\n def test_ignore_datelike_data(self):\n\n df = self.df.copy()\n df['date'] = pd.date_range('2010-01-01', periods=len(df), freq='d')\n result = ag.PairGrid(self.df).data\n expected = df.drop('date', axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_self_figure(self):\n\n g = ag.PairGrid(self.df)\n assert isinstance(g.figure, plt.Figure)\n assert g.figure is g._figure\n\n def test_self_axes(self):\n\n g = ag.PairGrid(self.df)\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)\n\n def test_default_axes(self):\n\n g = ag.PairGrid(self.df)\n assert g.axes.shape == (3, 3)\n assert g.x_vars == [\"x\", \"y\", \"z\"]\n assert g.y_vars == [\"x\", \"y\", \"z\"]\n assert g.square_grid\n\n @pytest.mark.parametrize(\"vars\", [[\"z\", \"x\"], np.array([\"z\", \"x\"])])\n def test_specific_square_axes(self, vars):\n\n g = ag.PairGrid(self.df, vars=vars)\n assert g.axes.shape == (len(vars), len(vars))\n assert g.x_vars == list(vars)\n assert g.y_vars == list(vars)\n assert g.square_grid\n\n def test_remove_hue_from_default(self):\n\n hue = \"z\"\n g = ag.PairGrid(self.df, hue=hue)\n assert hue not in g.x_vars\n assert hue not in g.y_vars\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, hue=hue, vars=vars)\n assert hue in g.x_vars\n assert hue in g.y_vars\n\n @pytest.mark.parametrize(\n \"x_vars, y_vars\",\n [\n ([\"x\", \"y\"], [\"z\", \"y\", \"x\"]),\n ([\"x\", \"y\"], \"z\"),\n (np.array([\"x\", \"y\"]), np.array([\"z\", \"y\", \"x\"])),\n ],\n )\n def test_specific_nonsquare_axes(self, x_vars, y_vars):\n\n g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n assert g.axes.shape == (len(y_vars), len(x_vars))\n assert g.x_vars == list(x_vars)\n assert g.y_vars == list(y_vars)\n assert not g.square_grid\n\n def test_corner(self):\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=plot_vars, corner=True)\n corner_size = sum(i + 1 for i in range(len(plot_vars)))\n assert len(g.figure.axes) == corner_size\n\n g.map_diag(plt.hist)\n assert len(g.figure.axes) == (corner_size + len(plot_vars))\n\n for ax in np.diag(g.axes):\n assert not ax.yaxis.get_visible()\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=plot_vars, corner=True)\n g.map(scatterplot)\n assert len(g.figure.axes) == corner_size\n assert g.axes[0, 0].get_ylabel() == \"x\"\n\n def test_size(self):\n\n g1 = ag.PairGrid(self.df, height=3)\n npt.assert_array_equal(g1.fig.get_size_inches(), (9, 9))\n\n g2 = ag.PairGrid(self.df, height=4, aspect=.5)\n npt.assert_array_equal(g2.fig.get_size_inches(), (6, 12))\n\n g3 = ag.PairGrid(self.df, y_vars=[\"z\"], x_vars=[\"x\", \"y\"],\n height=2, aspect=2)\n npt.assert_array_equal(g3.fig.get_size_inches(), (8, 2))\n\n def test_empty_grid(self):\n\n with pytest.raises(ValueError, match=\"No variables found\"):\n ag.PairGrid(self.df[[\"a\", \"b\"]])\n\n def test_map(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g1 = ag.PairGrid(self.df)\n g1.map(plt.scatter)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n g2 = ag.PairGrid(self.df, hue=\"a\")\n g2.map(plt.scatter)\n\n for i, axes_i in enumerate(g2.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n for k, k_level in enumerate(self.df.a.unique()):\n x_in_k = x_in[self.df.a == k_level]\n y_in_k = y_in[self.df.a == k_level]\n x_out, y_out = ax.collections[k].get_offsets().T\n npt.assert_array_equal(x_in_k, x_out)\n npt.assert_array_equal(y_in_k, y_out)\n\n def test_map_nonsquare(self):\n\n x_vars = [\"x\"]\n y_vars = [\"y\", \"z\"]\n g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g.map(plt.scatter)\n\n x_in = self.df.x\n for i, i_var in enumerate(y_vars):\n ax = g.axes[i, 0]\n y_in = self.df[i_var]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n def test_map_lower(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_lower(plt.scatter)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.triu_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_map_upper(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_upper(plt.scatter)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_map_mixed_funcsig(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=vars)\n g.map_lower(scatterplot)\n g.map_upper(plt.scatter)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n def test_map_diag(self):\n\n g = ag.PairGrid(self.df)\n g.map_diag(plt.hist)\n\n for var, ax in zip(g.diag_vars, g.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist)\n\n for ax in g.diag_axes:\n assert len(ax.patches) == 30\n\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist, histtype='step')\n\n for ax in g.diag_axes:\n for ptch in ax.patches:\n assert not ptch.fill\n\n def test_map_diag_rectangular(self):\n\n x_vars = [\"x\", \"y\"]\n y_vars = [\"x\", \"z\", \"y\"]\n g1 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g1.map_diag(plt.hist)\n g1.map_offdiag(plt.scatter)\n\n assert set(g1.diag_vars) == (set(x_vars) & set(y_vars))\n\n for var, ax in zip(g1.diag_vars, g1.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n for j, x_var in enumerate(x_vars):\n for i, y_var in enumerate(y_vars):\n\n ax = g1.axes[i, j]\n if x_var == y_var:\n diag_ax = g1.diag_axes[j] # because fewer x than y vars\n assert ax.bbox.bounds == diag_ax.bbox.bounds\n\n else:\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, self.df[x_var])\n assert_array_equal(y, self.df[y_var])\n\n g2 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars, hue=\"a\")\n g2.map_diag(plt.hist)\n g2.map_offdiag(plt.scatter)\n\n assert set(g2.diag_vars) == (set(x_vars) & set(y_vars))\n\n for ax in g2.diag_axes:\n assert len(ax.patches) == 30\n\n x_vars = [\"x\", \"y\", \"z\"]\n y_vars = [\"x\", \"z\"]\n g3 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g3.map_diag(plt.hist)\n g3.map_offdiag(plt.scatter)\n\n assert set(g3.diag_vars) == (set(x_vars) & set(y_vars))\n\n for var, ax in zip(g3.diag_vars, g3.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n for j, x_var in enumerate(x_vars):\n for i, y_var in enumerate(y_vars):\n\n ax = g3.axes[i, j]\n if x_var == y_var:\n diag_ax = g3.diag_axes[i] # because fewer y than x vars\n assert ax.bbox.bounds == diag_ax.bbox.bounds\n else:\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, self.df[x_var])\n assert_array_equal(y, self.df[y_var])\n\n def test_map_diag_color(self):\n\n color = \"red\"\n\n g1 = ag.PairGrid(self.df)\n g1.map_diag(plt.hist, color=color)\n\n for ax in g1.diag_axes:\n for patch in ax.patches:\n assert_colors_equal(patch.get_facecolor(), color)\n\n g2 = ag.PairGrid(self.df)\n g2.map_diag(kdeplot, color='red')\n\n for ax in g2.diag_axes:\n for line in ax.lines:\n assert_colors_equal(line.get_color(), color)\n\n def test_map_diag_palette(self):\n\n palette = \"muted\"\n pal = color_palette(palette, n_colors=len(self.df.a.unique()))\n g = ag.PairGrid(self.df, hue=\"a\", palette=palette)\n g.map_diag(kdeplot)\n\n for ax in g.diag_axes:\n for line, color in zip(ax.lines[::-1], pal):\n assert_colors_equal(line.get_color(), color)\n\n def test_map_diag_and_offdiag(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_offdiag(plt.scatter)\n g.map_diag(plt.hist)\n\n for ax in g.diag_axes:\n assert len(ax.patches) == 10\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_diag_sharey(self):\n\n g = ag.PairGrid(self.df, diag_sharey=True)\n g.map_diag(kdeplot)\n for ax in g.diag_axes[1:]:\n assert ax.get_ylim() == g.diag_axes[0].get_ylim()\n\n def test_map_diag_matplotlib(self):\n\n bins = 10\n g = ag.PairGrid(self.df)\n g.map_diag(plt.hist, bins=bins)\n for ax in g.diag_axes:\n assert len(ax.patches) == bins\n\n levels = len(self.df[\"a\"].unique())\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist, bins=bins)\n for ax in g.diag_axes:\n assert len(ax.patches) == (bins * levels)\n\n def test_palette(self):\n\n rcmod.set()\n\n g = ag.PairGrid(self.df, hue=\"a\")\n assert g.palette == color_palette(n_colors=len(self.df.a.unique()))\n\n g = ag.PairGrid(self.df, hue=\"b\")\n assert g.palette == color_palette(\"husl\", len(self.df.b.unique()))\n\n g = ag.PairGrid(self.df, hue=\"a\", palette=\"Set2\")\n assert g.palette == color_palette(\"Set2\", len(self.df.a.unique()))\n\n dict_pal = dict(a=\"red\", b=\"green\", c=\"blue\")\n list_pal = color_palette([\"red\", \"green\", \"blue\"])\n g = ag.PairGrid(self.df, hue=\"a\", palette=dict_pal)\n assert g.palette == list_pal\n\n list_pal = color_palette([\"blue\", \"red\", \"green\"])\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=list(\"cab\"),\n palette=dict_pal)\n assert g.palette == list_pal\n\n def test_hue_kws(self):\n\n kws = dict(marker=[\"o\", \"s\", \"d\", \"+\"])\n g = ag.PairGrid(self.df, hue=\"a\", hue_kws=kws)\n g.map(plt.plot)\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_kws=kws,\n hue_order=list(\"dcab\"))\n g.map(plt.plot)\n\n for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n assert line.get_marker() == marker\n\n def test_hue_order(self):\n\n order = list(\"dcab\")\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_diag(plt.plot)\n\n for line, level in zip(g.axes[0, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_lower(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_upper(plt.plot)\n\n for line, level in zip(g.axes[0, 1].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"y\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n def test_hue_order_missing_level(self):\n\n order = list(\"dcaeb\")\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_diag(plt.plot)\n\n for line, level in zip(g.axes[0, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_lower(plt.plot)\n\n for line, level in zip(g.axes[1, 0].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n plt.close(\"all\")\n\n g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n g.map_upper(plt.plot)\n\n for line, level in zip(g.axes[0, 1].lines, order):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"y\"])\n npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n plt.close(\"all\")\n\n def test_hue_in_map(self, long_df):\n\n g = ag.PairGrid(long_df, vars=[\"x\", \"y\"])\n g.map(scatterplot, hue=long_df[\"a\"])\n ax = g.axes.flat[0]\n points = ax.collections[0]\n assert len(set(map(tuple, points.get_facecolors()))) == 3\n\n def test_nondefault_index(self):\n\n df = self.df.copy().set_index(\"b\")\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g1 = ag.PairGrid(df)\n g1.map(plt.scatter)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[plot_vars[j]]\n y_in = self.df[plot_vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n g2 = ag.PairGrid(df, hue=\"a\")\n g2.map(plt.scatter)\n\n for i, axes_i in enumerate(g2.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[plot_vars[j]]\n y_in = self.df[plot_vars[i]]\n for k, k_level in enumerate(self.df.a.unique()):\n x_in_k = x_in[self.df.a == k_level]\n y_in_k = y_in[self.df.a == k_level]\n x_out, y_out = ax.collections[k].get_offsets().T\n npt.assert_array_equal(x_in_k, x_out)\n npt.assert_array_equal(y_in_k, y_out)\n\n @pytest.mark.parametrize(\"func\", [scatterplot, plt.scatter])\n def test_dropna(self, func):\n\n df = self.df.copy()\n n_null = 20\n df.loc[np.arange(n_null), \"x\"] = np.nan\n\n plot_vars = [\"x\", \"y\", \"z\"]\n\n g1 = ag.PairGrid(df, vars=plot_vars, dropna=True)\n g1.map(func)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = df[plot_vars[j]]\n y_in = df[plot_vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n\n n_valid = (x_in * y_in).notnull().sum()\n\n assert n_valid == len(x_out)\n assert n_valid == len(y_out)\n\n g1.map_diag(histplot)\n for i, ax in enumerate(g1.diag_axes):\n var = plot_vars[i]\n count = sum(p.get_height() for p in ax.patches)\n assert count == df[var].notna().sum()\n\n def test_histplot_legend(self):\n\n # Tests _extract_legend_handles\n g = ag.PairGrid(self.df, vars=[\"x\", \"y\"], hue=\"a\")\n g.map_offdiag(histplot)\n g.add_legend()\n\n assert len(g._legend.legendHandles) == len(self.df[\"a\"].unique())\n\n def test_pairplot(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.pairplot(self.df)\n\n for ax in g.diag_axes:\n assert len(ax.patches) > 1\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n g = ag.pairplot(self.df, hue=\"a\")\n n = len(self.df.a.unique())\n\n for ax in g.diag_axes:\n assert len(ax.collections) == n\n\n def test_pairplot_reg(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.pairplot(self.df, diag_kind=\"hist\", kind=\"reg\")\n\n for ax in g.diag_axes:\n assert len(ax.patches)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_pairplot_reg_hue(self):\n\n markers = [\"o\", \"s\", \"d\"]\n g = ag.pairplot(self.df, kind=\"reg\", hue=\"a\", markers=markers)\n\n ax = g.axes[-1, 0]\n c1 = ax.collections[0]\n c2 = ax.collections[2]\n\n assert not np.array_equal(c1.get_facecolor(), c2.get_facecolor())\n assert not np.array_equal(\n c1.get_paths()[0].vertices, c2.get_paths()[0].vertices,\n )\n\n def test_pairplot_diag_kde(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.pairplot(self.df, diag_kind=\"kde\")\n\n for ax in g.diag_axes:\n assert len(ax.collections) == 1\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.diag_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0\n\n def test_pairplot_kde(self):\n\n f, ax1 = plt.subplots()\n kdeplot(data=self.df, x=\"x\", y=\"y\", ax=ax1)\n\n g = ag.pairplot(self.df, kind=\"kde\")\n ax2 = g.axes[1, 0]\n\n assert_plots_equal(ax1, ax2, labels=False)\n\n def test_pairplot_hist(self):\n\n f, ax1 = plt.subplots()\n histplot(data=self.df, x=\"x\", y=\"y\", ax=ax1)\n\n g = ag.pairplot(self.df, kind=\"hist\")\n ax2 = g.axes[1, 0]\n\n assert_plots_equal(ax1, ax2, labels=False)\n\n def test_pairplot_markers(self):\n\n vars = [\"x\", \"y\", \"z\"]\n markers = [\"o\", \"X\", \"s\"]\n g = ag.pairplot(self.df, hue=\"a\", vars=vars, markers=markers)\n m1 = g._legend.legendHandles[0].get_paths()[0]\n m2 = g._legend.legendHandles[1].get_paths()[0]\n assert m1 != m2\n\n with pytest.warns(UserWarning):\n g = ag.pairplot(self.df, hue=\"a\", vars=vars, markers=markers[:-2])\n\n def test_corner_despine(self):\n\n g = ag.PairGrid(self.df, corner=True, despine=False)\n g.map_diag(histplot)\n assert g.axes[0, 0].spines[\"top\"].get_visible()\n\n def test_corner_set(self):\n\n g = ag.PairGrid(self.df, corner=True, despine=False)\n g.set(xlim=(0, 10))\n assert g.axes[-1, 0].get_xlim() == (0, 10)\n\n def test_legend(self):\n\n g1 = ag.pairplot(self.df, hue=\"a\")\n assert isinstance(g1.legend, mpl.legend.Legend)\n\n g2 = ag.pairplot(self.df)\n assert g2.legend is None\n\n def test_tick_params(self):\n\n g = ag.PairGrid(self.df)\n color = \"red\"\n pad = 3\n g.tick_params(pad=pad, color=color)\n for ax in g.axes.flat:\n for axis in [\"xaxis\", \"yaxis\"]:\n for tick in getattr(ax, axis).get_major_ticks():\n assert mpl.colors.same_color(tick.tick1line.get_color(), color)\n assert mpl.colors.same_color(tick.tick2line.get_color(), color)\n assert tick.get_pad() == pad"},{"col":0,"comment":"null","endLoc":60,"header":"def hex_to_huslp(hex)","id":2807,"name":"hex_to_huslp","nodeType":"Function","startLoc":59,"text":"def hex_to_huslp(hex):\n return rgb_to_huslp(*hex_to_rgb(hex))"},{"col":0,"comment":"null","endLoc":144,"header":"def from_linear(c)","id":2808,"name":"from_linear","nodeType":"Function","startLoc":140,"text":"def from_linear(c):\n if c <= 0.0031308:\n return 12.92 * c\n else:\n return (1.055 * math.pow(c, 1.0 / 2.4) - 0.055)"},{"col":4,"comment":"null","endLoc":1304,"header":"def get_last_color(self, ax)","id":2809,"name":"get_last_color","nodeType":"Function","startLoc":1299,"text":"def get_last_color(self, ax):\n\n colors = ax.collections[-1].get_facecolors()\n unique_colors = np.unique(colors, axis=0)\n assert len(unique_colors) == 1\n return to_rgba(unique_colors.squeeze())"},{"col":4,"comment":"null","endLoc":725,"header":"def test_self_data(self)","id":2810,"name":"test_self_data","nodeType":"Function","startLoc":722,"text":"def test_self_data(self):\n\n g = ag.PairGrid(self.df)\n assert g.data is self.df"},{"col":4,"comment":"null","endLoc":733,"header":"def test_ignore_datelike_data(self)","id":2811,"name":"test_ignore_datelike_data","nodeType":"Function","startLoc":727,"text":"def test_ignore_datelike_data(self):\n\n df = self.df.copy()\n df['date'] = pd.date_range('2010-01-01', periods=len(df), freq='d')\n result = ag.PairGrid(self.df).data\n expected = df.drop('date', axis=1)\n tm.assert_frame_equal(result, expected)"},{"col":4,"comment":"null","endLoc":1323,"header":"def test_color(self, long_df)","id":2812,"name":"test_color","nodeType":"Function","startLoc":1306,"text":"def test_color(self, long_df):\n\n super().test_color(long_df)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", facecolor=\"C5\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C5\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", facecolors=\"C6\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C6\")\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"x\", y=\"y\", fc=\"C4\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C4\")"},{"col":4,"comment":"null","endLoc":1358,"header":"def _plot_layer(self, p: Plot, layer: Layer) -> None","id":2813,"name":"_plot_layer","nodeType":"Function","startLoc":1290,"text":"def _plot_layer(self, p: Plot, layer: Layer) -> None:\n\n data = layer[\"data\"]\n mark = layer[\"mark\"]\n move = layer[\"move\"]\n\n default_grouping_vars = [\"col\", \"row\", \"group\"] # TODO where best to define?\n grouping_properties = [v for v in PROPERTIES if v[0] not in \"xy\"]\n\n pair_variables = p._pair_spec.get(\"structure\", {})\n\n for subplots, df, scales in self._generate_pairings(data, pair_variables):\n\n orient = layer[\"orient\"] or mark._infer_orient(scales)\n\n def get_order(var):\n # Ignore order for x/y: they have been scaled to numeric indices,\n # so any original order is no longer valid. Default ordering rules\n # sorted unique numbers will correctly reconstruct intended order\n # TODO This is tricky, make sure we add some tests for this\n if var not in \"xy\" and var in scales:\n return getattr(scales[var], \"order\", None)\n\n if \"width\" in mark._mappable_props:\n width = mark._resolve(df, \"width\", None)\n else:\n width = 0.8 if \"width\" not in df else df[\"width\"] # TODO what default?\n if orient in df:\n df[\"width\"] = width * scales[orient]._spacing(df[orient])\n\n if \"baseline\" in mark._mappable_props:\n # TODO what marks should have this?\n # If we can set baseline with, e.g., Bar(), then the\n # \"other\" (e.g. y for x oriented bars) parameterization\n # is somewhat ambiguous.\n baseline = mark._resolve(df, \"baseline\", None)\n else:\n # TODO unlike width, we might not want to add baseline to data\n # if the mark doesn't use it. Practically, there is a concern about\n # Mark abstraction like Area / Ribbon\n baseline = 0 if \"baseline\" not in df else df[\"baseline\"]\n df[\"baseline\"] = baseline\n\n if move is not None:\n moves = move if isinstance(move, list) else [move]\n for move_step in moves:\n move_by = getattr(move_step, \"by\", None)\n if move_by is None:\n move_by = grouping_properties\n move_groupers = [*move_by, *default_grouping_vars]\n if move_step.group_by_orient:\n move_groupers.insert(0, orient)\n order = {var: get_order(var) for var in move_groupers}\n groupby = GroupBy(order)\n df = move_step(df, groupby, orient, scales)\n\n df = self._unscale_coords(subplots, df, orient)\n\n grouping_vars = mark._grouping_props + default_grouping_vars\n split_generator = self._setup_split_generator(grouping_vars, df, subplots)\n\n mark._plot(split_generator, scales, orient)\n\n # TODO is this the right place for this?\n for view in self._subplots:\n view[\"ax\"].autoscale_view()\n\n if layer[\"legend\"]:\n self._update_legend_contents(p, mark, data, scales)"},{"col":0,"comment":"null","endLoc":153,"header":"def to_linear(c)","id":2814,"name":"to_linear","nodeType":"Function","startLoc":147,"text":"def to_linear(c):\n a = 0.055\n\n if c > 0.04045:\n return (math.pow((c + a) / (1.0 + a), 2.4))\n else:\n return (c / 12.92)"},{"attributeType":"str","col":0,"comment":"null","endLoc":4,"id":2815,"name":"__version__","nodeType":"Attribute","startLoc":4,"text":"__version__"},{"attributeType":"list","col":0,"comment":"null","endLoc":7,"id":2816,"name":"m","nodeType":"Attribute","startLoc":7,"text":"m"},{"col":4,"comment":"null","endLoc":739,"header":"def test_self_figure(self)","id":2817,"name":"test_self_figure","nodeType":"Function","startLoc":735,"text":"def test_self_figure(self):\n\n g = ag.PairGrid(self.df)\n assert isinstance(g.figure, plt.Figure)\n assert g.figure is g._figure"},{"col":0,"comment":"null","endLoc":46,"header":"@pytest.fixture\ndef flat_series(rng)","id":2818,"name":"flat_series","nodeType":"Function","startLoc":42,"text":"@pytest.fixture\ndef flat_series(rng):\n\n index = pd.RangeIndex(10, 30, name=\"t\")\n return pd.Series(rng.normal(size=20), index, name=\"s\")"},{"attributeType":"list","col":0,"comment":"null","endLoc":13,"id":2819,"name":"m_inv","nodeType":"Attribute","startLoc":13,"text":"m_inv"},{"col":4,"comment":"null","endLoc":745,"header":"def test_self_axes(self)","id":2820,"name":"test_self_axes","nodeType":"Function","startLoc":741,"text":"def test_self_axes(self):\n\n g = ag.PairGrid(self.df)\n for ax in g.axes.flat:\n assert isinstance(ax, plt.Axes)"},{"attributeType":"float","col":0,"comment":"null","endLoc":20,"id":2821,"name":"refX","nodeType":"Attribute","startLoc":20,"text":"refX"},{"attributeType":"float","col":0,"comment":"null","endLoc":21,"id":2822,"name":"refY","nodeType":"Attribute","startLoc":21,"text":"refY"},{"attributeType":"float","col":0,"comment":"null","endLoc":22,"id":2823,"name":"refZ","nodeType":"Attribute","startLoc":22,"text":"refZ"},{"attributeType":"float","col":0,"comment":"null","endLoc":23,"id":2824,"name":"refU","nodeType":"Attribute","startLoc":23,"text":"refU"},{"attributeType":"float","col":0,"comment":"null","endLoc":24,"id":2825,"name":"refV","nodeType":"Attribute","startLoc":24,"text":"refV"},{"attributeType":"float","col":0,"comment":"null","endLoc":25,"id":2826,"name":"lab_e","nodeType":"Attribute","startLoc":25,"text":"lab_e"},{"attributeType":"float","col":0,"comment":"null","endLoc":26,"id":2827,"name":"lab_k","nodeType":"Attribute","startLoc":26,"text":"lab_k"},{"col":0,"comment":"","endLoc":1,"header":"husl.py#","id":2828,"name":"","nodeType":"Function","startLoc":1,"text":"__version__ = \"2.1.0\"\n\nm = [\n [3.2406, -1.5372, -0.4986],\n [-0.9689, 1.8758, 0.0415],\n [0.0557, -0.2040, 1.0570]\n]\n\nm_inv = [\n [0.4124, 0.3576, 0.1805],\n [0.2126, 0.7152, 0.0722],\n [0.0193, 0.1192, 0.9505]\n]\n\nrefX = 0.95047\n\nrefY = 1.00000\n\nrefZ = 1.08883\n\nrefU = 0.19784\n\nrefV = 0.46834\n\nlab_e = 0.008856\n\nlab_k = 903.3"},{"col":4,"comment":"null","endLoc":753,"header":"def test_default_axes(self)","id":2829,"name":"test_default_axes","nodeType":"Function","startLoc":747,"text":"def test_default_axes(self):\n\n g = ag.PairGrid(self.df)\n assert g.axes.shape == (3, 3)\n assert g.x_vars == [\"x\", \"y\", \"z\"]\n assert g.y_vars == [\"x\", \"y\", \"z\"]\n assert g.square_grid"},{"col":4,"comment":"null","endLoc":1989,"header":"def test_mesh_unique_norm(self, long_df)","id":2830,"name":"test_mesh_unique_norm","nodeType":"Function","startLoc":1971,"text":"def test_mesh_unique_norm(self, long_df):\n\n stat = \"density\"\n ax = histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\", common_norm=False, stat=stat,\n )\n\n hist = Histogram()\n bin_kws = hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n\n for i, sub_df in long_df.groupby(\"c\"):\n\n sub_hist = Histogram(bins=bin_kws[\"bins\"], stat=stat)\n\n mesh = ax.collections[i]\n mesh_data = mesh.get_array()\n\n density, (x_edges, y_edges) = sub_hist(sub_df[\"x\"], sub_df[\"y\"])\n assert_array_equal(mesh_data.data, density.T.flat)"},{"col":4,"comment":"null","endLoc":762,"header":"@pytest.mark.parametrize(\"vars\", [[\"z\", \"x\"], np.array([\"z\", \"x\"])])\n def test_specific_square_axes(self, vars)","id":2831,"name":"test_specific_square_axes","nodeType":"Function","startLoc":755,"text":"@pytest.mark.parametrize(\"vars\", [[\"z\", \"x\"], np.array([\"z\", \"x\"])])\n def test_specific_square_axes(self, vars):\n\n g = ag.PairGrid(self.df, vars=vars)\n assert g.axes.shape == (len(vars), len(vars))\n assert g.x_vars == list(vars)\n assert g.y_vars == list(vars)\n assert g.square_grid"},{"id":2832,"name":"diverging_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"01295cb6-cc7a-4c6d-94cf-9b0e6cde9fa7\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme()\\n\",\n \"sns.palettes._patch_colormap_display()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"84880848-0805-4c41-999a-50808b397275\",\n \"metadata\": {},\n \"source\": [\n \"Generate diverging ramps from blue to red through white:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"643b3e07-8365-46e3-b033-af7a2fdcd158\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(240, 20)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5ae53941-d9d9-4b5a-8abc-173911ebee74\",\n \"metadata\": {},\n \"source\": [\n \"Change the center color to be dark:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"41f03771-8fb2-46f6-93c5-5a0e28be625c\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(240, 20, center=\\\"dark\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0aeb2402-2cbe-4546-a354-f1f501f762ae\",\n \"metadata\": {},\n \"source\": [\n \"Return a continuous colormap rather than a discrete palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"64d335a5-f8b2-433f-a83f-5aeff7db583a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(240, 20, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"77223a07-8492-4056-a0f7-14e133e3ce2c\",\n \"metadata\": {},\n \"source\": [\n \"Increase the amount of separation around the center value:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"82472c1e-4b16-40eb-be1d-480bbd2aa702\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(240, 20, sep=30, as_cmap=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"966e8594-b458-414c-a7b0-3e804ce407bf\",\n \"metadata\": {},\n \"source\": [\n \"Use a magenta-to-green palette instead:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a03f8ede-b424-4e06-beb6-cf63c94bcd9e\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(280, 150)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b3b17689-58e2-4065-9d52-1cf5ebcd4e89\",\n \"metadata\": {},\n \"source\": [\n \"Decrease the saturation of the endpoints:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"02aaa009-f257-4fc7-a2de-40fbb1464490\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(280, 150, s=50)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"db75ca48-ba72-4ca2-8480-bc72c20a70cc\",\n \"metadata\": {},\n \"source\": [\n \"Decrease the lightness of the endpoints:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"89e3bcb1-a17c-4465-830f-46043cb6c322\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.diverging_palette(280, 150, l=35)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4e42452a-a485-43e7-bbc3-338db58e4637\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e19f523f-c2f7-489a-ba00-326810e31a67\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":91,"header":"def test_bad_style(self)","id":2833,"name":"test_bad_style","nodeType":"Function","startLoc":88,"text":"def test_bad_style(self):\n\n with pytest.raises(ValueError):\n rcmod.axes_style(\"i_am_not_a_style\")"},{"col":4,"comment":"null","endLoc":2000,"header":"@pytest.mark.parametrize(\"stat\", [\"probability\", \"proportion\", \"percent\"])\n def test_mesh_normalization(self, long_df, stat)","id":2834,"name":"test_mesh_normalization","nodeType":"Function","startLoc":1991,"text":"@pytest.mark.parametrize(\"stat\", [\"probability\", \"proportion\", \"percent\"])\n def test_mesh_normalization(self, long_df, stat):\n\n ax = histplot(\n long_df, x=\"x\", y=\"y\", stat=stat,\n )\n\n mesh_data = ax.collections[0].get_array()\n expected_sum = {\"percent\": 100}.get(stat, 1)\n assert mesh_data.data.sum() == expected_sum"},{"col":4,"comment":"null","endLoc":98,"header":"def test_rc_override(self)","id":2835,"name":"test_rc_override","nodeType":"Function","startLoc":93,"text":"def test_rc_override(self):\n\n rc = {\"axes.facecolor\": \"blue\", \"foo.notaparam\": \"bar\"}\n out = rcmod.axes_style(\"darkgrid\", rc)\n assert out[\"axes.facecolor\"] == \"blue\"\n assert \"foo.notaparam\" not in out"},{"col":4,"comment":"null","endLoc":106,"header":"def test_set_style(self)","id":2836,"name":"test_set_style","nodeType":"Function","startLoc":100,"text":"def test_set_style(self):\n\n for style in self.styles:\n\n style_dict = rcmod.axes_style(style)\n rcmod.set_style(style)\n self.assert_rc_params(style_dict)"},{"col":4,"comment":"null","endLoc":122,"header":"def test_style_context_manager(self)","id":2837,"name":"test_style_context_manager","nodeType":"Function","startLoc":108,"text":"def test_style_context_manager(self):\n\n rcmod.set_style(\"darkgrid\")\n orig_params = rcmod.axes_style()\n context_params = rcmod.axes_style(\"whitegrid\")\n\n with rcmod.axes_style(\"whitegrid\"):\n self.assert_rc_params(context_params)\n self.assert_rc_params(orig_params)\n\n @rcmod.axes_style(\"whitegrid\")\n def func():\n self.assert_rc_params(context_params)\n func()\n self.assert_rc_params(orig_params)"},{"col":4,"comment":"null","endLoc":774,"header":"def test_remove_hue_from_default(self)","id":2838,"name":"test_remove_hue_from_default","nodeType":"Function","startLoc":764,"text":"def test_remove_hue_from_default(self):\n\n hue = \"z\"\n g = ag.PairGrid(self.df, hue=hue)\n assert hue not in g.x_vars\n assert hue not in g.y_vars\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, hue=hue, vars=vars)\n assert hue in g.x_vars\n assert hue in g.y_vars"},{"col":0,"comment":"null","endLoc":52,"header":"@pytest.fixture\ndef flat_array(flat_series)","id":2839,"name":"flat_array","nodeType":"Function","startLoc":49,"text":"@pytest.fixture\ndef flat_array(flat_series):\n\n return flat_series.to_numpy()"},{"fileName":"different_scatter_variables.py","filePath":"examples","id":2840,"nodeType":"File","text":"\"\"\"\nScatterplot with multiple semantics\n===================================\n\n_thumb: .45, .5\n\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_theme(style=\"whitegrid\")\n\n# Load the example diamonds dataset\ndiamonds = sns.load_dataset(\"diamonds\")\n\n# Draw a scatter plot while assigning point colors and sizes to different\n# variables in the dataset\nf, ax = plt.subplots(figsize=(6.5, 6.5))\nsns.despine(f, left=True, bottom=True)\nclarity_ranking = [\"I1\", \"SI2\", \"SI1\", \"VS2\", \"VS1\", \"VVS2\", \"VVS1\", \"IF\"]\nsns.scatterplot(x=\"carat\", y=\"price\",\n hue=\"clarity\", size=\"depth\",\n palette=\"ch:r=-.2,d=.3_r\",\n hue_order=clarity_ranking,\n sizes=(1, 8), linewidth=0,\n data=diamonds, ax=ax)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":2841,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"col":0,"comment":"null","endLoc":58,"header":"@pytest.fixture\ndef flat_list(flat_series)","id":2842,"name":"flat_list","nodeType":"Function","startLoc":55,"text":"@pytest.fixture\ndef flat_list(flat_series):\n\n return flat_series.to_list()"},{"col":4,"comment":"null","endLoc":126,"header":"def test_style_context_independence(self)","id":2844,"name":"test_style_context_independence","nodeType":"Function","startLoc":124,"text":"def test_style_context_independence(self):\n\n assert set(rcmod._style_keys) ^ set(rcmod._context_keys)"},{"col":0,"comment":"null","endLoc":72,"header":"@pytest.fixture(params=[\"series\", \"array\", \"list\"])\ndef flat_data(rng, request)","id":2845,"name":"flat_data","nodeType":"Function","startLoc":61,"text":"@pytest.fixture(params=[\"series\", \"array\", \"list\"])\ndef flat_data(rng, request):\n\n index = pd.RangeIndex(10, 30, name=\"t\")\n series = pd.Series(rng.normal(size=20), index, name=\"s\")\n if request.param == \"series\":\n data = series\n elif request.param == \"array\":\n data = series.to_numpy()\n elif request.param == \"list\":\n data = series.to_list()\n return data"},{"col":4,"comment":"null","endLoc":339,"header":"def test_join_replace_variable_new_data(self, long_df)","id":2846,"name":"test_join_replace_variable_new_data","nodeType":"Function","startLoc":323,"text":"def test_join_replace_variable_new_data(self, long_df):\n\n d1 = long_df[[\"x\", \"y\"]]\n d2 = long_df[[\"a\", \"s\"]]\n\n v1 = {\"x\": \"x\", \"y\": \"y\"}\n v2 = {\"x\": \"a\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n variables = v1.copy()\n variables.update(v2)\n\n for var, key in variables.items():\n assert p2.names[var] == key\n assert_vector_equal(p2.frame[var], long_df[key])"},{"col":4,"comment":"null","endLoc":1432,"header":"def _generate_pairings(\n self, data: PlotData, pair_variables: dict,\n ) -> Generator[\n tuple[list[dict], DataFrame, dict[str, Scale]], None, None\n ]","id":2847,"name":"_generate_pairings","nodeType":"Function","startLoc":1392,"text":"def _generate_pairings(\n self, data: PlotData, pair_variables: dict,\n ) -> Generator[\n tuple[list[dict], DataFrame, dict[str, Scale]], None, None\n ]:\n # TODO retype return with subplot_spec or similar\n\n iter_axes = itertools.product(*[\n pair_variables.get(axis, [axis]) for axis in \"xy\"\n ])\n\n for x, y in iter_axes:\n\n subplots = []\n for view in self._subplots:\n if (view[\"x\"] == x) and (view[\"y\"] == y):\n subplots.append(view)\n\n if data.frame.empty and data.frames:\n out_df = data.frames[(x, y)].copy()\n elif not pair_variables:\n out_df = data.frame.copy()\n else:\n if data.frame.empty and data.frames:\n out_df = data.frames[(x, y)].copy()\n else:\n out_df = data.frame.copy()\n\n scales = self._scales.copy()\n if x in out_df:\n scales[\"x\"] = self._scales[x]\n if y in out_df:\n scales[\"y\"] = self._scales[y]\n\n for axis, var in zip(\"xy\", (x, y)):\n if axis != var:\n out_df = out_df.rename(columns={var: axis})\n cols = [col for col in out_df if re.match(rf\"{axis}\\d+\", str(col))]\n out_df = out_df.drop(cols, axis=1)\n\n yield subplots, out_df, scales"},{"attributeType":"null","col":28,"comment":"null","endLoc":9,"id":2848,"name":"plt","nodeType":"Attribute","startLoc":9,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":2849,"name":"diamonds","nodeType":"Attribute","startLoc":13,"text":"diamonds"},{"col":4,"comment":"null","endLoc":2024,"header":"def test_mesh_colors(self, long_df)","id":2850,"name":"test_mesh_colors","nodeType":"Function","startLoc":2002,"text":"def test_mesh_colors(self, long_df):\n\n color = \"r\"\n f, ax = plt.subplots()\n histplot(\n long_df, x=\"x\", y=\"y\", color=color,\n )\n mesh = ax.collections[0]\n assert_array_equal(\n mesh.get_cmap().colors,\n _DistributionPlotter()._cmap_from_color(color).colors,\n )\n\n f, ax = plt.subplots()\n histplot(\n long_df, x=\"x\", y=\"y\", hue=\"c\",\n )\n colors = color_palette()\n for i, mesh in enumerate(ax.collections):\n assert_array_equal(\n mesh.get_cmap().colors,\n _DistributionPlotter()._cmap_from_color(colors[i]).colors,\n )"},{"col":4,"comment":"null","endLoc":359,"header":"def test_join_add_variable_different_index(self, long_df)","id":2851,"name":"test_join_add_variable_different_index","nodeType":"Function","startLoc":341,"text":"def test_join_add_variable_different_index(self, long_df):\n\n d1 = long_df.iloc[:70]\n d2 = long_df.iloc[30:]\n\n v1 = {\"x\": \"a\"}\n v2 = {\"y\": \"z\"}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n (var1, key1), = v1.items()\n (var2, key2), = v2.items()\n\n assert_vector_equal(p2.frame.loc[d1.index, var1], d1[key1])\n assert_vector_equal(p2.frame.loc[d2.index, var2], d2[key2])\n\n assert p2.frame.loc[d2.index.difference(d1.index), var1].isna().all()\n assert p2.frame.loc[d1.index.difference(d2.index), var2].isna().all()"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":2852,"name":"f","nodeType":"Attribute","startLoc":17,"text":"f"},{"attributeType":"null","col":3,"comment":"null","endLoc":17,"id":2853,"name":"ax","nodeType":"Attribute","startLoc":17,"text":"ax"},{"attributeType":"list","col":0,"comment":"null","endLoc":19,"id":2854,"name":"clarity_ranking","nodeType":"Attribute","startLoc":19,"text":"clarity_ranking"},{"col":0,"comment":"","endLoc":7,"header":"different_scatter_variables.py#","id":2855,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot with multiple semantics\n===================================\n\n_thumb: .45, .5\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\n\nf, ax = plt.subplots(figsize=(6.5, 6.5))\n\nsns.despine(f, left=True, bottom=True)\n\nclarity_ranking = [\"I1\", \"SI2\", \"SI1\", \"VS2\", \"VS1\", \"VVS2\", \"VVS1\", \"IF\"]\n\nsns.scatterplot(x=\"carat\", y=\"price\",\n hue=\"clarity\", size=\"depth\",\n palette=\"ch:r=-.2,d=.3_r\",\n hue_order=clarity_ranking,\n sizes=(1, 8), linewidth=0,\n data=diamonds, ax=ax)"},{"col":4,"comment":"null","endLoc":378,"header":"def test_join_replace_variable_different_index(self, long_df)","id":2856,"name":"test_join_replace_variable_different_index","nodeType":"Function","startLoc":361,"text":"def test_join_replace_variable_different_index(self, long_df):\n\n d1 = long_df.iloc[:70]\n d2 = long_df.iloc[30:]\n\n var = \"x\"\n k1, k2 = \"a\", \"z\"\n v1 = {var: k1}\n v2 = {var: k2}\n\n p1 = PlotData(d1, v1)\n p2 = p1.join(d2, v2)\n\n (var1, key1), = v1.items()\n (var2, key2), = v2.items()\n\n assert_vector_equal(p2.frame.loc[d2.index, var], d2[k2])\n assert p2.frame.loc[d1.index.difference(d2.index), var].isna().all()"},{"col":0,"comment":"null","endLoc":79,"header":"@pytest.fixture\ndef wide_list_of_series(rng)","id":2857,"name":"wide_list_of_series","nodeType":"Function","startLoc":75,"text":"@pytest.fixture\ndef wide_list_of_series(rng):\n\n return [pd.Series(rng.normal(size=20), np.arange(20), name=\"a\"),\n pd.Series(rng.normal(size=10), np.arange(5, 15), name=\"b\")]"},{"id":2858,"name":"v0.11.2.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.11.2 (August 2021)\n---------------------\n\nThis is a minor release that addresses issues in the v0.11 series and adds a small number of targeted enhancements. It is a recommended upgrade for all users.\n\n- |API| |Enhancement| In :func:`lmplot`, added a new `facet_kws` parameter and deprecated the `sharex`, `sharey`, and `legend_out` parameters from the function signature; pass them in a `facet_kws` dictionary instead (:pr:`2576`).\n\n- |Feature| Added a :func:`move_legend` convenience function for repositioning the legend on an existing axes or figure, along with updating its properties. This function should be preferred over calling `ax.legend` with no legend data, which does not reliably work across seaborn plot types (:pr:`2643`).\n\n- |Feature| In :func:`histplot`, added `stat=\"percent\"` as an option for normalization such that bar heights sum to 100 and `stat=\"proportion\"` as an alias for the existing `stat=\"probability\"` (:pr:`2461`, :pr:`2634`).\n\n- |Feature| Added :meth:`FacetGrid.refline` and :meth:`JointGrid.refline` methods for plotting horizontal and/or vertical reference lines on every subplot in one step (:pr:`2620`).\n\n- |Feature| In :func:`kdeplot`, added a `warn_singular` parameter to silence the warning about data with zero variance (:pr:`2566`).\n\n- |Enhancement| In :func:`histplot`, improved performance with large datasets and many groupings/facets (:pr:`2559`, :pr:`2570`).\n\n- |Enhancement| The :class:`FacetGrid`, :class:`PairGrid`, and :class:`JointGrid` objects now reference the underlying matplotlib figure with a `.figure` attribute. The existing `.fig` attribute still exists but is discouraged and may eventually be deprecated. The effect is that you can now call `obj.figure` on the return value from any seaborn function to access the matplotlib object (:pr:`2639`).\n\n- |Enhancement| In :class:`FacetGrid` and functions that use it, visibility of the interior axis labels is now disabled, and exterior axis labels are no longer erased when adding additional layers. This produces the same results for plots made by seaborn functions, but it may produce different (better, in most cases) results for customized facet plots (:pr:`2583`).\n\n- |Enhancement| In :class:`FacetGrid`, :class:`PairGrid`, and functions that use them, the matplotlib `figure.autolayout` parameter is disabled to avoid having the legend overlap the plot (:pr:`2571`).\n\n- |Enhancement| The :func:`load_dataset` helper now produces a more informative error when fed a dataframe, easing a common beginner mistake (:pr:`2604`).\n\n- |Fix| |Enhancement| Improved robustness to missing data, including some additional support for the `pd.NA` type (:pr:`2417`, :pr:`2435`).\n\n- |Fix| In :func:`ecdfplot` and :func:`rugplot`, fixed a bug where results were incorrect if the data axis had a log scale before plotting (:pr:`2504`).\n\n- |Fix| In :func:`histplot`, fixed a bug where using `shrink` with non-discrete bins shifted bar positions inaccurately (:pr:`2477`).\n\n- |Fix| In :func:`displot`, fixed a bug where `common_norm=False` was ignored when faceting was used without assigning `hue` (:pr:`2468`).\n\n- |Fix| In :func:`histplot`, fixed two bugs where automatically computed edge widths were too thick for log-scaled histograms and for categorical histograms on the y axis (:pr:`2522`).\n\n- |Fix| In :func:`histplot` and :func:`kdeplot`, fixed a bug where the `alpha` parameter was ignored when `fill=False` (:pr:`2460`).\n\n- |Fix| In :func:`histplot` and :func:`kdeplot`, fixed a bug where the `multiple` parameter was ignored when `hue` was provided as a vector without a name (:pr:`2462`).\n\n- |Fix| In :func:`displot`, the default alpha value now adjusts to a provided `multiple` parameter even when `hue` is not assigned (:pr:`2462`).\n\n- |Fix| In :func:`displot`, fixed a bug that caused faceted 2D histograms to error out with `common_bins=False` (:pr:`2640`).\n\n- |Fix| In :func:`rugplot`, fixed a bug that prevented the use of datetime data (:pr:`2458`).\n\n- |Fix| In :func:`relplot` and :func:`displot`, fixed a bug where the dataframe attached to the returned `FacetGrid` object dropped columns that were not used in the plot (:pr:`2623`).\n\n- |Fix| In :func:`relplot`, fixed an error that would be raised when one of the column names in the dataframe shared a name with one of the plot variables (:pr:`2581`).\n\n- |Fix| In the relational plots, fixed a bug where legend entries for the `size` semantic were incorrect when `size_norm` extrapolated beyond the range of the data (:pr:`2580`).\n\n- |Fix| In :func:`lmplot` and :func:`regplot`, fixed a bug where the x axis was clamped to the data limits with `truncate=True` (:pr:`2576`).\n\n- |Fix| In :func:`lmplot`, fixed a bug where `sharey=False` did not always work as expected (:pr:`2576`).\n\n- |Fix| In :func:`heatmap`, fixed a bug where vertically-rotated y-axis tick labels would be misaligned with their rows (:pr:`2574`).\n\n- |Fix| Fixed an issue that prevented Python from running in `-OO` mode while using seaborn (:pr:`2473`).\n\n- |Docs| Improved the API documentation for theme-related functions (:pr:`2573`).\n\n- |Docs| Added docstring pages for all methods on documented classes (:pr:`2644`).\n"},{"col":4,"comment":"null","endLoc":389,"header":"def test_join_subset_data_inherit_variables(self, long_df)","id":2859,"name":"test_join_subset_data_inherit_variables","nodeType":"Function","startLoc":380,"text":"def test_join_subset_data_inherit_variables(self, long_df):\n\n sub_df = long_df[long_df[\"a\"] == \"b\"]\n\n var = \"y\"\n p1 = PlotData(long_df, {var: var})\n p2 = p1.join(sub_df, None)\n\n assert_vector_equal(p2.frame.loc[sub_df.index, var], sub_df[var])\n assert p2.frame.loc[long_df.index.difference(sub_df.index), var].isna().all()"},{"col":0,"comment":"null","endLoc":85,"header":"@pytest.fixture\ndef wide_list_of_arrays(wide_list_of_series)","id":2860,"name":"wide_list_of_arrays","nodeType":"Function","startLoc":82,"text":"@pytest.fixture\ndef wide_list_of_arrays(wide_list_of_series):\n\n return [s.to_numpy() for s in wide_list_of_series]"},{"col":4,"comment":"null","endLoc":398,"header":"def test_join_multiple_inherits_from_orig(self, rng)","id":2861,"name":"test_join_multiple_inherits_from_orig","nodeType":"Function","startLoc":391,"text":"def test_join_multiple_inherits_from_orig(self, rng):\n\n d1 = pd.DataFrame(dict(a=rng.normal(0, 1, 100), b=rng.normal(0, 1, 100)))\n d2 = pd.DataFrame(dict(a=rng.normal(0, 1, 100)))\n\n p = PlotData(d1, {\"x\": \"a\"}).join(d2, {\"y\": \"a\"}).join(None, {\"y\": \"a\"})\n assert_vector_equal(p.frame[\"x\"], d1[\"a\"])\n assert_vector_equal(p.frame[\"y\"], d1[\"a\"])"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":2862,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":2863,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"attributeType":"partial","col":0,"comment":"null","endLoc":12,"id":2864,"name":"assert_vector_equal","nodeType":"Attribute","startLoc":12,"text":"assert_vector_equal"},{"col":0,"comment":"","endLoc":1,"header":"test_data.py#","id":2865,"name":"","nodeType":"Function","startLoc":1,"text":"assert_vector_equal = functools.partial(assert_series_equal, check_names=False)"},{"col":4,"comment":"null","endLoc":790,"header":"@pytest.mark.parametrize(\n \"x_vars, y_vars\",\n [\n ([\"x\", \"y\"], [\"z\", \"y\", \"x\"]),\n ([\"x\", \"y\"], \"z\"),\n (np.array([\"x\", \"y\"]), np.array([\"z\", \"y\", \"x\"])),\n ],\n )\n def test_specific_nonsquare_axes(self, x_vars, y_vars)","id":2866,"name":"test_specific_nonsquare_axes","nodeType":"Function","startLoc":776,"text":"@pytest.mark.parametrize(\n \"x_vars, y_vars\",\n [\n ([\"x\", \"y\"], [\"z\", \"y\", \"x\"]),\n ([\"x\", \"y\"], \"z\"),\n (np.array([\"x\", \"y\"]), np.array([\"z\", \"y\", \"x\"])),\n ],\n )\n def test_specific_nonsquare_axes(self, x_vars, y_vars):\n\n g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n assert g.axes.shape == (len(y_vars), len(x_vars))\n assert g.x_vars == list(x_vars)\n assert g.y_vars == list(y_vars)\n assert not g.square_grid"},{"id":2867,"name":"histplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"white\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assign a variable to ``x`` to plot a univariate distribution along the x axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Flip the plot by assigning the data variable to the y axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins, y=\\\"flipper_length_mm\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Check how well the histogram represents the data by specifying a different bin width:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\", binwidth=3)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"You can also define the total number of bins to use:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\", bins=30)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Add a kernel density estimate to smooth the histogram, providing complementary information about the shape of the distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\", kde=True)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"If neither `x` nor `y` is assigned, the dataset is treated as wide-form, and a histogram is drawn for each numeric column:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"You can otherwise draw multiple histograms from a long-form dataset with hue mapping:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"The default approach to plotting multiple distributions is to \\\"layer\\\" them, but you can also \\\"stack\\\" them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Overlapping bars can be hard to visually resolve. A different approach would be to draw a step function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", element=\\\"step\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"You can move even farther away from bars by drawing a polygon with vertices in the center of each bin. This may make it easier to see the shape of the distribution, but use with caution: it will be less obvious to your audience that they are looking at a histogram:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", element=\\\"poly\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"To compare the distribution of subsets that differ substantially in size, use independent density normalization:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" penguins, x=\\\"bill_length_mm\\\", hue=\\\"island\\\", element=\\\"step\\\",\\n\",\n \" stat=\\\"density\\\", common_norm=False,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to normalize so that each bar's height shows a probability, proportion, or percent, which make more sense for discrete variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.histplot(data=tips, x=\\\"size\\\", stat=\\\"percent\\\", discrete=True)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"You can even draw a histogram over categorical variables (although this is an experimental feature):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=tips, x=\\\"day\\\", shrink=.8)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"When using a ``hue`` semantic with discrete data, it can make sense to \\\"dodge\\\" the levels:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=tips, x=\\\"day\\\", hue=\\\"sex\\\", multiple=\\\"dodge\\\", shrink=.8)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Real-world data is often skewed. For heavily skewed distributions, it's better to define the bins in log space. Compare:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"planets = sns.load_dataset(\\\"planets\\\")\\n\",\n \"sns.histplot(data=planets, x=\\\"distance\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"To the log-scale version:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=planets, x=\\\"distance\\\", log_scale=True)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"There are also a number of options for how the histogram appears. You can show unfilled bars:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=planets, x=\\\"distance\\\", log_scale=True, fill=False)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Or an unfilled step function:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(data=planets, x=\\\"distance\\\", log_scale=True, element=\\\"step\\\", fill=False)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Step functions, esepcially when unfilled, make it easy to compare cumulative histograms:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" data=planets, x=\\\"distance\\\", hue=\\\"method\\\",\\n\",\n \" hue_order=[\\\"Radial Velocity\\\", \\\"Transit\\\"],\\n\",\n \" log_scale=True, element=\\\"step\\\", fill=False,\\n\",\n \" cumulative=True, stat=\\\"density\\\", common_norm=False,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"When both ``x`` and ``y`` are assigned, a bivariate histogram is computed and shown as a heatmap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(penguins, x=\\\"bill_depth_mm\\\", y=\\\"body_mass_g\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"It's possible to assign a ``hue`` variable too, although this will not work well if data from the different levels have substantial overlap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(penguins, x=\\\"bill_depth_mm\\\", y=\\\"body_mass_g\\\", hue=\\\"species\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Multiple color maps can make sense when one of the variables is discrete:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" penguins, x=\\\"bill_depth_mm\\\", y=\\\"species\\\", hue=\\\"species\\\", legend=False\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"The bivariate histogram accepts all of the same options for computation as its univariate counterpart, using tuples to parametrize ``x`` and ``y`` independently:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" planets, x=\\\"year\\\", y=\\\"distance\\\",\\n\",\n \" bins=30, discrete=(True, False), log_scale=(False, True),\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"The default behavior makes cells with no observations transparent, although this can be disabled: \"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" planets, x=\\\"year\\\", y=\\\"distance\\\",\\n\",\n \" bins=30, discrete=(True, False), log_scale=(False, True),\\n\",\n \" thresh=None,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to set the threshold and colormap saturation point in terms of the proportion of cumulative counts:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" planets, x=\\\"year\\\", y=\\\"distance\\\",\\n\",\n \" bins=30, discrete=(True, False), log_scale=(False, True),\\n\",\n \" pthresh=.05, pmax=.9,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"To annotate the colormap, add a colorbar:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.histplot(\\n\",\n \" planets, x=\\\"year\\\", y=\\\"distance\\\",\\n\",\n \" bins=30, discrete=(True, False), log_scale=(False, True),\\n\",\n \" cbar=True, cbar_kws=dict(shrink=.75),\\n\",\n \")\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"col":4,"comment":"null","endLoc":1499,"header":"def test_legend_data(self, long_df)","id":2868,"name":"test_legend_data","nodeType":"Function","startLoc":1325,"text":"def test_legend_data(self, long_df):\n\n m = mpl.markers.MarkerStyle(\"o\")\n default_mark = m.get_path().transformed(m.get_transform())\n\n m = mpl.markers.MarkerStyle(\"\")\n null = m.get_path().transformed(m.get_transform())\n\n f, ax = plt.subplots()\n\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert handles == []\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n legend=\"full\",\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n assert labels == p._hue_map.levels\n assert same_color(colors, expected_colors)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n paths = [h.get_paths()[0] for h in handles]\n expected_paths = p._style_map(p._style_map.levels, \"path\")\n assert labels == p._hue_map.levels\n assert labels == p._style_map.levels\n assert same_color(colors, expected_colors)\n assert self.paths_equal(paths, expected_paths)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n legend=\"full\",\n )\n p.map_style(markers=True)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n paths = [h.get_paths()[0] for h in handles]\n expected_colors = (\n [\"w\"] + p._hue_map(p._hue_map.levels)\n + [\"w\"] + [\".2\" for _ in p._style_map.levels]\n )\n expected_paths = (\n [null] + [default_mark for _ in p._hue_map.levels]\n + [null] + p._style_map(p._style_map.levels, \"path\")\n )\n assert labels == (\n [\"a\"] + p._hue_map.levels + [\"b\"] + p._style_map.levels\n )\n assert same_color(colors, expected_colors)\n assert self.paths_equal(paths, expected_paths)\n\n # --\n\n ax.clear()\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"a\"),\n legend=\"full\"\n )\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n colors = [h.get_facecolors()[0] for h in handles]\n expected_colors = p._hue_map(p._hue_map.levels)\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == p._hue_map.levels\n assert labels == p._size_map.levels\n assert same_color(colors, expected_colors)\n assert sizes == expected_sizes\n\n # --\n\n ax.clear()\n sizes_list = [10, 100, 200]\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n legend=\"full\",\n )\n p.map_size(sizes=sizes_list)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == [str(l) for l in p._size_map.levels]\n assert sizes == expected_sizes\n\n # --\n\n ax.clear()\n sizes_dict = {2: 10, 4: 100, 8: 200}\n p = _ScatterPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n legend=\"full\"\n )\n p.map_size(sizes=sizes_dict)\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n sizes = [h.get_sizes()[0] for h in handles]\n expected_sizes = p._size_map(p._size_map.levels)\n assert labels == [str(l) for l in p._size_map.levels]\n assert sizes == expected_sizes\n\n # --\n\n x, y = np.random.randn(2, 40)\n z = np.tile(np.arange(20), 2)\n\n p = _ScatterPlotter(\n variables=dict(x=x, y=y, hue=z),\n )\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._hue_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._hue_map.levels)\n\n p = _ScatterPlotter(\n variables=dict(x=x, y=y, size=z),\n )\n\n ax.clear()\n p.legend = \"full\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert labels == [str(l) for l in p._size_map.levels]\n\n ax.clear()\n p.legend = \"brief\"\n p.add_legend_data(ax)\n handles, labels = ax.get_legend_handles_labels()\n assert len(labels) < len(p._size_map.levels)\n\n ax.clear()\n p.legend = \"bad_value\"\n with pytest.raises(ValueError):\n p.add_legend_data(ax)"},{"col":4,"comment":"null","endLoc":2052,"header":"def test_color_limits(self, long_df)","id":2869,"name":"test_color_limits","nodeType":"Function","startLoc":2026,"text":"def test_color_limits(self, long_df):\n\n f, (ax1, ax2, ax3) = plt.subplots(3)\n kws = dict(data=long_df, x=\"x\", y=\"y\")\n hist = Histogram()\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n\n histplot(**kws, ax=ax1)\n assert ax1.collections[0].get_clim() == (0, counts.max())\n\n vmax = 10\n histplot(**kws, vmax=vmax, ax=ax2)\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n assert ax2.collections[0].get_clim() == (0, vmax)\n\n pmax = .8\n pthresh = .1\n f = _DistributionPlotter()._quantile_to_level\n\n histplot(**kws, pmax=pmax, pthresh=pthresh, ax=ax3)\n counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n mesh = ax3.collections[0]\n assert mesh.get_clim() == (0, f(counts, pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (counts <= f(counts, pthresh)).T.flat,\n )"},{"col":4,"comment":"null","endLoc":132,"header":"def test_set_rc(self)","id":2870,"name":"test_set_rc","nodeType":"Function","startLoc":128,"text":"def test_set_rc(self):\n\n rcmod.set_theme(rc={\"lines.linewidth\": 4})\n assert mpl.rcParams[\"lines.linewidth\"] == 4\n rcmod.set_theme()"},{"attributeType":"null","col":8,"comment":"null","endLoc":712,"id":2871,"name":"gray","nodeType":"Attribute","startLoc":712,"text":"self.gray"},{"col":4,"comment":"null","endLoc":155,"header":"def test_set_with_palette(self)","id":2872,"name":"test_set_with_palette","nodeType":"Function","startLoc":134,"text":"def test_set_with_palette(self):\n\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=\"deep\")\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=\"deep\", color_codes=False)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n pal = palettes.color_palette(\"deep\")\n rcmod.set_theme(palette=pal)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme(palette=pal, color_codes=False)\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n rcmod.reset_orig()\n\n rcmod.set_theme()"},{"col":0,"comment":"null","endLoc":91,"header":"@pytest.fixture\ndef wide_list_of_lists(wide_list_of_series)","id":2873,"name":"wide_list_of_lists","nodeType":"Function","startLoc":88,"text":"@pytest.fixture\ndef wide_list_of_lists(wide_list_of_series):\n\n return [s.to_list() for s in wide_list_of_series]"},{"col":0,"comment":"null","endLoc":97,"header":"@pytest.fixture\ndef wide_dict_of_series(wide_list_of_series)","id":2874,"name":"wide_dict_of_series","nodeType":"Function","startLoc":94,"text":"@pytest.fixture\ndef wide_dict_of_series(wide_list_of_series):\n\n return {s.name: s for s in wide_list_of_series}"},{"col":0,"comment":"null","endLoc":103,"header":"@pytest.fixture\ndef wide_dict_of_arrays(wide_list_of_series)","id":2875,"name":"wide_dict_of_arrays","nodeType":"Function","startLoc":100,"text":"@pytest.fixture\ndef wide_dict_of_arrays(wide_list_of_series):\n\n return {s.name: s.to_numpy() for s in wide_list_of_series}"},{"col":4,"comment":"null","endLoc":809,"header":"def test_corner(self)","id":2876,"name":"test_corner","nodeType":"Function","startLoc":792,"text":"def test_corner(self):\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=plot_vars, corner=True)\n corner_size = sum(i + 1 for i in range(len(plot_vars)))\n assert len(g.figure.axes) == corner_size\n\n g.map_diag(plt.hist)\n assert len(g.figure.axes) == (corner_size + len(plot_vars))\n\n for ax in np.diag(g.axes):\n assert not ax.yaxis.get_visible()\n\n plot_vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=plot_vars, corner=True)\n g.map(scatterplot)\n assert len(g.figure.axes) == corner_size\n assert g.axes[0, 0].get_ylabel() == \"x\""},{"col":4,"comment":"null","endLoc":161,"header":"def test_reset_defaults(self)","id":2877,"name":"test_reset_defaults","nodeType":"Function","startLoc":157,"text":"def test_reset_defaults(self):\n\n rcmod.reset_defaults()\n self.assert_rc_params(mpl.rcParamsDefault)\n rcmod.set_theme()"},{"col":0,"comment":"null","endLoc":109,"header":"@pytest.fixture\ndef wide_dict_of_lists(wide_list_of_series)","id":2878,"name":"wide_dict_of_lists","nodeType":"Function","startLoc":106,"text":"@pytest.fixture\ndef wide_dict_of_lists(wide_list_of_series):\n\n return {s.name: s.to_list() for s in wide_list_of_series}"},{"col":0,"comment":"Restore all RC params to default settings.","endLoc":137,"header":"def reset_defaults()","id":2879,"name":"reset_defaults","nodeType":"Function","startLoc":135,"text":"def reset_defaults():\n \"\"\"Restore all RC params to default settings.\"\"\"\n mpl.rcParams.update(mpl.rcParamsDefault)"},{"col":4,"comment":"null","endLoc":167,"header":"def test_reset_orig(self)","id":2880,"name":"test_reset_orig","nodeType":"Function","startLoc":163,"text":"def test_reset_orig(self):\n\n rcmod.reset_orig()\n self.assert_rc_params(mpl.rcParamsOrig)\n rcmod.set_theme()"},{"col":4,"comment":"null","endLoc":180,"header":"def test_set_is_alias(self)","id":2881,"name":"test_set_is_alias","nodeType":"Function","startLoc":169,"text":"def test_set_is_alias(self):\n\n rcmod.set_theme(context=\"paper\", style=\"white\")\n params1 = mpl.rcParams.copy()\n rcmod.reset_orig()\n\n rcmod.set_theme(context=\"paper\", style=\"white\")\n params2 = mpl.rcParams.copy()\n\n self.assert_rc_params_equal(params1, params2)\n\n rcmod.set_theme()"},{"col":0,"comment":"null","endLoc":136,"header":"@pytest.fixture\ndef long_df(rng)","id":2882,"name":"long_df","nodeType":"Function","startLoc":112,"text":"@pytest.fixture\ndef long_df(rng):\n\n n = 100\n df = pd.DataFrame(dict(\n x=rng.uniform(0, 20, n).round().astype(\"int\"),\n y=rng.normal(size=n),\n z=rng.lognormal(size=n),\n a=rng.choice(list(\"abc\"), n),\n b=rng.choice(list(\"mnop\"), n),\n c=rng.choice([0, 1], n, [.3, .7]),\n d=rng.choice(np.arange(\"2004-07-30\", \"2007-07-30\", dtype=\"datetime64[Y]\"), n),\n t=rng.choice(np.arange(\"2004-07-30\", \"2004-07-31\", dtype=\"datetime64[m]\"), n),\n s=rng.choice([2, 4, 8], n),\n f=rng.choice([0.2, 0.3], n),\n ))\n\n a_cat = df[\"a\"].astype(\"category\")\n new_categories = np.roll(a_cat.cat.categories, 1)\n df[\"a_cat\"] = a_cat.cat.reorder_categories(new_categories)\n\n df[\"s_cat\"] = df[\"s\"].astype(\"category\")\n df[\"s_str\"] = df[\"s\"].astype(str)\n\n return df"},{"attributeType":"list","col":4,"comment":"null","endLoc":75,"id":2883,"name":"styles","nodeType":"Attribute","startLoc":75,"text":"styles"},{"className":"TestPlottingContext","col":0,"comment":"null","endLoc":249,"id":2884,"nodeType":"Class","startLoc":183,"text":"class TestPlottingContext(RCParamFixtures):\n\n contexts = [\"paper\", \"notebook\", \"talk\", \"poster\"]\n\n def test_default_return(self):\n\n current = rcmod.plotting_context()\n self.assert_rc_params(current)\n\n def test_key_usage(self):\n\n _context_keys = set(rcmod._context_keys)\n for context in self.contexts:\n missing = set(rcmod.plotting_context(context)) ^ _context_keys\n assert not missing\n\n def test_bad_context(self):\n\n with pytest.raises(ValueError):\n rcmod.plotting_context(\"i_am_not_a_context\")\n\n def test_font_scale(self):\n\n notebook_ref = rcmod.plotting_context(\"notebook\")\n notebook_big = rcmod.plotting_context(\"notebook\", 2)\n\n font_keys = [\n \"font.size\",\n \"axes.labelsize\", \"axes.titlesize\",\n \"xtick.labelsize\", \"ytick.labelsize\",\n \"legend.fontsize\", \"legend.title_fontsize\",\n ]\n\n for k in font_keys:\n assert notebook_ref[k] * 2 == notebook_big[k]\n\n def test_rc_override(self):\n\n key, val = \"grid.linewidth\", 5\n rc = {key: val, \"foo\": \"bar\"}\n out = rcmod.plotting_context(\"talk\", rc=rc)\n assert out[key] == val\n assert \"foo\" not in out\n\n def test_set_context(self):\n\n for context in self.contexts:\n\n context_dict = rcmod.plotting_context(context)\n rcmod.set_context(context)\n self.assert_rc_params(context_dict)\n\n def test_context_context_manager(self):\n\n rcmod.set_context(\"notebook\")\n orig_params = rcmod.plotting_context()\n context_params = rcmod.plotting_context(\"paper\")\n\n with rcmod.plotting_context(\"paper\"):\n self.assert_rc_params(context_params)\n self.assert_rc_params(orig_params)\n\n @rcmod.plotting_context(\"paper\")\n def func():\n self.assert_rc_params(context_params)\n func()\n self.assert_rc_params(orig_params)"},{"col":4,"comment":"null","endLoc":190,"header":"def test_default_return(self)","id":2885,"name":"test_default_return","nodeType":"Function","startLoc":187,"text":"def test_default_return(self):\n\n current = rcmod.plotting_context()\n self.assert_rc_params(current)"},{"col":4,"comment":"null","endLoc":197,"header":"def test_key_usage(self)","id":2886,"name":"test_key_usage","nodeType":"Function","startLoc":192,"text":"def test_key_usage(self):\n\n _context_keys = set(rcmod._context_keys)\n for context in self.contexts:\n missing = set(rcmod.plotting_context(context)) ^ _context_keys\n assert not missing"},{"col":4,"comment":"null","endLoc":2094,"header":"def test_hue_color_limits(self, long_df)","id":2887,"name":"test_hue_color_limits","nodeType":"Function","startLoc":2054,"text":"def test_hue_color_limits(self, long_df):\n\n _, (ax1, ax2, ax3, ax4) = plt.subplots(4)\n kws = dict(data=long_df, x=\"x\", y=\"y\", hue=\"c\", bins=4)\n\n hist = Histogram(bins=kws[\"bins\"])\n hist.define_bin_params(long_df[\"x\"], long_df[\"y\"])\n full_counts, _ = hist(long_df[\"x\"], long_df[\"y\"])\n\n sub_counts = []\n for _, sub_df in long_df.groupby(kws[\"hue\"]):\n c, _ = hist(sub_df[\"x\"], sub_df[\"y\"])\n sub_counts.append(c)\n\n pmax = .8\n pthresh = .05\n f = _DistributionPlotter()._quantile_to_level\n\n histplot(**kws, common_norm=True, ax=ax1)\n for i, mesh in enumerate(ax1.collections):\n assert mesh.get_clim() == (0, full_counts.max())\n\n histplot(**kws, common_norm=False, ax=ax2)\n for i, mesh in enumerate(ax2.collections):\n assert mesh.get_clim() == (0, sub_counts[i].max())\n\n histplot(**kws, common_norm=True, pmax=pmax, pthresh=pthresh, ax=ax3)\n for i, mesh in enumerate(ax3.collections):\n assert mesh.get_clim() == (0, f(full_counts, pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (sub_counts[i] <= f(full_counts, pthresh)).T.flat,\n )\n\n histplot(**kws, common_norm=False, pmax=pmax, pthresh=pthresh, ax=ax4)\n for i, mesh in enumerate(ax4.collections):\n assert mesh.get_clim() == (0, f(sub_counts[i], pmax))\n assert_array_equal(\n mesh.get_array().mask,\n (sub_counts[i] <= f(sub_counts[i], pthresh)).T.flat,\n )"},{"attributeType":"str","col":8,"comment":"null","endLoc":620,"id":2888,"name":"orient","nodeType":"Attribute","startLoc":620,"text":"self.orient"},{"attributeType":"None | list","col":8,"comment":"null","endLoc":627,"id":2889,"name":"hue_names","nodeType":"Attribute","startLoc":627,"text":"self.hue_names"},{"col":4,"comment":"null","endLoc":202,"header":"def test_bad_context(self)","id":2890,"name":"test_bad_context","nodeType":"Function","startLoc":199,"text":"def test_bad_context(self):\n\n with pytest.raises(ValueError):\n rcmod.plotting_context(\"i_am_not_a_context\")"},{"col":4,"comment":"null","endLoc":217,"header":"def test_font_scale(self)","id":2891,"name":"test_font_scale","nodeType":"Function","startLoc":204,"text":"def test_font_scale(self):\n\n notebook_ref = rcmod.plotting_context(\"notebook\")\n notebook_big = rcmod.plotting_context(\"notebook\", 2)\n\n font_keys = [\n \"font.size\",\n \"axes.labelsize\", \"axes.titlesize\",\n \"xtick.labelsize\", \"ytick.labelsize\",\n \"legend.fontsize\", \"legend.title_fontsize\",\n ]\n\n for k in font_keys:\n assert notebook_ref[k] * 2 == notebook_big[k]"},{"col":4,"comment":"null","endLoc":821,"header":"def test_size(self)","id":2892,"name":"test_size","nodeType":"Function","startLoc":811,"text":"def test_size(self):\n\n g1 = ag.PairGrid(self.df, height=3)\n npt.assert_array_equal(g1.fig.get_size_inches(), (9, 9))\n\n g2 = ag.PairGrid(self.df, height=4, aspect=.5)\n npt.assert_array_equal(g2.fig.get_size_inches(), (6, 12))\n\n g3 = ag.PairGrid(self.df, y_vars=[\"z\"], x_vars=[\"x\", \"y\"],\n height=2, aspect=2)\n npt.assert_array_equal(g3.fig.get_size_inches(), (8, 2))"},{"col":4,"comment":"null","endLoc":225,"header":"def test_rc_override(self)","id":2893,"name":"test_rc_override","nodeType":"Function","startLoc":219,"text":"def test_rc_override(self):\n\n key, val = \"grid.linewidth\", 5\n rc = {key: val, \"foo\": \"bar\"}\n out = rcmod.plotting_context(\"talk\", rc=rc)\n assert out[key] == val\n assert \"foo\" not in out"},{"col":4,"comment":"null","endLoc":233,"header":"def test_set_context(self)","id":2894,"name":"test_set_context","nodeType":"Function","startLoc":227,"text":"def test_set_context(self):\n\n for context in self.contexts:\n\n context_dict = rcmod.plotting_context(context)\n rcmod.set_context(context)\n self.assert_rc_params(context_dict)"},{"col":4,"comment":"null","endLoc":249,"header":"def test_context_context_manager(self)","id":2895,"name":"test_context_context_manager","nodeType":"Function","startLoc":235,"text":"def test_context_context_manager(self):\n\n rcmod.set_context(\"notebook\")\n orig_params = rcmod.plotting_context()\n context_params = rcmod.plotting_context(\"paper\")\n\n with rcmod.plotting_context(\"paper\"):\n self.assert_rc_params(context_params)\n self.assert_rc_params(orig_params)\n\n @rcmod.plotting_context(\"paper\")\n def func():\n self.assert_rc_params(context_params)\n func()\n self.assert_rc_params(orig_params)"},{"attributeType":"list","col":8,"comment":"null","endLoc":621,"id":2896,"name":"plot_data","nodeType":"Attribute","startLoc":621,"text":"self.plot_data"},{"attributeType":"list","col":4,"comment":"null","endLoc":185,"id":2898,"name":"contexts","nodeType":"Attribute","startLoc":185,"text":"contexts"},{"className":"TestPalette","col":0,"comment":"null","endLoc":270,"id":2899,"nodeType":"Class","startLoc":252,"text":"class TestPalette(RCParamFixtures):\n\n def test_set_palette(self):\n\n rcmod.set_palette(\"deep\")\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n\n rcmod.set_palette(\"pastel6\")\n assert utils.get_color_cycle() == palettes.color_palette(\"pastel6\", 6)\n\n rcmod.set_palette(\"dark\", 4)\n assert utils.get_color_cycle() == palettes.color_palette(\"dark\", 4)\n\n rcmod.set_palette(\"Set2\", color_codes=True)\n assert utils.get_color_cycle() == palettes.color_palette(\"Set2\", 8)\n\n assert mpl.colors.same_color(\n mpl.rcParams[\"patch.facecolor\"], palettes.color_palette()[0]\n )"},{"col":4,"comment":"null","endLoc":270,"header":"def test_set_palette(self)","id":2900,"name":"test_set_palette","nodeType":"Function","startLoc":254,"text":"def test_set_palette(self):\n\n rcmod.set_palette(\"deep\")\n assert utils.get_color_cycle() == palettes.color_palette(\"deep\", 10)\n\n rcmod.set_palette(\"pastel6\")\n assert utils.get_color_cycle() == palettes.color_palette(\"pastel6\", 6)\n\n rcmod.set_palette(\"dark\", 4)\n assert utils.get_color_cycle() == palettes.color_palette(\"dark\", 4)\n\n rcmod.set_palette(\"Set2\", color_codes=True)\n assert utils.get_color_cycle() == palettes.color_palette(\"Set2\", 8)\n\n assert mpl.colors.same_color(\n mpl.rcParams[\"patch.facecolor\"], palettes.color_palette()[0]\n )"},{"col":0,"comment":"null","endLoc":142,"header":"@pytest.fixture\ndef long_dict(long_df)","id":2901,"name":"long_dict","nodeType":"Function","startLoc":139,"text":"@pytest.fixture\ndef long_dict(long_df):\n\n return long_df.to_dict()"},{"attributeType":"None","col":8,"comment":"null","endLoc":622,"id":2902,"name":"group_label","nodeType":"Attribute","startLoc":622,"text":"self.group_label"},{"className":"TestFonts","col":0,"comment":"null","endLoc":311,"id":2903,"nodeType":"Class","startLoc":273,"text":"class TestFonts(RCParamFixtures):\n\n _no_verdana = not has_verdana()\n\n @pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_set_font(self):\n\n rcmod.set_theme(font=\"Verdana\")\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() == \"Verdana\"\n\n rcmod.set_theme()\n\n def test_set_serif_font(self):\n\n rcmod.set_theme(font=\"serif\")\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() in mpl.rcParams[\"font.serif\"]\n\n rcmod.set_theme()\n\n @pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_different_sans_serif(self):\n\n rcmod.set_theme()\n rcmod.set_style(rc={\"font.sans-serif\": [\"Verdana\"]})\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() == \"Verdana\"\n\n rcmod.set_theme()"},{"col":4,"comment":"null","endLoc":287,"header":"@pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_set_font(self)","id":2904,"name":"test_set_font","nodeType":"Function","startLoc":277,"text":"@pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_set_font(self):\n\n rcmod.set_theme(font=\"Verdana\")\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() == \"Verdana\"\n\n rcmod.set_theme()"},{"col":0,"comment":"null","endLoc":154,"header":"@pytest.fixture\ndef repeated_df(rng)","id":2905,"name":"repeated_df","nodeType":"Function","startLoc":145,"text":"@pytest.fixture\ndef repeated_df(rng):\n\n n = 100\n return pd.DataFrame(dict(\n x=np.tile(np.arange(n // 2), 2),\n y=rng.normal(size=n),\n a=rng.choice(list(\"abc\"), n),\n u=np.repeat(np.arange(2), n // 2),\n ))"},{"col":4,"comment":"null","endLoc":298,"header":"def test_set_serif_font(self)","id":2906,"name":"test_set_serif_font","nodeType":"Function","startLoc":289,"text":"def test_set_serif_font(self):\n\n rcmod.set_theme(font=\"serif\")\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() in mpl.rcParams[\"font.serif\"]\n\n rcmod.set_theme()"},{"col":4,"comment":"null","endLoc":311,"header":"@pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_different_sans_serif(self)","id":2907,"name":"test_different_sans_serif","nodeType":"Function","startLoc":300,"text":"@pytest.mark.skipif(_no_verdana, reason=\"Verdana font is not present\")\n def test_different_sans_serif(self):\n\n rcmod.set_theme()\n rcmod.set_style(rc={\"font.sans-serif\": [\"Verdana\"]})\n\n _, ax = plt.subplots()\n ax.set_xlabel(\"foo\")\n\n assert ax.xaxis.label.get_fontname() == \"Verdana\"\n\n rcmod.set_theme()"},{"attributeType":"bool","col":4,"comment":"null","endLoc":275,"id":2908,"name":"_no_verdana","nodeType":"Attribute","startLoc":275,"text":"_no_verdana"},{"col":0,"comment":"Helper to verify if Verdana font is present","endLoc":30,"header":"def has_verdana()","id":2909,"name":"has_verdana","nodeType":"Function","startLoc":10,"text":"def has_verdana():\n \"\"\"Helper to verify if Verdana font is present\"\"\"\n # This import is relatively lengthy, so to prevent its import for\n # testing other tests in this module not requiring this knowledge,\n # import font_manager here\n import matplotlib.font_manager as mplfm\n try:\n verdana_font = mplfm.findfont('Verdana', fallback_to_default=False)\n except: # noqa\n # if https://github.com/matplotlib/matplotlib/pull/3435\n # gets accepted\n return False\n # otherwise check if not matching the logic for a 'default' one\n try:\n unlikely_font = mplfm.findfont(\"very_unlikely_to_exist1234\",\n fallback_to_default=False)\n except: # noqa\n # if matched verdana but not unlikely, Verdana must exist\n return True\n # otherwise -- if they match, must be the same default\n return verdana_font != unlikely_font"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":2910,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":3,"id":2911,"name":"mpl","nodeType":"Attribute","startLoc":3,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":4,"id":2912,"name":"plt","nodeType":"Attribute","startLoc":4,"text":"plt"},{"attributeType":"null","col":24,"comment":"null","endLoc":5,"id":2913,"name":"npt","nodeType":"Attribute","startLoc":5,"text":"npt"},{"col":4,"comment":"null","endLoc":826,"header":"def test_empty_grid(self)","id":2914,"name":"test_empty_grid","nodeType":"Function","startLoc":823,"text":"def test_empty_grid(self):\n\n with pytest.raises(ValueError, match=\"No variables found\"):\n ag.PairGrid(self.df[[\"a\", \"b\"]])"},{"col":4,"comment":"null","endLoc":854,"header":"def test_map(self)","id":2915,"name":"test_map","nodeType":"Function","startLoc":828,"text":"def test_map(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g1 = ag.PairGrid(self.df)\n g1.map(plt.scatter)\n\n for i, axes_i in enumerate(g1.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n g2 = ag.PairGrid(self.df, hue=\"a\")\n g2.map(plt.scatter)\n\n for i, axes_i in enumerate(g2.axes):\n for j, ax in enumerate(axes_i):\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n for k, k_level in enumerate(self.df.a.unique()):\n x_in_k = x_in[self.df.a == k_level]\n y_in_k = y_in[self.df.a == k_level]\n x_out, y_out = ax.collections[k].get_offsets().T\n npt.assert_array_equal(x_in_k, x_out)\n npt.assert_array_equal(y_in_k, y_out)"},{"col":0,"comment":"null","endLoc":164,"header":"@pytest.fixture\ndef missing_df(rng, long_df)","id":2916,"name":"missing_df","nodeType":"Function","startLoc":157,"text":"@pytest.fixture\ndef missing_df(rng, long_df):\n\n df = long_df.copy()\n for col in df:\n idx = rng.permutation(df.index)[:10]\n df.loc[idx, col] = np.nan\n return df"},{"col":0,"comment":"null","endLoc":174,"header":"@pytest.fixture\ndef object_df(rng, long_df)","id":2917,"name":"object_df","nodeType":"Function","startLoc":167,"text":"@pytest.fixture\ndef object_df(rng, long_df):\n\n df = long_df.copy()\n # objectify numeric columns\n for col in [\"c\", \"s\", \"f\"]:\n df[col] = df[col].astype(object)\n return df"},{"col":0,"comment":"null","endLoc":180,"header":"@pytest.fixture\ndef null_series(flat_series)","id":2918,"name":"null_series","nodeType":"Function","startLoc":177,"text":"@pytest.fixture\ndef null_series(flat_series):\n\n return pd.Series(index=flat_series.index, dtype='float64')"},{"attributeType":"null","col":16,"comment":"null","endLoc":1,"id":2919,"name":"np","nodeType":"Attribute","startLoc":1,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":2,"id":2920,"name":"pd","nodeType":"Attribute","startLoc":2,"text":"pd"},{"id":2921,"name":"LICENSE.md","nodeType":"TextFile","path":"","text":"Copyright (c) 2012-2021, Michael L. Waskom\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the project nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"col":4,"comment":"null","endLoc":392,"header":"def test_crayon_palette(self)","id":2922,"name":"test_crayon_palette","nodeType":"Function","startLoc":386,"text":"def test_crayon_palette(self):\n\n names = list(crayons.keys())[10:15]\n colors = palettes.crayon_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n assert as_hex == crayons[name].lower()"},{"fileName":"test_area.py","filePath":"tests/_marks","id":2923,"nodeType":"File","text":"\nimport matplotlib as mpl\nfrom matplotlib.colors import to_rgba, to_rgba_array\n\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.plot import Plot\nfrom seaborn._marks.area import Area, Band\n\n\nclass TestArea:\n\n def test_single_defaults(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n p = Plot(x=x, y=y).add(Area()).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n verts = poly.get_path().vertices.T\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n expected_x = [1, 2, 3, 3, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [0, 0, 0, 1, 2, 1, 0]\n assert_array_equal(verts[1], expected_y)\n\n fc = poly.get_facecolor()\n assert_array_equal(fc, to_rgba(colors[0], .2))\n\n ec = poly.get_edgecolor()\n assert_array_equal(ec, to_rgba(colors[0], 1))\n\n lw = poly.get_linewidth()\n assert_array_equal(lw, mpl.rcParams[\"patch.linewidth\"] * 2)\n\n def test_set_properties(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n mark = Area(\n color=\".33\",\n alpha=.3,\n edgecolor=\".88\",\n edgealpha=.8,\n edgewidth=2,\n edgestyle=(0, (2, 1)),\n )\n p = Plot(x=x, y=y).add(mark).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n\n fc = poly.get_facecolor()\n assert_array_equal(fc, to_rgba(mark.color, mark.alpha))\n\n ec = poly.get_edgecolor()\n assert_array_equal(ec, to_rgba(mark.edgecolor, mark.edgealpha))\n\n lw = poly.get_linewidth()\n assert_array_equal(lw, mark.edgewidth * 2)\n\n ls = poly.get_linestyle()\n dash_on, dash_off = mark.edgestyle[1]\n expected = (0, (mark.edgewidth * dash_on / 4, mark.edgewidth * dash_off / 4))\n assert ls == expected\n\n def test_mapped_properties(self):\n\n x, y = [1, 2, 3, 2, 3, 4], [1, 2, 1, 1, 3, 2]\n g = [\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"]\n cs = [\".2\", \".8\"]\n p = Plot(x=x, y=y, color=g, edgewidth=g).scale(color=cs).add(Area()).plot()\n ax = p._figure.axes[0]\n\n expected_x = [1, 2, 3, 3, 2, 1, 1], [2, 3, 4, 4, 3, 2, 2]\n expected_y = [0, 0, 0, 1, 2, 1, 0], [0, 0, 0, 2, 3, 1, 0]\n\n for i, poly in enumerate(ax.patches):\n verts = poly.get_path().vertices.T\n assert_array_equal(verts[0], expected_x[i])\n assert_array_equal(verts[1], expected_y[i])\n\n fcs = [p.get_facecolor() for p in ax.patches]\n assert_array_equal(fcs, to_rgba_array(cs, .2))\n\n ecs = [p.get_edgecolor() for p in ax.patches]\n assert_array_equal(ecs, to_rgba_array(cs, 1))\n\n lws = [p.get_linewidth() for p in ax.patches]\n assert lws[0] > lws[1]\n\n def test_unfilled(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n c = \".5\"\n p = Plot(x=x, y=y).add(Area(fill=False, color=c)).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n assert poly.get_facecolor() == to_rgba(c, 0)\n\n\nclass TestBand:\n\n def test_range(self):\n\n x, ymin, ymax = [1, 2, 4], [2, 1, 4], [3, 3, 5]\n p = Plot(x=x, ymin=ymin, ymax=ymax).add(Band()).plot()\n ax = p._figure.axes[0]\n verts = ax.patches[0].get_path().vertices.T\n\n expected_x = [1, 2, 4, 4, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [2, 1, 4, 5, 3, 3, 2]\n assert_array_equal(verts[1], expected_y)\n\n def test_auto_range(self):\n\n x = [1, 1, 2, 2, 2]\n y = [1, 2, 3, 4, 5]\n p = Plot(x=x, y=y).add(Band()).plot()\n ax = p._figure.axes[0]\n verts = ax.patches[0].get_path().vertices.T\n\n expected_x = [1, 2, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [1, 3, 5, 2, 1]\n assert_array_equal(verts[1], expected_y)\n"},{"className":"TestArea","col":0,"comment":"null","endLoc":98,"id":2924,"nodeType":"Class","startLoc":11,"text":"class TestArea:\n\n def test_single_defaults(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n p = Plot(x=x, y=y).add(Area()).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n verts = poly.get_path().vertices.T\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n expected_x = [1, 2, 3, 3, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [0, 0, 0, 1, 2, 1, 0]\n assert_array_equal(verts[1], expected_y)\n\n fc = poly.get_facecolor()\n assert_array_equal(fc, to_rgba(colors[0], .2))\n\n ec = poly.get_edgecolor()\n assert_array_equal(ec, to_rgba(colors[0], 1))\n\n lw = poly.get_linewidth()\n assert_array_equal(lw, mpl.rcParams[\"patch.linewidth\"] * 2)\n\n def test_set_properties(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n mark = Area(\n color=\".33\",\n alpha=.3,\n edgecolor=\".88\",\n edgealpha=.8,\n edgewidth=2,\n edgestyle=(0, (2, 1)),\n )\n p = Plot(x=x, y=y).add(mark).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n\n fc = poly.get_facecolor()\n assert_array_equal(fc, to_rgba(mark.color, mark.alpha))\n\n ec = poly.get_edgecolor()\n assert_array_equal(ec, to_rgba(mark.edgecolor, mark.edgealpha))\n\n lw = poly.get_linewidth()\n assert_array_equal(lw, mark.edgewidth * 2)\n\n ls = poly.get_linestyle()\n dash_on, dash_off = mark.edgestyle[1]\n expected = (0, (mark.edgewidth * dash_on / 4, mark.edgewidth * dash_off / 4))\n assert ls == expected\n\n def test_mapped_properties(self):\n\n x, y = [1, 2, 3, 2, 3, 4], [1, 2, 1, 1, 3, 2]\n g = [\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"]\n cs = [\".2\", \".8\"]\n p = Plot(x=x, y=y, color=g, edgewidth=g).scale(color=cs).add(Area()).plot()\n ax = p._figure.axes[0]\n\n expected_x = [1, 2, 3, 3, 2, 1, 1], [2, 3, 4, 4, 3, 2, 2]\n expected_y = [0, 0, 0, 1, 2, 1, 0], [0, 0, 0, 2, 3, 1, 0]\n\n for i, poly in enumerate(ax.patches):\n verts = poly.get_path().vertices.T\n assert_array_equal(verts[0], expected_x[i])\n assert_array_equal(verts[1], expected_y[i])\n\n fcs = [p.get_facecolor() for p in ax.patches]\n assert_array_equal(fcs, to_rgba_array(cs, .2))\n\n ecs = [p.get_edgecolor() for p in ax.patches]\n assert_array_equal(ecs, to_rgba_array(cs, 1))\n\n lws = [p.get_linewidth() for p in ax.patches]\n assert lws[0] > lws[1]\n\n def test_unfilled(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n c = \".5\"\n p = Plot(x=x, y=y).add(Area(fill=False, color=c)).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n assert poly.get_facecolor() == to_rgba(c, 0)"},{"col":4,"comment":"null","endLoc":35,"header":"def test_single_defaults(self)","id":2925,"name":"test_single_defaults","nodeType":"Function","startLoc":13,"text":"def test_single_defaults(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n p = Plot(x=x, y=y).add(Area()).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n verts = poly.get_path().vertices.T\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n expected_x = [1, 2, 3, 3, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [0, 0, 0, 1, 2, 1, 0]\n assert_array_equal(verts[1], expected_y)\n\n fc = poly.get_facecolor()\n assert_array_equal(fc, to_rgba(colors[0], .2))\n\n ec = poly.get_edgecolor()\n assert_array_equal(ec, to_rgba(colors[0], 1))\n\n lw = poly.get_linewidth()\n assert_array_equal(lw, mpl.rcParams[\"patch.linewidth\"] * 2)"},{"attributeType":"None | list","col":8,"comment":"null","endLoc":628,"id":2926,"name":"plot_units","nodeType":"Attribute","startLoc":628,"text":"self.plot_units"},{"col":4,"comment":"null","endLoc":2104,"header":"def test_colorbar(self, long_df)","id":2927,"name":"test_colorbar","nodeType":"Function","startLoc":2096,"text":"def test_colorbar(self, long_df):\n\n f, ax = plt.subplots()\n histplot(long_df, x=\"x\", y=\"y\", cbar=True, ax=ax)\n assert len(ax.figure.axes) == 2\n\n f, (ax, cax) = plt.subplots(2)\n histplot(long_df, x=\"x\", y=\"y\", cbar=True, cbar_ax=cax, ax=ax)\n assert len(ax.figure.axes) == 2"},{"fileName":"multiple_bivariate_kde.py","filePath":"examples","id":2928,"nodeType":"File","text":"\"\"\"\nMultiple bivariate KDE plots\n============================\n\n_thumb: .6, .45\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"darkgrid\")\niris = sns.load_dataset(\"iris\")\n\n# Set up the figure\nf, ax = plt.subplots(figsize=(8, 8))\nax.set_aspect(\"equal\")\n\n# Draw a contour plot to represent each bivariate density\nsns.kdeplot(\n data=iris.query(\"species != 'versicolor'\"),\n x=\"sepal_width\",\n y=\"sepal_length\",\n hue=\"species\",\n thresh=.1,\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":2929,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"col":0,"comment":"Make a palette with color names from Crayola crayons.\n\n Colors are taken from here:\n https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors\n\n This is just a simple wrapper around the `seaborn.crayons` dictionary.\n\n Parameters\n ----------\n colors : list of strings\n List of keys in the `seaborn.crayons` dictionary.\n\n Returns\n -------\n palette\n A list of colors as RGB tuples.\n\n See Also\n --------\n xkcd_palette : Make a palette with named colors from the XKCD color survey.\n\n ","endLoc":662,"header":"def crayon_palette(colors)","id":2930,"name":"crayon_palette","nodeType":"Function","startLoc":638,"text":"def crayon_palette(colors):\n \"\"\"Make a palette with color names from Crayola crayons.\n\n Colors are taken from here:\n https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors\n\n This is just a simple wrapper around the `seaborn.crayons` dictionary.\n\n Parameters\n ----------\n colors : list of strings\n List of keys in the `seaborn.crayons` dictionary.\n\n Returns\n -------\n palette\n A list of colors as RGB tuples.\n\n See Also\n --------\n xkcd_palette : Make a palette with named colors from the XKCD color survey.\n\n \"\"\"\n palette = [crayons[name] for name in colors]\n return color_palette(palette, len(palette))"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":2931,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":2932,"name":"iris","nodeType":"Attribute","startLoc":11,"text":"iris"},{"className":"TestECDFPlotUnivariate","col":0,"comment":"null","endLoc":2220,"id":2933,"nodeType":"Class","startLoc":2107,"text":"class TestECDFPlotUnivariate(SharedAxesLevelTests):\n\n func = staticmethod(ecdfplot)\n\n def get_last_color(self, ax):\n\n return to_rgb(ax.lines[-1].get_color())\n\n @pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n ecdfplot(data=long_df, ax=ax, **{variable: vector})\n\n xdata = [l.get_xdata() for l in ax.lines]\n for a, b in itertools.product(xdata, xdata):\n assert_array_equal(a, b)\n\n ydata = [l.get_ydata() for l in ax.lines]\n for a, b in itertools.product(ydata, ydata):\n assert_array_equal(a, b)\n\n def test_hue(self, long_df):\n\n ax = ecdfplot(long_df, x=\"x\", hue=\"a\")\n\n for line, color in zip(ax.lines[::-1], color_palette()):\n assert_colors_equal(line.get_color(), color)\n\n def test_line_kwargs(self, long_df):\n\n color = \"r\"\n ls = \"--\"\n lw = 3\n ax = ecdfplot(long_df, x=\"x\", color=color, ls=ls, lw=lw)\n\n for line in ax.lines:\n assert_colors_equal(line.get_color(), color)\n assert line.get_linestyle() == ls\n assert line.get_linewidth() == lw\n\n @pytest.mark.parametrize(\"data_var\", [\"x\", \"y\"])\n def test_drawstyle(self, flat_series, data_var):\n\n ax = ecdfplot(**{data_var: flat_series})\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n assert ax.lines[0].get_drawstyle() == drawstyles[data_var]\n\n @pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits(self, flat_series, data_var, stat_var):\n\n ax = ecdfplot(**{data_var: flat_series})\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 0\n assert data[-1] == 1\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, 1]\n\n @pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits_complementary(self, flat_series, data_var, stat_var):\n\n ax = ecdfplot(**{data_var: flat_series}, complementary=True)\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 1\n assert data[-1] == 0\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, 1]\n\n @pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_count(self, flat_series, data_var, stat_var):\n\n n = len(flat_series)\n ax = ecdfplot(**{data_var: flat_series}, stat=\"count\")\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 0\n assert data[-1] == n\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, n]\n\n def test_weights(self):\n\n ax = ecdfplot(x=[1, 2, 3], weights=[1, 1, 2])\n y = ax.lines[0].get_ydata()\n assert_array_equal(y, [0, .25, .5, 1])\n\n def test_bivariate_error(self, long_df):\n\n with pytest.raises(NotImplementedError, match=\"Bivariate ECDF plots\"):\n ecdfplot(data=long_df, x=\"x\", y=\"y\")\n\n def test_log_scale(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n\n ecdfplot(data=long_df, x=\"z\", ax=ax1)\n ecdfplot(data=long_df, x=\"z\", log_scale=True, ax=ax2)\n\n # Ignore first point, which either -inf (in linear) or 0 (in log)\n line1 = ax1.lines[0].get_xydata()[1:]\n line2 = ax2.lines[0].get_xydata()[1:]\n\n assert_array_almost_equal(line1, line2)"},{"col":4,"comment":"null","endLoc":2113,"header":"def get_last_color(self, ax)","id":2934,"name":"get_last_color","nodeType":"Function","startLoc":2111,"text":"def get_last_color(self, ax):\n\n return to_rgb(ax.lines[-1].get_color())"},{"col":4,"comment":"null","endLoc":405,"header":"def test_color_codes(self)","id":2935,"name":"test_color_codes","nodeType":"Function","startLoc":394,"text":"def test_color_codes(self):\n\n palettes.set_color_codes(\"deep\")\n colors = palettes.color_palette(\"deep6\") + [\".1\"]\n for code, color in zip(\"bgrmyck\", colors):\n rgb_want = mpl.colors.colorConverter.to_rgb(color)\n rgb_got = mpl.colors.colorConverter.to_rgb(code)\n assert rgb_want == rgb_got\n palettes.set_color_codes(\"reset\")\n\n with pytest.raises(ValueError):\n palettes.set_color_codes(\"Set1\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":2936,"name":"f","nodeType":"Attribute","startLoc":14,"text":"f"},{"col":4,"comment":"null","endLoc":2133,"header":"@pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_vectors(self, long_df, variable)","id":2937,"name":"test_long_vectors","nodeType":"Function","startLoc":2115,"text":"@pytest.mark.parametrize(\"variable\", [\"x\", \"y\"])\n def test_long_vectors(self, long_df, variable):\n\n vector = long_df[variable]\n vectors = [\n variable, vector, vector.to_numpy(), vector.to_list(),\n ]\n\n f, ax = plt.subplots()\n for vector in vectors:\n ecdfplot(data=long_df, ax=ax, **{variable: vector})\n\n xdata = [l.get_xdata() for l in ax.lines]\n for a, b in itertools.product(xdata, xdata):\n assert_array_equal(a, b)\n\n ydata = [l.get_ydata() for l in ax.lines]\n for a, b in itertools.product(ydata, ydata):\n assert_array_equal(a, b)"},{"attributeType":"null","col":3,"comment":"null","endLoc":14,"id":2938,"name":"ax","nodeType":"Attribute","startLoc":14,"text":"ax"},{"col":0,"comment":"","endLoc":6,"header":"multiple_bivariate_kde.py#","id":2939,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nMultiple bivariate KDE plots\n============================\n\n_thumb: .6, .45\n\"\"\"\n\nsns.set_theme(style=\"darkgrid\")\n\niris = sns.load_dataset(\"iris\")\n\nf, ax = plt.subplots(figsize=(8, 8))\n\nax.set_aspect(\"equal\")\n\nsns.kdeplot(\n data=iris.query(\"species != 'versicolor'\"),\n x=\"sepal_width\",\n y=\"sepal_length\",\n hue=\"species\",\n thresh=.1,\n)"},{"attributeType":"list | list | list","col":8,"comment":"null","endLoc":624,"id":2940,"name":"group_names","nodeType":"Attribute","startLoc":624,"text":"self.group_names"},{"attributeType":"None | list","col":8,"comment":"null","endLoc":625,"id":2941,"name":"plot_hues","nodeType":"Attribute","startLoc":625,"text":"self.plot_hues"},{"col":4,"comment":"null","endLoc":64,"header":"def test_set_properties(self)","id":2942,"name":"test_set_properties","nodeType":"Function","startLoc":37,"text":"def test_set_properties(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n mark = Area(\n color=\".33\",\n alpha=.3,\n edgecolor=\".88\",\n edgealpha=.8,\n edgewidth=2,\n edgestyle=(0, (2, 1)),\n )\n p = Plot(x=x, y=y).add(mark).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n\n fc = poly.get_facecolor()\n assert_array_equal(fc, to_rgba(mark.color, mark.alpha))\n\n ec = poly.get_edgecolor()\n assert_array_equal(ec, to_rgba(mark.edgecolor, mark.edgealpha))\n\n lw = poly.get_linewidth()\n assert_array_equal(lw, mark.edgewidth * 2)\n\n ls = poly.get_linestyle()\n dash_on, dash_off = mark.edgestyle[1]\n expected = (0, (mark.edgewidth * dash_on / 4, mark.edgewidth * dash_off / 4))\n assert ls == expected"},{"attributeType":"None","col":8,"comment":"null","endLoc":626,"id":2943,"name":"hue_title","nodeType":"Attribute","startLoc":626,"text":"self.hue_title"},{"id":2944,"name":"objects.Jitter.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f2e5a85d-c710-492b-a4fc-09b45ae26471\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"penguins = load_dataset(\\\"penguins\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"14b5927c-42f1-4934-adee-3d380b8b3228\",\n \"metadata\": {},\n \"source\": [\n \"When used without any arguments, a small amount of jitter will be applied along the orientation axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"bc1b4941-bbe6-4afc-b51a-0ac67cbe417d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, \\\"species\\\", \\\"body_mass_g\\\")\\n\",\n \" .add(so.Dots(), so.Jitter())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"1101690e-6c19-4219-aa4e-180798454df1\",\n \"metadata\": {},\n \"source\": [\n \"The `width` parameter controls the amount of jitter relative to the spacing between the marks:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c4251b9d-8b11-4c2c-905c-2f3b523dee70\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, \\\"species\\\", \\\"body_mass_g\\\")\\n\",\n \" .add(so.Dots(), so.Jitter(.5))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"38aa639a-356e-4674-970b-53d55379b2b7\",\n \"metadata\": {},\n \"source\": [\n \"The `width` parameter always applies to the orientation axis, so the direction of jitter will adapt along with the orientation:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"1cfe1c07-7e81-45a0-a989-240503046133\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, \\\"body_mass_g\\\", \\\"species\\\")\\n\",\n \" .add(so.Dots(), so.Jitter(.5))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"0f5de4cc-3383-4503-8b59-9c48230a12a5\",\n \"metadata\": {},\n \"source\": [\n \"Because the `width` jitter is relative, it can be used when the orientation axis is numeric without further tweaking:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c94c41e8-29c4-4439-a5d1-0b8ffb244890\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins[\\\"body_mass_g\\\"].round(-3), penguins[\\\"flipper_length_mm\\\"])\\n\",\n \" .add(so.Dots(), so.Jitter())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"dd982dfa-fd9f-4edc-8190-18f0e101ae1a\",\n \"metadata\": {},\n \"source\": [\n \"In contrast to `width`, the `x` and `y` parameters always refer to specific axes and control the jitter in data units:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b0f2e5ca-68ad-4439-a4ee-f32f65682e95\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins[\\\"body_mass_g\\\"].round(-3), penguins[\\\"flipper_length_mm\\\"])\\n\",\n \" .add(so.Dots(), so.Jitter(x=100))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a90ba526-8043-42ed-8f57-36445c163c0d\",\n \"metadata\": {},\n \"source\": [\n \"Both `x` and `y` can be used in a single transform:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"6c07ed1d-ac77-4b30-90a8-e1b8760f9fad\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(\\n\",\n \" penguins[\\\"body_mass_g\\\"].round(-3),\\n\",\n \" penguins[\\\"flipper_length_mm\\\"].round(-1),\\n\",\n \" )\\n\",\n \" .add(so.Dots(), so.Jitter(x=200, y=5))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"bb04c7a2-93f0-44cf-aacf-0eb436d0f14b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":89,"header":"def test_mapped_properties(self)","id":2945,"name":"test_mapped_properties","nodeType":"Function","startLoc":66,"text":"def test_mapped_properties(self):\n\n x, y = [1, 2, 3, 2, 3, 4], [1, 2, 1, 1, 3, 2]\n g = [\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"]\n cs = [\".2\", \".8\"]\n p = Plot(x=x, y=y, color=g, edgewidth=g).scale(color=cs).add(Area()).plot()\n ax = p._figure.axes[0]\n\n expected_x = [1, 2, 3, 3, 2, 1, 1], [2, 3, 4, 4, 3, 2, 2]\n expected_y = [0, 0, 0, 1, 2, 1, 0], [0, 0, 0, 2, 3, 1, 0]\n\n for i, poly in enumerate(ax.patches):\n verts = poly.get_path().vertices.T\n assert_array_equal(verts[0], expected_x[i])\n assert_array_equal(verts[1], expected_y[i])\n\n fcs = [p.get_facecolor() for p in ax.patches]\n assert_array_equal(fcs, to_rgba_array(cs, .2))\n\n ecs = [p.get_edgecolor() for p in ax.patches]\n assert_array_equal(ecs, to_rgba_array(cs, 1))\n\n lws = [p.get_linewidth() for p in ax.patches]\n assert lws[0] > lws[1]"},{"attributeType":"null","col":8,"comment":"null","endLoc":711,"id":2946,"name":"colors","nodeType":"Attribute","startLoc":711,"text":"self.colors"},{"col":4,"comment":"null","endLoc":411,"header":"def test_as_hex(self)","id":2947,"name":"test_as_hex","nodeType":"Function","startLoc":407,"text":"def test_as_hex(self):\n\n pal = palettes.color_palette(\"deep\")\n for rgb, hex in zip(pal, pal.as_hex()):\n assert mpl.colors.rgb2hex(rgb) == hex"},{"fileName":"palette_generation.py","filePath":"examples","id":2948,"nodeType":"File","text":"\"\"\"\nDifferent cubehelix palettes\n============================\n\n_thumb: .4, .65\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"white\")\nrs = np.random.RandomState(50)\n\n# Set up the matplotlib figure\nf, axes = plt.subplots(3, 3, figsize=(9, 9), sharex=True, sharey=True)\n\n# Rotate the starting point around the cubehelix hue circle\nfor ax, s in zip(axes.flat, np.linspace(0, 3, 10)):\n\n # Create a cubehelix colormap to use with kdeplot\n cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True)\n\n # Generate and plot a random bivariate dataset\n x, y = rs.normal(size=(2, 50))\n sns.kdeplot(\n x=x, y=y,\n cmap=cmap, fill=True,\n clip=(-5, 5), cut=10,\n thresh=0, levels=15,\n ax=ax,\n )\n ax.set_axis_off()\n\nax.set(xlim=(-3.5, 3.5), ylim=(-3.5, 3.5))\nf.subplots_adjust(0, 0, 1, 1, .08, .08)\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":7,"id":2949,"name":"np","nodeType":"Attribute","startLoc":7,"text":"np"},{"className":"_BoxPlotter","col":0,"comment":"null","endLoc":891,"id":2951,"nodeType":"Class","startLoc":779,"text":"class _BoxPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n\n self.dodge = dodge\n self.width = width\n self.fliersize = fliersize\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n def draw_boxplot(self, ax, kws):\n \"\"\"Use matplotlib to draw a boxplot on an Axes.\"\"\"\n vert = self.orient == \"v\"\n\n props = {}\n for obj in [\"box\", \"whisker\", \"cap\", \"median\", \"flier\"]:\n props[obj] = kws.pop(obj + \"props\", {})\n\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = np.asarray(remove_na(group_data))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[i],\n widths=self.width,\n **kws)\n color = self.colors[i]\n self.restyle_boxplot(artist_dict, color, props)\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = np.asarray(remove_na(group_data[hue_mask]))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n center = i + offsets[j]\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[center],\n widths=self.nested_width,\n **kws)\n self.restyle_boxplot(artist_dict, self.colors[j], props)\n # Add legend data, but just for one set of boxes\n\n def restyle_boxplot(self, artist_dict, color, props):\n \"\"\"Take a drawn matplotlib boxplot and make it look nice.\"\"\"\n for box in artist_dict[\"boxes\"]:\n box.update(dict(facecolor=color,\n zorder=.9,\n edgecolor=self.gray,\n linewidth=self.linewidth))\n box.update(props[\"box\"])\n for whisk in artist_dict[\"whiskers\"]:\n whisk.update(dict(color=self.gray,\n linewidth=self.linewidth,\n linestyle=\"-\"))\n whisk.update(props[\"whisker\"])\n for cap in artist_dict[\"caps\"]:\n cap.update(dict(color=self.gray,\n linewidth=self.linewidth))\n cap.update(props[\"cap\"])\n for med in artist_dict[\"medians\"]:\n med.update(dict(color=self.gray,\n linewidth=self.linewidth))\n med.update(props[\"median\"])\n for fly in artist_dict[\"fliers\"]:\n fly.update(dict(markerfacecolor=self.gray,\n marker=\"d\",\n markeredgecolor=self.gray,\n markersize=self.fliersize))\n fly.update(props[\"flier\"])\n\n def plot(self, ax, boxplot_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_boxplot(ax, boxplot_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":2952,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"col":4,"comment":"Use matplotlib to draw a boxplot on an Axes.","endLoc":856,"header":"def draw_boxplot(self, ax, kws)","id":2953,"name":"draw_boxplot","nodeType":"Function","startLoc":796,"text":"def draw_boxplot(self, ax, kws):\n \"\"\"Use matplotlib to draw a boxplot on an Axes.\"\"\"\n vert = self.orient == \"v\"\n\n props = {}\n for obj in [\"box\", \"whisker\", \"cap\", \"median\", \"flier\"]:\n props[obj] = kws.pop(obj + \"props\", {})\n\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = np.asarray(remove_na(group_data))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[i],\n widths=self.width,\n **kws)\n color = self.colors[i]\n self.restyle_boxplot(artist_dict, color, props)\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = np.asarray(remove_na(group_data[hue_mask]))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n center = i + offsets[j]\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[center],\n widths=self.nested_width,\n **kws)\n self.restyle_boxplot(artist_dict, self.colors[j], props)\n # Add legend data, but just for one set of boxes"},{"attributeType":"null","col":28,"comment":"null","endLoc":9,"id":2954,"name":"plt","nodeType":"Attribute","startLoc":9,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":2955,"name":"rs","nodeType":"Attribute","startLoc":12,"text":"rs"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":2956,"name":"f","nodeType":"Attribute","startLoc":15,"text":"f"},{"attributeType":"null","col":3,"comment":"null","endLoc":15,"id":2957,"name":"axes","nodeType":"Attribute","startLoc":15,"text":"axes"},{"attributeType":"null","col":4,"comment":"null","endLoc":18,"id":2958,"name":"ax","nodeType":"Attribute","startLoc":18,"text":"ax"},{"col":4,"comment":"null","endLoc":869,"header":"def test_map_nonsquare(self)","id":2959,"name":"test_map_nonsquare","nodeType":"Function","startLoc":856,"text":"def test_map_nonsquare(self):\n\n x_vars = [\"x\"]\n y_vars = [\"y\", \"z\"]\n g = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g.map(plt.scatter)\n\n x_in = self.df.x\n for i, i_var in enumerate(y_vars):\n ax = g.axes[i, 0]\n y_in = self.df[i_var]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)"},{"col":4,"comment":"null","endLoc":417,"header":"def test_preserved_palette_length(self)","id":2960,"name":"test_preserved_palette_length","nodeType":"Function","startLoc":413,"text":"def test_preserved_palette_length(self):\n\n pal_in = palettes.color_palette(\"Set1\", 10)\n pal_out = palettes.color_palette(pal_in)\n assert pal_in == pal_out"},{"col":4,"comment":"null","endLoc":887,"header":"def test_map_lower(self)","id":2961,"name":"test_map_lower","nodeType":"Function","startLoc":871,"text":"def test_map_lower(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_lower(plt.scatter)\n\n for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.triu_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0"},{"col":4,"comment":"null","endLoc":424,"header":"def test_html_repr(self)","id":2962,"name":"test_html_repr","nodeType":"Function","startLoc":419,"text":"def test_html_repr(self):\n\n pal = palettes.color_palette()\n html = pal._repr_html_()\n for color in pal.as_hex():\n assert color in html"},{"col":4,"comment":"null","endLoc":439,"header":"def test_colormap_display_patch(self)","id":2963,"name":"test_colormap_display_patch","nodeType":"Function","startLoc":426,"text":"def test_colormap_display_patch(self):\n\n orig_repr_png = getattr(mpl.colors.Colormap, \"_repr_png_\", None)\n orig_repr_html = getattr(mpl.colors.Colormap, \"_repr_html_\", None)\n\n try:\n palettes._patch_colormap_display()\n cmap = mpl.cm.Reds\n assert cmap._repr_html_().startswith('\"Reds')\n')\n\n mpl.colors.Colormap._repr_png_ = _repr_png_\n mpl.colors.Colormap._repr_html_ = _repr_html_"},{"col":4,"comment":"null","endLoc":905,"header":"def test_map_upper(self)","id":2965,"name":"test_map_upper","nodeType":"Function","startLoc":889,"text":"def test_map_upper(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df)\n g.map_upper(plt.scatter)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)\n\n for i, j in zip(*np.tril_indices_from(g.axes)):\n ax = g.axes[i, j]\n assert len(ax.collections) == 0"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":2968,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":3,"id":2969,"name":"mpl","nodeType":"Attribute","startLoc":3,"text":"mpl"},{"attributeType":"null","col":24,"comment":"null","endLoc":6,"id":2970,"name":"npt","nodeType":"Attribute","startLoc":6,"text":"npt"},{"col":4,"comment":"null","endLoc":98,"header":"def test_unfilled(self)","id":2971,"name":"test_unfilled","nodeType":"Function","startLoc":91,"text":"def test_unfilled(self):\n\n x, y = [1, 2, 3], [1, 2, 1]\n c = \".5\"\n p = Plot(x=x, y=y).add(Area(fill=False, color=c)).plot()\n ax = p._figure.axes[0]\n poly = ax.patches[0]\n assert poly.get_facecolor() == to_rgba(c, 0)"},{"className":"TestBand","col":0,"comment":"null","endLoc":128,"id":2972,"nodeType":"Class","startLoc":101,"text":"class TestBand:\n\n def test_range(self):\n\n x, ymin, ymax = [1, 2, 4], [2, 1, 4], [3, 3, 5]\n p = Plot(x=x, ymin=ymin, ymax=ymax).add(Band()).plot()\n ax = p._figure.axes[0]\n verts = ax.patches[0].get_path().vertices.T\n\n expected_x = [1, 2, 4, 4, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [2, 1, 4, 5, 3, 3, 2]\n assert_array_equal(verts[1], expected_y)\n\n def test_auto_range(self):\n\n x = [1, 1, 2, 2, 2]\n y = [1, 2, 3, 4, 5]\n p = Plot(x=x, y=y).add(Band()).plot()\n ax = p._figure.axes[0]\n verts = ax.patches[0].get_path().vertices.T\n\n expected_x = [1, 2, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [1, 3, 5, 2, 1]\n assert_array_equal(verts[1], expected_y)"},{"col":4,"comment":"null","endLoc":114,"header":"def test_range(self)","id":2973,"name":"test_range","nodeType":"Function","startLoc":103,"text":"def test_range(self):\n\n x, ymin, ymax = [1, 2, 4], [2, 1, 4], [3, 3, 5]\n p = Plot(x=x, ymin=ymin, ymax=ymax).add(Band()).plot()\n ax = p._figure.axes[0]\n verts = ax.patches[0].get_path().vertices.T\n\n expected_x = [1, 2, 4, 4, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [2, 1, 4, 5, 3, 3, 2]\n assert_array_equal(verts[1], expected_y)"},{"col":4,"comment":"null","endLoc":2140,"header":"def test_hue(self, long_df)","id":2974,"name":"test_hue","nodeType":"Function","startLoc":2135,"text":"def test_hue(self, long_df):\n\n ax = ecdfplot(long_df, x=\"x\", hue=\"a\")\n\n for line, color in zip(ax.lines[::-1], color_palette()):\n assert_colors_equal(line.get_color(), color)"},{"fileName":"test_line.py","filePath":"tests/_marks","id":2975,"nodeType":"File","text":"\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib.colors import same_color, to_rgba\n\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.plot import Plot\nfrom seaborn._marks.line import Line, Path, Lines, Paths, Range\n\n\nclass TestPath:\n\n def test_xy_data(self):\n\n x = [1, 5, 3, np.nan, 2]\n y = [1, 4, 2, 5, 3]\n g = [1, 2, 1, 1, 2]\n p = Plot(x=x, y=y, group=g).add(Path()).plot()\n line1, line2 = p._figure.axes[0].get_lines()\n\n assert_array_equal(line1.get_xdata(), [1, 3, np.nan])\n assert_array_equal(line1.get_ydata(), [1, 2, np.nan])\n assert_array_equal(line2.get_xdata(), [5, 2])\n assert_array_equal(line2.get_ydata(), [4, 3])\n\n def test_shared_colors_direct(self):\n\n x = y = [1, 2, 3]\n color = \".44\"\n m = Path(color=color)\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), color)\n assert same_color(line.get_markeredgecolor(), color)\n assert same_color(line.get_markerfacecolor(), color)\n\n def test_separate_colors_direct(self):\n\n x = y = [1, 2, 3]\n y = [1, 2, 3]\n m = Path(color=\".22\", edgecolor=\".55\", fillcolor=\".77\")\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), m.color)\n assert same_color(line.get_markeredgecolor(), m.edgecolor)\n assert same_color(line.get_markerfacecolor(), m.fillcolor)\n\n def test_shared_colors_mapped(self):\n\n x = y = [1, 2, 3, 4]\n c = [\"a\", \"a\", \"b\", \"b\"]\n m = Path()\n p = Plot(x=x, y=y, color=c).add(m).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, line in enumerate(ax.get_lines()):\n assert same_color(line.get_color(), colors[i])\n assert same_color(line.get_markeredgecolor(), colors[i])\n assert same_color(line.get_markerfacecolor(), colors[i])\n\n def test_separate_colors_mapped(self):\n\n x = y = [1, 2, 3, 4]\n c = [\"a\", \"a\", \"b\", \"b\"]\n d = [\"x\", \"y\", \"x\", \"y\"]\n m = Path()\n p = Plot(x=x, y=y, color=c, fillcolor=d).add(m).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, line in enumerate(ax.get_lines()):\n assert same_color(line.get_color(), colors[i // 2])\n assert same_color(line.get_markeredgecolor(), colors[i // 2])\n assert same_color(line.get_markerfacecolor(), colors[i % 2])\n\n def test_color_with_alpha(self):\n\n x = y = [1, 2, 3]\n m = Path(color=(.4, .9, .2, .5), fillcolor=(.2, .2, .3, .9))\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), m.color)\n assert same_color(line.get_markeredgecolor(), m.color)\n assert same_color(line.get_markerfacecolor(), m.fillcolor)\n\n def test_color_and_alpha(self):\n\n x = y = [1, 2, 3]\n m = Path(color=(.4, .9, .2), fillcolor=(.2, .2, .3), alpha=.5)\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), to_rgba(m.color, m.alpha))\n assert same_color(line.get_markeredgecolor(), to_rgba(m.color, m.alpha))\n assert same_color(line.get_markerfacecolor(), to_rgba(m.fillcolor, m.alpha))\n\n def test_other_props_direct(self):\n\n x = y = [1, 2, 3]\n m = Path(marker=\"s\", linestyle=\"--\", linewidth=3, pointsize=10, edgewidth=1)\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_marker() == m.marker\n assert line.get_linestyle() == m.linestyle\n assert line.get_linewidth() == m.linewidth\n assert line.get_markersize() == m.pointsize\n assert line.get_markeredgewidth() == m.edgewidth\n\n def test_other_props_mapped(self):\n\n x = y = [1, 2, 3, 4]\n g = [\"a\", \"a\", \"b\", \"b\"]\n m = Path()\n p = Plot(x=x, y=y, marker=g, linestyle=g, pointsize=g).add(m).plot()\n line1, line2 = p._figure.axes[0].get_lines()\n assert line1.get_marker() != line2.get_marker()\n # Matplotlib bug in storing linestyle from dash pattern\n # assert line1.get_linestyle() != line2.get_linestyle()\n assert line1.get_markersize() != line2.get_markersize()\n\n def test_capstyle(self):\n\n x = y = [1, 2]\n rc = {\"lines.solid_capstyle\": \"projecting\", \"lines.dash_capstyle\": \"round\"}\n\n p = Plot(x, y).add(Path()).theme(rc).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_dash_capstyle() == \"projecting\"\n\n p = Plot(x, y).add(Path(linestyle=\"--\")).theme(rc).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_dash_capstyle() == \"round\"\n\n p = Plot(x, y).add(Path({\"solid_capstyle\": \"butt\"})).theme(rc).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_solid_capstyle() == \"butt\"\n\n\nclass TestLine:\n\n # Most behaviors shared with Path and covered by above tests\n\n def test_xy_data(self):\n\n x = [1, 5, 3, np.nan, 2]\n y = [1, 4, 2, 5, 3]\n g = [1, 2, 1, 1, 2]\n p = Plot(x=x, y=y, group=g).add(Line()).plot()\n line1, line2 = p._figure.axes[0].get_lines()\n\n assert_array_equal(line1.get_xdata(), [1, 3])\n assert_array_equal(line1.get_ydata(), [1, 2])\n assert_array_equal(line2.get_xdata(), [2, 5])\n assert_array_equal(line2.get_ydata(), [3, 4])\n\n\nclass TestPaths:\n\n def test_xy_data(self):\n\n x = [1, 5, 3, np.nan, 2]\n y = [1, 4, 2, 5, 3]\n g = [1, 2, 1, 1, 2]\n p = Plot(x=x, y=y, group=g).add(Paths()).plot()\n lines, = p._figure.axes[0].collections\n\n verts = lines.get_paths()[0].vertices.T\n assert_array_equal(verts[0], [1, 3, np.nan])\n assert_array_equal(verts[1], [1, 2, np.nan])\n\n verts = lines.get_paths()[1].vertices.T\n assert_array_equal(verts[0], [5, 2])\n assert_array_equal(verts[1], [4, 3])\n\n def test_set_properties(self):\n\n x = y = [1, 2, 3]\n m = Paths(color=\".737\", linewidth=1, linestyle=(3, 1))\n p = Plot(x=x, y=y).add(m).plot()\n lines, = p._figure.axes[0].collections\n\n assert same_color(lines.get_color().squeeze(), m.color)\n assert lines.get_linewidth().item() == m.linewidth\n assert lines.get_linestyle()[0] == (0, list(m.linestyle))\n\n def test_mapped_properties(self):\n\n x = y = [1, 2, 3, 4]\n g = [\"a\", \"a\", \"b\", \"b\"]\n p = Plot(x=x, y=y, color=g, linewidth=g, linestyle=g).add(Paths()).plot()\n lines, = p._figure.axes[0].collections\n\n assert not np.array_equal(lines.get_colors()[0], lines.get_colors()[1])\n assert lines.get_linewidths()[0] != lines.get_linewidth()[1]\n assert lines.get_linestyle()[0] != lines.get_linestyle()[1]\n\n def test_color_with_alpha(self):\n\n x = y = [1, 2, 3]\n m = Paths(color=(.2, .6, .9, .5))\n p = Plot(x=x, y=y).add(m).plot()\n lines, = p._figure.axes[0].collections\n assert same_color(lines.get_colors().squeeze(), m.color)\n\n def test_color_and_alpha(self):\n\n x = y = [1, 2, 3]\n m = Paths(color=(.2, .6, .9), alpha=.5)\n p = Plot(x=x, y=y).add(m).plot()\n lines, = p._figure.axes[0].collections\n assert same_color(lines.get_colors().squeeze(), to_rgba(m.color, m.alpha))\n\n def test_capstyle(self):\n\n x = y = [1, 2]\n rc = {\"lines.solid_capstyle\": \"projecting\"}\n\n with mpl.rc_context(rc):\n p = Plot(x, y).add(Paths()).plot()\n lines = p._figure.axes[0].collections[0]\n assert lines.get_capstyle() == \"projecting\"\n\n p = Plot(x, y).add(Paths(linestyle=\"--\")).plot()\n lines = p._figure.axes[0].collections[0]\n assert lines.get_capstyle() == \"projecting\"\n\n p = Plot(x, y).add(Paths({\"capstyle\": \"butt\"})).plot()\n lines = p._figure.axes[0].collections[0]\n assert lines.get_capstyle() == \"butt\"\n\n\nclass TestLines:\n\n def test_xy_data(self):\n\n x = [1, 5, 3, np.nan, 2]\n y = [1, 4, 2, 5, 3]\n g = [1, 2, 1, 1, 2]\n p = Plot(x=x, y=y, group=g).add(Lines()).plot()\n lines, = p._figure.axes[0].collections\n\n verts = lines.get_paths()[0].vertices.T\n assert_array_equal(verts[0], [1, 3])\n assert_array_equal(verts[1], [1, 2])\n\n verts = lines.get_paths()[1].vertices.T\n assert_array_equal(verts[0], [2, 5])\n assert_array_equal(verts[1], [3, 4])\n\n def test_single_orient_value(self):\n\n x = [1, 1, 1]\n y = [1, 2, 3]\n p = Plot(x, y).add(Lines()).plot()\n lines, = p._figure.axes[0].collections\n paths, = lines.get_paths()\n assert paths.vertices.shape == (0, 2)\n\n\nclass TestRange:\n\n def test_xy_data(self):\n\n x = [1, 2]\n ymin = [1, 4]\n ymax = [2, 3]\n\n p = Plot(x=x, ymin=ymin, ymax=ymax).add(Range()).plot()\n lines, = p._figure.axes[0].collections\n\n for i, path in enumerate(lines.get_paths()):\n verts = path.vertices.T\n assert_array_equal(verts[0], [x[i], x[i]])\n assert_array_equal(verts[1], [ymin[i], ymax[i]])\n\n def test_auto_range(self):\n\n x = [1, 1, 2, 2, 2]\n y = [1, 2, 3, 4, 5]\n\n p = Plot(x=x, y=y).add(Range()).plot()\n lines, = p._figure.axes[0].collections\n paths = lines.get_paths()\n assert_array_equal(paths[0].vertices, [(1, 1), (1, 2)])\n assert_array_equal(paths[1].vertices, [(2, 3), (2, 5)])\n\n def test_mapped_color(self):\n\n x = [1, 2, 1, 2]\n ymin = [1, 4, 3, 2]\n ymax = [2, 3, 1, 4]\n group = [\"a\", \"a\", \"b\", \"b\"]\n\n p = Plot(x=x, ymin=ymin, ymax=ymax, color=group).add(Range()).plot()\n lines, = p._figure.axes[0].collections\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n for i, path in enumerate(lines.get_paths()):\n verts = path.vertices.T\n assert_array_equal(verts[0], [x[i], x[i]])\n assert_array_equal(verts[1], [ymin[i], ymax[i]])\n assert same_color(lines.get_colors()[i], colors[i // 2])\n\n def test_direct_properties(self):\n\n x = [1, 2]\n ymin = [1, 4]\n ymax = [2, 3]\n\n m = Range(color=\".654\", linewidth=4)\n p = Plot(x=x, ymin=ymin, ymax=ymax).add(m).plot()\n lines, = p._figure.axes[0].collections\n\n for i, path in enumerate(lines.get_paths()):\n assert same_color(lines.get_colors()[i], m.color)\n assert lines.get_linewidths()[i] == m.linewidth\n"},{"className":"TestPath","col":0,"comment":"null","endLoc":135,"id":2976,"nodeType":"Class","startLoc":12,"text":"class TestPath:\n\n def test_xy_data(self):\n\n x = [1, 5, 3, np.nan, 2]\n y = [1, 4, 2, 5, 3]\n g = [1, 2, 1, 1, 2]\n p = Plot(x=x, y=y, group=g).add(Path()).plot()\n line1, line2 = p._figure.axes[0].get_lines()\n\n assert_array_equal(line1.get_xdata(), [1, 3, np.nan])\n assert_array_equal(line1.get_ydata(), [1, 2, np.nan])\n assert_array_equal(line2.get_xdata(), [5, 2])\n assert_array_equal(line2.get_ydata(), [4, 3])\n\n def test_shared_colors_direct(self):\n\n x = y = [1, 2, 3]\n color = \".44\"\n m = Path(color=color)\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), color)\n assert same_color(line.get_markeredgecolor(), color)\n assert same_color(line.get_markerfacecolor(), color)\n\n def test_separate_colors_direct(self):\n\n x = y = [1, 2, 3]\n y = [1, 2, 3]\n m = Path(color=\".22\", edgecolor=\".55\", fillcolor=\".77\")\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), m.color)\n assert same_color(line.get_markeredgecolor(), m.edgecolor)\n assert same_color(line.get_markerfacecolor(), m.fillcolor)\n\n def test_shared_colors_mapped(self):\n\n x = y = [1, 2, 3, 4]\n c = [\"a\", \"a\", \"b\", \"b\"]\n m = Path()\n p = Plot(x=x, y=y, color=c).add(m).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, line in enumerate(ax.get_lines()):\n assert same_color(line.get_color(), colors[i])\n assert same_color(line.get_markeredgecolor(), colors[i])\n assert same_color(line.get_markerfacecolor(), colors[i])\n\n def test_separate_colors_mapped(self):\n\n x = y = [1, 2, 3, 4]\n c = [\"a\", \"a\", \"b\", \"b\"]\n d = [\"x\", \"y\", \"x\", \"y\"]\n m = Path()\n p = Plot(x=x, y=y, color=c, fillcolor=d).add(m).plot()\n ax = p._figure.axes[0]\n colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n for i, line in enumerate(ax.get_lines()):\n assert same_color(line.get_color(), colors[i // 2])\n assert same_color(line.get_markeredgecolor(), colors[i // 2])\n assert same_color(line.get_markerfacecolor(), colors[i % 2])\n\n def test_color_with_alpha(self):\n\n x = y = [1, 2, 3]\n m = Path(color=(.4, .9, .2, .5), fillcolor=(.2, .2, .3, .9))\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), m.color)\n assert same_color(line.get_markeredgecolor(), m.color)\n assert same_color(line.get_markerfacecolor(), m.fillcolor)\n\n def test_color_and_alpha(self):\n\n x = y = [1, 2, 3]\n m = Path(color=(.4, .9, .2), fillcolor=(.2, .2, .3), alpha=.5)\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert same_color(line.get_color(), to_rgba(m.color, m.alpha))\n assert same_color(line.get_markeredgecolor(), to_rgba(m.color, m.alpha))\n assert same_color(line.get_markerfacecolor(), to_rgba(m.fillcolor, m.alpha))\n\n def test_other_props_direct(self):\n\n x = y = [1, 2, 3]\n m = Path(marker=\"s\", linestyle=\"--\", linewidth=3, pointsize=10, edgewidth=1)\n p = Plot(x=x, y=y).add(m).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_marker() == m.marker\n assert line.get_linestyle() == m.linestyle\n assert line.get_linewidth() == m.linewidth\n assert line.get_markersize() == m.pointsize\n assert line.get_markeredgewidth() == m.edgewidth\n\n def test_other_props_mapped(self):\n\n x = y = [1, 2, 3, 4]\n g = [\"a\", \"a\", \"b\", \"b\"]\n m = Path()\n p = Plot(x=x, y=y, marker=g, linestyle=g, pointsize=g).add(m).plot()\n line1, line2 = p._figure.axes[0].get_lines()\n assert line1.get_marker() != line2.get_marker()\n # Matplotlib bug in storing linestyle from dash pattern\n # assert line1.get_linestyle() != line2.get_linestyle()\n assert line1.get_markersize() != line2.get_markersize()\n\n def test_capstyle(self):\n\n x = y = [1, 2]\n rc = {\"lines.solid_capstyle\": \"projecting\", \"lines.dash_capstyle\": \"round\"}\n\n p = Plot(x, y).add(Path()).theme(rc).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_dash_capstyle() == \"projecting\"\n\n p = Plot(x, y).add(Path(linestyle=\"--\")).theme(rc).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_dash_capstyle() == \"round\"\n\n p = Plot(x, y).add(Path({\"solid_capstyle\": \"butt\"})).theme(rc).plot()\n line, = p._figure.axes[0].get_lines()\n assert line.get_solid_capstyle() == \"butt\""},{"col":4,"comment":"null","endLoc":25,"header":"def test_xy_data(self)","id":2977,"name":"test_xy_data","nodeType":"Function","startLoc":14,"text":"def test_xy_data(self):\n\n x = [1, 5, 3, np.nan, 2]\n y = [1, 4, 2, 5, 3]\n g = [1, 2, 1, 1, 2]\n p = Plot(x=x, y=y, group=g).add(Path()).plot()\n line1, line2 = p._figure.axes[0].get_lines()\n\n assert_array_equal(line1.get_xdata(), [1, 3, np.nan])\n assert_array_equal(line1.get_ydata(), [1, 2, np.nan])\n assert_array_equal(line2.get_xdata(), [5, 2])\n assert_array_equal(line2.get_ydata(), [4, 3])"},{"col":4,"comment":"null","endLoc":920,"header":"def test_map_mixed_funcsig(self)","id":2978,"name":"test_map_mixed_funcsig","nodeType":"Function","startLoc":907,"text":"def test_map_mixed_funcsig(self):\n\n vars = [\"x\", \"y\", \"z\"]\n g = ag.PairGrid(self.df, vars=vars)\n g.map_lower(scatterplot)\n g.map_upper(plt.scatter)\n\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n ax = g.axes[i, j]\n x_in = self.df[vars[j]]\n y_in = self.df[vars[i]]\n x_out, y_out = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x_in, x_out)\n npt.assert_array_equal(y_in, y_out)"},{"col":4,"comment":"null","endLoc":942,"header":"def test_map_diag(self)","id":2979,"name":"test_map_diag","nodeType":"Function","startLoc":922,"text":"def test_map_diag(self):\n\n g = ag.PairGrid(self.df)\n g.map_diag(plt.hist)\n\n for var, ax in zip(g.diag_vars, g.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist)\n\n for ax in g.diag_axes:\n assert len(ax.patches) == 30\n\n g = ag.PairGrid(self.df, hue=\"a\")\n g.map_diag(plt.hist, histtype='step')\n\n for ax in g.diag_axes:\n for ptch in ax.patches:\n assert not ptch.fill"},{"col":4,"comment":"null","endLoc":1390,"header":"def _unscale_coords(\n self, subplots: list[dict], df: DataFrame, orient: str,\n ) -> DataFrame","id":2980,"name":"_unscale_coords","nodeType":"Function","startLoc":1360,"text":"def _unscale_coords(\n self, subplots: list[dict], df: DataFrame, orient: str,\n ) -> DataFrame:\n # TODO do we still have numbers in the variable name at this point?\n coord_cols = [c for c in df if re.match(r\"^[xy]\\D*$\", str(c))]\n drop_cols = [*coord_cols, \"width\"] if \"width\" in df else coord_cols\n out_df = (\n df\n .drop(drop_cols, axis=1)\n .reindex(df.columns, axis=1) # So unscaled columns retain their place\n .copy(deep=False)\n )\n\n for view in subplots:\n view_df = self._filter_subplot_data(df, view)\n axes_df = view_df[coord_cols]\n for var, values in axes_df.items():\n\n axis = getattr(view[\"ax\"], f\"{str(var)[0]}axis\")\n # TODO see https://github.com/matplotlib/matplotlib/issues/22713\n transform = axis.get_transform().inverted().transform\n inverted = transform(values)\n out_df.loc[values.index, str(var)] = inverted\n\n if var == orient and \"width\" in view_df:\n width = view_df[\"width\"]\n out_df.loc[values.index, \"width\"] = (\n transform(values + width / 2) - transform(values - width / 2)\n )\n\n return out_df"},{"col":4,"comment":"null","endLoc":1454,"header":"def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame","id":2981,"name":"_filter_subplot_data","nodeType":"Function","startLoc":1445,"text":"def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame:\n # TODO note redundancies with preceding function ... needs refactoring\n dims = df.columns.intersection([\"col\", \"row\"])\n if dims.empty:\n return df\n\n keep_rows = pd.Series(True, df.index, dtype=bool)\n for dim in dims:\n keep_rows &= df[dim] == subplot[dim]\n return df[keep_rows]"},{"col":4,"comment":"null","endLoc":2152,"header":"def test_line_kwargs(self, long_df)","id":2982,"name":"test_line_kwargs","nodeType":"Function","startLoc":2142,"text":"def test_line_kwargs(self, long_df):\n\n color = \"r\"\n ls = \"--\"\n lw = 3\n ax = ecdfplot(long_df, x=\"x\", color=color, ls=ls, lw=lw)\n\n for line in ax.lines:\n assert_colors_equal(line.get_color(), color)\n assert line.get_linestyle() == ls\n assert line.get_linewidth() == lw"},{"col":4,"comment":"null","endLoc":128,"header":"def test_auto_range(self)","id":2983,"name":"test_auto_range","nodeType":"Function","startLoc":116,"text":"def test_auto_range(self):\n\n x = [1, 1, 2, 2, 2]\n y = [1, 2, 3, 4, 5]\n p = Plot(x=x, y=y).add(Band()).plot()\n ax = p._figure.axes[0]\n verts = ax.patches[0].get_path().vertices.T\n\n expected_x = [1, 2, 2, 1, 1]\n assert_array_equal(verts[0], expected_x)\n\n expected_y = [1, 3, 5, 2, 1]\n assert_array_equal(verts[1], expected_y)"},{"col":4,"comment":"null","endLoc":2159,"header":"@pytest.mark.parametrize(\"data_var\", [\"x\", \"y\"])\n def test_drawstyle(self, flat_series, data_var)","id":2984,"name":"test_drawstyle","nodeType":"Function","startLoc":2154,"text":"@pytest.mark.parametrize(\"data_var\", [\"x\", \"y\"])\n def test_drawstyle(self, flat_series, data_var):\n\n ax = ecdfplot(**{data_var: flat_series})\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n assert ax.lines[0].get_drawstyle() == drawstyles[data_var]"},{"col":4,"comment":"null","endLoc":1529,"header":"def _setup_split_generator(\n self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]],\n ) -> Callable[[], Generator]","id":2985,"name":"_setup_split_generator","nodeType":"Function","startLoc":1456,"text":"def _setup_split_generator(\n self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]],\n ) -> Callable[[], Generator]:\n\n allow_empty = False # TODO will need to recreate previous categorical plots\n\n grouping_keys = []\n grouping_vars = [\n v for v in grouping_vars if v in df and v not in [\"col\", \"row\"]\n ]\n for var in grouping_vars:\n order = getattr(self._scales[var], \"order\", None)\n if order is None:\n order = categorical_order(df[var])\n grouping_keys.append(order)\n\n def split_generator(keep_na=False) -> Generator:\n\n for view in subplots:\n\n axes_df = self._filter_subplot_data(df, view)\n\n with pd.option_context(\"mode.use_inf_as_null\", True):\n if keep_na:\n # The simpler thing to do would be x.dropna().reindex(x.index).\n # But that doesn't work with the way that the subset iteration\n # is written below, which assumes data for grouping vars.\n # Matplotlib (usually?) masks nan data, so this should \"work\".\n # Downstream code can also drop these rows, at some speed cost.\n present = axes_df.notna().all(axis=1)\n nulled = {}\n for axis in \"xy\":\n if axis in axes_df:\n nulled[axis] = axes_df[axis].where(present)\n axes_df = axes_df.assign(**nulled)\n else:\n axes_df = axes_df.dropna()\n\n subplot_keys = {}\n for dim in [\"col\", \"row\"]:\n if view[dim] is not None:\n subplot_keys[dim] = view[dim]\n\n if not grouping_vars or not any(grouping_keys):\n yield subplot_keys, axes_df.copy(), view[\"ax\"]\n continue\n\n grouped_df = axes_df.groupby(grouping_vars, sort=False, as_index=False)\n\n for key in itertools.product(*grouping_keys):\n\n # Pandas fails with singleton tuple inputs\n pd_key = key[0] if len(key) == 1 else key\n\n try:\n df_subset = grouped_df.get_group(pd_key)\n except KeyError:\n # TODO (from initial work on categorical plots refactor)\n # We are adding this to allow backwards compatability\n # with the empty artists that old categorical plots would\n # add (before 0.12), which we may decide to break, in which\n # case this option could be removed\n df_subset = axes_df.loc[[]]\n\n if df_subset.empty and not allow_empty:\n continue\n\n sub_vars = dict(zip(grouping_vars, key))\n sub_vars.update(subplot_keys)\n\n # TODO need copy(deep=...) policy (here, above, anywhere else?)\n yield sub_vars, df_subset.copy(), view[\"ax\"]\n\n return split_generator"},{"col":4,"comment":"null","endLoc":2171,"header":"@pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits(self, flat_series, data_var, stat_var)","id":2986,"name":"test_proportion_limits","nodeType":"Function","startLoc":2161,"text":"@pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits(self, flat_series, data_var, stat_var):\n\n ax = ecdfplot(**{data_var: flat_series})\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 0\n assert data[-1] == 1\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, 1]"},{"id":2987,"name":"logo-mark-lightbg.svg","nodeType":"TextFile","path":"doc/_static","text":"\n\n\n\n \n \n \n \n 2020-09-07T14:13:57.855925\n image/svg+xml\n \n \n Matplotlib v3.3.1, https://matplotlib.org/\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"id":2988,"name":"CITATION.cff","nodeType":"TextFile","path":"","text":"cff-version: 1.2.0\nmessage: \"If seaborn is integral to a scientific publication, please cite the following paper:\"\npreferred-citation:\n type: article\n authors:\n - family-names: \"Waskom\"\n given-names: \"Michael Lawrence\"\n orcid: \"https://orcid.org/0000-0002-9817-6869\"\n doi: \"10.21105/joss.03021\"\n journal: \"Journal of Open Source Software\"\n month: April\n title: \"seaborn: statistical data visualization\"\n issue: 6\n volume: 60\n year: 2021\n url: \"https://joss.theoj.org/papers/10.21105/joss.03021\"\n"},{"fileName":"many_facets.py","filePath":"examples","id":2989,"nodeType":"File","text":"\"\"\"\nPlotting on a large number of facets\n====================================\n\n_thumb: .4, .3\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(style=\"ticks\")\n\n# Create a dataset with many short random walks\nrs = np.random.RandomState(4)\npos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1)\npos -= pos[:, 0, np.newaxis]\nstep = np.tile(range(5), 20)\nwalk = np.repeat(range(20), 5)\ndf = pd.DataFrame(np.c_[pos.flat, step, walk],\n columns=[\"position\", \"step\", \"walk\"])\n\n# Initialize a grid of plots with an Axes for each walk\ngrid = sns.FacetGrid(df, col=\"walk\", hue=\"walk\", palette=\"tab20c\",\n col_wrap=4, height=1.5)\n\n# Draw a horizontal line to show the starting point\ngrid.refline(y=0, linestyle=\":\")\n\n# Draw a line plot to show the trajectory of each random walk\ngrid.map(plt.plot, \"step\", \"position\", marker=\"o\")\n\n# Adjust the tick positions and labels\ngrid.set(xticks=np.arange(5), yticks=[-3, 3],\n xlim=(-.5, 4.5), ylim=(-3.5, 3.5))\n\n# Adjust the arrangement of the plots\ngrid.fig.tight_layout(w_pad=1)\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":8,"id":2990,"name":"np","nodeType":"Attribute","startLoc":8,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":9,"id":2991,"name":"pd","nodeType":"Attribute","startLoc":9,"text":"pd"},{"attributeType":"null","col":18,"comment":"null","endLoc":10,"id":2992,"name":"sns","nodeType":"Attribute","startLoc":10,"text":"sns"},{"attributeType":"null","col":28,"comment":"null","endLoc":11,"id":2993,"name":"plt","nodeType":"Attribute","startLoc":11,"text":"plt"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":2994,"name":"rs","nodeType":"Attribute","startLoc":16,"text":"rs"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":2995,"name":"pos","nodeType":"Attribute","startLoc":17,"text":"pos"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":2996,"name":"step","nodeType":"Attribute","startLoc":19,"text":"step"},{"attributeType":"null","col":0,"comment":"null","endLoc":20,"id":2997,"name":"walk","nodeType":"Attribute","startLoc":20,"text":"walk"},{"col":4,"comment":"null","endLoc":1002,"header":"def test_map_diag_rectangular(self)","id":2998,"name":"test_map_diag_rectangular","nodeType":"Function","startLoc":944,"text":"def test_map_diag_rectangular(self):\n\n x_vars = [\"x\", \"y\"]\n y_vars = [\"x\", \"z\", \"y\"]\n g1 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g1.map_diag(plt.hist)\n g1.map_offdiag(plt.scatter)\n\n assert set(g1.diag_vars) == (set(x_vars) & set(y_vars))\n\n for var, ax in zip(g1.diag_vars, g1.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n for j, x_var in enumerate(x_vars):\n for i, y_var in enumerate(y_vars):\n\n ax = g1.axes[i, j]\n if x_var == y_var:\n diag_ax = g1.diag_axes[j] # because fewer x than y vars\n assert ax.bbox.bounds == diag_ax.bbox.bounds\n\n else:\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, self.df[x_var])\n assert_array_equal(y, self.df[y_var])\n\n g2 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars, hue=\"a\")\n g2.map_diag(plt.hist)\n g2.map_offdiag(plt.scatter)\n\n assert set(g2.diag_vars) == (set(x_vars) & set(y_vars))\n\n for ax in g2.diag_axes:\n assert len(ax.patches) == 30\n\n x_vars = [\"x\", \"y\", \"z\"]\n y_vars = [\"x\", \"z\"]\n g3 = ag.PairGrid(self.df, x_vars=x_vars, y_vars=y_vars)\n g3.map_diag(plt.hist)\n g3.map_offdiag(plt.scatter)\n\n assert set(g3.diag_vars) == (set(x_vars) & set(y_vars))\n\n for var, ax in zip(g3.diag_vars, g3.diag_axes):\n assert len(ax.patches) == 10\n assert pytest.approx(ax.patches[0].get_x()) == self.df[var].min()\n\n for j, x_var in enumerate(x_vars):\n for i, y_var in enumerate(y_vars):\n\n ax = g3.axes[i, j]\n if x_var == y_var:\n diag_ax = g3.diag_axes[i] # because fewer y than x vars\n assert ax.bbox.bounds == diag_ax.bbox.bounds\n else:\n x, y = ax.collections[0].get_offsets().T\n assert_array_equal(x, self.df[x_var])\n assert_array_equal(y, self.df[y_var])"},{"attributeType":"null","col":21,"comment":"null","endLoc":2,"id":2999,"name":"mpl","nodeType":"Attribute","startLoc":2,"text":"mpl"},{"col":4,"comment":"null","endLoc":2183,"header":"@pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits_complementary(self, flat_series, data_var, stat_var)","id":3000,"name":"test_proportion_limits_complementary","nodeType":"Function","startLoc":2173,"text":"@pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_limits_complementary(self, flat_series, data_var, stat_var):\n\n ax = ecdfplot(**{data_var: flat_series}, complementary=True)\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 1\n assert data[-1] == 0\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, 1]"},{"col":4,"comment":"null","endLoc":2196,"header":"@pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_count(self, flat_series, data_var, stat_var)","id":3001,"name":"test_proportion_count","nodeType":"Function","startLoc":2185,"text":"@pytest.mark.parametrize(\n \"data_var,stat_var\", [[\"x\", \"y\"], [\"y\", \"x\"]],\n )\n def test_proportion_count(self, flat_series, data_var, stat_var):\n\n n = len(flat_series)\n ax = ecdfplot(**{data_var: flat_series}, stat=\"count\")\n data = getattr(ax.lines[0], f\"get_{stat_var}data\")()\n assert data[0] == 0\n assert data[-1] == n\n sticky_edges = getattr(ax.lines[0].sticky_edges, stat_var)\n assert sticky_edges[:] == [0, n]"},{"fileName":"version.py","filePath":"seaborn/external","id":3002,"nodeType":"File","text":"\"\"\"Extract reference documentation from the pypa/packaging source tree.\n\nIn the process of copying, some unused methods / classes were removed.\nThese include:\n\n- parse()\n- anything involving LegacyVersion\n\nThis software is made available under the terms of *either* of the licenses\nfound in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made\nunder the terms of *both* these licenses.\n\nVendored from:\n- https://github.com/pypa/packaging/\n- commit ba07d8287b4554754ac7178d177033ea3f75d489 (09/09/2021)\n\"\"\"\n\n\n# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n\nimport collections\nimport itertools\nimport re\nfrom typing import Callable, Optional, SupportsInt, Tuple, Union\n\n__all__ = [\"Version\", \"InvalidVersion\", \"VERSION_PATTERN\"]\n\n\n# Vendored from https://github.com/pypa/packaging/blob/main/packaging/_structures.py\n\nclass InfinityType:\n def __repr__(self) -> str:\n return \"Infinity\"\n\n def __hash__(self) -> int:\n return hash(repr(self))\n\n def __lt__(self, other: object) -> bool:\n return False\n\n def __le__(self, other: object) -> bool:\n return False\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, self.__class__)\n\n def __ne__(self, other: object) -> bool:\n return not isinstance(other, self.__class__)\n\n def __gt__(self, other: object) -> bool:\n return True\n\n def __ge__(self, other: object) -> bool:\n return True\n\n def __neg__(self: object) -> \"NegativeInfinityType\":\n return NegativeInfinity\n\n\nInfinity = InfinityType()\n\n\nclass NegativeInfinityType:\n def __repr__(self) -> str:\n return \"-Infinity\"\n\n def __hash__(self) -> int:\n return hash(repr(self))\n\n def __lt__(self, other: object) -> bool:\n return True\n\n def __le__(self, other: object) -> bool:\n return True\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, self.__class__)\n\n def __ne__(self, other: object) -> bool:\n return not isinstance(other, self.__class__)\n\n def __gt__(self, other: object) -> bool:\n return False\n\n def __ge__(self, other: object) -> bool:\n return False\n\n def __neg__(self: object) -> InfinityType:\n return Infinity\n\n\nNegativeInfinity = NegativeInfinityType()\n\n\n# Vendored from https://github.com/pypa/packaging/blob/main/packaging/version.py\n\nInfiniteTypes = Union[InfinityType, NegativeInfinityType]\nPrePostDevType = Union[InfiniteTypes, Tuple[str, int]]\nSubLocalType = Union[InfiniteTypes, int, str]\nLocalType = Union[\n NegativeInfinityType,\n Tuple[\n Union[\n SubLocalType,\n Tuple[SubLocalType, str],\n Tuple[NegativeInfinityType, SubLocalType],\n ],\n ...,\n ],\n]\nCmpKey = Tuple[\n int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType\n]\nLegacyCmpKey = Tuple[int, Tuple[str, ...]]\nVersionComparisonMethod = Callable[\n [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool\n]\n\n_Version = collections.namedtuple(\n \"_Version\", [\"epoch\", \"release\", \"dev\", \"pre\", \"post\", \"local\"]\n)\n\n\n\nclass InvalidVersion(ValueError):\n \"\"\"\n An invalid version was found, users should refer to PEP 440.\n \"\"\"\n\n\nclass _BaseVersion:\n _key: Union[CmpKey, LegacyCmpKey]\n\n def __hash__(self) -> int:\n return hash(self._key)\n\n # Please keep the duplicated `isinstance` check\n # in the six comparisons hereunder\n # unless you find a way to avoid adding overhead function calls.\n def __lt__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key < other._key\n\n def __le__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key <= other._key\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key == other._key\n\n def __ge__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key >= other._key\n\n def __gt__(self, other: \"_BaseVersion\") -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key > other._key\n\n def __ne__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key != other._key\n\n\n# Deliberately not anchored to the start and end of the string, to make it\n# easier for 3rd party code to reuse\nVERSION_PATTERN = r\"\"\"\n v?\n (?:\n (?:(?P[0-9]+)!)? # epoch\n (?P[0-9]+(?:\\.[0-9]+)*) # release segment\n (?P
                                          # pre-release\n            [-_\\.]?\n            (?P(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P[0-9]+)?\n        )?\n        (?P                                         # post release\n            (?:-(?P[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?Ppost|rev|r)\n                [-_\\.]?\n                (?P[0-9]+)?\n            )\n        )?\n        (?P                                          # dev release\n            [-_\\.]?\n            (?Pdev)\n            [-_\\.]?\n            (?P[0-9]+)?\n        )?\n    )\n    (?:\\+(?P[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n\"\"\"\n\n\nclass Version(_BaseVersion):\n\n    _regex = re.compile(r\"^\\s*\" + VERSION_PATTERN + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    def __init__(self, version: str) -> None:\n\n        # Validate the version and parse it into pieces\n        match = self._regex.search(version)\n        if not match:\n            raise InvalidVersion(f\"Invalid version: '{version}'\")\n\n        # Store the parsed out pieces of the version\n        self._version = _Version(\n            epoch=int(match.group(\"epoch\")) if match.group(\"epoch\") else 0,\n            release=tuple(int(i) for i in match.group(\"release\").split(\".\")),\n            pre=_parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\")),\n            post=_parse_letter_version(\n                match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n            ),\n            dev=_parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\")),\n            local=_parse_local_version(match.group(\"local\")),\n        )\n\n        # Generate a key which will be used for sorting\n        self._key = _cmpkey(\n            self._version.epoch,\n            self._version.release,\n            self._version.pre,\n            self._version.post,\n            self._version.dev,\n            self._version.local,\n        )\n\n    def __repr__(self) -> str:\n        return f\"\"\n\n    def __str__(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        # Pre-release\n        if self.pre is not None:\n            parts.append(\"\".join(str(x) for x in self.pre))\n\n        # Post-release\n        if self.post is not None:\n            parts.append(f\".post{self.post}\")\n\n        # Development release\n        if self.dev is not None:\n            parts.append(f\".dev{self.dev}\")\n\n        # Local version segment\n        if self.local is not None:\n            parts.append(f\"+{self.local}\")\n\n        return \"\".join(parts)\n\n    @property\n    def epoch(self) -> int:\n        _epoch: int = self._version.epoch\n        return _epoch\n\n    @property\n    def release(self) -> Tuple[int, ...]:\n        _release: Tuple[int, ...] = self._version.release\n        return _release\n\n    @property\n    def pre(self) -> Optional[Tuple[str, int]]:\n        _pre: Optional[Tuple[str, int]] = self._version.pre\n        return _pre\n\n    @property\n    def post(self) -> Optional[int]:\n        return self._version.post[1] if self._version.post else None\n\n    @property\n    def dev(self) -> Optional[int]:\n        return self._version.dev[1] if self._version.dev else None\n\n    @property\n    def local(self) -> Optional[str]:\n        if self._version.local:\n            return \".\".join(str(x) for x in self._version.local)\n        else:\n            return None\n\n    @property\n    def public(self) -> str:\n        return str(self).split(\"+\", 1)[0]\n\n    @property\n    def base_version(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        return \"\".join(parts)\n\n    @property\n    def is_prerelease(self) -> bool:\n        return self.dev is not None or self.pre is not None\n\n    @property\n    def is_postrelease(self) -> bool:\n        return self.post is not None\n\n    @property\n    def is_devrelease(self) -> bool:\n        return self.dev is not None\n\n    @property\n    def major(self) -> int:\n        return self.release[0] if len(self.release) >= 1 else 0\n\n    @property\n    def minor(self) -> int:\n        return self.release[1] if len(self.release) >= 2 else 0\n\n    @property\n    def micro(self) -> int:\n        return self.release[2] if len(self.release) >= 3 else 0\n\n\ndef _parse_letter_version(\n    letter: str, number: Union[str, bytes, SupportsInt]\n) -> Optional[Tuple[str, int]]:\n\n    if letter:\n        # We consider there to be an implicit 0 in a pre-release if there is\n        # not a numeral associated with it.\n        if number is None:\n            number = 0\n\n        # We normalize any letters to their lower case form\n        letter = letter.lower()\n\n        # We consider some words to be alternate spellings of other words and\n        # in those cases we want to normalize the spellings to our preferred\n        # spelling.\n        if letter == \"alpha\":\n            letter = \"a\"\n        elif letter == \"beta\":\n            letter = \"b\"\n        elif letter in [\"c\", \"pre\", \"preview\"]:\n            letter = \"rc\"\n        elif letter in [\"rev\", \"r\"]:\n            letter = \"post\"\n\n        return letter, int(number)\n    if not letter and number:\n        # We assume if we are given a number, but we are not given a letter\n        # then this is using the implicit post release syntax (e.g. 1.0-1)\n        letter = \"post\"\n\n        return letter, int(number)\n\n    return None\n\n\n_local_version_separators = re.compile(r\"[\\._-]\")\n\n\ndef _parse_local_version(local: str) -> Optional[LocalType]:\n    \"\"\"\n    Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n    \"\"\"\n    if local is not None:\n        return tuple(\n            part.lower() if not part.isdigit() else int(part)\n            for part in _local_version_separators.split(local)\n        )\n    return None\n\n\ndef _cmpkey(\n    epoch: int,\n    release: Tuple[int, ...],\n    pre: Optional[Tuple[str, int]],\n    post: Optional[Tuple[str, int]],\n    dev: Optional[Tuple[str, int]],\n    local: Optional[Tuple[SubLocalType]],\n) -> CmpKey:\n\n    # When we compare a release version, we want to compare it with all of the\n    # trailing zeros removed. So we'll use a reverse the list, drop all the now\n    # leading zeros until we come to something non zero, then take the rest\n    # re-reverse it back into the correct order and make it a tuple and use\n    # that for our sorting key.\n    _release = tuple(\n        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))\n    )\n\n    # We need to \"trick\" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n    # We'll do this by abusing the pre segment, but we _only_ want to do this\n    # if there is not a pre or a post segment. If we have one of those then\n    # the normal sorting rules will handle this case correctly.\n    if pre is None and post is None and dev is not None:\n        _pre: PrePostDevType = NegativeInfinity\n    # Versions without a pre-release (except as noted above) should sort after\n    # those with one.\n    elif pre is None:\n        _pre = Infinity\n    else:\n        _pre = pre\n\n    # Versions without a post segment should sort before those with one.\n    if post is None:\n        _post: PrePostDevType = NegativeInfinity\n\n    else:\n        _post = post\n\n    # Versions without a development segment should sort after those with one.\n    if dev is None:\n        _dev: PrePostDevType = Infinity\n\n    else:\n        _dev = dev\n\n    if local is None:\n        # Versions without a local segment should sort before those with one.\n        _local: LocalType = NegativeInfinity\n    else:\n        # Versions with a local segment need that segment parsed to implement\n        # the sorting rules in PEP440.\n        # - Alpha numeric segments sort before numeric segments\n        # - Alpha numeric segments sort lexicographically\n        # - Numeric segments sort numerically\n        # - Shorter versions sort before longer versions when the prefixes\n        #   match exactly\n        _local = tuple(\n            (i, \"\") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n        )\n\n    return epoch, _release, _pre, _post, _dev, _local\n"},{"className":"SupportsInt","col":0,"comment":"null","endLoc":371,"id":3003,"nodeType":"Class","startLoc":368,"text":"@runtime_checkable\nclass SupportsInt(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __int__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":371,"header":"@abstractmethod\n    def __int__(self) -> int","id":3004,"name":"__int__","nodeType":"Function","startLoc":370,"text":"@abstractmethod\n    def __int__(self) -> int: ..."},{"className":"InfinityType","col":0,"comment":"null","endLoc":60,"id":3005,"nodeType":"Class","startLoc":34,"text":"class InfinityType:\n    def __repr__(self) -> str:\n        return \"Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return False\n\n    def __le__(self, other: object) -> bool:\n        return False\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __ne__(self, other: object) -> bool:\n        return not isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return True\n\n    def __ge__(self, other: object) -> bool:\n        return True\n\n    def __neg__(self: object) -> \"NegativeInfinityType\":\n        return NegativeInfinity"},{"col":4,"comment":"null","endLoc":36,"header":"def __repr__(self) -> str","id":3006,"name":"__repr__","nodeType":"Function","startLoc":35,"text":"def __repr__(self) -> str:\n        return \"Infinity\""},{"col":4,"comment":"null","endLoc":39,"header":"def __hash__(self) -> int","id":3007,"name":"__hash__","nodeType":"Function","startLoc":38,"text":"def __hash__(self) -> int:\n        return hash(repr(self))"},{"col":4,"comment":"null","endLoc":42,"header":"def __lt__(self, other: object) -> bool","id":3008,"name":"__lt__","nodeType":"Function","startLoc":41,"text":"def __lt__(self, other: object) -> bool:\n        return False"},{"col":4,"comment":"null","endLoc":45,"header":"def __le__(self, other: object) -> bool","id":3009,"name":"__le__","nodeType":"Function","startLoc":44,"text":"def __le__(self, other: object) -> bool:\n        return False"},{"col":4,"comment":"null","endLoc":48,"header":"def __eq__(self, other: object) -> bool","id":3010,"name":"__eq__","nodeType":"Function","startLoc":47,"text":"def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)"},{"col":4,"comment":"null","endLoc":36,"header":"def test_shared_colors_direct(self)","id":3011,"name":"test_shared_colors_direct","nodeType":"Function","startLoc":27,"text":"def test_shared_colors_direct(self):\n\n        x = y = [1, 2, 3]\n        color = \".44\"\n        m = Path(color=color)\n        p = Plot(x=x, y=y).add(m).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert same_color(line.get_color(), color)\n        assert same_color(line.get_markeredgecolor(), color)\n        assert same_color(line.get_markerfacecolor(), color)"},{"col":4,"comment":"null","endLoc":51,"header":"def __ne__(self, other: object) -> bool","id":3012,"name":"__ne__","nodeType":"Function","startLoc":50,"text":"def __ne__(self, other: object) -> bool:\n        return not isinstance(other, self.__class__)"},{"attributeType":"null","col":0,"comment":"null","endLoc":21,"id":3013,"name":"df","nodeType":"Attribute","startLoc":21,"text":"df"},{"col":4,"comment":"null","endLoc":54,"header":"def __gt__(self, other: object) -> bool","id":3014,"name":"__gt__","nodeType":"Function","startLoc":53,"text":"def __gt__(self, other: object) -> bool:\n        return True"},{"col":4,"comment":"null","endLoc":57,"header":"def __ge__(self, other: object) -> bool","id":3015,"name":"__ge__","nodeType":"Function","startLoc":56,"text":"def __ge__(self, other: object) -> bool:\n        return True"},{"col":4,"comment":"null","endLoc":60,"header":"def __neg__(self: object) -> \"NegativeInfinityType\"","id":3016,"name":"__neg__","nodeType":"Function","startLoc":59,"text":"def __neg__(self: object) -> \"NegativeInfinityType\":\n        return NegativeInfinity"},{"className":"NegativeInfinityType","col":0,"comment":"null","endLoc":92,"id":3017,"nodeType":"Class","startLoc":66,"text":"class NegativeInfinityType:\n    def __repr__(self) -> str:\n        return \"-Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return True\n\n    def __le__(self, other: object) -> bool:\n        return True\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __ne__(self, other: object) -> bool:\n        return not isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return False\n\n    def __ge__(self, other: object) -> bool:\n        return False\n\n    def __neg__(self: object) -> InfinityType:\n        return Infinity"},{"col":4,"comment":"null","endLoc":68,"header":"def __repr__(self) -> str","id":3018,"name":"__repr__","nodeType":"Function","startLoc":67,"text":"def __repr__(self) -> str:\n        return \"-Infinity\""},{"col":4,"comment":"null","endLoc":71,"header":"def __hash__(self) -> int","id":3019,"name":"__hash__","nodeType":"Function","startLoc":70,"text":"def __hash__(self) -> int:\n        return hash(repr(self))"},{"col":4,"comment":"null","endLoc":74,"header":"def __lt__(self, other: object) -> bool","id":3020,"name":"__lt__","nodeType":"Function","startLoc":73,"text":"def __lt__(self, other: object) -> bool:\n        return True"},{"col":4,"comment":"null","endLoc":77,"header":"def __le__(self, other: object) -> bool","id":3021,"name":"__le__","nodeType":"Function","startLoc":76,"text":"def __le__(self, other: object) -> bool:\n        return True"},{"col":4,"comment":"null","endLoc":80,"header":"def __eq__(self, other: object) -> bool","id":3022,"name":"__eq__","nodeType":"Function","startLoc":79,"text":"def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)"},{"col":4,"comment":"null","endLoc":83,"header":"def __ne__(self, other: object) -> bool","id":3023,"name":"__ne__","nodeType":"Function","startLoc":82,"text":"def __ne__(self, other: object) -> bool:\n        return not isinstance(other, self.__class__)"},{"col":4,"comment":"null","endLoc":86,"header":"def __gt__(self, other: object) -> bool","id":3024,"name":"__gt__","nodeType":"Function","startLoc":85,"text":"def __gt__(self, other: object) -> bool:\n        return False"},{"col":4,"comment":"null","endLoc":89,"header":"def __ge__(self, other: object) -> bool","id":3025,"name":"__ge__","nodeType":"Function","startLoc":88,"text":"def __ge__(self, other: object) -> bool:\n        return False"},{"col":4,"comment":"null","endLoc":92,"header":"def __neg__(self: object) -> InfinityType","id":3026,"name":"__neg__","nodeType":"Function","startLoc":91,"text":"def __neg__(self: object) -> InfinityType:\n        return Infinity"},{"className":"InvalidVersion","col":0,"comment":"\n    An invalid version was found, users should refer to PEP 440.\n    ","endLoc":131,"id":3027,"nodeType":"Class","startLoc":128,"text":"class InvalidVersion(ValueError):\n    \"\"\"\n    An invalid version was found, users should refer to PEP 440.\n    \"\"\""},{"col":4,"comment":"null","endLoc":2202,"header":"def test_weights(self)","id":3028,"name":"test_weights","nodeType":"Function","startLoc":2198,"text":"def test_weights(self):\n\n        ax = ecdfplot(x=[1, 2, 3], weights=[1, 1, 2])\n        y = ax.lines[0].get_ydata()\n        assert_array_equal(y, [0, .25, .5, 1])"},{"col":4,"comment":"null","endLoc":2207,"header":"def test_bivariate_error(self, long_df)","id":3029,"name":"test_bivariate_error","nodeType":"Function","startLoc":2204,"text":"def test_bivariate_error(self, long_df):\n\n        with pytest.raises(NotImplementedError, match=\"Bivariate ECDF plots\"):\n            ecdfplot(data=long_df, x=\"x\", y=\"y\")"},{"col":4,"comment":"null","endLoc":2220,"header":"def test_log_scale(self, long_df)","id":3030,"name":"test_log_scale","nodeType":"Function","startLoc":2209,"text":"def test_log_scale(self, long_df):\n\n        ax1, ax2 = plt.figure().subplots(2)\n\n        ecdfplot(data=long_df, x=\"z\", ax=ax1)\n        ecdfplot(data=long_df, x=\"z\", log_scale=True, ax=ax2)\n\n        # Ignore first point, which either -inf (in linear) or 0 (in log)\n        line1 = ax1.lines[0].get_xydata()[1:]\n        line2 = ax2.lines[0].get_xydata()[1:]\n\n        assert_array_almost_equal(line1, line2)"},{"attributeType":"FacetGrid","col":0,"comment":"null","endLoc":25,"id":3031,"name":"grid","nodeType":"Attribute","startLoc":25,"text":"grid"},{"col":4,"comment":"null","endLoc":47,"header":"def test_separate_colors_direct(self)","id":3032,"name":"test_separate_colors_direct","nodeType":"Function","startLoc":38,"text":"def test_separate_colors_direct(self):\n\n        x = y = [1, 2, 3]\n        y = [1, 2, 3]\n        m = Path(color=\".22\", edgecolor=\".55\", fillcolor=\".77\")\n        p = Plot(x=x, y=y).add(m).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert same_color(line.get_color(), m.color)\n        assert same_color(line.get_markeredgecolor(), m.edgecolor)\n        assert same_color(line.get_markerfacecolor(), m.fillcolor)"},{"className":"ValueError","col":0,"comment":"null","endLoc":2011,"id":3033,"nodeType":"Class","startLoc":2011,"text":"class ValueError(Exception): ..."},{"col":0,"comment":"","endLoc":7,"header":"many_facets.py#","id":3034,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPlotting on a large number of facets\n====================================\n\n_thumb: .4, .3\n\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\nrs = np.random.RandomState(4)\n\npos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1)\n\npos -= pos[:, 0, np.newaxis]\n\nstep = np.tile(range(5), 20)\n\nwalk = np.repeat(range(20), 5)\n\ndf = pd.DataFrame(np.c_[pos.flat, step, walk],\n                  columns=[\"position\", \"step\", \"walk\"])\n\ngrid = sns.FacetGrid(df, col=\"walk\", hue=\"walk\", palette=\"tab20c\",\n                     col_wrap=4, height=1.5)\n\ngrid.refline(y=0, linestyle=\":\")\n\ngrid.map(plt.plot, \"step\", \"position\", marker=\"o\")\n\ngrid.set(xticks=np.arange(5), yticks=[-3, 3],\n         xlim=(-.5, 4.5), ylim=(-3.5, 3.5))\n\ngrid.fig.tight_layout(w_pad=1)"},{"attributeType":"null","col":0,"comment":"null","endLoc":29,"id":3035,"name":"__all__","nodeType":"Attribute","startLoc":29,"text":"__all__"},{"attributeType":"InfinityType","col":0,"comment":"null","endLoc":63,"id":3036,"name":"Infinity","nodeType":"Attribute","startLoc":63,"text":"Infinity"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":2109,"id":3037,"name":"func","nodeType":"Attribute","startLoc":2109,"text":"func"},{"className":"TestDisPlot","col":0,"comment":"null","endLoc":2448,"id":3038,"nodeType":"Class","startLoc":2223,"text":"class TestDisPlot:\n\n    # TODO probably good to move these utility attributes/methods somewhere else\n    @pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"a\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", binwidth=4),\n            dict(x=\"x\", weights=\"f\", bins=5),\n            dict(x=\"x\", color=\"green\", linewidth=2, binwidth=4),\n            dict(x=\"x\", hue=\"a\", fill=False),\n            dict(x=\"y\", hue=\"a\", fill=False),\n            dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n            dict(x=\"x\", hue=\"a\", element=\"step\"),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n            dict(x=\"x\", hue=\"a\", kde=True),\n            dict(x=\"x\", hue=\"a\", stat=\"density\", common_norm=False),\n            dict(x=\"x\", y=\"y\"),\n        ],\n    )\n    def test_versus_single_histplot(self, long_df, kwargs):\n\n        ax = histplot(long_df, **kwargs)\n        g = displot(long_df, **kwargs)\n        assert_plots_equal(ax, g.ax)\n\n        if ax.legend_ is not None:\n            assert_legends_equal(ax.legend_, g._legend)\n\n        if kwargs:\n            long_df[\"_\"] = \"_\"\n            g2 = displot(long_df, col=\"_\", **kwargs)\n            assert_plots_equal(ax, g2.ax)\n\n    @pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", bw_adjust=.5),\n            dict(x=\"x\", weights=\"f\"),\n            dict(x=\"x\", color=\"green\", linewidth=2),\n            dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n            dict(x=\"x\", hue=\"a\", fill=True),\n            dict(x=\"y\", hue=\"a\", fill=False),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n            dict(x=\"x\", y=\"y\"),\n        ],\n    )\n    def test_versus_single_kdeplot(self, long_df, kwargs):\n\n        ax = kdeplot(data=long_df, **kwargs)\n        g = displot(long_df, kind=\"kde\", **kwargs)\n        assert_plots_equal(ax, g.ax)\n\n        if ax.legend_ is not None:\n            assert_legends_equal(ax.legend_, g._legend)\n\n        if kwargs:\n            long_df[\"_\"] = \"_\"\n            g2 = displot(long_df, kind=\"kde\", col=\"_\", **kwargs)\n            assert_plots_equal(ax, g2.ax)\n\n    @pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", weights=\"f\"),\n            dict(y=\"x\"),\n            dict(x=\"x\", color=\"green\", linewidth=2),\n            dict(x=\"x\", hue=\"a\", complementary=True),\n            dict(x=\"x\", hue=\"a\", stat=\"count\"),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n        ],\n    )\n    def test_versus_single_ecdfplot(self, long_df, kwargs):\n\n        ax = ecdfplot(data=long_df, **kwargs)\n        g = displot(long_df, kind=\"ecdf\", **kwargs)\n        assert_plots_equal(ax, g.ax)\n\n        if ax.legend_ is not None:\n            assert_legends_equal(ax.legend_, g._legend)\n\n        if kwargs:\n            long_df[\"_\"] = \"_\"\n            g2 = displot(long_df, kind=\"ecdf\", col=\"_\", **kwargs)\n            assert_plots_equal(ax, g2.ax)\n\n    @pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(x=\"x\"),\n            dict(x=\"x\", y=\"y\"),\n            dict(x=\"x\", hue=\"a\"),\n        ]\n    )\n    def test_with_rug(self, long_df, kwargs):\n\n        ax = plt.figure().subplots()\n        histplot(data=long_df, **kwargs, ax=ax)\n        rugplot(data=long_df, **kwargs, ax=ax)\n\n        g = displot(long_df, rug=True, **kwargs)\n\n        assert_plots_equal(ax, g.ax, labels=False)\n\n        long_df[\"_\"] = \"_\"\n        g2 = displot(long_df, col=\"_\", rug=True, **kwargs)\n\n        assert_plots_equal(ax, g2.ax, labels=False)\n\n    @pytest.mark.parametrize(\n        \"facet_var\", [\"col\", \"row\"],\n    )\n    def test_facets(self, long_df, facet_var):\n\n        kwargs = {facet_var: \"a\"}\n        ax = kdeplot(data=long_df, x=\"x\", hue=\"a\")\n        g = displot(long_df, x=\"x\", kind=\"kde\", **kwargs)\n\n        legend_texts = ax.legend_.get_texts()\n\n        for i, line in enumerate(ax.lines[::-1]):\n            facet_ax = g.axes.flat[i]\n            facet_line = facet_ax.lines[0]\n            assert_array_equal(line.get_xydata(), facet_line.get_xydata())\n\n            text = legend_texts[i].get_text()\n            assert text in facet_ax.get_title()\n\n    @pytest.mark.parametrize(\"multiple\", [\"dodge\", \"stack\", \"fill\"])\n    def test_facet_multiple(self, long_df, multiple):\n\n        bins = np.linspace(0, 20, 5)\n        ax = histplot(\n            data=long_df[long_df[\"c\"] == 0],\n            x=\"x\", hue=\"a\", hue_order=[\"a\", \"b\", \"c\"],\n            multiple=multiple, bins=bins,\n        )\n\n        g = displot(\n            data=long_df, x=\"x\", hue=\"a\", col=\"c\", hue_order=[\"a\", \"b\", \"c\"],\n            multiple=multiple, bins=bins,\n        )\n\n        assert_plots_equal(ax, g.axes_dict[0])\n\n    def test_ax_warning(self, long_df):\n\n        ax = plt.figure().subplots()\n        with pytest.warns(UserWarning, match=\"`displot` is a figure-level\"):\n            displot(long_df, x=\"x\", ax=ax)\n\n    @pytest.mark.parametrize(\"key\", [\"col\", \"row\"])\n    def test_array_faceting(self, long_df, key):\n\n        a = long_df[\"a\"].to_numpy()\n        vals = categorical_order(a)\n        g = displot(long_df, x=\"x\", **{key: a})\n        assert len(g.axes.flat) == len(vals)\n        for ax, val in zip(g.axes.flat, vals):\n            assert val in ax.get_title()\n\n    def test_legend(self, long_df):\n\n        g = displot(long_df, x=\"x\", hue=\"a\")\n        assert g._legend is not None\n\n    def test_empty(self):\n\n        g = displot(x=[], y=[])\n        assert isinstance(g, FacetGrid)\n\n    def test_bivariate_ecdf_error(self, long_df):\n\n        with pytest.raises(NotImplementedError):\n            displot(long_df, x=\"x\", y=\"y\", kind=\"ecdf\")\n\n    def test_bivariate_kde_norm(self, rng):\n\n        x, y = rng.normal(0, 1, (2, 100))\n        z = [0] * 80 + [1] * 20\n\n        g = displot(x=x, y=y, col=z, kind=\"kde\", levels=10)\n        l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)\n        l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)\n        assert l1 > l2\n\n        g = displot(x=x, y=y, col=z, kind=\"kde\", levels=10, common_norm=False)\n        l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)\n        l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)\n        assert l1 == l2\n\n    def test_bivariate_hist_norm(self, rng):\n\n        x, y = rng.normal(0, 1, (2, 100))\n        z = [0] * 80 + [1] * 20\n\n        g = displot(x=x, y=y, col=z, kind=\"hist\")\n        clim1 = g.axes.flat[0].collections[0].get_clim()\n        clim2 = g.axes.flat[1].collections[0].get_clim()\n        assert clim1 == clim2\n\n        g = displot(x=x, y=y, col=z, kind=\"hist\", common_norm=False)\n        clim1 = g.axes.flat[0].collections[0].get_clim()\n        clim2 = g.axes.flat[1].collections[0].get_clim()\n        assert clim1[1] > clim2[1]\n\n    def test_facetgrid_data(self, long_df):\n\n        g = displot(\n            data=long_df.to_dict(orient=\"list\"),\n            x=\"z\",\n            hue=long_df[\"a\"].rename(\"hue_var\"),\n            col=long_df[\"c\"].to_numpy(),\n        )\n        expected_cols = set(long_df.columns.to_list() + [\"hue_var\", \"_col_\"])\n        assert set(g.data.columns) == expected_cols\n        assert_array_equal(g.data[\"hue_var\"], long_df[\"a\"])\n        assert_array_equal(g.data[\"_col_\"], long_df[\"c\"])"},{"col":4,"comment":"null","endLoc":2258,"header":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"a\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", binwidth=4),\n            dict(x=\"x\", weights=\"f\", bins=5),\n            dict(x=\"x\", color=\"green\", linewidth=2, binwidth=4),\n            dict(x=\"x\", hue=\"a\", fill=False),\n            dict(x=\"y\", hue=\"a\", fill=False),\n            dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n            dict(x=\"x\", hue=\"a\", element=\"step\"),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n            dict(x=\"x\", hue=\"a\", kde=True),\n            dict(x=\"x\", hue=\"a\", stat=\"density\", common_norm=False),\n            dict(x=\"x\", y=\"y\"),\n        ],\n    )\n    def test_versus_single_histplot(self, long_df, kwargs)","id":3039,"name":"test_versus_single_histplot","nodeType":"Function","startLoc":2226,"text":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"a\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", binwidth=4),\n            dict(x=\"x\", weights=\"f\", bins=5),\n            dict(x=\"x\", color=\"green\", linewidth=2, binwidth=4),\n            dict(x=\"x\", hue=\"a\", fill=False),\n            dict(x=\"y\", hue=\"a\", fill=False),\n            dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n            dict(x=\"x\", hue=\"a\", element=\"step\"),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n            dict(x=\"x\", hue=\"a\", kde=True),\n            dict(x=\"x\", hue=\"a\", stat=\"density\", common_norm=False),\n            dict(x=\"x\", y=\"y\"),\n        ],\n    )\n    def test_versus_single_histplot(self, long_df, kwargs):\n\n        ax = histplot(long_df, **kwargs)\n        g = displot(long_df, **kwargs)\n        assert_plots_equal(ax, g.ax)\n\n        if ax.legend_ is not None:\n            assert_legends_equal(ax.legend_, g._legend)\n\n        if kwargs:\n            long_df[\"_\"] = \"_\"\n            g2 = displot(long_df, col=\"_\", **kwargs)\n            assert_plots_equal(ax, g2.ax)"},{"attributeType":"NegativeInfinityType","col":0,"comment":"null","endLoc":95,"id":3040,"name":"NegativeInfinity","nodeType":"Attribute","startLoc":95,"text":"NegativeInfinity"},{"col":4,"comment":"null","endLoc":60,"header":"def test_shared_colors_mapped(self)","id":3041,"name":"test_shared_colors_mapped","nodeType":"Function","startLoc":49,"text":"def test_shared_colors_mapped(self):\n\n        x = y = [1, 2, 3, 4]\n        c = [\"a\", \"a\", \"b\", \"b\"]\n        m = Path()\n        p = Plot(x=x, y=y, color=c).add(m).plot()\n        ax = p._figure.axes[0]\n        colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        for i, line in enumerate(ax.get_lines()):\n            assert same_color(line.get_color(), colors[i])\n            assert same_color(line.get_markeredgecolor(), colors[i])\n            assert same_color(line.get_markerfacecolor(), colors[i])"},{"id":3042,"name":"plotting_context.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"perceived-worry\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"seventh-volleyball\",\n   \"metadata\": {},\n   \"source\": [\n    \"Calling with no arguments will return the current defaults for the parameters that get scaled:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"roman-villa\",\n   \"metadata\": {\n    \"tags\": [\n     \"show-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"sns.plotting_context()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"handled-texas\",\n   \"metadata\": {},\n   \"source\": [\n    \"Calling with the name of a predefined style will show those values:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"distant-caribbean\",\n   \"metadata\": {\n    \"tags\": [\n     \"show-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"sns.plotting_context(\\\"talk\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"lightweight-anime\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the function as a context manager to temporarily change the parameter values:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"contemporary-hampshire\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with sns.plotting_context(\\\"talk\\\"):\\n\",\n    \"    sns.lineplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"accompanied-brisbane\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":3043,"name":"doc/example_thumbs","nodeType":"Package"},{"id":3044,"name":".gitkeep","nodeType":"TextFile","path":"doc/example_thumbs","text":""},{"attributeType":"InfinityType | NegativeInfinityType","col":0,"comment":"null","endLoc":100,"id":3045,"name":"InfiniteTypes","nodeType":"Attribute","startLoc":100,"text":"InfiniteTypes"},{"id":3046,"name":"rugplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Add a rug along one of the axes:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns; sns.set_theme()\\n\",\n    \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n    \"sns.kdeplot(data=tips, x=\\\"total_bill\\\")\\n\",\n    \"sns.rugplot(data=tips, x=\\\"total_bill\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Add a rug along both axes:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n    \"sns.rugplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Represent a third variable with hue mapping:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"time\\\")\\n\",\n    \"sns.rugplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"time\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Draw a taller rug:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n    \"sns.rugplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", height=.1)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Put the rug outside the axes:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.scatterplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n    \"sns.rugplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", height=-.02, clip_on=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Show the density of a larger dataset using thinner lines and alpha blending:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"diamonds = sns.load_dataset(\\\"diamonds\\\")\\n\",\n    \"sns.scatterplot(data=diamonds, x=\\\"carat\\\", y=\\\"price\\\", s=5)\\n\",\n    \"sns.rugplot(data=diamonds, x=\\\"carat\\\", y=\\\"price\\\", lw=1, alpha=.005)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":18,"id":3047,"name":"s","nodeType":"Attribute","startLoc":18,"text":"s"},{"attributeType":"null","col":4,"comment":"null","endLoc":21,"id":3048,"name":"cmap","nodeType":"Attribute","startLoc":21,"text":"cmap"},{"attributeType":"InfinityType | NegativeInfinityType | tuple","col":0,"comment":"null","endLoc":101,"id":3049,"name":"PrePostDevType","nodeType":"Attribute","startLoc":101,"text":"PrePostDevType"},{"fileName":"test_statistics.py","filePath":"tests","id":3050,"nodeType":"File","text":"import numpy as np\nimport pandas as pd\n\ntry:\n    import statsmodels.distributions as smdist\nexcept ImportError:\n    smdist = None\n\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom seaborn._statistics import (\n    KDE,\n    Histogram,\n    ECDF,\n    EstimateAggregator,\n    _validate_errorbar_arg,\n    _no_scipy,\n)\n\n\nclass DistributionFixtures:\n\n    @pytest.fixture\n    def x(self, rng):\n        return rng.normal(0, 1, 100)\n\n    @pytest.fixture\n    def y(self, rng):\n        return rng.normal(0, 5, 100)\n\n    @pytest.fixture\n    def weights(self, rng):\n        return rng.uniform(0, 5, 100)\n\n\nclass TestKDE:\n\n    def integrate(self, y, x):\n        y = np.asarray(y)\n        x = np.asarray(x)\n        dx = np.diff(x)\n        return (dx * y[:-1] + dx * y[1:]).sum() / 2\n\n    def test_gridsize(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n\n        n = 200\n        kde = KDE(gridsize=n)\n        density, support = kde(x)\n        assert density.size == n\n        assert support.size == n\n\n    def test_cut(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n\n        kde = KDE(cut=0)\n        _, support = kde(x)\n        assert support.min() == x.min()\n        assert support.max() == x.max()\n\n        cut = 2\n        bw_scale = .5\n        bw = x.std() * bw_scale\n        kde = KDE(cut=cut, bw_method=bw_scale, gridsize=1000)\n        _, support = kde(x)\n        assert support.min() == pytest.approx(x.min() - bw * cut, abs=1e-2)\n        assert support.max() == pytest.approx(x.max() + bw * cut, abs=1e-2)\n\n    def test_clip(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        clip = -1, 1\n        kde = KDE(clip=clip)\n        _, support = kde(x)\n\n        assert support.min() >= clip[0]\n        assert support.max() <= clip[1]\n\n    def test_density_normalization(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n        kde = KDE()\n        density, support = kde(x)\n        assert self.integrate(density, support) == pytest.approx(1, abs=1e-5)\n\n    @pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_cumulative(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n        kde = KDE(cumulative=True)\n        density, _ = kde(x)\n        assert density[0] == pytest.approx(0, abs=1e-5)\n        assert density[-1] == pytest.approx(1, abs=1e-5)\n\n    def test_cached_support(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde = KDE()\n        kde.define_support(x)\n        _, support = kde(x[(x > -1) & (x < 1)])\n        assert_array_equal(support, kde.support)\n\n    def test_bw_method(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde1 = KDE(bw_method=.2)\n        kde2 = KDE(bw_method=2)\n\n        d1, _ = kde1(x)\n        d2, _ = kde2(x)\n\n        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()\n\n    def test_bw_adjust(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde1 = KDE(bw_adjust=.2)\n        kde2 = KDE(bw_adjust=2)\n\n        d1, _ = kde1(x)\n        d2, _ = kde2(x)\n\n        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()\n\n    def test_bivariate_grid(self, rng):\n\n        n = 100\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=n)\n        density, (xx, yy) = kde(x, y)\n\n        assert density.shape == (n, n)\n        assert xx.size == n\n        assert yy.size == n\n\n    def test_bivariate_normalization(self, rng):\n\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=100)\n        density, (xx, yy) = kde(x, y)\n\n        dx = xx[1] - xx[0]\n        dy = yy[1] - yy[0]\n\n        total = density.sum() * (dx * dy)\n        assert total == pytest.approx(1, abs=1e-2)\n\n    @pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_bivariate_cumulative(self, rng):\n\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=100, cumulative=True)\n        density, _ = kde(x, y)\n\n        assert density[0, 0] == pytest.approx(0, abs=1e-2)\n        assert density[-1, -1] == pytest.approx(1, abs=1e-2)\n\n\nclass TestHistogram(DistributionFixtures):\n\n    def test_string_bins(self, x):\n\n        h = Histogram(bins=\"sqrt\")\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min(), x.max())\n        assert bin_kws[\"bins\"] == int(np.sqrt(len(x)))\n\n    def test_int_bins(self, x):\n\n        n = 24\n        h = Histogram(bins=n)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min(), x.max())\n        assert bin_kws[\"bins\"] == n\n\n    def test_array_bins(self, x):\n\n        bins = [-3, -2, 1, 2, 3]\n        h = Histogram(bins=bins)\n        bin_kws = h.define_bin_params(x)\n        assert_array_equal(bin_kws[\"bins\"], bins)\n\n    def test_bivariate_string_bins(self, x, y):\n\n        s1, s2 = \"sqrt\", \"fd\"\n\n        h = Histogram(bins=s1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, np.histogram_bin_edges(x, s1))\n        assert_array_equal(e2, np.histogram_bin_edges(y, s1))\n\n        h = Histogram(bins=(s1, s2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, np.histogram_bin_edges(x, s1))\n        assert_array_equal(e2, np.histogram_bin_edges(y, s2))\n\n    def test_bivariate_int_bins(self, x, y):\n\n        b1, b2 = 5, 10\n\n        h = Histogram(bins=b1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert len(e1) == b1 + 1\n        assert len(e2) == b1 + 1\n\n        h = Histogram(bins=(b1, b2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert len(e1) == b1 + 1\n        assert len(e2) == b2 + 1\n\n    def test_bivariate_array_bins(self, x, y):\n\n        b1 = [-3, -2, 1, 2, 3]\n        b2 = [-5, -2, 3, 6]\n\n        h = Histogram(bins=b1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, b1)\n        assert_array_equal(e2, b1)\n\n        h = Histogram(bins=(b1, b2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, b1)\n        assert_array_equal(e2, b2)\n\n    def test_binwidth(self, x):\n\n        binwidth = .5\n        h = Histogram(binwidth=binwidth)\n        bin_kws = h.define_bin_params(x)\n        n_bins = bin_kws[\"bins\"]\n        left, right = bin_kws[\"range\"]\n        assert (right - left) / n_bins == pytest.approx(binwidth)\n\n    def test_bivariate_binwidth(self, x, y):\n\n        w1, w2 = .5, 1\n\n        h = Histogram(binwidth=w1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert np.all(np.diff(e1) == w1)\n        assert np.all(np.diff(e2) == w1)\n\n        h = Histogram(binwidth=(w1, w2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert np.all(np.diff(e1) == w1)\n        assert np.all(np.diff(e2) == w2)\n\n    def test_binrange(self, x):\n\n        binrange = (-4, 4)\n        h = Histogram(binrange=binrange)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == binrange\n\n    def test_bivariate_binrange(self, x, y):\n\n        r1, r2 = (-4, 4), (-10, 10)\n\n        h = Histogram(binrange=r1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert e1.min() == r1[0]\n        assert e1.max() == r1[1]\n        assert e2.min() == r1[0]\n        assert e2.max() == r1[1]\n\n        h = Histogram(binrange=(r1, r2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert e1.min() == r1[0]\n        assert e1.max() == r1[1]\n        assert e2.min() == r2[0]\n        assert e2.max() == r2[1]\n\n    def test_discrete_bins(self, rng):\n\n        x = rng.binomial(20, .5, 100)\n        h = Histogram(discrete=True)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n        assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)\n\n    def test_odd_single_observation(self):\n        # GH2721\n        x = np.array([0.49928])\n        h, e = Histogram(binwidth=0.03)(x)\n        assert len(h) == 1\n        assert (e[1] - e[0]) == pytest.approx(.03)\n\n    def test_binwidth_roundoff(self):\n        # GH2785\n        x = np.array([2.4, 2.5, 2.6])\n        h, e = Histogram(binwidth=0.01)(x)\n        assert h.sum() == 3\n\n    def test_histogram(self, x):\n\n        h = Histogram()\n        heights, edges = h(x)\n        heights_mpl, edges_mpl = np.histogram(x, bins=\"auto\")\n\n        assert_array_equal(heights, heights_mpl)\n        assert_array_equal(edges, edges_mpl)\n\n    def test_count_stat(self, x):\n\n        h = Histogram(stat=\"count\")\n        heights, _ = h(x)\n        assert heights.sum() == len(x)\n\n    def test_density_stat(self, x):\n\n        h = Histogram(stat=\"density\")\n        heights, edges = h(x)\n        assert (heights * np.diff(edges)).sum() == 1\n\n    def test_probability_stat(self, x):\n\n        h = Histogram(stat=\"probability\")\n        heights, _ = h(x)\n        assert heights.sum() == 1\n\n    def test_frequency_stat(self, x):\n\n        h = Histogram(stat=\"frequency\")\n        heights, edges = h(x)\n        assert (heights * np.diff(edges)).sum() == len(x)\n\n    def test_cumulative_count(self, x):\n\n        h = Histogram(stat=\"count\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == len(x)\n\n    def test_cumulative_density(self, x):\n\n        h = Histogram(stat=\"density\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == 1\n\n    def test_cumulative_probability(self, x):\n\n        h = Histogram(stat=\"probability\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == 1\n\n    def test_cumulative_frequency(self, x):\n\n        h = Histogram(stat=\"frequency\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == len(x)\n\n    def test_bivariate_histogram(self, x, y):\n\n        h = Histogram()\n        heights, edges = h(x, y)\n        bins_mpl = (\n            np.histogram_bin_edges(x, \"auto\"),\n            np.histogram_bin_edges(y, \"auto\"),\n        )\n        heights_mpl, *edges_mpl = np.histogram2d(x, y, bins_mpl)\n        assert_array_equal(heights, heights_mpl)\n        assert_array_equal(edges[0], edges_mpl[0])\n        assert_array_equal(edges[1], edges_mpl[1])\n\n    def test_bivariate_count_stat(self, x, y):\n\n        h = Histogram(stat=\"count\")\n        heights, _ = h(x, y)\n        assert heights.sum() == len(x)\n\n    def test_bivariate_density_stat(self, x, y):\n\n        h = Histogram(stat=\"density\")\n        heights, (edges_x, edges_y) = h(x, y)\n        areas = np.outer(np.diff(edges_x), np.diff(edges_y))\n        assert (heights * areas).sum() == pytest.approx(1)\n\n    def test_bivariate_probability_stat(self, x, y):\n\n        h = Histogram(stat=\"probability\")\n        heights, _ = h(x, y)\n        assert heights.sum() == 1\n\n    def test_bivariate_frequency_stat(self, x, y):\n\n        h = Histogram(stat=\"frequency\")\n        heights, (x_edges, y_edges) = h(x, y)\n        area = np.outer(np.diff(x_edges), np.diff(y_edges))\n        assert (heights * area).sum() == len(x)\n\n    def test_bivariate_cumulative_count(self, x, y):\n\n        h = Histogram(stat=\"count\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == len(x)\n\n    def test_bivariate_cumulative_density(self, x, y):\n\n        h = Histogram(stat=\"density\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == pytest.approx(1)\n\n    def test_bivariate_cumulative_frequency(self, x, y):\n\n        h = Histogram(stat=\"frequency\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == len(x)\n\n    def test_bivariate_cumulative_probability(self, x, y):\n\n        h = Histogram(stat=\"probability\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == pytest.approx(1)\n\n    def test_bad_stat(self):\n\n        with pytest.raises(ValueError):\n            Histogram(stat=\"invalid\")\n\n\nclass TestECDF(DistributionFixtures):\n\n    def test_univariate_proportion(self, x):\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x)\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], np.linspace(0, 1, len(x) + 1)[1:])\n        assert stat[0] == 0\n\n    def test_univariate_count(self, x):\n\n        ecdf = ECDF(stat=\"count\")\n        stat, vals = ecdf(x)\n\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], np.arange(len(x)) + 1)\n        assert stat[0] == 0\n\n    def test_univariate_proportion_weights(self, x, weights):\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x, weights=weights)\n        assert_array_equal(vals[1:], np.sort(x))\n        expected_stats = weights[x.argsort()].cumsum() / weights.sum()\n        assert_array_almost_equal(stat[1:], expected_stats)\n        assert stat[0] == 0\n\n    def test_univariate_count_weights(self, x, weights):\n\n        ecdf = ECDF(stat=\"count\")\n        stat, vals = ecdf(x, weights=weights)\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], weights[x.argsort()].cumsum())\n        assert stat[0] == 0\n\n    @pytest.mark.skipif(smdist is None, reason=\"Requires statsmodels\")\n    def test_against_statsmodels(self, x):\n\n        sm_ecdf = smdist.empirical_distribution.ECDF(x)\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x)\n        assert_array_equal(vals, sm_ecdf.x)\n        assert_array_almost_equal(stat, sm_ecdf.y)\n\n        ecdf = ECDF(complementary=True)\n        stat, vals = ecdf(x)\n        assert_array_equal(vals, sm_ecdf.x)\n        assert_array_almost_equal(stat, sm_ecdf.y[::-1])\n\n    def test_invalid_stat(self, x):\n\n        with pytest.raises(ValueError, match=\"`stat` must be one of\"):\n            ECDF(stat=\"density\")\n\n    def test_bivariate_error(self, x, y):\n\n        with pytest.raises(NotImplementedError, match=\"Bivariate ECDF\"):\n            ecdf = ECDF()\n            ecdf(x, y)\n\n\nclass TestEstimateAggregator:\n\n    def test_func_estimator(self, long_df):\n\n        func = np.mean\n        agg = EstimateAggregator(func)\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == func(long_df[\"x\"])\n\n    def test_name_estimator(self, long_df):\n\n        agg = EstimateAggregator(\"mean\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n\n    def test_custom_func_estimator(self, long_df):\n\n        def func(x):\n            return np.asarray(x).min()\n\n        agg = EstimateAggregator(func)\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == func(long_df[\"x\"])\n\n    def test_se_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"se\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - long_df[\"x\"].sem())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + long_df[\"x\"].sem())\n\n        agg = EstimateAggregator(\"mean\", (\"se\", 2))\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - 2 * long_df[\"x\"].sem())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + 2 * long_df[\"x\"].sem())\n\n    def test_sd_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"sd\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - long_df[\"x\"].std())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + long_df[\"x\"].std())\n\n        agg = EstimateAggregator(\"mean\", (\"sd\", 2))\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - 2 * long_df[\"x\"].std())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + 2 * long_df[\"x\"].std())\n\n    def test_pi_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"pi\")\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == np.percentile(long_df[\"y\"], 2.5)\n        assert out[\"ymax\"] == np.percentile(long_df[\"y\"], 97.5)\n\n        agg = EstimateAggregator(\"mean\", (\"pi\", 50))\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == np.percentile(long_df[\"y\"], 25)\n        assert out[\"ymax\"] == np.percentile(long_df[\"y\"], 75)\n\n    def test_ci_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"ci\", n_boot=100000, seed=0)\n        out = agg(long_df, \"y\")\n\n        agg_ref = EstimateAggregator(\"mean\", (\"se\", 1.96))\n        out_ref = agg_ref(long_df, \"y\")\n\n        assert out[\"ymin\"] == pytest.approx(out_ref[\"ymin\"], abs=1e-2)\n        assert out[\"ymax\"] == pytest.approx(out_ref[\"ymax\"], abs=1e-2)\n\n        agg = EstimateAggregator(\"mean\", (\"ci\", 68), n_boot=100000, seed=0)\n        out = agg(long_df, \"y\")\n\n        agg_ref = EstimateAggregator(\"mean\", (\"se\", 1))\n        out_ref = agg_ref(long_df, \"y\")\n\n        assert out[\"ymin\"] == pytest.approx(out_ref[\"ymin\"], abs=1e-2)\n        assert out[\"ymax\"] == pytest.approx(out_ref[\"ymax\"], abs=1e-2)\n\n        agg = EstimateAggregator(\"mean\", \"ci\", seed=0)\n        out_orig = agg_ref(long_df, \"y\")\n        out_test = agg_ref(long_df, \"y\")\n        assert_array_equal(out_orig, out_test)\n\n    def test_custom_errorbars(self, long_df):\n\n        f = lambda x: (x.min(), x.max())  # noqa: E731\n        agg = EstimateAggregator(\"mean\", f)\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == long_df[\"y\"].min()\n        assert out[\"ymax\"] == long_df[\"y\"].max()\n\n    def test_singleton_errorbars(self):\n\n        agg = EstimateAggregator(\"mean\", \"ci\")\n        val = 7\n        out = agg(pd.DataFrame(dict(y=[val])), \"y\")\n        assert out[\"y\"] == val\n        assert pd.isna(out[\"ymin\"])\n        assert pd.isna(out[\"ymax\"])\n\n    def test_errorbar_validation(self):\n\n        method, level = _validate_errorbar_arg((\"ci\", 99))\n        assert method == \"ci\"\n        assert level == 99\n\n        method, level = _validate_errorbar_arg(\"sd\")\n        assert method == \"sd\"\n        assert level == 1\n\n        f = lambda x: (x.min(), x.max())  # noqa: E731\n        method, level = _validate_errorbar_arg(f)\n        assert method is f\n        assert level is None\n\n        bad_args = [\n            (\"sem\", ValueError),\n            ((\"std\", 2), ValueError),\n            ((\"pi\", 5, 95), ValueError),\n            (95, TypeError),\n            ((\"ci\", \"large\"), TypeError),\n        ]\n\n        for arg, exception in bad_args:\n            with pytest.raises(exception, match=\"`errorbar` must be\"):\n                _validate_errorbar_arg(arg)\n"},{"className":"ECDF","col":0,"comment":"Univariate empirical cumulative distribution estimator.","endLoc":451,"id":3051,"nodeType":"Class","startLoc":401,"text":"class ECDF:\n    \"\"\"Univariate empirical cumulative distribution estimator.\"\"\"\n    def __init__(self, stat=\"proportion\", complementary=False):\n        \"\"\"Initialize the class with its parameters\n\n        Parameters\n        ----------\n        stat : {{\"proportion\", \"count\"}}\n            Distribution statistic to compute.\n        complementary : bool\n            If True, use the complementary CDF (1 - CDF)\n\n        \"\"\"\n        _check_argument(\"stat\", [\"count\", \"proportion\"], stat)\n        self.stat = stat\n        self.complementary = complementary\n\n    def _eval_bivariate(self, x1, x2, weights):\n        \"\"\"Inner function for ECDF of two variables.\"\"\"\n        raise NotImplementedError(\"Bivariate ECDF is not implemented\")\n\n    def _eval_univariate(self, x, weights):\n        \"\"\"Inner function for ECDF of one variable.\"\"\"\n        sorter = x.argsort()\n        x = x[sorter]\n        weights = weights[sorter]\n        y = weights.cumsum()\n\n        if self.stat == \"proportion\":\n            y = y / y.max()\n\n        x = np.r_[-np.inf, x]\n        y = np.r_[0, y]\n\n        if self.complementary:\n            y = y.max() - y\n\n        return y, x\n\n    def __call__(self, x1, x2=None, weights=None):\n        \"\"\"Return proportion or count of observations below each sorted datapoint.\"\"\"\n        x1 = np.asarray(x1)\n        if weights is None:\n            weights = np.ones_like(x1)\n        else:\n            weights = np.asarray(weights)\n\n        if x2 is None:\n            return self._eval_univariate(x1, weights)\n        else:\n            return self._eval_bivariate(x1, x2, weights)"},{"col":4,"comment":"Inner function for ECDF of two variables.","endLoc":420,"header":"def _eval_bivariate(self, x1, x2, weights)","id":3052,"name":"_eval_bivariate","nodeType":"Function","startLoc":418,"text":"def _eval_bivariate(self, x1, x2, weights):\n        \"\"\"Inner function for ECDF of two variables.\"\"\"\n        raise NotImplementedError(\"Bivariate ECDF is not implemented\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":24,"id":3053,"name":"x","nodeType":"Attribute","startLoc":24,"text":"x"},{"attributeType":"null","col":7,"comment":"null","endLoc":24,"id":3054,"name":"y","nodeType":"Attribute","startLoc":24,"text":"y"},{"col":0,"comment":"","endLoc":6,"header":"palette_generation.py#","id":3055,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nDifferent cubehelix palettes\n============================\n\n_thumb: .4, .65\n\"\"\"\n\nsns.set_theme(style=\"white\")\n\nrs = np.random.RandomState(50)\n\nf, axes = plt.subplots(3, 3, figsize=(9, 9), sharex=True, sharey=True)\n\nfor ax, s in zip(axes.flat, np.linspace(0, 3, 10)):\n\n    # Create a cubehelix colormap to use with kdeplot\n    cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True)\n\n    # Generate and plot a random bivariate dataset\n    x, y = rs.normal(size=(2, 50))\n    sns.kdeplot(\n        x=x, y=y,\n        cmap=cmap, fill=True,\n        clip=(-5, 5), cut=10,\n        thresh=0, levels=15,\n        ax=ax,\n    )\n    ax.set_axis_off()\n\nax.set(xlim=(-3.5, 3.5), ylim=(-3.5, 3.5))\n\nf.subplots_adjust(0, 0, 1, 1, .08, .08)"},{"fileName":"timeseries_facets.py","filePath":"examples","id":3056,"nodeType":"File","text":"\"\"\"\nSmall multiple time series\n--------------------------\n\n_thumb: .42, .58\n\n\"\"\"\nimport seaborn as sns\n\nsns.set_theme(style=\"dark\")\nflights = sns.load_dataset(\"flights\")\n\n# Plot each year's time series in its own facet\ng = sns.relplot(\n    data=flights,\n    x=\"month\", y=\"passengers\", col=\"year\", hue=\"year\",\n    kind=\"line\", palette=\"crest\", linewidth=4, zorder=5,\n    col_wrap=3, height=2, aspect=1.5, legend=False,\n)\n\n# Iterate over each subplot to customize further\nfor year, ax in g.axes_dict.items():\n\n    # Add the title as an annotation within the plot\n    ax.text(.8, .85, year, transform=ax.transAxes, fontweight=\"bold\")\n\n    # Plot every year's time series in the background\n    sns.lineplot(\n        data=flights, x=\"month\", y=\"passengers\", units=\"year\",\n        estimator=None, color=\".7\", linewidth=1, ax=ax,\n    )\n\n# Reduce the frequency of the x axis ticks\nax.set_xticks(ax.get_xticks()[::2])\n\n# Tweak the supporting aspects of the plot\ng.set_titles(\"\")\ng.set_axis_labels(\"\", \"Passengers\")\ng.tight_layout()\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":3057,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"InfinityType | NegativeInfinityType | int | str","col":0,"comment":"null","endLoc":102,"id":3058,"name":"SubLocalType","nodeType":"Attribute","startLoc":102,"text":"SubLocalType"},{"col":4,"comment":"Inner function for ECDF of one variable.","endLoc":438,"header":"def _eval_univariate(self, x, weights)","id":3059,"name":"_eval_univariate","nodeType":"Function","startLoc":422,"text":"def _eval_univariate(self, x, weights):\n        \"\"\"Inner function for ECDF of one variable.\"\"\"\n        sorter = x.argsort()\n        x = x[sorter]\n        weights = weights[sorter]\n        y = weights.cumsum()\n\n        if self.stat == \"proportion\":\n            y = y / y.max()\n\n        x = np.r_[-np.inf, x]\n        y = np.r_[0, y]\n\n        if self.complementary:\n            y = y.max() - y\n\n        return y, x"},{"id":3060,"name":"v0.6.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.6.0 (June 2015)\n------------------\n\nThis is a major release from 0.5. The main objective of this release was to unify the API for categorical plots, which means that there are some relatively large API changes in some of the older functions. See below for details of those changes, which may break code written for older versions of seaborn. There are also some new functions (:func:`stripplot`,  and :func:`countplot`), numerous enhancements to existing functions, and bug fixes.\n\nAdditionally, the documentation has been completely revamped and expanded for the 0.6 release. Now, the API docs page for each function has multiple examples with embedded plots showing how to use the various options. These pages should be considered the most comprehensive resource for examples, and the tutorial pages are now streamlined and oriented towards a higher-level overview of the various features.\n\nChanges and updates to categorical plots\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn version 0.6, the \"categorical\" plots have been unified with a common API. This new category of functions groups together plots that show the relationship between one numeric variable and one or two categorical variables. This includes plots that show distribution of the numeric variable in each bin (:func:`boxplot`, :func:`violinplot`, and :func:`stripplot`) and plots that apply a statistical estimation within each bin (:func:`pointplot`, :func:`barplot`, and :func:`countplot`). There is a new :ref:`tutorial chapter ` that introduces these functions.\n\nThe categorical functions now each accept the same formats of input data and can be invoked in the same way. They can plot using long- or wide-form data, and can be drawn vertically or horizontally. When long-form data is used, the orientation of the plots is inferred from the types of the input data. Additionally, all functions natively take a ``hue`` variable to add a second layer of categorization.\n\nWith the (in some cases new) API, these functions can all be drawn correctly by :class:`FacetGrid`. However, ``factorplot`` can also now create faceted versions of any of these kinds of plots, so in most cases it will be unnecessary to use :class:`FacetGrid` directly. By default, ``factorplot`` draws a point plot, but this is controlled by the ``kind`` parameter.\n\nHere are details on what has changed in the process of unifying these APIs:\n\n- Changes to :func:`boxplot` and :func:`violinplot` will probably be the most disruptive. Both functions maintain backwards-compatibility in terms of the kind of data they can accept, but the syntax has changed to be more similar to other seaborn functions. These functions are now invoked with ``x`` and/or ``y`` parameters that are either vectors of data or names of variables in a long-form DataFrame passed to the new ``data`` parameter. You can still pass wide-form DataFrames or arrays to ``data``, but it is no longer the first positional argument. See the `github pull request (#410) `_ for more information on these changes and the logic behind them.\n\n- As :func:`pointplot` and :func:`barplot` can now plot with the major categorical variable on the y axis, the ``x_order`` parameter has been renamed to ``order``.\n\n- Added a ``hue`` argument to :func:`boxplot` and :func:`violinplot`, which allows for nested grouping the plot elements by a third categorical variable. For :func:`violinplot`, this nesting can also be accomplished by splitting the violins when there are two levels of the ``hue`` variable (using ``split=True``). To make this functionality feasible, the ability to specify where the plots will be draw in data coordinates has been removed. These plots now are drawn at set positions, like (and identical to) :func:`barplot` and :func:`pointplot`.\n\n- Added a ``palette`` parameter to :func:`boxplot`/:func:`violinplot`. The ``color`` parameter still exists, but no longer does double-duty in accepting the name of a seaborn palette. ``palette`` supersedes ``color`` so that it can be used with a :class:`FacetGrid`.\n\nAlong with these API changes, the following changes/enhancements were made to the plotting functions:\n\n- The default rules for ordering the categories has changed. Instead of automatically sorting the category levels, the plots now show the levels in the order they appear in the input data (i.e., the order given by ``Series.unique()``). Order can be specified when plotting with the ``order`` and ``hue_order`` parameters. Additionally, when variables are pandas objects with a \"categorical\" dtype, the category order is inferred from the data object. This change also affects :class:`FacetGrid` and :class:`PairGrid`.\n\n- Added the ``scale`` and ``scale_hue`` parameters to :func:`violinplot`. These control how the width of the violins are scaled. The default is ``area``, which is different from how the violins used to be drawn. Use ``scale='width'`` to get the old behavior.\n\n- Used a different style for the ``box`` kind of interior plot in :func:`violinplot`, which shows the whisker range in addition to the quartiles. Use ``inner='quartile'`` to get the old style.\n\nNew plotting functions\n~~~~~~~~~~~~~~~~~~~~~~\n\n- Added the :func:`stripplot` function, which draws a scatterplot where one of the variables is categorical. This plot has the same API as :func:`boxplot` and :func:`violinplot`. It is useful both on its own and when composed with one of these other plot kinds to show both the observations and underlying distribution.\n\n- Added the :func:`countplot` function, which uses a bar plot representation to show counts of variables in one or more categorical bins. This replaces the old approach of calling :func:`barplot` without a numeric variable.\n\nOther additions and changes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n- The :func:`corrplot` and underlying :func:`symmatplot` functions have been deprecated in favor of :func:`heatmap`, which is much more flexible and robust. These two functions are still available in version 0.6, but they will be removed in a future version.\n\n- Added the :func:`set_color_codes` function and the ``color_codes`` argument to :func:`set` and :func:`set_palette`. This changes the interpretation of shorthand color codes (i.e. \"b\", \"g\", k\", etc.) within matplotlib to use the values from one of the named seaborn palettes (i.e. \"deep\", \"muted\", etc.). That makes it easier to have a more uniform look when using matplotlib functions directly with seaborn imported. This could be disruptive to existing plots, so it does not happen by default. It is possible this could change in the future.\n\n- The :func:`color_palette` function no longer trims palettes that are longer than 6 colors when passed into it.\n\n- Added the ``as_hex`` method to color palette objects, to return a list of hex codes rather than rgb tuples.\n\n- :func:`jointplot` now passes additional keyword arguments to the function used to draw the plot on the joint axes.\n\n- Changed the default ``linewidths`` in :func:`heatmap` and :func:`clustermap` to 0 so that larger matrices plot correctly. This parameter still exists and can be used to get the old effect of lines demarcating each cell in the heatmap (the old default ``linewidths`` was 0.5).\n\n- :func:`heatmap` and :func:`clustermap` now automatically use a mask for missing values, which previously were shown with the \"under\" value of the colormap per default `plt.pcolormesh` behavior.\n\n- Added the ``seaborn.crayons`` dictionary and the :func:`crayon_palette` function to define colors from the 120 box (!) of `Crayola crayons `_.\n\n- Added the ``line_kws`` parameter to :func:`residplot` to change the style of the lowess line, when used.\n\n- Added open-ended ``**kwargs`` to the ``add_legend`` method on :class:`FacetGrid` and :class:`PairGrid`, which will pass additional keyword arguments through when calling the legend function on the ``Figure`` or ``Axes``.\n\n- Added the ``gridspec_kws`` parameter to :class:`FacetGrid`, which allows for control over the size of individual facets in the grid to emphasize certain plots or account for differences in variable ranges.\n\n- The interactive palette widgets now show a continuous colorbar, rather than a discrete palette, when `as_cmap` is True.\n\n- The default Axes size for :func:`pairplot` and :class:`PairGrid` is now slightly smaller.\n\n- Added the ``shade_lowest`` parameter to :func:`kdeplot` which will set the alpha for the lowest contour level to 0, making it easier to plot multiple bivariate distributions on the same axes.\n\n- The ``height`` parameter of :func:`rugplot` is now interpreted as a function of the axis size and is invariant to changes in the data scale on that axis. The rug lines are also slightly narrower by default.\n\n- Added a catch in :func:`distplot` when calculating a default number of bins. For highly skewed data it will now use sqrt(n) bins, where previously the reference rule would return \"infinite\" bins and cause an exception in matplotlib.\n\n- Added a ceiling (50) to the default number of bins used for :func:`distplot` histograms. This will help avoid confusing errors with certain kinds of datasets that heavily violate the assumptions of the reference rule used to get a default number of bins. The ceiling is not applied when passing a specific number of bins.\n\n- The various property dictionaries that can be passed to ``plt.boxplot`` are now applied after the seaborn restyling to allow for full customizability.\n\n- Added a ``savefig`` method to :class:`JointGrid` that defaults to a tight bounding box to make it easier to save figures using this class, and set a tight bbox as the default for the ``savefig`` method on other Grid objects.\n\n- You can now pass an integer to the ``xticklabels`` and ``yticklabels`` parameter of :func:`heatmap` (and, by extension, :func:`clustermap`). This will make the plot use the ticklabels inferred from the data, but only plot every ``n`` label, where ``n`` is the number you pass. This can help when visualizing larger matrices with some sensible ordering to the rows or columns of the dataframe.\n\n- Added `\"figure.facecolor\"` to the style parameters and set the default to white.\n\n- The :func:`load_dataset` function now caches datasets locally after downloading them, and uses the local copy on subsequent calls.\n\nBug fixes\n~~~~~~~~~\n\n- Fixed bugs in :func:`clustermap` where the mask and specified ticklabels were not being reorganized using the dendrograms.\n\n- Fixed a bug in :class:`FacetGrid` and :class:`PairGrid` that lead to incorrect legend labels when levels of the ``hue`` variable appeared in ``hue_order`` but not in the data.\n\n- Fixed a bug in :meth:`FacetGrid.set_xticklabels` or :meth:`FacetGrid.set_yticklabels` when ``col_wrap`` is being used.\n\n- Fixed a bug in :class:`PairGrid` where the ``hue_order`` parameter was ignored.\n\n- Fixed two bugs in :func:`despine` that caused errors when trying to trim the spines on plots that had inverted axes or no ticks.\n\n- Improved support for the ``margin_titles`` option in :class:`FacetGrid`, which can now be used with a legend.\n"},{"col":4,"comment":"Return proportion or count of observations below each sorted datapoint.","endLoc":451,"header":"def __call__(self, x1, x2=None, weights=None)","id":3061,"name":"__call__","nodeType":"Function","startLoc":440,"text":"def __call__(self, x1, x2=None, weights=None):\n        \"\"\"Return proportion or count of observations below each sorted datapoint.\"\"\"\n        x1 = np.asarray(x1)\n        if weights is None:\n            weights = np.ones_like(x1)\n        else:\n            weights = np.asarray(weights)\n\n        if x2 is None:\n            return self._eval_univariate(x1, weights)\n        else:\n            return self._eval_bivariate(x1, x2, weights)"},{"attributeType":"NegativeInfinityType | tuple","col":0,"comment":"null","endLoc":103,"id":3062,"name":"LocalType","nodeType":"Attribute","startLoc":103,"text":"LocalType"},{"attributeType":"null","col":8,"comment":"null","endLoc":415,"id":3063,"name":"stat","nodeType":"Attribute","startLoc":415,"text":"self.stat"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3064,"name":"flights","nodeType":"Attribute","startLoc":11,"text":"flights"},{"attributeType":"bool","col":8,"comment":"null","endLoc":416,"id":3065,"name":"complementary","nodeType":"Attribute","startLoc":416,"text":"self.complementary"},{"fileName":"_statistics.py","filePath":"seaborn","id":3066,"nodeType":"File","text":"\"\"\"Statistical transformations for visualization.\n\nThis module is currently private, but is being written to eventually form part\nof the public API.\n\nThe classes should behave roughly in the style of scikit-learn.\n\n- All data-independent parameters should be passed to the class constructor.\n- Each class should implement a default transformation that is exposed through\n  __call__. These are currently written for vector arguments, but I think\n  consuming a whole `plot_data` DataFrame and return it with transformed\n  variables would make more sense.\n- Some class have data-dependent preprocessing that should be cached and used\n  multiple times (think defining histogram bins off all data and then counting\n  observations within each bin multiple times per data subsets). These currently\n  have unique names, but it would be good to have a common name. Not quite\n  `fit`, but something similar.\n- Alternatively, the transform interface could take some information about grouping\n  variables and do a groupby internally.\n- Some classes should define alternate transforms that might make the most sense\n  with a different function. For example, KDE usually evaluates the distribution\n  on a regular grid, but it would be useful for it to transform at the actual\n  datapoints. Then again, this could be controlled by a parameter at  the time of\n  class instantiation.\n\n\"\"\"\nfrom numbers import Number\nimport numpy as np\nimport pandas as pd\ntry:\n    from scipy.stats import gaussian_kde\n    _no_scipy = False\nexcept ImportError:\n    from .external.kde import gaussian_kde\n    _no_scipy = True\n\nfrom .algorithms import bootstrap\nfrom .utils import _check_argument\n\n\nclass KDE:\n    \"\"\"Univariate and bivariate kernel density estimator.\"\"\"\n    def __init__(\n        self, *,\n        bw_method=None,\n        bw_adjust=1,\n        gridsize=200,\n        cut=3,\n        clip=None,\n        cumulative=False,\n    ):\n        \"\"\"Initialize the estimator with its parameters.\n\n        Parameters\n        ----------\n        bw_method : string, scalar, or callable, optional\n            Method for determining the smoothing bandwidth to use; passed to\n            :class:`scipy.stats.gaussian_kde`.\n        bw_adjust : number, optional\n            Factor that multiplicatively scales the value chosen using\n            ``bw_method``. Increasing will make the curve smoother. See Notes.\n        gridsize : int, optional\n            Number of points on each dimension of the evaluation grid.\n        cut : number, optional\n            Factor, multiplied by the smoothing bandwidth, that determines how\n            far the evaluation grid extends past the extreme datapoints. When\n            set to 0, truncate the curve at the data limits.\n        clip : pair of numbers or None, or a pair of such pairs\n            Do not evaluate the density outside of these limits.\n        cumulative : bool, optional\n            If True, estimate a cumulative distribution function. Requires scipy.\n\n        \"\"\"\n        if clip is None:\n            clip = None, None\n\n        self.bw_method = bw_method\n        self.bw_adjust = bw_adjust\n        self.gridsize = gridsize\n        self.cut = cut\n        self.clip = clip\n        self.cumulative = cumulative\n\n        if cumulative and _no_scipy:\n            raise RuntimeError(\"Cumulative KDE evaluation requires scipy\")\n\n        self.support = None\n\n    def _define_support_grid(self, x, bw, cut, clip, gridsize):\n        \"\"\"Create the grid of evaluation points depending for vector x.\"\"\"\n        clip_lo = -np.inf if clip[0] is None else clip[0]\n        clip_hi = +np.inf if clip[1] is None else clip[1]\n        gridmin = max(x.min() - bw * cut, clip_lo)\n        gridmax = min(x.max() + bw * cut, clip_hi)\n        return np.linspace(gridmin, gridmax, gridsize)\n\n    def _define_support_univariate(self, x, weights):\n        \"\"\"Create a 1D grid of evaluation points.\"\"\"\n        kde = self._fit(x, weights)\n        bw = np.sqrt(kde.covariance.squeeze())\n        grid = self._define_support_grid(\n            x, bw, self.cut, self.clip, self.gridsize\n        )\n        return grid\n\n    def _define_support_bivariate(self, x1, x2, weights):\n        \"\"\"Create a 2D grid of evaluation points.\"\"\"\n        clip = self.clip\n        if clip[0] is None or np.isscalar(clip[0]):\n            clip = (clip, clip)\n\n        kde = self._fit([x1, x2], weights)\n        bw = np.sqrt(np.diag(kde.covariance).squeeze())\n\n        grid1 = self._define_support_grid(\n            x1, bw[0], self.cut, clip[0], self.gridsize\n        )\n        grid2 = self._define_support_grid(\n            x2, bw[1], self.cut, clip[1], self.gridsize\n        )\n\n        return grid1, grid2\n\n    def define_support(self, x1, x2=None, weights=None, cache=True):\n        \"\"\"Create the evaluation grid for a given data set.\"\"\"\n        if x2 is None:\n            support = self._define_support_univariate(x1, weights)\n        else:\n            support = self._define_support_bivariate(x1, x2, weights)\n\n        if cache:\n            self.support = support\n\n        return support\n\n    def _fit(self, fit_data, weights=None):\n        \"\"\"Fit the scipy kde while adding bw_adjust logic and version check.\"\"\"\n        fit_kws = {\"bw_method\": self.bw_method}\n        if weights is not None:\n            fit_kws[\"weights\"] = weights\n\n        kde = gaussian_kde(fit_data, **fit_kws)\n        kde.set_bandwidth(kde.factor * self.bw_adjust)\n\n        return kde\n\n    def _eval_univariate(self, x, weights=None):\n        \"\"\"Fit and evaluate a univariate on univariate data.\"\"\"\n        support = self.support\n        if support is None:\n            support = self.define_support(x, cache=False)\n\n        kde = self._fit(x, weights)\n\n        if self.cumulative:\n            s_0 = support[0]\n            density = np.array([\n                kde.integrate_box_1d(s_0, s_i) for s_i in support\n            ])\n        else:\n            density = kde(support)\n\n        return density, support\n\n    def _eval_bivariate(self, x1, x2, weights=None):\n        \"\"\"Fit and evaluate a univariate on bivariate data.\"\"\"\n        support = self.support\n        if support is None:\n            support = self.define_support(x1, x2, cache=False)\n\n        kde = self._fit([x1, x2], weights)\n\n        if self.cumulative:\n\n            grid1, grid2 = support\n            density = np.zeros((grid1.size, grid2.size))\n            p0 = grid1.min(), grid2.min()\n            for i, xi in enumerate(grid1):\n                for j, xj in enumerate(grid2):\n                    density[i, j] = kde.integrate_box(p0, (xi, xj))\n\n        else:\n\n            xx1, xx2 = np.meshgrid(*support)\n            density = kde([xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)\n\n        return density, support\n\n    def __call__(self, x1, x2=None, weights=None):\n        \"\"\"Fit and evaluate on univariate or bivariate data.\"\"\"\n        if x2 is None:\n            return self._eval_univariate(x1, weights)\n        else:\n            return self._eval_bivariate(x1, x2, weights)\n\n\n# Note: we no longer use this for univariate histograms in histplot,\n# preferring _stats.Hist. We'll deprecate this once we have a bivariate Stat class.\nclass Histogram:\n    \"\"\"Univariate and bivariate histogram estimator.\"\"\"\n    def __init__(\n        self,\n        stat=\"count\",\n        bins=\"auto\",\n        binwidth=None,\n        binrange=None,\n        discrete=False,\n        cumulative=False,\n    ):\n        \"\"\"Initialize the estimator with its parameters.\n\n        Parameters\n        ----------\n        stat : str\n            Aggregate statistic to compute in each bin.\n\n            - `count`: show the number of observations in each bin\n            - `frequency`: show the number of observations divided by the bin width\n            - `probability` or `proportion`: normalize such that bar heights sum to 1\n            - `percent`: normalize such that bar heights sum to 100\n            - `density`: normalize such that the total area of the histogram equals 1\n\n        bins : str, number, vector, or a pair of such values\n            Generic bin parameter that can be the name of a reference rule,\n            the number of bins, or the breaks of the bins.\n            Passed to :func:`numpy.histogram_bin_edges`.\n        binwidth : number or pair of numbers\n            Width of each bin, overrides ``bins`` but can be used with\n            ``binrange``.\n        binrange : pair of numbers or a pair of pairs\n            Lowest and highest value for bin edges; can be used either\n            with ``bins`` or ``binwidth``. Defaults to data extremes.\n        discrete : bool or pair of bools\n            If True, set ``binwidth`` and ``binrange`` such that bin\n            edges cover integer values in the dataset.\n        cumulative : bool\n            If True, return the cumulative statistic.\n\n        \"\"\"\n        stat_choices = [\n            \"count\", \"frequency\", \"density\", \"probability\", \"proportion\", \"percent\",\n        ]\n        _check_argument(\"stat\", stat_choices, stat)\n\n        self.stat = stat\n        self.bins = bins\n        self.binwidth = binwidth\n        self.binrange = binrange\n        self.discrete = discrete\n        self.cumulative = cumulative\n\n        self.bin_kws = None\n\n    def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete):\n        \"\"\"Inner function that takes bin parameters as arguments.\"\"\"\n        if binrange is None:\n            start, stop = x.min(), x.max()\n        else:\n            start, stop = binrange\n\n        if discrete:\n            bin_edges = np.arange(start - .5, stop + 1.5)\n        elif binwidth is not None:\n            step = binwidth\n            bin_edges = np.arange(start, stop + step, step)\n            # Handle roundoff error (maybe there is a less clumsy way?)\n            if bin_edges.max() < stop or len(bin_edges) < 2:\n                bin_edges = np.append(bin_edges, bin_edges.max() + step)\n        else:\n            bin_edges = np.histogram_bin_edges(\n                x, bins, binrange, weights,\n            )\n        return bin_edges\n\n    def define_bin_params(self, x1, x2=None, weights=None, cache=True):\n        \"\"\"Given data, return numpy.histogram parameters to define bins.\"\"\"\n        if x2 is None:\n\n            bin_edges = self._define_bin_edges(\n                x1, weights, self.bins, self.binwidth, self.binrange, self.discrete,\n            )\n\n            if isinstance(self.bins, (str, Number)):\n                n_bins = len(bin_edges) - 1\n                bin_range = bin_edges.min(), bin_edges.max()\n                bin_kws = dict(bins=n_bins, range=bin_range)\n            else:\n                bin_kws = dict(bins=bin_edges)\n\n        else:\n\n            bin_edges = []\n            for i, x in enumerate([x1, x2]):\n\n                # Resolve out whether bin parameters are shared\n                # or specific to each variable\n\n                bins = self.bins\n                if not bins or isinstance(bins, (str, Number)):\n                    pass\n                elif isinstance(bins[i], str):\n                    bins = bins[i]\n                elif len(bins) == 2:\n                    bins = bins[i]\n\n                binwidth = self.binwidth\n                if binwidth is None:\n                    pass\n                elif not isinstance(binwidth, Number):\n                    binwidth = binwidth[i]\n\n                binrange = self.binrange\n                if binrange is None:\n                    pass\n                elif not isinstance(binrange[0], Number):\n                    binrange = binrange[i]\n\n                discrete = self.discrete\n                if not isinstance(discrete, bool):\n                    discrete = discrete[i]\n\n                # Define the bins for this variable\n\n                bin_edges.append(self._define_bin_edges(\n                    x, weights, bins, binwidth, binrange, discrete,\n                ))\n\n            bin_kws = dict(bins=tuple(bin_edges))\n\n        if cache:\n            self.bin_kws = bin_kws\n\n        return bin_kws\n\n    def _eval_bivariate(self, x1, x2, weights):\n        \"\"\"Inner function for histogram of two variables.\"\"\"\n        bin_kws = self.bin_kws\n        if bin_kws is None:\n            bin_kws = self.define_bin_params(x1, x2, cache=False)\n\n        density = self.stat == \"density\"\n\n        hist, *bin_edges = np.histogram2d(\n            x1, x2, **bin_kws, weights=weights, density=density\n        )\n\n        area = np.outer(\n            np.diff(bin_edges[0]),\n            np.diff(bin_edges[1]),\n        )\n\n        if self.stat == \"probability\" or self.stat == \"proportion\":\n            hist = hist.astype(float) / hist.sum()\n        elif self.stat == \"percent\":\n            hist = hist.astype(float) / hist.sum() * 100\n        elif self.stat == \"frequency\":\n            hist = hist.astype(float) / area\n\n        if self.cumulative:\n            if self.stat in [\"density\", \"frequency\"]:\n                hist = (hist * area).cumsum(axis=0).cumsum(axis=1)\n            else:\n                hist = hist.cumsum(axis=0).cumsum(axis=1)\n\n        return hist, bin_edges\n\n    def _eval_univariate(self, x, weights):\n        \"\"\"Inner function for histogram of one variable.\"\"\"\n        bin_kws = self.bin_kws\n        if bin_kws is None:\n            bin_kws = self.define_bin_params(x, weights=weights, cache=False)\n\n        density = self.stat == \"density\"\n        hist, bin_edges = np.histogram(\n            x, **bin_kws, weights=weights, density=density,\n        )\n\n        if self.stat == \"probability\" or self.stat == \"proportion\":\n            hist = hist.astype(float) / hist.sum()\n        elif self.stat == \"percent\":\n            hist = hist.astype(float) / hist.sum() * 100\n        elif self.stat == \"frequency\":\n            hist = hist.astype(float) / np.diff(bin_edges)\n\n        if self.cumulative:\n            if self.stat in [\"density\", \"frequency\"]:\n                hist = (hist * np.diff(bin_edges)).cumsum()\n            else:\n                hist = hist.cumsum()\n\n        return hist, bin_edges\n\n    def __call__(self, x1, x2=None, weights=None):\n        \"\"\"Count the occurrences in each bin, maybe normalize.\"\"\"\n        if x2 is None:\n            return self._eval_univariate(x1, weights)\n        else:\n            return self._eval_bivariate(x1, x2, weights)\n\n\nclass ECDF:\n    \"\"\"Univariate empirical cumulative distribution estimator.\"\"\"\n    def __init__(self, stat=\"proportion\", complementary=False):\n        \"\"\"Initialize the class with its parameters\n\n        Parameters\n        ----------\n        stat : {{\"proportion\", \"count\"}}\n            Distribution statistic to compute.\n        complementary : bool\n            If True, use the complementary CDF (1 - CDF)\n\n        \"\"\"\n        _check_argument(\"stat\", [\"count\", \"proportion\"], stat)\n        self.stat = stat\n        self.complementary = complementary\n\n    def _eval_bivariate(self, x1, x2, weights):\n        \"\"\"Inner function for ECDF of two variables.\"\"\"\n        raise NotImplementedError(\"Bivariate ECDF is not implemented\")\n\n    def _eval_univariate(self, x, weights):\n        \"\"\"Inner function for ECDF of one variable.\"\"\"\n        sorter = x.argsort()\n        x = x[sorter]\n        weights = weights[sorter]\n        y = weights.cumsum()\n\n        if self.stat == \"proportion\":\n            y = y / y.max()\n\n        x = np.r_[-np.inf, x]\n        y = np.r_[0, y]\n\n        if self.complementary:\n            y = y.max() - y\n\n        return y, x\n\n    def __call__(self, x1, x2=None, weights=None):\n        \"\"\"Return proportion or count of observations below each sorted datapoint.\"\"\"\n        x1 = np.asarray(x1)\n        if weights is None:\n            weights = np.ones_like(x1)\n        else:\n            weights = np.asarray(weights)\n\n        if x2 is None:\n            return self._eval_univariate(x1, weights)\n        else:\n            return self._eval_bivariate(x1, x2, weights)\n\n\nclass EstimateAggregator:\n\n    def __init__(self, estimator, errorbar=None, **boot_kws):\n        \"\"\"\n        Data aggregator that produces an estimate and error bar interval.\n\n        Parameters\n        ----------\n        estimator : callable or string\n            Function (or method name) that maps a vector to a scalar.\n        errorbar : string, (string, number) tuple, or callable\n            Name of errorbar method (either \"ci\", \"pi\", \"se\", or \"sd\"), or a tuple\n            with a method name and a level parameter, or a function that maps from a\n            vector to a (min, max) interval.\n        boot_kws\n            Additional keywords are passed to bootstrap when error_method is \"ci\".\n\n        \"\"\"\n        self.estimator = estimator\n\n        method, level = _validate_errorbar_arg(errorbar)\n        self.error_method = method\n        self.error_level = level\n\n        self.boot_kws = boot_kws\n\n    def __call__(self, data, var):\n        \"\"\"Aggregate over `var` column of `data` with estimate and error interval.\"\"\"\n        vals = data[var]\n        if callable(self.estimator):\n            # You would think we could pass to vals.agg, and yet:\n            # https://github.com/mwaskom/seaborn/issues/2943\n            estimate = self.estimator(vals)\n        else:\n            estimate = vals.agg(self.estimator)\n\n        # Options that produce no error bars\n        if self.error_method is None:\n            err_min = err_max = np.nan\n        elif len(data) <= 1:\n            err_min = err_max = np.nan\n\n        # Generic errorbars from user-supplied function\n        elif callable(self.error_method):\n            err_min, err_max = self.error_method(vals)\n\n        # Parametric options\n        elif self.error_method == \"sd\":\n            half_interval = vals.std() * self.error_level\n            err_min, err_max = estimate - half_interval, estimate + half_interval\n        elif self.error_method == \"se\":\n            half_interval = vals.sem() * self.error_level\n            err_min, err_max = estimate - half_interval, estimate + half_interval\n\n        # Nonparametric options\n        elif self.error_method == \"pi\":\n            err_min, err_max = _percentile_interval(vals, self.error_level)\n        elif self.error_method == \"ci\":\n            units = data.get(\"units\", None)\n            boots = bootstrap(vals, units=units, func=self.estimator, **self.boot_kws)\n            err_min, err_max = _percentile_interval(boots, self.error_level)\n\n        return pd.Series({var: estimate, f\"{var}min\": err_min, f\"{var}max\": err_max})\n\n\ndef _percentile_interval(data, width):\n    \"\"\"Return a percentile interval from data of a given width.\"\"\"\n    edge = (100 - width) / 2\n    percentiles = edge, 100 - edge\n    return np.nanpercentile(data, percentiles)\n\n\ndef _validate_errorbar_arg(arg):\n    \"\"\"Check type and value of errorbar argument and assign default level.\"\"\"\n    DEFAULT_LEVELS = {\n        \"ci\": 95,\n        \"pi\": 95,\n        \"se\": 1,\n        \"sd\": 1,\n    }\n\n    usage = \"`errorbar` must be a callable, string, or (string, number) tuple\"\n\n    if arg is None:\n        return None, None\n    elif callable(arg):\n        return arg, None\n    elif isinstance(arg, str):\n        method = arg\n        level = DEFAULT_LEVELS.get(method, None)\n    else:\n        try:\n            method, level = arg\n        except (ValueError, TypeError) as err:\n            raise err.__class__(usage) from err\n\n    _check_argument(\"errorbar\", list(DEFAULT_LEVELS), method)\n    if level is not None and not isinstance(level, Number):\n        raise TypeError(usage)\n\n    return method, level\n"},{"col":0,"comment":"","endLoc":26,"header":"_statistics.py#","id":3067,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Statistical transformations for visualization.\n\nThis module is currently private, but is being written to eventually form part\nof the public API.\n\nThe classes should behave roughly in the style of scikit-learn.\n\n- All data-independent parameters should be passed to the class constructor.\n- Each class should implement a default transformation that is exposed through\n  __call__. These are currently written for vector arguments, but I think\n  consuming a whole `plot_data` DataFrame and return it with transformed\n  variables would make more sense.\n- Some class have data-dependent preprocessing that should be cached and used\n  multiple times (think defining histogram bins off all data and then counting\n  observations within each bin multiple times per data subsets). These currently\n  have unique names, but it would be good to have a common name. Not quite\n  `fit`, but something similar.\n- Alternatively, the transform interface could take some information about grouping\n  variables and do a groupby internally.\n- Some classes should define alternate transforms that might make the most sense\n  with a different function. For example, KDE usually evaluates the distribution\n  on a regular grid, but it would be useful for it to transform at the actual\n  datapoints. Then again, this could be controlled by a parameter at  the time of\n  class instantiation.\n\n\"\"\"\n\ntry:\n    from scipy.stats import gaussian_kde\n    _no_scipy = False\nexcept ImportError:\n    from .external.kde import gaussian_kde\n    _no_scipy = True"},{"id":3068,"name":"v0.12.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"v0.12.0 (September 2022)\n------------------------\n\nIntroduction of the objects interface\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis release debuts the `seaborn.objects` interface, an entirely new approach to making plots with seaborn. It is the product of several years of design and 16 months of implementation work. The interface aims to provide a more declarative, composable, and extensible API for making statistical graphics. It is inspired by Wilkinson's grammar of graphics, offering a Pythonic API that is informed by the design of libraries such as `ggplot2` and `vega-lite` along with lessons from the past 10 years of seaborn's development.\n\nFor more information and numerous examples, see the :doc:`tutorial chapter ` and :ref:`API reference `\n\nThis initial release should be considered \"experimental\". While it is stable enough for serious use, there are definitely some rough edges, and some key features remain to be implemented. It is possible that breaking changes may occur over the next few minor releases. Please be patient with any limitations that you encounter and help the development by reporting issues when you find behavior surprising.\n\nKeyword-only arguments\n~~~~~~~~~~~~~~~~~~~~~~\n\n|API|\n\nSeaborn's plotting functions now require explicit keywords for most arguments, following the deprecation of positional arguments in v0.11.0. With this enforcement, most functions have also had their parameter lists rearranged so that `data` is the first and only positional argument. This adds consistency across the various functions in the library. It also means that calling `func(data)` will do something for nearly all functions (those that support wide-form data) and that :class:`pandas.DataFrame` can be piped directly into a plot. It is possible that the signatures will be loosened a bit in future releases so that `x` and `y` can be positional, but minimal support for positional arguments after this change will reduce the chance of inadvertent mis-specification (:pr:`2804`).\n\nModernization of categorical scatterplots\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis release begins the process of modernizing the :ref:`categorical plots `, beginning with :func:`stripplot` and :func:`swarmplot`. These functions are sporting some enhancements that alleviate a few long-running frustrations (:pr:`2413`, :pr:`2447`):\n\n- |Feature| The new `native_scale` parameter allows numeric or datetime categories to be plotted with their original scale rather than converted to strings and plotted at fixed intervals.\n\n- |Feature| The new `formatter` parameter allows more control over the string representation of values on the categorical axis. There should also be improved defaults for some types, such as dates.\n\n- |Enhancement| It is now possible to assign `hue` when using only one coordinate variable (i.e. only `x` or `y`).\n\n- |Enhancement| It is now possible to disable the legend.\n\nThe updates also harmonize behavior with functions that have been more recently introduced. This should be relatively non-disruptive, although a few defaults will change:\n\n- |Defaults| The functions now hook into matplotlib's unit system for plotting categorical data. (Seaborn's categorical functions actually predate support for categorical data in matplotlib.) This should mostly be transparent to the user, but it may resolve a few edge cases. For example, matplotlib interactivity should work better (e.g., for showing the data value under the cursor).\n\n- |Defaults| A color palette is no longer applied to levels of the categorical variable by default. It is now necessary to explicitly assign `hue` to see multiple colors (i.e., assign the same variable to `x`/`y` and `hue`). Passing `palette` without `hue` will continue to be honored for one release cycle.\n\n- |Defaults| Numeric `hue` variables now receive a continuous mapping by default, using the same rules as :func:`scatterplot`. Pass `palette=\"deep\"` to reproduce previous defaults.\n\n- |Defaults| The plots now follow the default property cycle; i.e. calling an axes-level function multiple times with the same active axes will produce different-colored artists.\n\n- |API| Currently, assigning `hue` and then passing a `color` will produce a gradient palette. This is now deprecated, as it is easy to request a gradient with, e.g. `palette=\"light:blue\"`.\n\nSimilar enhancements / updates should be expected to roll out to other categorical plotting functions in future releases. There are also several function-specific enhancements:\n\n- |Enhancement| In :func:`stripplot`, a \"strip\" with a single observation will be plotted without jitter (:pr:`2413`)\n\n- |Enhancement| In :func:`swarmplot`, the points are now swarmed at draw time, meaning that the plot will adapt to further changes in axis scaling or tweaks to the plot layout (:pr:`2443`).\n\n- |Feature| In :func:`swarmplot`, the proportion of points that must overlap before issuing a warning can now be controlled with the `warn_thresh` parameter (:pr:`2447`).\n\n- |Fix| In :func:`swarmplot`, the order of the points in each swarm now matches the order in the original dataset; previously they were sorted. This affects only the underlying data stored in the matplotlib artist, not the visual representation (:pr:`2443`).\n\nMore flexible errorbars\n~~~~~~~~~~~~~~~~~~~~~~~\n\n|API| |Feature|\n\nIncreased the flexibility of what can be shown by the internally-calculated errorbars for :func:`lineplot`, :func:`barplot`, and :func:`pointplot`.\n\nWith the new `errorbar` parameter, it is now possible to select bootstrap confidence intervals, percentile / predictive intervals, or intervals formed by scaled standard deviations or standard errors. The parameter also accepts an arbitrary function that maps from a vector to an interval. There is a new :doc:`user guide chapter ` demonstrating these options and explaining when you might want to use each one.\n\nAs a consequence of this change, the `ci` parameter has been deprecated. Note that :func:`regplot` retains the previous API, but it will likely be updated in a future release (:pr:`2407`, :pr:`2866`).\n\nOther updates\n~~~~~~~~~~~~~\n\n- |Feature| It is now possible to aggregate / sort a :func:`lineplot` along the y axis using `orient=\"y\"` (:pr:`2854`).\n\n- |Feature| Made it easier to customize :class:`FacetGrid` / :class:`PairGrid` / :class:`JointGrid` with a fluent (method-chained) style by adding `apply`/ `pipe` methods. Additionally, fixed the `tight_layout` and `refline` methods so that they return `self` (:pr:`2926`).\n\n- |Feature| Added :meth:`FacetGrid.tick_params` and :meth:`PairGrid.tick_params` to customize the appearance of the ticks, tick labels, and gridlines of all subplots at once (:pr:`2944`).\n\n- |Enhancement| Added a `width` parameter to :func:`barplot` (:pr:`2860`).\n\n- |Enhancement| It is now possible to specify `estimator` as a string in :func:`barplot` and :func:`pointplot`, in addition to a callable (:pr:`2866`).\n\n- |Enhancement| Error bars in :func:`regplot` now inherit the alpha value of the points they correspond to (:pr:`2540`).\n\n- |Enhancement| When using :func:`pairplot` with `corner=True` and `diag_kind=None`, the top left y axis label is no longer hidden (:pr:`2850`).\n\n- |Enhancement| It is now possible to plot a discrete :func:`histplot` as a step function or polygon (:pr:`2859`).\n\n- |Enhancement| It is now possible to customize the appearance of elements in a :func:`boxenplot` with `box_kws`/`line_kws`/`flier_kws` (:pr:`2909`).\n\n- |Fix| Improved integration with the matplotlib color cycle in most axes-level functions (:pr:`2449`).\n\n- |Fix| Fixed a regression in 0.11.2 that caused some functions to stall indefinitely or raise when the input data had a duplicate index (:pr:`2776`).\n\n- |Fix| Fixed a bug in :func:`histplot` and :func:`kdeplot` where weights were not factored into the normalization (:pr:`2812`).\n\n- |Fix| Fixed two edgecases in :func:`histplot` when only `binwidth` was provided (:pr:`2813`).\n\n- |Fix| Fixed a bug in :func:`violinplot` where inner boxes/points could be missing with unpaired split violins (:pr:`2814`).\n\n- |Fix| Fixed a bug in :class:`PairGrid` where an error would be raised when defining `hue` only in the mapping methods (:pr:`2847`).\n\n- |Fix| Fixed a bug in :func:`scatterplot` where an error would be raised when `hue_order` was a subset of the hue levels (:pr:`2848`).\n\n- |Fix| Fixed a bug in :func:`histplot` where dodged bars would have different widths on a log scale (:pr:`2849`).\n\n- |Fix| In :func:`lineplot`, allowed the `dashes` keyword to set the style of a line without mapping a `style` variable (:pr:`2449`).\n\n- |Fix| Improved support in :func:`relplot` for \"wide\" data and for faceting variables passed as non-pandas objects (:pr:`2846`).\n\n- |Fix| Subplot titles will no longer be reset when calling :meth:`FacetGrid.map` or :meth:`FacetGrid.map_dataframe` (:pr:`2705`).\n\n- |Fix| Added a workaround for a matplotlib issue that caused figure-level functions to freeze when `plt.show` was called (:pr:`2925`).\n\n- |Fix| Improved robustness to numerical errors in :func:`kdeplot` (:pr:`2862`).\n\n- |Fix| Fixed a bug where :func:`rugplot` was ignoring expand_margins=False (:pr:`2953`).\n\n- |Defaults| The `patch.facecolor` rc param is no longer set by :func:`set_palette` (or :func:`set_theme`). This should have no general effect, because the matplotlib default is now `\"C0\"` (:pr:`2906`).\n\n- |Build| Made `scipy` an optional dependency and added `pip install seaborn[stats]` as a method for ensuring the availability of compatible `scipy` and `statsmodels` libraries at install time. This has a few minor implications for existing code, which are explained in the Github pull request (:pr:`2398`).\n\n- |Build| Example datasets are now stored in an OS-specific cache location (as determined by `appdirs`) rather than in the user's home directory. Users should feel free to remove `~/seaborn-data` if desired (:pr:`2773`).\n\n- |Build| The unit test suite is no longer part of the source or wheel distribution. Seaborn has never had a runtime API for exercising the tests, so this should not have workflow implications (:pr:`2833`).\n\n- |Build| Following `NEP29 `_, dropped support for Python 3.6 and bumped the minimally-supported versions of the library dependencies.\n\n- |API| Removed the previously-deprecated `factorplot` along with several previously-deprecated utility functions (`iqr`, `percentiles`, `pmf_hist`, and `sort_df`).\n\n- |API| Removed the (previously-unused) option to pass additional keyword arguments to :func:`pointplot`.\n"},{"id":3069,"name":"objects.Plot.layout.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn.objects as so\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"406f8f8d-b590-46f4-a230-626e32e52c71\",\n   \"metadata\": {},\n   \"source\": [\n    \"Control the overall dimensions of the figure with `size`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"fefc2b45-3510-4cd7-9de9-4806d71fc4c1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = so.Plot().layout(size=(4, 4))\\n\",\n    \"p\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"909a47bb-82f5-455a-99c3-7049d548561b\",\n   \"metadata\": {},\n   \"source\": [\n    \"Subplots created by using :meth:`Plot.facet` or :meth:`Plot.pair` will shrink to fit in the available space:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3163687c-8d48-4e88-8dc2-35e16341e30e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet([\\\"A\\\", \\\"B\\\"], [\\\"X\\\", \\\"Y\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"feda7c3a-3862-48d4-bb18-419cd03fc081\",\n   \"metadata\": {},\n   \"source\": [\n    \"You may find that different automatic layout engines give better or worse results with specific plots:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c2107939-c6a9-414c-b3a2-6f5d0dd60daf\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet([\\\"A\\\", \\\"B\\\"], [\\\"X\\\", \\\"Y\\\"]).layout(engine=\\\"constrained\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"781ff58c-b805-4e93-8cae-be0442e273ea\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":3070,"name":"heatmap.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"987b9549-532e-4091-a6cf-007d1b23e825\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"2c78ca60-e232-44f6-956b-b86b472b1c28\",\n   \"metadata\": {},\n   \"source\": [\n    \"Pass a :class:`DataFrame` to plot with indices as row/column labels:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"fad17798-c2e3-4334-abf0-0d46153971fa\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"glue = sns.load_dataset(\\\"glue\\\").pivot(\\\"Model\\\", \\\"Task\\\", \\\"Score\\\")\\n\",\n    \"sns.heatmap(glue)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"f3255c5f-2477-4d13-b4c2-7e56380e9cc2\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use `annot` to represent the cell values with text:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3c9f3c73-c8bc-426e-bc67-dec8f807082e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, annot=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"bc412da8-866a-49b7-8496-01fbf06dd908\",\n   \"metadata\": {},\n   \"source\": [\n    \"Control the annotations with a formatting string:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ac952d0d-9187-4dff-a560-88430076851a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, annot=True, fmt=\\\".1f\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"5eb12725-e9ee-4df0-9708-243d7e0a77b5\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use a separate dataframe for the annotations:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1189a37f-9f74-455a-a09a-c22e056d8ba7\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, annot=glue.rank(axis=\\\"columns\\\"))\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"253dfb7f-aa12-4716-adc2-3a38b003b2c3\",\n   \"metadata\": {},\n   \"source\": [\n    \"Add lines between cells:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"5cac673e-9b86-490b-9e67-ec0cf865bede\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, annot=True, linewidth=.5)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"b7d3659c-f996-4af3-a612-430d97799c72\",\n   \"metadata\": {},\n   \"source\": [\n    \"Select a different colormap by name:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"86806d72-e784-430e-8320-48f2c91115bb\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, cmap=\\\"crest\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"8336fd53-3841-458f-b26c-411efff54d45\",\n   \"metadata\": {},\n   \"source\": [\n    \"Or pass a colormap object:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9944ff33-991f-4138-a951-e3015c0326f1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, cmap=sns.cubehelix_palette(as_cmap=True))\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"52cc4dba-b86a-4da8-9cbd-3f8aa06b43b4\",\n   \"metadata\": {},\n   \"source\": [\n    \"Set the colormap norm (data values corresponding to minimum and maximum points):\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b4ddb41e-c075-41a5-8afe-422ad6d105bf\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.heatmap(glue, vmin=50, vmax=100)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"6e828517-a532-49b1-be11-eda47c50cc37\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use methods on the :class:`matplotlib.axes.Axes` object to tweak the plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1aab26fc-2de4-4d4f-ad08-487809573deb\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"ax = sns.heatmap(glue, annot=True)\\n\",\n    \"ax.set(xlabel=\\\"\\\", ylabel=\\\"\\\")\\n\",\n    \"ax.xaxis.tick_top()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1d8e738c-388a-453a-b9c7-4c71a674b69c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"className":"DistributionFixtures","col":0,"comment":"null","endLoc":34,"id":3071,"nodeType":"Class","startLoc":22,"text":"class DistributionFixtures:\n\n    @pytest.fixture\n    def x(self, rng):\n        return rng.normal(0, 1, 100)\n\n    @pytest.fixture\n    def y(self, rng):\n        return rng.normal(0, 5, 100)\n\n    @pytest.fixture\n    def weights(self, rng):\n        return rng.uniform(0, 5, 100)"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":3072,"name":"g","nodeType":"Attribute","startLoc":14,"text":"g"},{"col":4,"comment":"null","endLoc":26,"header":"@pytest.fixture\n    def x(self, rng)","id":3073,"name":"x","nodeType":"Function","startLoc":24,"text":"@pytest.fixture\n    def x(self, rng):\n        return rng.normal(0, 1, 100)"},{"id":3074,"name":"lmplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"034a9a5b-91ff-4ccc-932d-0f314e2cd6d2\",\n   \"metadata\": {},\n   \"source\": [\n    \"See the :func:`regplot` docs for demonstrations of various options for specifying the regression model, which are also accepted here.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"76c91243-3bd8-49a1-b8c8-b7272f09a3f1\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme(style=\\\"ticks\\\")\\n\",\n    \"penguins = sns.load_dataset(\\\"penguins\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"0ba9f55d-17ea-4084-a74f-852d51771380\",\n   \"metadata\": {},\n   \"source\": [\n    \"Plot a regression fit over a scatter plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"2f789265-93c0-4867-b666-798713e4e7e5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lmplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"7e4b0ad4-446c-4109-9393-961f76132e34\",\n   \"metadata\": {},\n   \"source\": [\n    \"Condition the regression fit on another variable and represent it using color:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"61347189-34e5-42ea-b77b-4acdef843326\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lmplot(data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"c9b6d059-49dc-46a7-869b-86baa3a7ed65\",\n   \"metadata\": {},\n   \"source\": [\n    \"Condition the regression fit on another variable and split across subplots:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d8ec2955-ccc9-493c-b9ec-c78648ce9f53\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lmplot(\\n\",\n    \"    data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n    \"    hue=\\\"species\\\", col=\\\"sex\\\", height=4,\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"de01dee1-b2ce-445c-8d0d-d054ca0dfedb\",\n   \"metadata\": {},\n   \"source\": [\n    \"Condition across two variables using both columns and rows:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6f1264aa-829c-416a-805a-b989e5f11a17\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lmplot(\\n\",\n    \"    data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n    \"    col=\\\"species\\\", row=\\\"sex\\\", height=3,\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"b3888f04-b22f-4205-8acc-24ce5b59568e\",\n   \"metadata\": {},\n   \"source\": [\n    \"Allow axis limits to vary across subplots:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"67ed5af1-d228-4b81-b4f8-21937c513a10\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lmplot(\\n\",\n    \"    data=penguins, x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\",\\n\",\n    \"    col=\\\"species\\\", row=\\\"sex\\\", height=3,\\n\",\n    \"    facet_kws=dict(sharex=False, sharey=False),\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"46e9cf18-c847-4c40-8e38-6c20cdde2be5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":3075,"name":"v0.12.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.12.1 (Unreleased)\n--------------------\n\n- |Feature| Added the :class:`objects.Text` mark (:pr:`3051`).\n\n- |Feature| Added the :class:`objects.Perc` stat (:pr:`3063`).\n\n- |Feature| The :class:`Band` and :class:`Range` marks will now cover the full extent of the data if `min` / `max` variables are not explicitly assigned or added in a transform (:pr:`3056`).\n\n- |Enhancement| The :class:`Jitter` move now applies a small amount of jitter by default (:pr:`3066`).\n\n- |Enhancement| Marks that sort along the orient axis (e.g. :class:`Line`) now use a stable algorithm (:pr:`3064`).\n\n- |Fix| Make :class:`objects.PolyFit` robust to missing data (:pr:`3010`).\n\n- |Fix| Fixed a bug that caused an exception when more than two layers with the same mappings were added (:pr:`3055`).\n\n- |Fix| Fixed a regression in :func:`kdeplot` where passing `cmap` for an unfilled bivariate plot would raise an exception (:pr:`3065`).\n\n- |Build| Seaborn no longer contains doctest-style examples, simplifying the testing infrastructure (:pr:`3034`).\n"},{"id":3076,"name":"v0.8.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.8.1 (September 2017)\n-----------------------\n\n- Added a warning in :class:`FacetGrid` when passing a categorical plot function without specifying ``order`` (or ``hue_order`` when ``hue`` is used), which is likely to produce a plot that is incorrect.\n\n- Improved compatibility between :class:`FacetGrid` or :class:`PairGrid` and interactive matplotlib backends so that the legend no longer remains inside the figure when using ``legend_out=True``.\n\n- Changed categorical plot functions with small plot elements to use :func:`dark_palette` instead of :func:`light_palette` when generating a sequential palette from a specified color.\n\n- Improved robustness of :func:`kdeplot` and :func:`distplot` to data with fewer than two observations.\n\n- Fixed a bug in :func:`clustermap` when using ``yticklabels=False``.\n\n- Fixed a bug in :func:`pointplot` where colors were wrong if exactly three points were being drawn.\n\n- Fixed a bug in :func:`pointplot` where legend entries for missing data appeared with empty markers.\n\n- Fixed a bug in :func:`clustermap` where an error was raised when annotating the main heatmap and showing category colors.\n\n- Fixed a bug in :func:`clustermap` where row labels were not being properly rotated when they overlapped.\n\n- Fixed a bug in :func:`kdeplot` where the maximum limit on the density axes was not being updated when multiple densities were drawn.\n\n- Improved compatibility with future versions of pandas.\n"},{"id":3077,"name":"v0.3.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.3.1 (April 2014)\n-------------------\n\nThis is a minor release from 0.3 with fixes for several bugs.\n\nPlotting functions\n~~~~~~~~~~~~~~~~~~\n\n- The size of the points in :func:`pointplot` and ``factorplot`` are now scaled with the linewidth for better aesthetics across different plotting contexts.\n\n- The :func:`pointplot` glyphs for different levels of the hue variable are drawn at different z-orders so that they appear uniform.\n\nBug Fixes\n~~~~~~~~~\n\n- Fixed a bug in :class:`FacetGrid` (and thus affecting lmplot and factorplot) that appeared when ``col_wrap`` was used with a number of facets that did not evenly divide into the column width.\n\n- Fixed an issue where the support for kernel density estimates was sometimes computed incorrectly.\n\n- Fixed a problem where ``hue`` variable levels that were not strings were missing in :class:`FacetGrid` legends.\n\n- When passing a color palette list in a ``with`` statement, the entire palette is now used instead of the first six colors.\n"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":114,"id":3078,"name":"CmpKey","nodeType":"Attribute","startLoc":114,"text":"CmpKey"},{"attributeType":"null","col":4,"comment":"null","endLoc":22,"id":3079,"name":"year","nodeType":"Attribute","startLoc":22,"text":"year"},{"attributeType":"null","col":10,"comment":"null","endLoc":22,"id":3080,"name":"ax","nodeType":"Attribute","startLoc":22,"text":"ax"},{"col":0,"comment":"","endLoc":7,"header":"timeseries_facets.py#","id":3081,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nSmall multiple time series\n--------------------------\n\n_thumb: .42, .58\n\n\"\"\"\n\nsns.set_theme(style=\"dark\")\n\nflights = sns.load_dataset(\"flights\")\n\ng = sns.relplot(\n    data=flights,\n    x=\"month\", y=\"passengers\", col=\"year\", hue=\"year\",\n    kind=\"line\", palette=\"crest\", linewidth=4, zorder=5,\n    col_wrap=3, height=2, aspect=1.5, legend=False,\n)\n\nfor year, ax in g.axes_dict.items():\n\n    # Add the title as an annotation within the plot\n    ax.text(.8, .85, year, transform=ax.transAxes, fontweight=\"bold\")\n\n    # Plot every year's time series in the background\n    sns.lineplot(\n        data=flights, x=\"month\", y=\"passengers\", units=\"year\",\n        estimator=None, color=\".7\", linewidth=1, ax=ax,\n    )\n\nax.set_xticks(ax.get_xticks()[::2])\n\ng.set_titles(\"\")\n\ng.set_axis_labels(\"\", \"Passengers\")\n\ng.tight_layout()"},{"col":4,"comment":"null","endLoc":30,"header":"@pytest.fixture\n    def y(self, rng)","id":3082,"name":"y","nodeType":"Function","startLoc":28,"text":"@pytest.fixture\n    def y(self, rng):\n        return rng.normal(0, 5, 100)"},{"col":4,"comment":"null","endLoc":34,"header":"@pytest.fixture\n    def weights(self, rng)","id":3083,"name":"weights","nodeType":"Function","startLoc":32,"text":"@pytest.fixture\n    def weights(self, rng):\n        return rng.uniform(0, 5, 100)"},{"className":"TestKDE","col":0,"comment":"null","endLoc":159,"id":3084,"nodeType":"Class","startLoc":37,"text":"class TestKDE:\n\n    def integrate(self, y, x):\n        y = np.asarray(y)\n        x = np.asarray(x)\n        dx = np.diff(x)\n        return (dx * y[:-1] + dx * y[1:]).sum() / 2\n\n    def test_gridsize(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n\n        n = 200\n        kde = KDE(gridsize=n)\n        density, support = kde(x)\n        assert density.size == n\n        assert support.size == n\n\n    def test_cut(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n\n        kde = KDE(cut=0)\n        _, support = kde(x)\n        assert support.min() == x.min()\n        assert support.max() == x.max()\n\n        cut = 2\n        bw_scale = .5\n        bw = x.std() * bw_scale\n        kde = KDE(cut=cut, bw_method=bw_scale, gridsize=1000)\n        _, support = kde(x)\n        assert support.min() == pytest.approx(x.min() - bw * cut, abs=1e-2)\n        assert support.max() == pytest.approx(x.max() + bw * cut, abs=1e-2)\n\n    def test_clip(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        clip = -1, 1\n        kde = KDE(clip=clip)\n        _, support = kde(x)\n\n        assert support.min() >= clip[0]\n        assert support.max() <= clip[1]\n\n    def test_density_normalization(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n        kde = KDE()\n        density, support = kde(x)\n        assert self.integrate(density, support) == pytest.approx(1, abs=1e-5)\n\n    @pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_cumulative(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n        kde = KDE(cumulative=True)\n        density, _ = kde(x)\n        assert density[0] == pytest.approx(0, abs=1e-5)\n        assert density[-1] == pytest.approx(1, abs=1e-5)\n\n    def test_cached_support(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde = KDE()\n        kde.define_support(x)\n        _, support = kde(x[(x > -1) & (x < 1)])\n        assert_array_equal(support, kde.support)\n\n    def test_bw_method(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde1 = KDE(bw_method=.2)\n        kde2 = KDE(bw_method=2)\n\n        d1, _ = kde1(x)\n        d2, _ = kde2(x)\n\n        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()\n\n    def test_bw_adjust(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde1 = KDE(bw_adjust=.2)\n        kde2 = KDE(bw_adjust=2)\n\n        d1, _ = kde1(x)\n        d2, _ = kde2(x)\n\n        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()\n\n    def test_bivariate_grid(self, rng):\n\n        n = 100\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=n)\n        density, (xx, yy) = kde(x, y)\n\n        assert density.shape == (n, n)\n        assert xx.size == n\n        assert yy.size == n\n\n    def test_bivariate_normalization(self, rng):\n\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=100)\n        density, (xx, yy) = kde(x, y)\n\n        dx = xx[1] - xx[0]\n        dy = yy[1] - yy[0]\n\n        total = density.sum() * (dx * dy)\n        assert total == pytest.approx(1, abs=1e-2)\n\n    @pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_bivariate_cumulative(self, rng):\n\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=100, cumulative=True)\n        density, _ = kde(x, y)\n\n        assert density[0, 0] == pytest.approx(0, abs=1e-2)\n        assert density[-1, -1] == pytest.approx(1, abs=1e-2)"},{"col":4,"comment":"null","endLoc":43,"header":"def integrate(self, y, x)","id":3085,"name":"integrate","nodeType":"Function","startLoc":39,"text":"def integrate(self, y, x):\n        y = np.asarray(y)\n        x = np.asarray(x)\n        dx = np.diff(x)\n        return (dx * y[:-1] + dx * y[1:]).sum() / 2"},{"attributeType":"tuple","col":0,"comment":"null","endLoc":117,"id":3086,"name":"LegacyCmpKey","nodeType":"Attribute","startLoc":117,"text":"LegacyCmpKey"},{"attributeType":"null","col":0,"comment":"null","endLoc":118,"id":3087,"name":"VersionComparisonMethod","nodeType":"Attribute","startLoc":118,"text":"VersionComparisonMethod"},{"attributeType":"_Version","col":0,"comment":"null","endLoc":122,"id":3088,"name":"_Version","nodeType":"Attribute","startLoc":122,"text":"_Version"},{"col":4,"comment":"Take a drawn matplotlib boxplot and make it look nice.","endLoc":884,"header":"def restyle_boxplot(self, artist_dict, color, props)","id":3089,"name":"restyle_boxplot","nodeType":"Function","startLoc":858,"text":"def restyle_boxplot(self, artist_dict, color, props):\n        \"\"\"Take a drawn matplotlib boxplot and make it look nice.\"\"\"\n        for box in artist_dict[\"boxes\"]:\n            box.update(dict(facecolor=color,\n                            zorder=.9,\n                            edgecolor=self.gray,\n                            linewidth=self.linewidth))\n            box.update(props[\"box\"])\n        for whisk in artist_dict[\"whiskers\"]:\n            whisk.update(dict(color=self.gray,\n                              linewidth=self.linewidth,\n                              linestyle=\"-\"))\n            whisk.update(props[\"whisker\"])\n        for cap in artist_dict[\"caps\"]:\n            cap.update(dict(color=self.gray,\n                            linewidth=self.linewidth))\n            cap.update(props[\"cap\"])\n        for med in artist_dict[\"medians\"]:\n            med.update(dict(color=self.gray,\n                            linewidth=self.linewidth))\n            med.update(props[\"median\"])\n        for fly in artist_dict[\"fliers\"]:\n            fly.update(dict(markerfacecolor=self.gray,\n                            marker=\"d\",\n                            markeredgecolor=self.gray,\n                            markersize=self.fliersize))\n            fly.update(props[\"flier\"])"},{"attributeType":"str","col":0,"comment":"null","endLoc":182,"id":3090,"name":"VERSION_PATTERN","nodeType":"Attribute","startLoc":182,"text":"VERSION_PATTERN"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":386,"id":3091,"name":"_local_version_separators","nodeType":"Attribute","startLoc":386,"text":"_local_version_separators"},{"col":0,"comment":"","endLoc":16,"header":"version.py#","id":3092,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Extract reference documentation from the pypa/packaging source tree.\n\nIn the process of copying, some unused methods / classes were removed.\nThese include:\n\n- parse()\n- anything involving LegacyVersion\n\nThis software is made available under the terms of *either* of the licenses\nfound in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made\nunder the terms of *both* these licenses.\n\nVendored from:\n- https://github.com/pypa/packaging/\n- commit ba07d8287b4554754ac7178d177033ea3f75d489 (09/09/2021)\n\"\"\"\n\n__all__ = [\"Version\", \"InvalidVersion\", \"VERSION_PATTERN\"]\n\nInfinity = InfinityType()\n\nNegativeInfinity = NegativeInfinityType()\n\nInfiniteTypes = Union[InfinityType, NegativeInfinityType]\n\nPrePostDevType = Union[InfiniteTypes, Tuple[str, int]]\n\nSubLocalType = Union[InfiniteTypes, int, str]\n\nLocalType = Union[\n    NegativeInfinityType,\n    Tuple[\n        Union[\n            SubLocalType,\n            Tuple[SubLocalType, str],\n            Tuple[NegativeInfinityType, SubLocalType],\n        ],\n        ...,\n    ],\n]\n\nCmpKey = Tuple[\n    int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType\n]\n\nLegacyCmpKey = Tuple[int, Tuple[str, ...]]\n\nVersionComparisonMethod = Callable[\n    [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool\n]\n\n_Version = collections.namedtuple(\n    \"_Version\", [\"epoch\", \"release\", \"dev\", \"pre\", \"post\", \"local\"]\n)\n\nVERSION_PATTERN = r\"\"\"\n    v?\n    (?:\n        (?:(?P[0-9]+)!)?                           # epoch\n        (?P[0-9]+(?:\\.[0-9]+)*)                  # release segment\n        (?P
                                          # pre-release\n            [-_\\.]?\n            (?P(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P[0-9]+)?\n        )?\n        (?P                                         # post release\n            (?:-(?P[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?Ppost|rev|r)\n                [-_\\.]?\n                (?P[0-9]+)?\n            )\n        )?\n        (?P                                          # dev release\n            [-_\\.]?\n            (?Pdev)\n            [-_\\.]?\n            (?P[0-9]+)?\n        )?\n    )\n    (?:\\+(?P[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n\"\"\"\n\n_local_version_separators = re.compile(r\"[\\._-]\")"},{"col":0,"comment":"null","endLoc":47,"header":"def namedtuple(\n    typename: str,\n    field_names: str | Iterable[str],\n    *,\n    rename: bool = False,\n    module: str | None = None,\n    defaults: Iterable[Any] | None = None,\n) -> type[tuple[Any, ...]]","id":3093,"name":"namedtuple","nodeType":"Function","startLoc":40,"text":"def namedtuple(\n    typename: str,\n    field_names: str | Iterable[str],\n    *,\n    rename: bool = False,\n    module: str | None = None,\n    defaults: Iterable[Any] | None = None,\n) -> type[tuple[Any, ...]]: ..."},{"fileName":"_testing.py","filePath":"seaborn","id":3094,"nodeType":"File","text":"import numpy as np\nimport matplotlib as mpl\nfrom matplotlib.colors import to_rgb, to_rgba\nfrom numpy.testing import assert_array_equal\n\n\nUSE_PROPS = [\n    \"alpha\",\n    \"edgecolor\",\n    \"facecolor\",\n    \"fill\",\n    \"hatch\",\n    \"height\",\n    \"linestyle\",\n    \"linewidth\",\n    \"paths\",\n    \"xy\",\n    \"xydata\",\n    \"sizes\",\n    \"zorder\",\n]\n\n\ndef assert_artists_equal(list1, list2):\n\n    assert len(list1) == len(list2)\n    for a1, a2 in zip(list1, list2):\n        assert a1.__class__ == a2.__class__\n        prop1 = a1.properties()\n        prop2 = a2.properties()\n        for key in USE_PROPS:\n            if key not in prop1:\n                continue\n            v1 = prop1[key]\n            v2 = prop2[key]\n            if key == \"paths\":\n                for p1, p2 in zip(v1, v2):\n                    assert_array_equal(p1.vertices, p2.vertices)\n                    assert_array_equal(p1.codes, p2.codes)\n            elif key == \"color\":\n                v1 = mpl.colors.to_rgba(v1)\n                v2 = mpl.colors.to_rgba(v2)\n                assert v1 == v2\n            elif isinstance(v1, np.ndarray):\n                assert_array_equal(v1, v2)\n            else:\n                assert v1 == v2\n\n\ndef assert_legends_equal(leg1, leg2):\n\n    assert leg1.get_title().get_text() == leg2.get_title().get_text()\n    for t1, t2 in zip(leg1.get_texts(), leg2.get_texts()):\n        assert t1.get_text() == t2.get_text()\n\n    assert_artists_equal(\n        leg1.get_patches(), leg2.get_patches(),\n    )\n    assert_artists_equal(\n        leg1.get_lines(), leg2.get_lines(),\n    )\n\n\ndef assert_plots_equal(ax1, ax2, labels=True):\n\n    assert_artists_equal(ax1.patches, ax2.patches)\n    assert_artists_equal(ax1.lines, ax2.lines)\n    assert_artists_equal(ax1.collections, ax2.collections)\n\n    if labels:\n        assert ax1.get_xlabel() == ax2.get_xlabel()\n        assert ax1.get_ylabel() == ax2.get_ylabel()\n\n\ndef assert_colors_equal(a, b, check_alpha=True):\n\n    def handle_array(x):\n\n        if isinstance(x, np.ndarray):\n            if x.ndim > 1:\n                x = np.unique(x, axis=0).squeeze()\n            if x.ndim > 1:\n                raise ValueError(\"Color arrays must be 1 dimensional\")\n        return x\n\n    a = handle_array(a)\n    b = handle_array(b)\n\n    f = to_rgba if check_alpha else to_rgb\n    assert f(a) == f(b)\n"},{"col":4,"comment":"null","endLoc":53,"header":"def test_gridsize(self, rng)","id":3095,"name":"test_gridsize","nodeType":"Function","startLoc":45,"text":"def test_gridsize(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n\n        n = 200\n        kde = KDE(gridsize=n)\n        density, support = kde(x)\n        assert density.size == n\n        assert support.size == n"},{"attributeType":"list","col":0,"comment":"null","endLoc":7,"id":3096,"name":"USE_PROPS","nodeType":"Attribute","startLoc":7,"text":"USE_PROPS"},{"col":0,"comment":"","endLoc":1,"header":"_testing.py#","id":3097,"name":"","nodeType":"Function","startLoc":1,"text":"USE_PROPS = [\n    \"alpha\",\n    \"edgecolor\",\n    \"facecolor\",\n    \"fill\",\n    \"hatch\",\n    \"height\",\n    \"linestyle\",\n    \"linewidth\",\n    \"paths\",\n    \"xy\",\n    \"xydata\",\n    \"sizes\",\n    \"zorder\",\n]"},{"fileName":"_docstrings.py","filePath":"seaborn","id":3098,"nodeType":"File","text":"import re\nimport pydoc\nfrom .external.docscrape import NumpyDocString\n\n\nclass DocstringComponents:\n\n    regexp = re.compile(r\"\\n((\\n|.)+)\\n\\s*\", re.MULTILINE)\n\n    def __init__(self, comp_dict, strip_whitespace=True):\n        \"\"\"Read entries from a dict, optionally stripping outer whitespace.\"\"\"\n        if strip_whitespace:\n            entries = {}\n            for key, val in comp_dict.items():\n                m = re.match(self.regexp, val)\n                if m is None:\n                    entries[key] = val\n                else:\n                    entries[key] = m.group(1)\n        else:\n            entries = comp_dict.copy()\n\n        self.entries = entries\n\n    def __getattr__(self, attr):\n        \"\"\"Provide dot access to entries for clean raw docstrings.\"\"\"\n        if attr in self.entries:\n            return self.entries[attr]\n        else:\n            try:\n                return self.__getattribute__(attr)\n            except AttributeError as err:\n                # If Python is run with -OO, it will strip docstrings and our lookup\n                # from self.entries will fail. We check for __debug__, which is actually\n                # set to False by -O (it is True for normal execution).\n                # But we only want to see an error when building the docs;\n                # not something users should see, so this slight inconsistency is fine.\n                if __debug__:\n                    raise err\n                else:\n                    pass\n\n    @classmethod\n    def from_nested_components(cls, **kwargs):\n        \"\"\"Add multiple sub-sets of components.\"\"\"\n        return cls(kwargs, strip_whitespace=False)\n\n    @classmethod\n    def from_function_params(cls, func):\n        \"\"\"Use the numpydoc parser to extract components from existing func.\"\"\"\n        params = NumpyDocString(pydoc.getdoc(func))[\"Parameters\"]\n        comp_dict = {}\n        for p in params:\n            name = p.name\n            type = p.type\n            desc = \"\\n    \".join(p.desc)\n            comp_dict[name] = f\"{name} : {type}\\n    {desc}\"\n\n        return cls(comp_dict)\n\n\n# TODO is \"vector\" the best term here? We mean to imply 1D data with a variety\n# of types?\n\n# TODO now that we can parse numpydoc style strings, do we need to define dicts\n# of docstring components, or just write out a docstring?\n\n\n_core_params = dict(\n    data=\"\"\"\ndata : :class:`pandas.DataFrame`, :class:`numpy.ndarray`, mapping, or sequence\n    Input data structure. Either a long-form collection of vectors that can be\n    assigned to named variables or a wide-form dataset that will be internally\n    reshaped.\n    \"\"\",  # TODO add link to user guide narrative when exists\n    xy=\"\"\"\nx, y : vectors or keys in ``data``\n    Variables that specify positions on the x and y axes.\n    \"\"\",\n    hue=\"\"\"\nhue : vector or key in ``data``\n    Semantic variable that is mapped to determine the color of plot elements.\n    \"\"\",\n    palette=\"\"\"\npalette : string, list, dict, or :class:`matplotlib.colors.Colormap`\n    Method for choosing the colors to use when mapping the ``hue`` semantic.\n    String values are passed to :func:`color_palette`. List or dict values\n    imply categorical mapping, while a colormap object implies numeric mapping.\n    \"\"\",  # noqa: E501\n    hue_order=\"\"\"\nhue_order : vector of strings\n    Specify the order of processing and plotting for categorical levels of the\n    ``hue`` semantic.\n    \"\"\",\n    hue_norm=\"\"\"\nhue_norm : tuple or :class:`matplotlib.colors.Normalize`\n    Either a pair of values that set the normalization range in data units\n    or an object that will map from data units into a [0, 1] interval. Usage\n    implies numeric mapping.\n    \"\"\",\n    color=\"\"\"\ncolor : :mod:`matplotlib color `\n    Single color specification for when hue mapping is not used. Otherwise, the\n    plot will try to hook into the matplotlib property cycle.\n    \"\"\",\n    ax=\"\"\"\nax : :class:`matplotlib.axes.Axes`\n    Pre-existing axes for the plot. Otherwise, call :func:`matplotlib.pyplot.gca`\n    internally.\n    \"\"\",  # noqa: E501\n)\n\n\n_core_returns = dict(\n    ax=\"\"\"\n:class:`matplotlib.axes.Axes`\n    The matplotlib axes containing the plot.\n    \"\"\",\n    facetgrid=\"\"\"\n:class:`FacetGrid`\n    An object managing one or more subplots that correspond to conditional data\n    subsets with convenient methods for batch-setting of axes attributes.\n    \"\"\",\n    jointgrid=\"\"\"\n:class:`JointGrid`\n    An object managing multiple subplots that correspond to joint and marginal axes\n    for plotting a bivariate relationship or distribution.\n    \"\"\",\n    pairgrid=\"\"\"\n:class:`PairGrid`\n    An object managing multiple subplots that correspond to joint and marginal axes\n    for pairwise combinations of multiple variables in a dataset.\n    \"\"\",\n)\n\n\n_seealso_blurbs = dict(\n\n    # Relational plots\n    scatterplot=\"\"\"\nscatterplot : Plot data using points.\n    \"\"\",\n    lineplot=\"\"\"\nlineplot : Plot data using lines.\n    \"\"\",\n\n    # Distribution plots\n    displot=\"\"\"\ndisplot : Figure-level interface to distribution plot functions.\n    \"\"\",\n    histplot=\"\"\"\nhistplot : Plot a histogram of binned counts with optional normalization or smoothing.\n    \"\"\",\n    kdeplot=\"\"\"\nkdeplot : Plot univariate or bivariate distributions using kernel density estimation.\n    \"\"\",\n    ecdfplot=\"\"\"\necdfplot : Plot empirical cumulative distribution functions.\n    \"\"\",\n    rugplot=\"\"\"\nrugplot : Plot a tick at each observation value along the x and/or y axes.\n    \"\"\",\n\n    # Categorical plots\n    stripplot=\"\"\"\nstripplot : Plot a categorical scatter with jitter.\n    \"\"\",\n    swarmplot=\"\"\"\nswarmplot : Plot a categorical scatter with non-overlapping points.\n    \"\"\",\n    violinplot=\"\"\"\nviolinplot : Draw an enhanced boxplot using kernel density estimation.\n    \"\"\",\n    pointplot=\"\"\"\npointplot : Plot point estimates and CIs using markers and lines.\n    \"\"\",\n\n    # Multiples\n    jointplot=\"\"\"\njointplot : Draw a bivariate plot with univariate marginal distributions.\n    \"\"\",\n    pairplot=\"\"\"\njointplot : Draw multiple bivariate plots with univariate marginal distributions.\n    \"\"\",\n    jointgrid=\"\"\"\nJointGrid : Set up a figure with joint and marginal views on bivariate data.\n    \"\"\",\n    pairgrid=\"\"\"\nPairGrid : Set up a figure with joint and marginal views on multiple variables.\n    \"\"\",\n)\n\n\n_core_docs = dict(\n    params=DocstringComponents(_core_params),\n    returns=DocstringComponents(_core_returns),\n    seealso=DocstringComponents(_seealso_blurbs),\n)\n"},{"className":"NumpyDocString","col":0,"comment":"Parses a numpydoc string to an abstract representation\n\n    Instances define a mapping from section title to structured data.\n\n    ","endLoc":561,"id":3099,"nodeType":"Class","startLoc":136,"text":"class NumpyDocString(Mapping):\n    \"\"\"Parses a numpydoc string to an abstract representation\n\n    Instances define a mapping from section title to structured data.\n\n    \"\"\"\n\n    sections = {\n        'Signature': '',\n        'Summary': [''],\n        'Extended Summary': [],\n        'Parameters': [],\n        'Returns': [],\n        'Yields': [],\n        'Receives': [],\n        'Raises': [],\n        'Warns': [],\n        'Other Parameters': [],\n        'Attributes': [],\n        'Methods': [],\n        'See Also': [],\n        'Notes': [],\n        'Warnings': [],\n        'References': '',\n        'Examples': '',\n        'index': {}\n    }\n\n    def __init__(self, docstring, config={}):\n        orig_docstring = docstring\n        docstring = textwrap.dedent(docstring).split('\\n')\n\n        self._doc = Reader(docstring)\n        self._parsed_data = copy.deepcopy(self.sections)\n\n        try:\n            self._parse()\n        except ParseError as e:\n            e.docstring = orig_docstring\n            raise\n\n    def __getitem__(self, key):\n        return self._parsed_data[key]\n\n    def __setitem__(self, key, val):\n        if key not in self._parsed_data:\n            self._error_location(f\"Unknown section {key}\", error=False)\n        else:\n            self._parsed_data[key] = val\n\n    def __iter__(self):\n        return iter(self._parsed_data)\n\n    def __len__(self):\n        return len(self._parsed_data)\n\n    def _is_at_section(self):\n        self._doc.seek_next_non_empty_line()\n\n        if self._doc.eof():\n            return False\n\n        l1 = self._doc.peek().strip()  # e.g. Parameters\n\n        if l1.startswith('.. index::'):\n            return True\n\n        l2 = self._doc.peek(1).strip()  # ---------- or ==========\n        return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))\n\n    def _strip(self, doc):\n        i = 0\n        j = 0\n        for i, line in enumerate(doc):\n            if line.strip():\n                break\n\n        for j, line in enumerate(doc[::-1]):\n            if line.strip():\n                break\n\n        return doc[i:len(doc)-j]\n\n    def _read_to_next_section(self):\n        section = self._doc.read_to_next_empty_line()\n\n        while not self._is_at_section() and not self._doc.eof():\n            if not self._doc.peek(-1).strip():  # previous line was empty\n                section += ['']\n\n            section += self._doc.read_to_next_empty_line()\n\n        return section\n\n    def _read_sections(self):\n        while not self._doc.eof():\n            data = self._read_to_next_section()\n            name = data[0].strip()\n\n            if name.startswith('..'):  # index section\n                yield name, data[1:]\n            elif len(data) < 2:\n                yield StopIteration\n            else:\n                yield name, self._strip(data[2:])\n\n    def _parse_param_list(self, content, single_element_is_type=False):\n        r = Reader(content)\n        params = []\n        while not r.eof():\n            header = r.read().strip()\n            if ' : ' in header:\n                arg_name, arg_type = header.split(' : ')[:2]\n            else:\n                if single_element_is_type:\n                    arg_name, arg_type = '', header\n                else:\n                    arg_name, arg_type = header, ''\n\n            desc = r.read_to_next_unindented_line()\n            desc = dedent_lines(desc)\n            desc = strip_blank_lines(desc)\n\n            params.append(Parameter(arg_name, arg_type, desc))\n\n        return params\n\n    # See also supports the following formats.\n    #\n    # \n    #  SPACE* COLON SPACE+  SPACE*\n    #  ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE*\n    #  ( COMMA SPACE+ )* SPACE* COLON SPACE+  SPACE*\n\n    #  is one of\n    #   \n    #   COLON  COLON BACKTICK  BACKTICK\n    # where\n    #    is a legal function name, and\n    #    is any nonempty sequence of word characters.\n    # Examples: func_f1  :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`\n    #  is a string describing the function.\n\n    _role = r\":(?P\\w+):\"\n    _funcbacktick = r\"`(?P(?:~\\w+\\.)?[a-zA-Z0-9_\\.-]+)`\"\n    _funcplain = r\"(?P[a-zA-Z0-9_\\.-]+)\"\n    _funcname = r\"(\" + _role + _funcbacktick + r\"|\" + _funcplain + r\")\"\n    _funcnamenext = _funcname.replace('role', 'rolenext')\n    _funcnamenext = _funcnamenext.replace('name', 'namenext')\n    _description = r\"(?P\\s*:(\\s+(?P\\S+.*))?)?\\s*$\"\n    _func_rgx = re.compile(r\"^\\s*\" + _funcname + r\"\\s*\")\n    _line_rgx = re.compile(\n        r\"^\\s*\" +\n        r\"(?P\" +        # group for all function names\n        _funcname +\n        r\"(?P([,]\\s+\" + _funcnamenext + r\")*)\" +\n        r\")\" +                     # end of \"allfuncs\"\n        r\"(?P[,\\.])?\" +   # Some function lists have a trailing comma (or period)  '\\s*'\n        _description)\n\n    # Empty  elements are replaced with '..'\n    empty_description = '..'\n\n    def _parse_see_also(self, content):\n        \"\"\"\n        func_name : Descriptive text\n            continued text\n        another_func_name : Descriptive text\n        func_name1, func_name2, :meth:`func_name`, func_name3\n\n        \"\"\"\n\n        items = []\n\n        def parse_item_name(text):\n            \"\"\"Match ':role:`name`' or 'name'.\"\"\"\n            m = self._func_rgx.match(text)\n            if not m:\n                raise ParseError(f\"{text} is not a item name\")\n            role = m.group('role')\n            name = m.group('name') if role else m.group('name2')\n            return name, role, m.end()\n\n        rest = []\n        for line in content:\n            if not line.strip():\n                continue\n\n            line_match = self._line_rgx.match(line)\n            description = None\n            if line_match:\n                description = line_match.group('desc')\n                if line_match.group('trailing') and description:\n                    self._error_location(\n                        'Unexpected comma or period after function list at index %d of '\n                        'line \"%s\"' % (line_match.end('trailing'), line),\n                        error=False)\n            if not description and line.startswith(' '):\n                rest.append(line.strip())\n            elif line_match:\n                funcs = []\n                text = line_match.group('allfuncs')\n                while True:\n                    if not text.strip():\n                        break\n                    name, role, match_end = parse_item_name(text)\n                    funcs.append((name, role))\n                    text = text[match_end:].strip()\n                    if text and text[0] == ',':\n                        text = text[1:].strip()\n                rest = list(filter(None, [description]))\n                items.append((funcs, rest))\n            else:\n                raise ParseError(f\"{line} is not a item name\")\n        return items\n\n    def _parse_index(self, section, content):\n        \"\"\"\n        .. index: default\n           :refguide: something, else, and more\n\n        \"\"\"\n        def strip_each_in(lst):\n            return [s.strip() for s in lst]\n\n        out = {}\n        section = section.split('::')\n        if len(section) > 1:\n            out['default'] = strip_each_in(section[1].split(','))[0]\n        for line in content:\n            line = line.split(':')\n            if len(line) > 2:\n                out[line[1]] = strip_each_in(line[2].split(','))\n        return out\n\n    def _parse_summary(self):\n        \"\"\"Grab signature (if given) and summary\"\"\"\n        if self._is_at_section():\n            return\n\n        # If several signatures present, take the last one\n        while True:\n            summary = self._doc.read_to_next_empty_line()\n            summary_str = \" \".join([s.strip() for s in summary]).strip()\n            compiled = re.compile(r'^([\\w., ]+=)?\\s*[\\w\\.]+\\(.*\\)$')\n            if compiled.match(summary_str):\n                self['Signature'] = summary_str\n                if not self._is_at_section():\n                    continue\n            break\n\n        if summary is not None:\n            self['Summary'] = summary\n\n        if not self._is_at_section():\n            self['Extended Summary'] = self._read_to_next_section()\n\n    def _parse(self):\n        self._doc.reset()\n        self._parse_summary()\n\n        sections = list(self._read_sections())\n        section_names = {section for section, content in sections}\n\n        has_returns = 'Returns' in section_names\n        has_yields = 'Yields' in section_names\n        # We could do more tests, but we are not. Arbitrarily.\n        if has_returns and has_yields:\n            msg = 'Docstring contains both a Returns and Yields section.'\n            raise ValueError(msg)\n        if not has_yields and 'Receives' in section_names:\n            msg = 'Docstring contains a Receives section but not Yields.'\n            raise ValueError(msg)\n\n        for (section, content) in sections:\n            if not section.startswith('..'):\n                section = (s.capitalize() for s in section.split(' '))\n                section = ' '.join(section)\n                if self.get(section):\n                    self._error_location(f\"The section {section} appears twice\")\n\n            if section in ('Parameters', 'Other Parameters', 'Attributes',\n                           'Methods'):\n                self[section] = self._parse_param_list(content)\n            elif section in ('Returns', 'Yields', 'Raises', 'Warns', 'Receives'):\n                self[section] = self._parse_param_list(\n                    content, single_element_is_type=True)\n            elif section.startswith('.. index::'):\n                self['index'] = self._parse_index(section, content)\n            elif section == 'See Also':\n                self['See Also'] = self._parse_see_also(content)\n            else:\n                self[section] = content\n\n    def _error_location(self, msg, error=True):\n        if hasattr(self, '_obj'):\n            # we know where the docs came from:\n            try:\n                filename = inspect.getsourcefile(self._obj)\n            except TypeError:\n                filename = None\n            msg = msg + f\" in the docstring of {self._obj} in {filename}.\"\n        if error:\n            raise ValueError(msg)\n        else:\n            warn(msg)\n\n    # string conversion routines\n\n    def _str_header(self, name, symbol='-'):\n        return [name, len(name)*symbol]\n\n    def _str_indent(self, doc, indent=4):\n        out = []\n        for line in doc:\n            out += [' '*indent + line]\n        return out\n\n    def _str_signature(self):\n        if self['Signature']:\n            return [self['Signature'].replace('*', r'\\*')] + ['']\n        else:\n            return ['']\n\n    def _str_summary(self):\n        if self['Summary']:\n            return self['Summary'] + ['']\n        else:\n            return []\n\n    def _str_extended_summary(self):\n        if self['Extended Summary']:\n            return self['Extended Summary'] + ['']\n        else:\n            return []\n\n    def _str_param_list(self, name):\n        out = []\n        if self[name]:\n            out += self._str_header(name)\n            for param in self[name]:\n                parts = []\n                if param.name:\n                    parts.append(param.name)\n                if param.type:\n                    parts.append(param.type)\n                out += [' : '.join(parts)]\n                if param.desc and ''.join(param.desc).strip():\n                    out += self._str_indent(param.desc)\n            out += ['']\n        return out\n\n    def _str_section(self, name):\n        out = []\n        if self[name]:\n            out += self._str_header(name)\n            out += self[name]\n            out += ['']\n        return out\n\n    def _str_see_also(self, func_role):\n        if not self['See Also']:\n            return []\n        out = []\n        out += self._str_header(\"See Also\")\n        out += ['']\n        last_had_desc = True\n        for funcs, desc in self['See Also']:\n            assert isinstance(funcs, list)\n            links = []\n            for func, role in funcs:\n                if role:\n                    link = f':{role}:`{func}`'\n                elif func_role:\n                    link = f':{func_role}:`{func}`'\n                else:\n                    link = f\"`{func}`_\"\n                links.append(link)\n            link = ', '.join(links)\n            out += [link]\n            if desc:\n                out += self._str_indent([' '.join(desc)])\n                last_had_desc = True\n            else:\n                last_had_desc = False\n                out += self._str_indent([self.empty_description])\n\n        if last_had_desc:\n            out += ['']\n        out += ['']\n        return out\n\n    def _str_index(self):\n        idx = self['index']\n        out = []\n        output_index = False\n        default_index = idx.get('default', '')\n        if default_index:\n            output_index = True\n        out += [f'.. index:: {default_index}']\n        for section, references in idx.items():\n            if section == 'default':\n                continue\n            output_index = True\n            out += [f\"   :{section}: {', '.join(references)}\"]\n        if output_index:\n            return out\n        else:\n            return ''\n\n    def __str__(self, func_role=''):\n        out = []\n        out += self._str_signature()\n        out += self._str_summary()\n        out += self._str_extended_summary()\n        for param_list in ('Parameters', 'Returns', 'Yields', 'Receives',\n                           'Other Parameters', 'Raises', 'Warns'):\n            out += self._str_param_list(param_list)\n        out += self._str_section('Warnings')\n        out += self._str_see_also(func_role)\n        for s in ('Notes', 'References', 'Examples'):\n            out += self._str_section(s)\n        for param_list in ('Attributes', 'Methods'):\n            out += self._str_param_list(param_list)\n        out += self._str_index()\n        return '\\n'.join(out)"},{"col":4,"comment":"Make the plot.","endLoc":891,"header":"def plot(self, ax, boxplot_kws)","id":3100,"name":"plot","nodeType":"Function","startLoc":886,"text":"def plot(self, ax, boxplot_kws):\n        \"\"\"Make the plot.\"\"\"\n        self.draw_boxplot(ax, boxplot_kws)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"col":4,"comment":"null","endLoc":178,"header":"def __getitem__(self, key)","id":3101,"name":"__getitem__","nodeType":"Function","startLoc":177,"text":"def __getitem__(self, key):\n        return self._parsed_data[key]"},{"col":4,"comment":"null","endLoc":184,"header":"def __setitem__(self, key, val)","id":3102,"name":"__setitem__","nodeType":"Function","startLoc":180,"text":"def __setitem__(self, key, val):\n        if key not in self._parsed_data:\n            self._error_location(f\"Unknown section {key}\", error=False)\n        else:\n            self._parsed_data[key] = val"},{"id":3103,"name":"v0.8.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.8.0 (July 2017)\n------------------\n\n- The default style is no longer applied when seaborn is imported. It is now necessary to explicitly call :func:`set` or one or more of :func:`set_style`, :func:`set_context`, and :func:`set_palette`. Correspondingly, the ``seaborn.apionly`` module has been deprecated.\n\n- Changed the behavior of :func:`heatmap` (and by extension :func:`clustermap`) when plotting divergent dataesets (i.e. when the ``center`` parameter is used). Instead of extending the lower and upper limits of the colormap to be symmetrical around the ``center`` value, the colormap is modified so that its middle color corresponds to ``center``. This means that the full range of the colormap will not be used (unless the data or specified ``vmin`` and ``vmax`` are symmetric), but the upper and lower limits of the colorbar will correspond to the range of the data. See the Github pull request `(#1184) `_ for examples of the behavior.\n\n- Removed automatic detection of diverging data in :func:`heatmap` (and by extension :func:`clustermap`). If you want the colormap to be treated as diverging (see above), it is now necessary to specify the ``center`` value. When no colormap is specified, specifying ``center`` will still change the default to be one that is more appropriate for displaying diverging data.\n\n- Added four new colormaps, created using `viscm `_ for perceptual uniformity. The new colormaps include two sequential colormaps (\"rocket\" and \"mako\") and two diverging colormaps (\"icefire\" and \"vlag\"). These colormaps are registered with matplotlib on seaborn import and the colormap objects can be accessed in the ``seaborn.cm`` namespace.\n\n- Changed the default :func:`heatmap` colormaps to be \"rocket\" (in the case of sequential data) or \"icefire\" (in the case of diverging data). Note that this change reverses the direction of the luminance ramp from the previous defaults. While potentially confusing and disruptive, this change better aligns the seaborn defaults with the new matplotlib default colormap (\"viridis\") and arguably better aligns the semantics of a \"heat\" map with the appearance of the colormap.\n\n- Added ``\"auto\"`` as a (default) option for tick labels in :func:`heatmap` and :func:`clustermap`. This will try to estimate how many ticks can be labeled without the text objects overlapping, which should improve performance for larger matrices.\n\n- Added the ``dodge`` parameter to :func:`boxplot`, :func:`violinplot`, and :func:`barplot` to allow use of ``hue`` without changing the position or width of the plot elements, as when the ``hue`` variable is not nested within the main categorical variable.\n\n- Correspondingly, the ``split`` parameter for :func:`stripplot` and :func:`swarmplot` has been renamed to ``dodge`` for consistency with the other categorical functions (and for differentiation from the meaning of ``split`` in :func:`violinplot`).\n\n- Added the ability to draw a colorbar for a bivariate :func:`kdeplot` with the ``cbar`` parameter (and related ``cbar_ax`` and ``cbar_kws`` parameters).\n\n- Added the ability to use error bars to show standard deviations rather than bootstrap confidence intervals in most statistical functions by putting ``ci=\"sd\"``.\n\n- Allow side-specific offsets in :func:`despine`.\n\n- Figure size is no longer part of the seaborn plotting context parameters.\n\n- Put a cap on the number of bins used in :func:`jointplot` for ``type==\"hex\"`` to avoid hanging when the reference rule prescribes too many.\n\n- Changed the y axis in :func:`heatmap`. Instead of reversing the rows of the data internally, the y axis is now inverted. This may affect code that draws on top of the heatmap in data coordinates.\n\n- Turn off dendrogram axes in :func:`clustermap` rather than setting the background color to white.\n\n- New matplotlib qualitative palettes (e.g. \"tab10\") are now handled correctly.\n\n- Some modules and functions have been internally reorganized; there should be no effect on code that uses the ``seaborn`` namespace.\n\n- Added a deprecation warning to ``tsplot`` function to indicate that it will be removed or replaced with a substantially altered version in a future release.\n\n- The ``interactplot`` and ``coefplot`` functions are officially deprecated and will be removed in a future release.\n"},{"col":4,"comment":"null","endLoc":70,"header":"def test_cut(self, rng)","id":3104,"name":"test_cut","nodeType":"Function","startLoc":55,"text":"def test_cut(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n\n        kde = KDE(cut=0)\n        _, support = kde(x)\n        assert support.min() == x.min()\n        assert support.max() == x.max()\n\n        cut = 2\n        bw_scale = .5\n        bw = x.std() * bw_scale\n        kde = KDE(cut=cut, bw_method=bw_scale, gridsize=1000)\n        _, support = kde(x)\n        assert support.min() == pytest.approx(x.min() - bw * cut, abs=1e-2)\n        assert support.max() == pytest.approx(x.max() + bw * cut, abs=1e-2)"},{"attributeType":"null","col":8,"comment":"null","endLoc":788,"id":3105,"name":"dodge","nodeType":"Attribute","startLoc":788,"text":"self.dodge"},{"col":4,"comment":"null","endLoc":187,"header":"def __iter__(self)","id":3106,"name":"__iter__","nodeType":"Function","startLoc":186,"text":"def __iter__(self):\n        return iter(self._parsed_data)"},{"attributeType":"null","col":8,"comment":"null","endLoc":790,"id":3107,"name":"fliersize","nodeType":"Attribute","startLoc":790,"text":"self.fliersize"},{"attributeType":"null","col":8,"comment":"null","endLoc":789,"id":3108,"name":"width","nodeType":"Attribute","startLoc":789,"text":"self.width"},{"col":4,"comment":"null","endLoc":190,"header":"def __len__(self)","id":3113,"name":"__len__","nodeType":"Function","startLoc":189,"text":"def __len__(self):\n        return len(self._parsed_data)"},{"attributeType":"null","col":8,"comment":"null","endLoc":794,"id":3114,"name":"linewidth","nodeType":"Attribute","startLoc":794,"text":"self.linewidth"},{"className":"_ViolinPlotter","col":0,"comment":"null","endLoc":1422,"id":3115,"nodeType":"Class","startLoc":894,"text":"class _ViolinPlotter(_CategoricalPlotter):\n\n    def __init__(self, x, y, hue, data, order, hue_order,\n                 bw, cut, scale, scale_hue, gridsize,\n                 width, inner, split, dodge, orient, linewidth,\n                 color, palette, saturation):\n\n        self.establish_variables(x, y, hue, data, orient, order, hue_order)\n        self.establish_colors(color, palette, saturation)\n        self.estimate_densities(bw, cut, scale, scale_hue, gridsize)\n\n        self.gridsize = gridsize\n        self.width = width\n        self.dodge = dodge\n\n        if inner is not None:\n            if not any([inner.startswith(\"quart\"),\n                        inner.startswith(\"box\"),\n                        inner.startswith(\"stick\"),\n                        inner.startswith(\"point\")]):\n                err = f\"Inner style '{inner}' not recognized\"\n                raise ValueError(err)\n        self.inner = inner\n\n        if split and self.hue_names is not None and len(self.hue_names) != 2:\n            msg = \"There must be exactly two hue levels to use `split`.'\"\n            raise ValueError(msg)\n        self.split = split\n\n        if linewidth is None:\n            linewidth = mpl.rcParams[\"lines.linewidth\"]\n        self.linewidth = linewidth\n\n    def estimate_densities(self, bw, cut, scale, scale_hue, gridsize):\n        \"\"\"Find the support and density for all of the data.\"\"\"\n        # Initialize data structures to keep track of plotting data\n        if self.hue_names is None:\n            support = []\n            density = []\n            counts = np.zeros(len(self.plot_data))\n            max_density = np.zeros(len(self.plot_data))\n        else:\n            support = [[] for _ in self.plot_data]\n            density = [[] for _ in self.plot_data]\n            size = len(self.group_names), len(self.hue_names)\n            counts = np.zeros(size)\n            max_density = np.zeros(size)\n\n        for i, group_data in enumerate(self.plot_data):\n\n            # Option 1: we have a single level of grouping\n            # --------------------------------------------\n\n            if self.plot_hues is None:\n\n                # Strip missing datapoints\n                kde_data = remove_na(group_data)\n\n                # Handle special case of no data at this level\n                if kde_data.size == 0:\n                    support.append(np.array([]))\n                    density.append(np.array([1.]))\n                    counts[i] = 0\n                    max_density[i] = 0\n                    continue\n\n                # Handle special case of a single unique datapoint\n                elif np.unique(kde_data).size == 1:\n                    support.append(np.unique(kde_data))\n                    density.append(np.array([1.]))\n                    counts[i] = 1\n                    max_density[i] = 0\n                    continue\n\n                # Fit the KDE and get the used bandwidth size\n                kde, bw_used = self.fit_kde(kde_data, bw)\n\n                # Determine the support grid and get the density over it\n                support_i = self.kde_support(kde_data, bw_used, cut, gridsize)\n                density_i = kde.evaluate(support_i)\n\n                # Update the data structures with these results\n                support.append(support_i)\n                density.append(density_i)\n                counts[i] = kde_data.size\n                max_density[i] = density_i.max()\n\n            # Option 2: we have nested grouping by a hue variable\n            # ---------------------------------------------------\n\n            else:\n                for j, hue_level in enumerate(self.hue_names):\n\n                    # Handle special case of no data at this category level\n                    if not group_data.size:\n                        support[i].append(np.array([]))\n                        density[i].append(np.array([1.]))\n                        counts[i, j] = 0\n                        max_density[i, j] = 0\n                        continue\n\n                    # Select out the observations for this hue level\n                    hue_mask = self.plot_hues[i] == hue_level\n\n                    # Strip missing datapoints\n                    kde_data = remove_na(group_data[hue_mask])\n\n                    # Handle special case of no data at this level\n                    if kde_data.size == 0:\n                        support[i].append(np.array([]))\n                        density[i].append(np.array([1.]))\n                        counts[i, j] = 0\n                        max_density[i, j] = 0\n                        continue\n\n                    # Handle special case of a single unique datapoint\n                    elif np.unique(kde_data).size == 1:\n                        support[i].append(np.unique(kde_data))\n                        density[i].append(np.array([1.]))\n                        counts[i, j] = 1\n                        max_density[i, j] = 0\n                        continue\n\n                    # Fit the KDE and get the used bandwidth size\n                    kde, bw_used = self.fit_kde(kde_data, bw)\n\n                    # Determine the support grid and get the density over it\n                    support_ij = self.kde_support(kde_data, bw_used,\n                                                  cut, gridsize)\n                    density_ij = kde.evaluate(support_ij)\n\n                    # Update the data structures with these results\n                    support[i].append(support_ij)\n                    density[i].append(density_ij)\n                    counts[i, j] = kde_data.size\n                    max_density[i, j] = density_ij.max()\n\n        # Scale the height of the density curve.\n        # For a violinplot the density is non-quantitative.\n        # The objective here is to scale the curves relative to 1 so that\n        # they can be multiplied by the width parameter during plotting.\n\n        if scale == \"area\":\n            self.scale_area(density, max_density, scale_hue)\n\n        elif scale == \"width\":\n            self.scale_width(density)\n\n        elif scale == \"count\":\n            self.scale_count(density, counts, scale_hue)\n\n        else:\n            raise ValueError(f\"scale method '{scale}' not recognized\")\n\n        # Set object attributes that will be used while plotting\n        self.support = support\n        self.density = density\n\n    def fit_kde(self, x, bw):\n        \"\"\"Estimate a KDE for a vector of data with flexible bandwidth.\"\"\"\n        kde = gaussian_kde(x, bw)\n\n        # Extract the numeric bandwidth from the KDE object\n        bw_used = kde.factor\n\n        # At this point, bw will be a numeric scale factor.\n        # To get the actual bandwidth of the kernel, we multiple by the\n        # unbiased standard deviation of the data, which we will use\n        # elsewhere to compute the range of the support.\n        bw_used = bw_used * x.std(ddof=1)\n\n        return kde, bw_used\n\n    def kde_support(self, x, bw, cut, gridsize):\n        \"\"\"Define a grid of support for the violin.\"\"\"\n        support_min = x.min() - bw * cut\n        support_max = x.max() + bw * cut\n        return np.linspace(support_min, support_max, gridsize)\n\n    def scale_area(self, density, max_density, scale_hue):\n        \"\"\"Scale the relative area under the KDE curve.\n\n        This essentially preserves the \"standard\" KDE scaling, but the\n        resulting maximum density will be 1 so that the curve can be\n        properly multiplied by the violin width.\n\n        \"\"\"\n        if self.hue_names is None:\n            for d in density:\n                if d.size > 1:\n                    d /= max_density.max()\n        else:\n            for i, group in enumerate(density):\n                for d in group:\n                    if scale_hue:\n                        max = max_density[i].max()\n                    else:\n                        max = max_density.max()\n                    if d.size > 1:\n                        d /= max\n\n    def scale_width(self, density):\n        \"\"\"Scale each density curve to the same height.\"\"\"\n        if self.hue_names is None:\n            for d in density:\n                d /= d.max()\n        else:\n            for group in density:\n                for d in group:\n                    d /= d.max()\n\n    def scale_count(self, density, counts, scale_hue):\n        \"\"\"Scale each density curve by the number of observations.\"\"\"\n        if self.hue_names is None:\n            if counts.max() == 0:\n                d = 0\n            else:\n                for count, d in zip(counts, density):\n                    d /= d.max()\n                    d *= count / counts.max()\n        else:\n            for i, group in enumerate(density):\n                for j, d in enumerate(group):\n                    if counts[i].max() == 0:\n                        d = 0\n                    else:\n                        count = counts[i, j]\n                        if scale_hue:\n                            scaler = count / counts[i].max()\n                        else:\n                            scaler = count / counts.max()\n                        d /= d.max()\n                        d *= scaler\n\n    @property\n    def dwidth(self):\n\n        if self.hue_names is None or not self.dodge:\n            return self.width / 2\n        elif self.split:\n            return self.width / 2\n        else:\n            return self.width / (2 * len(self.hue_names))\n\n    def draw_violins(self, ax):\n        \"\"\"Draw the violins onto `ax`.\"\"\"\n        fill_func = ax.fill_betweenx if self.orient == \"v\" else ax.fill_between\n        for i, group_data in enumerate(self.plot_data):\n\n            kws = dict(edgecolor=self.gray, linewidth=self.linewidth)\n\n            # Option 1: we have a single level of grouping\n            # --------------------------------------------\n\n            if self.plot_hues is None:\n\n                support, density = self.support[i], self.density[i]\n\n                # Handle special case of no observations in this bin\n                if support.size == 0:\n                    continue\n\n                # Handle special case of a single observation\n                elif support.size == 1:\n                    val = support.item()\n                    d = density.item()\n                    self.draw_single_observation(ax, i, val, d)\n                    continue\n\n                # Draw the violin for this group\n                grid = np.ones(self.gridsize) * i\n                fill_func(support,\n                          grid - density * self.dwidth,\n                          grid + density * self.dwidth,\n                          facecolor=self.colors[i],\n                          **kws)\n\n                # Draw the interior representation of the data\n                if self.inner is None:\n                    continue\n\n                # Get a nan-free vector of datapoints\n                violin_data = remove_na(group_data)\n\n                # Draw box and whisker information\n                if self.inner.startswith(\"box\"):\n                    self.draw_box_lines(ax, violin_data, i)\n\n                # Draw quartile lines\n                elif self.inner.startswith(\"quart\"):\n                    self.draw_quartiles(ax, violin_data, support, density, i)\n\n                # Draw stick observations\n                elif self.inner.startswith(\"stick\"):\n                    self.draw_stick_lines(ax, violin_data, support, density, i)\n\n                # Draw point observations\n                elif self.inner.startswith(\"point\"):\n                    self.draw_points(ax, violin_data, i)\n\n            # Option 2: we have nested grouping by a hue variable\n            # ---------------------------------------------------\n\n            else:\n                offsets = self.hue_offsets\n                for j, hue_level in enumerate(self.hue_names):\n\n                    support, density = self.support[i][j], self.density[i][j]\n                    kws[\"facecolor\"] = self.colors[j]\n\n                    # Add legend data, but just for one set of violins\n                    if not i:\n                        self.add_legend_data(ax, self.colors[j], hue_level)\n\n                    # Handle the special case where we have no observations\n                    if support.size == 0:\n                        continue\n\n                    # Handle the special case where we have one observation\n                    elif support.size == 1:\n                        val = support.item()\n                        d = density.item()\n                        if self.split:\n                            d = d / 2\n                        at_group = i + offsets[j]\n                        self.draw_single_observation(ax, at_group, val, d)\n                        continue\n\n                    # Option 2a: we are drawing a single split violin\n                    # -----------------------------------------------\n\n                    if self.split:\n\n                        grid = np.ones(self.gridsize) * i\n                        if j:\n                            fill_func(support,\n                                      grid,\n                                      grid + density * self.dwidth,\n                                      **kws)\n                        else:\n                            fill_func(support,\n                                      grid - density * self.dwidth,\n                                      grid,\n                                      **kws)\n\n                        # Draw the interior representation of the data\n                        if self.inner is None:\n                            continue\n\n                        # Get a nan-free vector of datapoints\n                        hue_mask = self.plot_hues[i] == hue_level\n                        violin_data = remove_na(group_data[hue_mask])\n\n                        # Draw quartile lines\n                        if self.inner.startswith(\"quart\"):\n                            self.draw_quartiles(ax, violin_data,\n                                                support, density, i,\n                                                [\"left\", \"right\"][j])\n\n                        # Draw stick observations\n                        elif self.inner.startswith(\"stick\"):\n                            self.draw_stick_lines(ax, violin_data,\n                                                  support, density, i,\n                                                  [\"left\", \"right\"][j])\n\n                        # The box and point interior plots are drawn for\n                        # all data at the group level, so we just do that once\n                        if j and any(self.plot_hues[0] == hue_level):\n                            continue\n\n                        # Get the whole vector for this group level\n                        violin_data = remove_na(group_data)\n\n                        # Draw box and whisker information\n                        if self.inner.startswith(\"box\"):\n                            self.draw_box_lines(ax, violin_data, i)\n\n                        # Draw point observations\n                        elif self.inner.startswith(\"point\"):\n                            self.draw_points(ax, violin_data, i)\n\n                    # Option 2b: we are drawing full nested violins\n                    # -----------------------------------------------\n\n                    else:\n                        grid = np.ones(self.gridsize) * (i + offsets[j])\n                        fill_func(support,\n                                  grid - density * self.dwidth,\n                                  grid + density * self.dwidth,\n                                  **kws)\n\n                        # Draw the interior representation\n                        if self.inner is None:\n                            continue\n\n                        # Get a nan-free vector of datapoints\n                        hue_mask = self.plot_hues[i] == hue_level\n                        violin_data = remove_na(group_data[hue_mask])\n\n                        # Draw box and whisker information\n                        if self.inner.startswith(\"box\"):\n                            self.draw_box_lines(ax, violin_data, i + offsets[j])\n\n                        # Draw quartile lines\n                        elif self.inner.startswith(\"quart\"):\n                            self.draw_quartiles(ax, violin_data,\n                                                support, density,\n                                                i + offsets[j])\n\n                        # Draw stick observations\n                        elif self.inner.startswith(\"stick\"):\n                            self.draw_stick_lines(ax, violin_data,\n                                                  support, density,\n                                                  i + offsets[j])\n\n                        # Draw point observations\n                        elif self.inner.startswith(\"point\"):\n                            self.draw_points(ax, violin_data, i + offsets[j])\n\n    def draw_single_observation(self, ax, at_group, at_quant, density):\n        \"\"\"Draw a line to mark a single observation.\"\"\"\n        d_width = density * self.dwidth\n        if self.orient == \"v\":\n            ax.plot([at_group - d_width, at_group + d_width],\n                    [at_quant, at_quant],\n                    color=self.gray,\n                    linewidth=self.linewidth)\n        else:\n            ax.plot([at_quant, at_quant],\n                    [at_group - d_width, at_group + d_width],\n                    color=self.gray,\n                    linewidth=self.linewidth)\n\n    def draw_box_lines(self, ax, data, center):\n        \"\"\"Draw boxplot information at center of the density.\"\"\"\n        # Compute the boxplot statistics\n        q25, q50, q75 = np.percentile(data, [25, 50, 75])\n        whisker_lim = 1.5 * (q75 - q25)\n        h1 = np.min(data[data >= (q25 - whisker_lim)])\n        h2 = np.max(data[data <= (q75 + whisker_lim)])\n\n        # Draw a boxplot using lines and a point\n        if self.orient == \"v\":\n            ax.plot([center, center], [h1, h2],\n                    linewidth=self.linewidth,\n                    color=self.gray)\n            ax.plot([center, center], [q25, q75],\n                    linewidth=self.linewidth * 3,\n                    color=self.gray)\n            ax.scatter(center, q50,\n                       zorder=3,\n                       color=\"white\",\n                       edgecolor=self.gray,\n                       s=np.square(self.linewidth * 2))\n        else:\n            ax.plot([h1, h2], [center, center],\n                    linewidth=self.linewidth,\n                    color=self.gray)\n            ax.plot([q25, q75], [center, center],\n                    linewidth=self.linewidth * 3,\n                    color=self.gray)\n            ax.scatter(q50, center,\n                       zorder=3,\n                       color=\"white\",\n                       edgecolor=self.gray,\n                       s=np.square(self.linewidth * 2))\n\n    def draw_quartiles(self, ax, data, support, density, center, split=False):\n        \"\"\"Draw the quartiles as lines at width of density.\"\"\"\n        q25, q50, q75 = np.percentile(data, [25, 50, 75])\n\n        self.draw_to_density(ax, center, q25, support, density, split,\n                             linewidth=self.linewidth,\n                             dashes=[self.linewidth * 1.5] * 2)\n        self.draw_to_density(ax, center, q50, support, density, split,\n                             linewidth=self.linewidth,\n                             dashes=[self.linewidth * 3] * 2)\n        self.draw_to_density(ax, center, q75, support, density, split,\n                             linewidth=self.linewidth,\n                             dashes=[self.linewidth * 1.5] * 2)\n\n    def draw_points(self, ax, data, center):\n        \"\"\"Draw individual observations as points at middle of the violin.\"\"\"\n        kws = dict(s=np.square(self.linewidth * 2),\n                   color=self.gray,\n                   edgecolor=self.gray)\n\n        grid = np.ones(len(data)) * center\n\n        if self.orient == \"v\":\n            ax.scatter(grid, data, **kws)\n        else:\n            ax.scatter(data, grid, **kws)\n\n    def draw_stick_lines(self, ax, data, support, density,\n                         center, split=False):\n        \"\"\"Draw individual observations as sticks at width of density.\"\"\"\n        for val in data:\n            self.draw_to_density(ax, center, val, support, density, split,\n                                 linewidth=self.linewidth * .5)\n\n    def draw_to_density(self, ax, center, val, support, density, split, **kws):\n        \"\"\"Draw a line orthogonal to the value axis at width of density.\"\"\"\n        idx = np.argmin(np.abs(support - val))\n        width = self.dwidth * density[idx] * .99\n\n        kws[\"color\"] = self.gray\n\n        if self.orient == \"v\":\n            if split == \"left\":\n                ax.plot([center - width, center], [val, val], **kws)\n            elif split == \"right\":\n                ax.plot([center, center + width], [val, val], **kws)\n            else:\n                ax.plot([center - width, center + width], [val, val], **kws)\n        else:\n            if split == \"left\":\n                ax.plot([val, val], [center - width, center], **kws)\n            elif split == \"right\":\n                ax.plot([val, val], [center, center + width], **kws)\n            else:\n                ax.plot([val, val], [center - width, center + width], **kws)\n\n    def plot(self, ax):\n        \"\"\"Make the violin plot.\"\"\"\n        self.draw_violins(ax)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"col":4,"comment":"null","endLoc":446,"header":"def _str_header(self, name, symbol='-')","id":3116,"name":"_str_header","nodeType":"Function","startLoc":445,"text":"def _str_header(self, name, symbol='-'):\n        return [name, len(name)*symbol]"},{"col":4,"comment":"null","endLoc":452,"header":"def _str_indent(self, doc, indent=4)","id":3117,"name":"_str_indent","nodeType":"Function","startLoc":448,"text":"def _str_indent(self, doc, indent=4):\n        out = []\n        for line in doc:\n            out += [' '*indent + line]\n        return out"},{"col":4,"comment":"null","endLoc":458,"header":"def _str_signature(self)","id":3118,"name":"_str_signature","nodeType":"Function","startLoc":454,"text":"def _str_signature(self):\n        if self['Signature']:\n            return [self['Signature'].replace('*', r'\\*')] + ['']\n        else:\n            return ['']"},{"col":4,"comment":"null","endLoc":1136,"header":"@property\n    def dwidth(self)","id":3119,"name":"dwidth","nodeType":"Function","startLoc":1128,"text":"@property\n    def dwidth(self):\n\n        if self.hue_names is None or not self.dodge:\n            return self.width / 2\n        elif self.split:\n            return self.width / 2\n        else:\n            return self.width / (2 * len(self.hue_names))"},{"fileName":"rcmod.py","filePath":"seaborn","id":3120,"nodeType":"File","text":"\"\"\"Control plot style and scaling using the matplotlib rcParams interface.\"\"\"\nimport functools\nimport matplotlib as mpl\nfrom cycler import cycler\nfrom . import palettes\n\n\n__all__ = [\"set_theme\", \"set\", \"reset_defaults\", \"reset_orig\",\n           \"axes_style\", \"set_style\", \"plotting_context\", \"set_context\",\n           \"set_palette\"]\n\n\n_style_keys = [\n\n    \"axes.facecolor\",\n    \"axes.edgecolor\",\n    \"axes.grid\",\n    \"axes.axisbelow\",\n    \"axes.labelcolor\",\n\n    \"figure.facecolor\",\n\n    \"grid.color\",\n    \"grid.linestyle\",\n\n    \"text.color\",\n\n    \"xtick.color\",\n    \"ytick.color\",\n    \"xtick.direction\",\n    \"ytick.direction\",\n    \"lines.solid_capstyle\",\n\n    \"patch.edgecolor\",\n    \"patch.force_edgecolor\",\n\n    \"image.cmap\",\n    \"font.family\",\n    \"font.sans-serif\",\n\n    \"xtick.bottom\",\n    \"xtick.top\",\n    \"ytick.left\",\n    \"ytick.right\",\n\n    \"axes.spines.left\",\n    \"axes.spines.bottom\",\n    \"axes.spines.right\",\n    \"axes.spines.top\",\n\n]\n\n_context_keys = [\n\n    \"font.size\",\n    \"axes.labelsize\",\n    \"axes.titlesize\",\n    \"xtick.labelsize\",\n    \"ytick.labelsize\",\n    \"legend.fontsize\",\n    \"legend.title_fontsize\",\n\n    \"axes.linewidth\",\n    \"grid.linewidth\",\n    \"lines.linewidth\",\n    \"lines.markersize\",\n    \"patch.linewidth\",\n\n    \"xtick.major.width\",\n    \"ytick.major.width\",\n    \"xtick.minor.width\",\n    \"ytick.minor.width\",\n\n    \"xtick.major.size\",\n    \"ytick.major.size\",\n    \"xtick.minor.size\",\n    \"ytick.minor.size\",\n\n]\n\n\ndef set_theme(context=\"notebook\", style=\"darkgrid\", palette=\"deep\",\n              font=\"sans-serif\", font_scale=1, color_codes=True, rc=None):\n    \"\"\"\n    Set aspects of the visual theme for all matplotlib and seaborn plots.\n\n    This function changes the global defaults for all plots using the\n    matplotlib rcParams system. The themeing is decomposed into several distinct\n    sets of parameter values.\n\n    The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`\n    and :doc:`color palette <../tutorial/color_palettes>` tutorials.\n\n    Parameters\n    ----------\n    context : string or dict\n        Scaling parameters, see :func:`plotting_context`.\n    style : string or dict\n        Axes style parameters, see :func:`axes_style`.\n    palette : string or sequence\n        Color palette, see :func:`color_palette`.\n    font : string\n        Font family, see matplotlib font manager.\n    font_scale : float, optional\n        Separate scaling factor to independently scale the size of the\n        font elements.\n    color_codes : bool\n        If ``True`` and ``palette`` is a seaborn palette, remap the shorthand\n        color codes (e.g. \"b\", \"g\", \"r\", etc.) to the colors from this palette.\n    rc : dict or None\n        Dictionary of rc parameter mappings to override the above.\n\n    Examples\n    --------\n\n    .. include:: ../docstrings/set_theme.rst\n\n    \"\"\"\n    set_context(context, font_scale)\n    set_style(style, rc={\"font.family\": font})\n    set_palette(palette, color_codes=color_codes)\n    if rc is not None:\n        mpl.rcParams.update(rc)\n\n\ndef set(*args, **kwargs):\n    \"\"\"\n    Alias for :func:`set_theme`, which is the preferred interface.\n\n    This function may be removed in the future.\n    \"\"\"\n    set_theme(*args, **kwargs)\n\n\ndef reset_defaults():\n    \"\"\"Restore all RC params to default settings.\"\"\"\n    mpl.rcParams.update(mpl.rcParamsDefault)\n\n\ndef reset_orig():\n    \"\"\"Restore all RC params to original settings (respects custom rc).\"\"\"\n    from . import _orig_rc_params\n    mpl.rcParams.update(_orig_rc_params)\n\n\ndef axes_style(style=None, rc=None):\n    \"\"\"\n    Get the parameters that control the general style of the plots.\n\n    The style parameters control properties like the color of the background and\n    whether a grid is enabled by default. This is accomplished using the\n    matplotlib rcParams system.\n\n    The options are illustrated in the\n    :doc:`aesthetics tutorial <../tutorial/aesthetics>`.\n\n    This function can also be used as a context manager to temporarily\n    alter the global defaults. See :func:`set_theme` or :func:`set_style`\n    to modify the global defaults for all plots.\n\n    Parameters\n    ----------\n    style : None, dict, or one of {darkgrid, whitegrid, dark, white, ticks}\n        A dictionary of parameters or the name of a preconfigured style.\n    rc : dict, optional\n        Parameter mappings to override the values in the preset seaborn\n        style dictionaries. This only updates parameters that are\n        considered part of the style definition.\n\n    Examples\n    --------\n\n    .. include:: ../docstrings/axes_style.rst\n\n    \"\"\"\n    if style is None:\n        style_dict = {k: mpl.rcParams[k] for k in _style_keys}\n\n    elif isinstance(style, dict):\n        style_dict = style\n\n    else:\n        styles = [\"white\", \"dark\", \"whitegrid\", \"darkgrid\", \"ticks\"]\n        if style not in styles:\n            raise ValueError(f\"style must be one of {', '.join(styles)}\")\n\n        # Define colors here\n        dark_gray = \".15\"\n        light_gray = \".8\"\n\n        # Common parameters\n        style_dict = {\n\n            \"figure.facecolor\": \"white\",\n            \"axes.labelcolor\": dark_gray,\n\n            \"xtick.direction\": \"out\",\n            \"ytick.direction\": \"out\",\n            \"xtick.color\": dark_gray,\n            \"ytick.color\": dark_gray,\n\n            \"axes.axisbelow\": True,\n            \"grid.linestyle\": \"-\",\n\n\n            \"text.color\": dark_gray,\n            \"font.family\": [\"sans-serif\"],\n            \"font.sans-serif\": [\"Arial\", \"DejaVu Sans\", \"Liberation Sans\",\n                                \"Bitstream Vera Sans\", \"sans-serif\"],\n\n\n            \"lines.solid_capstyle\": \"round\",\n            \"patch.edgecolor\": \"w\",\n            \"patch.force_edgecolor\": True,\n\n            \"image.cmap\": \"rocket\",\n\n            \"xtick.top\": False,\n            \"ytick.right\": False,\n\n        }\n\n        # Set grid on or off\n        if \"grid\" in style:\n            style_dict.update({\n                \"axes.grid\": True,\n            })\n        else:\n            style_dict.update({\n                \"axes.grid\": False,\n            })\n\n        # Set the color of the background, spines, and grids\n        if style.startswith(\"dark\"):\n            style_dict.update({\n\n                \"axes.facecolor\": \"#EAEAF2\",\n                \"axes.edgecolor\": \"white\",\n                \"grid.color\": \"white\",\n\n                \"axes.spines.left\": True,\n                \"axes.spines.bottom\": True,\n                \"axes.spines.right\": True,\n                \"axes.spines.top\": True,\n\n            })\n\n        elif style == \"whitegrid\":\n            style_dict.update({\n\n                \"axes.facecolor\": \"white\",\n                \"axes.edgecolor\": light_gray,\n                \"grid.color\": light_gray,\n\n                \"axes.spines.left\": True,\n                \"axes.spines.bottom\": True,\n                \"axes.spines.right\": True,\n                \"axes.spines.top\": True,\n\n            })\n\n        elif style in [\"white\", \"ticks\"]:\n            style_dict.update({\n\n                \"axes.facecolor\": \"white\",\n                \"axes.edgecolor\": dark_gray,\n                \"grid.color\": light_gray,\n\n                \"axes.spines.left\": True,\n                \"axes.spines.bottom\": True,\n                \"axes.spines.right\": True,\n                \"axes.spines.top\": True,\n\n            })\n\n        # Show or hide the axes ticks\n        if style == \"ticks\":\n            style_dict.update({\n                \"xtick.bottom\": True,\n                \"ytick.left\": True,\n            })\n        else:\n            style_dict.update({\n                \"xtick.bottom\": False,\n                \"ytick.left\": False,\n            })\n\n    # Remove entries that are not defined in the base list of valid keys\n    # This lets us handle matplotlib <=/> 2.0\n    style_dict = {k: v for k, v in style_dict.items() if k in _style_keys}\n\n    # Override these settings with the provided rc dictionary\n    if rc is not None:\n        rc = {k: v for k, v in rc.items() if k in _style_keys}\n        style_dict.update(rc)\n\n    # Wrap in an _AxesStyle object so this can be used in a with statement\n    style_object = _AxesStyle(style_dict)\n\n    return style_object\n\n\ndef set_style(style=None, rc=None):\n    \"\"\"\n    Set the parameters that control the general style of the plots.\n\n    The style parameters control properties like the color of the background and\n    whether a grid is enabled by default. This is accomplished using the\n    matplotlib rcParams system.\n\n    The options are illustrated in the\n    :doc:`aesthetics tutorial <../tutorial/aesthetics>`.\n\n    See :func:`axes_style` to get the parameter values.\n\n    Parameters\n    ----------\n    style : dict, or one of {darkgrid, whitegrid, dark, white, ticks}\n        A dictionary of parameters or the name of a preconfigured style.\n    rc : dict, optional\n        Parameter mappings to override the values in the preset seaborn\n        style dictionaries. This only updates parameters that are\n        considered part of the style definition.\n\n    Examples\n    --------\n\n    .. include:: ../docstrings/set_style.rst\n\n    \"\"\"\n    style_object = axes_style(style, rc)\n    mpl.rcParams.update(style_object)\n\n\ndef plotting_context(context=None, font_scale=1, rc=None):\n    \"\"\"\n    Get the parameters that control the scaling of plot elements.\n\n    This affects things like the size of the labels, lines, and other elements\n    of the plot, but not the overall style. This is accomplished using the\n    matplotlib rcParams system.\n\n    The base context is \"notebook\", and the other contexts are \"paper\", \"talk\",\n    and \"poster\", which are version of the notebook parameters scaled by different\n    values. Font elements can also be scaled independently of (but relative to)\n    the other values.\n\n    This function can also be used as a context manager to temporarily\n    alter the global defaults. See :func:`set_theme` or :func:`set_context`\n    to modify the global defaults for all plots.\n\n    Parameters\n    ----------\n    context : None, dict, or one of {paper, notebook, talk, poster}\n        A dictionary of parameters or the name of a preconfigured set.\n    font_scale : float, optional\n        Separate scaling factor to independently scale the size of the\n        font elements.\n    rc : dict, optional\n        Parameter mappings to override the values in the preset seaborn\n        context dictionaries. This only updates parameters that are\n        considered part of the context definition.\n\n    Examples\n    --------\n\n    .. include:: ../docstrings/plotting_context.rst\n\n    \"\"\"\n    if context is None:\n        context_dict = {k: mpl.rcParams[k] for k in _context_keys}\n\n    elif isinstance(context, dict):\n        context_dict = context\n\n    else:\n\n        contexts = [\"paper\", \"notebook\", \"talk\", \"poster\"]\n        if context not in contexts:\n            raise ValueError(f\"context must be in {', '.join(contexts)}\")\n\n        # Set up dictionary of default parameters\n        texts_base_context = {\n\n            \"font.size\": 12,\n            \"axes.labelsize\": 12,\n            \"axes.titlesize\": 12,\n            \"xtick.labelsize\": 11,\n            \"ytick.labelsize\": 11,\n            \"legend.fontsize\": 11,\n            \"legend.title_fontsize\": 12,\n\n        }\n\n        base_context = {\n\n            \"axes.linewidth\": 1.25,\n            \"grid.linewidth\": 1,\n            \"lines.linewidth\": 1.5,\n            \"lines.markersize\": 6,\n            \"patch.linewidth\": 1,\n\n            \"xtick.major.width\": 1.25,\n            \"ytick.major.width\": 1.25,\n            \"xtick.minor.width\": 1,\n            \"ytick.minor.width\": 1,\n\n            \"xtick.major.size\": 6,\n            \"ytick.major.size\": 6,\n            \"xtick.minor.size\": 4,\n            \"ytick.minor.size\": 4,\n\n        }\n        base_context.update(texts_base_context)\n\n        # Scale all the parameters by the same factor depending on the context\n        scaling = dict(paper=.8, notebook=1, talk=1.5, poster=2)[context]\n        context_dict = {k: v * scaling for k, v in base_context.items()}\n\n        # Now independently scale the fonts\n        font_keys = texts_base_context.keys()\n        font_dict = {k: context_dict[k] * font_scale for k in font_keys}\n        context_dict.update(font_dict)\n\n    # Override these settings with the provided rc dictionary\n    if rc is not None:\n        rc = {k: v for k, v in rc.items() if k in _context_keys}\n        context_dict.update(rc)\n\n    # Wrap in a _PlottingContext object so this can be used in a with statement\n    context_object = _PlottingContext(context_dict)\n\n    return context_object\n\n\ndef set_context(context=None, font_scale=1, rc=None):\n    \"\"\"\n    Set the parameters that control the scaling of plot elements.\n\n    This affects things like the size of the labels, lines, and other elements\n    of the plot, but not the overall style. This is accomplished using the\n    matplotlib rcParams system.\n\n    The base context is \"notebook\", and the other contexts are \"paper\", \"talk\",\n    and \"poster\", which are version of the notebook parameters scaled by different\n    values. Font elements can also be scaled independently of (but relative to)\n    the other values.\n\n    See :func:`plotting_context` to get the parameter values.\n\n    Parameters\n    ----------\n    context : dict, or one of {paper, notebook, talk, poster}\n        A dictionary of parameters or the name of a preconfigured set.\n    font_scale : float, optional\n        Separate scaling factor to independently scale the size of the\n        font elements.\n    rc : dict, optional\n        Parameter mappings to override the values in the preset seaborn\n        context dictionaries. This only updates parameters that are\n        considered part of the context definition.\n\n    Examples\n    --------\n\n    .. include:: ../docstrings/set_context.rst\n\n    \"\"\"\n    context_object = plotting_context(context, font_scale, rc)\n    mpl.rcParams.update(context_object)\n\n\nclass _RCAesthetics(dict):\n    def __enter__(self):\n        rc = mpl.rcParams\n        self._orig = {k: rc[k] for k in self._keys}\n        self._set(self)\n\n    def __exit__(self, exc_type, exc_value, exc_tb):\n        self._set(self._orig)\n\n    def __call__(self, func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            with self:\n                return func(*args, **kwargs)\n        return wrapper\n\n\nclass _AxesStyle(_RCAesthetics):\n    \"\"\"Light wrapper on a dict to set style temporarily.\"\"\"\n    _keys = _style_keys\n    _set = staticmethod(set_style)\n\n\nclass _PlottingContext(_RCAesthetics):\n    \"\"\"Light wrapper on a dict to set context temporarily.\"\"\"\n    _keys = _context_keys\n    _set = staticmethod(set_context)\n\n\ndef set_palette(palette, n_colors=None, desat=None, color_codes=False):\n    \"\"\"Set the matplotlib color cycle using a seaborn palette.\n\n    Parameters\n    ----------\n    palette : seaborn color paltte | matplotlib colormap | hls | husl\n        Palette definition. Should be something :func:`color_palette` can process.\n    n_colors : int\n        Number of colors in the cycle. The default number of colors will depend\n        on the format of ``palette``, see the :func:`color_palette`\n        documentation for more information.\n    desat : float\n        Proportion to desaturate each color by.\n    color_codes : bool\n        If ``True`` and ``palette`` is a seaborn palette, remap the shorthand\n        color codes (e.g. \"b\", \"g\", \"r\", etc.) to the colors from this palette.\n\n    See Also\n    --------\n    color_palette : build a color palette or set the color cycle temporarily\n                    in a ``with`` statement.\n    set_context : set parameters to scale plot elements\n    set_style : set the default parameters for figure style\n\n    \"\"\"\n    colors = palettes.color_palette(palette, n_colors, desat)\n    cyl = cycler('color', colors)\n    mpl.rcParams['axes.prop_cycle'] = cyl\n    if color_codes:\n        try:\n            palettes.set_color_codes(palette)\n        except (ValueError, TypeError):\n            pass\n"},{"col":4,"comment":"Draw the violins onto `ax`.","endLoc":1311,"header":"def draw_violins(self, ax)","id":3121,"name":"draw_violins","nodeType":"Function","startLoc":1138,"text":"def draw_violins(self, ax):\n        \"\"\"Draw the violins onto `ax`.\"\"\"\n        fill_func = ax.fill_betweenx if self.orient == \"v\" else ax.fill_between\n        for i, group_data in enumerate(self.plot_data):\n\n            kws = dict(edgecolor=self.gray, linewidth=self.linewidth)\n\n            # Option 1: we have a single level of grouping\n            # --------------------------------------------\n\n            if self.plot_hues is None:\n\n                support, density = self.support[i], self.density[i]\n\n                # Handle special case of no observations in this bin\n                if support.size == 0:\n                    continue\n\n                # Handle special case of a single observation\n                elif support.size == 1:\n                    val = support.item()\n                    d = density.item()\n                    self.draw_single_observation(ax, i, val, d)\n                    continue\n\n                # Draw the violin for this group\n                grid = np.ones(self.gridsize) * i\n                fill_func(support,\n                          grid - density * self.dwidth,\n                          grid + density * self.dwidth,\n                          facecolor=self.colors[i],\n                          **kws)\n\n                # Draw the interior representation of the data\n                if self.inner is None:\n                    continue\n\n                # Get a nan-free vector of datapoints\n                violin_data = remove_na(group_data)\n\n                # Draw box and whisker information\n                if self.inner.startswith(\"box\"):\n                    self.draw_box_lines(ax, violin_data, i)\n\n                # Draw quartile lines\n                elif self.inner.startswith(\"quart\"):\n                    self.draw_quartiles(ax, violin_data, support, density, i)\n\n                # Draw stick observations\n                elif self.inner.startswith(\"stick\"):\n                    self.draw_stick_lines(ax, violin_data, support, density, i)\n\n                # Draw point observations\n                elif self.inner.startswith(\"point\"):\n                    self.draw_points(ax, violin_data, i)\n\n            # Option 2: we have nested grouping by a hue variable\n            # ---------------------------------------------------\n\n            else:\n                offsets = self.hue_offsets\n                for j, hue_level in enumerate(self.hue_names):\n\n                    support, density = self.support[i][j], self.density[i][j]\n                    kws[\"facecolor\"] = self.colors[j]\n\n                    # Add legend data, but just for one set of violins\n                    if not i:\n                        self.add_legend_data(ax, self.colors[j], hue_level)\n\n                    # Handle the special case where we have no observations\n                    if support.size == 0:\n                        continue\n\n                    # Handle the special case where we have one observation\n                    elif support.size == 1:\n                        val = support.item()\n                        d = density.item()\n                        if self.split:\n                            d = d / 2\n                        at_group = i + offsets[j]\n                        self.draw_single_observation(ax, at_group, val, d)\n                        continue\n\n                    # Option 2a: we are drawing a single split violin\n                    # -----------------------------------------------\n\n                    if self.split:\n\n                        grid = np.ones(self.gridsize) * i\n                        if j:\n                            fill_func(support,\n                                      grid,\n                                      grid + density * self.dwidth,\n                                      **kws)\n                        else:\n                            fill_func(support,\n                                      grid - density * self.dwidth,\n                                      grid,\n                                      **kws)\n\n                        # Draw the interior representation of the data\n                        if self.inner is None:\n                            continue\n\n                        # Get a nan-free vector of datapoints\n                        hue_mask = self.plot_hues[i] == hue_level\n                        violin_data = remove_na(group_data[hue_mask])\n\n                        # Draw quartile lines\n                        if self.inner.startswith(\"quart\"):\n                            self.draw_quartiles(ax, violin_data,\n                                                support, density, i,\n                                                [\"left\", \"right\"][j])\n\n                        # Draw stick observations\n                        elif self.inner.startswith(\"stick\"):\n                            self.draw_stick_lines(ax, violin_data,\n                                                  support, density, i,\n                                                  [\"left\", \"right\"][j])\n\n                        # The box and point interior plots are drawn for\n                        # all data at the group level, so we just do that once\n                        if j and any(self.plot_hues[0] == hue_level):\n                            continue\n\n                        # Get the whole vector for this group level\n                        violin_data = remove_na(group_data)\n\n                        # Draw box and whisker information\n                        if self.inner.startswith(\"box\"):\n                            self.draw_box_lines(ax, violin_data, i)\n\n                        # Draw point observations\n                        elif self.inner.startswith(\"point\"):\n                            self.draw_points(ax, violin_data, i)\n\n                    # Option 2b: we are drawing full nested violins\n                    # -----------------------------------------------\n\n                    else:\n                        grid = np.ones(self.gridsize) * (i + offsets[j])\n                        fill_func(support,\n                                  grid - density * self.dwidth,\n                                  grid + density * self.dwidth,\n                                  **kws)\n\n                        # Draw the interior representation\n                        if self.inner is None:\n                            continue\n\n                        # Get a nan-free vector of datapoints\n                        hue_mask = self.plot_hues[i] == hue_level\n                        violin_data = remove_na(group_data[hue_mask])\n\n                        # Draw box and whisker information\n                        if self.inner.startswith(\"box\"):\n                            self.draw_box_lines(ax, violin_data, i + offsets[j])\n\n                        # Draw quartile lines\n                        elif self.inner.startswith(\"quart\"):\n                            self.draw_quartiles(ax, violin_data,\n                                                support, density,\n                                                i + offsets[j])\n\n                        # Draw stick observations\n                        elif self.inner.startswith(\"stick\"):\n                            self.draw_stick_lines(ax, violin_data,\n                                                  support, density,\n                                                  i + offsets[j])\n\n                        # Draw point observations\n                        elif self.inner.startswith(\"point\"):\n                            self.draw_points(ax, violin_data, i + offsets[j])"},{"className":"_RCAesthetics","col":0,"comment":"null","endLoc":487,"id":3122,"nodeType":"Class","startLoc":473,"text":"class _RCAesthetics(dict):\n    def __enter__(self):\n        rc = mpl.rcParams\n        self._orig = {k: rc[k] for k in self._keys}\n        self._set(self)\n\n    def __exit__(self, exc_type, exc_value, exc_tb):\n        self._set(self._orig)\n\n    def __call__(self, func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            with self:\n                return func(*args, **kwargs)\n        return wrapper"},{"className":"dict","col":0,"comment":"null","endLoc":1134,"id":3123,"nodeType":"Class","startLoc":1063,"text":"class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):\n    # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics\n    # Also multiprocessing.managers.SyncManager.dict()\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ...\n    @overload\n    def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ...\n    @overload\n    def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ...\n    @overload\n    def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ...\n    @overload\n    def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ...\n    # Next two overloads are for dict(string.split(sep) for string in iterable)\n    # Cannot be Iterable[Sequence[_T]] or otherwise dict([\"foo\", \"bar\", \"baz\"]) is not an error\n    @overload\n    def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ...\n    @overload\n    def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ...\n    def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...\n    def copy(self) -> dict[_KT, _VT]: ...\n    def keys(self) -> dict_keys[_KT, _VT]: ...\n    def values(self) -> dict_values[_KT, _VT]: ...\n    def items(self) -> dict_items[_KT, _VT]: ...\n    # Signature of `dict.fromkeys` should be kept identical to `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections`\n    # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system.\n    # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963.\n    @classmethod\n    @overload\n    def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]: ...\n    @classmethod\n    @overload\n    def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ...\n    # Positional-only in dict, but not in MutableMapping\n    @overload  # type: ignore[override]\n    def get(self, __key: _KT) -> _VT | None: ...\n    @overload\n    def get(self, __key: _KT, __default: _VT) -> _VT: ...\n    @overload\n    def get(self, __key: _KT, __default: _T) -> _VT | _T: ...\n    @overload\n    def pop(self, __key: _KT) -> _VT: ...\n    @overload\n    def pop(self, __key: _KT, __default: _VT) -> _VT: ...\n    @overload\n    def pop(self, __key: _KT, __default: _T) -> _VT | _T: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, __key: _KT) -> _VT: ...\n    def __setitem__(self, __key: _KT, __value: _VT) -> None: ...\n    def __delitem__(self, __key: _KT) -> None: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def __eq__(self, __value: object) -> bool: ...\n    if sys.version_info >= (3, 8):\n        def __reversed__(self) -> Iterator[_KT]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, __item: Any) -> GenericAlias: ...\n        @overload\n        def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ...\n        @overload\n        def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ...\n        @overload\n        def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ...\n        @overload\n        def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ...\n        # dict.__ior__ should be kept roughly in line with MutableMapping.update()\n        @overload  # type: ignore[misc]\n        def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n        @overload\n        def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ..."},{"col":4,"comment":"null","endLoc":1588,"header":"def test_plot(self, long_df, repeated_df)","id":3124,"name":"test_plot","nodeType":"Function","startLoc":1501,"text":"def test_plot(self, long_df, repeated_df):\n\n        f, ax = plt.subplots()\n\n        p = _ScatterPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n        p.plot(ax, {})\n        points = ax.collections[0]\n        assert_array_equal(points.get_offsets(), long_df[[\"x\", \"y\"]].to_numpy())\n\n        ax.clear()\n        p.plot(ax, {\"color\": \"k\", \"label\": \"test\"})\n        points = ax.collections[0]\n        assert same_color(points.get_facecolor(), \"k\")\n        assert points.get_label() == \"test\"\n\n        p = _ScatterPlotter(\n            data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n        )\n\n        ax.clear()\n        p.plot(ax, {})\n        points = ax.collections[0]\n        expected_colors = p._hue_map(p.plot_data[\"hue\"])\n        assert same_color(points.get_facecolors(), expected_colors)\n\n        p = _ScatterPlotter(\n            data=long_df,\n            variables=dict(x=\"x\", y=\"y\", style=\"c\"),\n        )\n        p.map_style(markers=[\"+\", \"x\"])\n\n        ax.clear()\n        color = (1, .3, .8)\n        p.plot(ax, {\"color\": color})\n        points = ax.collections[0]\n        assert same_color(points.get_edgecolors(), [color])\n\n        p = _ScatterPlotter(\n            data=long_df, variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n        )\n\n        ax.clear()\n        p.plot(ax, {})\n        points = ax.collections[0]\n        expected_sizes = p._size_map(p.plot_data[\"size\"])\n        assert_array_equal(points.get_sizes(), expected_sizes)\n\n        p = _ScatterPlotter(\n            data=long_df,\n            variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n        )\n        p.map_style(markers=True)\n\n        ax.clear()\n        p.plot(ax, {})\n        points = ax.collections[0]\n        expected_colors = p._hue_map(p.plot_data[\"hue\"])\n        expected_paths = p._style_map(p.plot_data[\"style\"], \"path\")\n        assert same_color(points.get_facecolors(), expected_colors)\n        assert self.paths_equal(points.get_paths(), expected_paths)\n\n        p = _ScatterPlotter(\n            data=long_df,\n            variables=dict(x=\"x\", y=\"y\", hue=\"a\", style=\"b\"),\n        )\n        p.map_style(markers=True)\n\n        ax.clear()\n        p.plot(ax, {})\n        points = ax.collections[0]\n        expected_colors = p._hue_map(p.plot_data[\"hue\"])\n        expected_paths = p._style_map(p.plot_data[\"style\"], \"path\")\n        assert same_color(points.get_facecolors(), expected_colors)\n        assert self.paths_equal(points.get_paths(), expected_paths)\n\n        x_str = long_df[\"x\"].astype(str)\n        p = _ScatterPlotter(\n            data=long_df, variables=dict(x=\"x\", y=\"y\", hue=x_str),\n        )\n        ax.clear()\n        p.plot(ax, {})\n\n        p = _ScatterPlotter(\n            data=long_df, variables=dict(x=\"x\", y=\"y\", size=x_str),\n        )\n        ax.clear()\n        p.plot(ax, {})"},{"col":4,"comment":"null","endLoc":1084,"header":"def __new__(cls, *args: Any, **kwargs: Any) -> Self","id":3125,"name":"__new__","nodeType":"Function","startLoc":1084,"text":"def __new__(cls, *args: Any, **kwargs: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":1094,"header":"@classmethod\n    @overload\n    def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]","id":3126,"name":"fromkeys","nodeType":"Function","startLoc":1092,"text":"@classmethod\n    @overload\n    def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]: ..."},{"col":4,"comment":"null","endLoc":1097,"header":"@classmethod\n    @overload\n    def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]","id":3127,"name":"fromkeys","nodeType":"Function","startLoc":1095,"text":"@classmethod\n    @overload\n    def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ..."},{"col":4,"comment":"null","endLoc":1111,"header":"def __len__(self) -> int","id":3128,"name":"__len__","nodeType":"Function","startLoc":1111,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1112,"header":"def __getitem__(self, __key: _KT) -> _VT","id":3129,"name":"__getitem__","nodeType":"Function","startLoc":1112,"text":"def __getitem__(self, __key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1113,"header":"def __setitem__(self, __key: _KT, __value: _VT) -> None","id":3130,"name":"__setitem__","nodeType":"Function","startLoc":1113,"text":"def __setitem__(self, __key: _KT, __value: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1114,"header":"def __delitem__(self, __key: _KT) -> None","id":3131,"name":"__delitem__","nodeType":"Function","startLoc":1114,"text":"def __delitem__(self, __key: _KT) -> None: ..."},{"col":4,"comment":"null","endLoc":1115,"header":"def __iter__(self) -> Iterator[_KT]","id":3132,"name":"__iter__","nodeType":"Function","startLoc":1115,"text":"def __iter__(self) -> Iterator[_KT]: ..."},{"col":4,"comment":"null","endLoc":1116,"header":"def __eq__(self, __value: object) -> bool","id":3133,"name":"__eq__","nodeType":"Function","startLoc":1116,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":8,"comment":"null","endLoc":1118,"header":"def __reversed__(self) -> Iterator[_KT]","id":3134,"name":"__reversed__","nodeType":"Function","startLoc":1118,"text":"def __reversed__(self) -> Iterator[_KT]: ..."},{"col":8,"comment":"null","endLoc":1121,"header":"def __class_getitem__(cls, __item: Any) -> GenericAlias","id":3135,"name":"__class_getitem__","nodeType":"Function","startLoc":1121,"text":"def __class_getitem__(cls, __item: Any) -> GenericAlias: ..."},{"col":8,"comment":"null","endLoc":1123,"header":"@overload\n        def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]","id":3136,"name":"__or__","nodeType":"Function","startLoc":1122,"text":"@overload\n        def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ..."},{"col":8,"comment":"null","endLoc":1125,"header":"@overload\n        def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]","id":3137,"name":"__or__","nodeType":"Function","startLoc":1124,"text":"@overload\n        def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":1127,"header":"@overload\n        def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]","id":3138,"name":"__ror__","nodeType":"Function","startLoc":1126,"text":"@overload\n        def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ..."},{"col":8,"comment":"null","endLoc":1129,"header":"@overload\n        def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]","id":3139,"name":"__ror__","nodeType":"Function","startLoc":1128,"text":"@overload\n        def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":1132,"header":"@overload  # type: ignore[misc]\n        def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self","id":3140,"name":"__ior__","nodeType":"Function","startLoc":1131,"text":"@overload  # type: ignore[misc]\n        def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ..."},{"col":8,"comment":"null","endLoc":1134,"header":"@overload\n        def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self","id":3141,"name":"__ior__","nodeType":"Function","startLoc":1133,"text":"@overload\n        def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ..."},{"attributeType":"None","col":4,"comment":"null","endLoc":1119,"id":3142,"name":"__hash__","nodeType":"Attribute","startLoc":1119,"text":"__hash__"},{"col":4,"comment":"null","endLoc":74,"header":"def test_separate_colors_mapped(self)","id":3143,"name":"test_separate_colors_mapped","nodeType":"Function","startLoc":62,"text":"def test_separate_colors_mapped(self):\n\n        x = y = [1, 2, 3, 4]\n        c = [\"a\", \"a\", \"b\", \"b\"]\n        d = [\"x\", \"y\", \"x\", \"y\"]\n        m = Path()\n        p = Plot(x=x, y=y, color=c, fillcolor=d).add(m).plot()\n        ax = p._figure.axes[0]\n        colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        for i, line in enumerate(ax.get_lines()):\n            assert same_color(line.get_color(), colors[i // 2])\n            assert same_color(line.get_markeredgecolor(), colors[i // 2])\n            assert same_color(line.get_markerfacecolor(), colors[i % 2])"},{"col":4,"comment":"null","endLoc":477,"header":"def __enter__(self)","id":3144,"name":"__enter__","nodeType":"Function","startLoc":474,"text":"def __enter__(self):\n        rc = mpl.rcParams\n        self._orig = {k: rc[k] for k in self._keys}\n        self._set(self)"},{"col":4,"comment":"null","endLoc":480,"header":"def __exit__(self, exc_type, exc_value, exc_tb)","id":3145,"name":"__exit__","nodeType":"Function","startLoc":479,"text":"def __exit__(self, exc_type, exc_value, exc_tb):\n        self._set(self._orig)"},{"col":4,"comment":"null","endLoc":80,"header":"def test_clip(self, rng)","id":3146,"name":"test_clip","nodeType":"Function","startLoc":72,"text":"def test_clip(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        clip = -1, 1\n        kde = KDE(clip=clip)\n        _, support = kde(x)\n\n        assert support.min() >= clip[0]\n        assert support.max() <= clip[1]"},{"col":4,"comment":"null","endLoc":487,"header":"def __call__(self, func)","id":3147,"name":"__call__","nodeType":"Function","startLoc":482,"text":"def __call__(self, func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            with self:\n                return func(*args, **kwargs)\n        return wrapper"},{"col":4,"comment":"null","endLoc":84,"header":"def test_color_with_alpha(self)","id":3149,"name":"test_color_with_alpha","nodeType":"Function","startLoc":76,"text":"def test_color_with_alpha(self):\n\n        x = y = [1, 2, 3]\n        m = Path(color=(.4, .9, .2, .5), fillcolor=(.2, .2, .3, .9))\n        p = Plot(x=x, y=y).add(m).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert same_color(line.get_color(), m.color)\n        assert same_color(line.get_markeredgecolor(), m.color)\n        assert same_color(line.get_markerfacecolor(), m.fillcolor)"},{"attributeType":"dict","col":8,"comment":"null","endLoc":476,"id":3150,"name":"_orig","nodeType":"Attribute","startLoc":476,"text":"self._orig"},{"col":4,"comment":"null","endLoc":87,"header":"def test_density_normalization(self, rng)","id":3151,"name":"test_density_normalization","nodeType":"Function","startLoc":82,"text":"def test_density_normalization(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n        kde = KDE()\n        density, support = kde(x)\n        assert self.integrate(density, support) == pytest.approx(1, abs=1e-5)"},{"className":"_AxesStyle","col":0,"comment":"Light wrapper on a dict to set style temporarily.","endLoc":493,"id":3152,"nodeType":"Class","startLoc":490,"text":"class _AxesStyle(_RCAesthetics):\n    \"\"\"Light wrapper on a dict to set style temporarily.\"\"\"\n    _keys = _style_keys\n    _set = staticmethod(set_style)"},{"attributeType":"list","col":4,"comment":"null","endLoc":492,"id":3153,"name":"_keys","nodeType":"Attribute","startLoc":492,"text":"_keys"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":493,"id":3154,"name":"_set","nodeType":"Attribute","startLoc":493,"text":"_set"},{"col":4,"comment":"null","endLoc":94,"header":"def test_color_and_alpha(self)","id":3155,"name":"test_color_and_alpha","nodeType":"Function","startLoc":86,"text":"def test_color_and_alpha(self):\n\n        x = y = [1, 2, 3]\n        m = Path(color=(.4, .9, .2), fillcolor=(.2, .2, .3), alpha=.5)\n        p = Plot(x=x, y=y).add(m).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert same_color(line.get_color(), to_rgba(m.color, m.alpha))\n        assert same_color(line.get_markeredgecolor(), to_rgba(m.color, m.alpha))\n        assert same_color(line.get_markerfacecolor(), to_rgba(m.fillcolor, m.alpha))"},{"col":4,"comment":"null","endLoc":96,"header":"@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_cumulative(self, rng)","id":3156,"name":"test_cumulative","nodeType":"Function","startLoc":89,"text":"@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_cumulative(self, rng):\n\n        x = rng.normal(0, 3, 1000)\n        kde = KDE(cumulative=True)\n        density, _ = kde(x)\n        assert density[0] == pytest.approx(0, abs=1e-5)\n        assert density[-1] == pytest.approx(1, abs=1e-5)"},{"col":4,"comment":"null","endLoc":104,"header":"def test_cached_support(self, rng)","id":3157,"name":"test_cached_support","nodeType":"Function","startLoc":98,"text":"def test_cached_support(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde = KDE()\n        kde.define_support(x)\n        _, support = kde(x[(x > -1) & (x < 1)])\n        assert_array_equal(support, kde.support)"},{"col":4,"comment":"null","endLoc":115,"header":"def test_bw_method(self, rng)","id":3158,"name":"test_bw_method","nodeType":"Function","startLoc":106,"text":"def test_bw_method(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde1 = KDE(bw_method=.2)\n        kde2 = KDE(bw_method=2)\n\n        d1, _ = kde1(x)\n        d2, _ = kde2(x)\n\n        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()"},{"col":4,"comment":"null","endLoc":464,"header":"def _str_summary(self)","id":3159,"name":"_str_summary","nodeType":"Function","startLoc":460,"text":"def _str_summary(self):\n        if self['Summary']:\n            return self['Summary'] + ['']\n        else:\n            return []"},{"col":4,"comment":"null","endLoc":470,"header":"def _str_extended_summary(self)","id":3160,"name":"_str_extended_summary","nodeType":"Function","startLoc":466,"text":"def _str_extended_summary(self):\n        if self['Extended Summary']:\n            return self['Extended Summary'] + ['']\n        else:\n            return []"},{"col":4,"comment":"null","endLoc":486,"header":"def _str_param_list(self, name)","id":3161,"name":"_str_param_list","nodeType":"Function","startLoc":472,"text":"def _str_param_list(self, name):\n        out = []\n        if self[name]:\n            out += self._str_header(name)\n            for param in self[name]:\n                parts = []\n                if param.name:\n                    parts.append(param.name)\n                if param.type:\n                    parts.append(param.type)\n                out += [' : '.join(parts)]\n                if param.desc and ''.join(param.desc).strip():\n                    out += self._str_indent(param.desc)\n            out += ['']\n        return out"},{"fileName":"palettes.py","filePath":"seaborn","id":3162,"nodeType":"File","text":"import colorsys\nfrom itertools import cycle\n\nimport numpy as np\nimport matplotlib as mpl\n\nfrom .external import husl\n\nfrom .utils import desaturate, get_color_cycle\nfrom .colors import xkcd_rgb, crayons\nfrom ._compat import get_colormap\n\n\n__all__ = [\"color_palette\", \"hls_palette\", \"husl_palette\", \"mpl_palette\",\n           \"dark_palette\", \"light_palette\", \"diverging_palette\",\n           \"blend_palette\", \"xkcd_palette\", \"crayon_palette\",\n           \"cubehelix_palette\", \"set_color_codes\"]\n\n\nSEABORN_PALETTES = dict(\n    deep=[\"#4C72B0\", \"#DD8452\", \"#55A868\", \"#C44E52\", \"#8172B3\",\n          \"#937860\", \"#DA8BC3\", \"#8C8C8C\", \"#CCB974\", \"#64B5CD\"],\n    deep6=[\"#4C72B0\", \"#55A868\", \"#C44E52\",\n           \"#8172B3\", \"#CCB974\", \"#64B5CD\"],\n    muted=[\"#4878D0\", \"#EE854A\", \"#6ACC64\", \"#D65F5F\", \"#956CB4\",\n           \"#8C613C\", \"#DC7EC0\", \"#797979\", \"#D5BB67\", \"#82C6E2\"],\n    muted6=[\"#4878D0\", \"#6ACC64\", \"#D65F5F\",\n            \"#956CB4\", \"#D5BB67\", \"#82C6E2\"],\n    pastel=[\"#A1C9F4\", \"#FFB482\", \"#8DE5A1\", \"#FF9F9B\", \"#D0BBFF\",\n            \"#DEBB9B\", \"#FAB0E4\", \"#CFCFCF\", \"#FFFEA3\", \"#B9F2F0\"],\n    pastel6=[\"#A1C9F4\", \"#8DE5A1\", \"#FF9F9B\",\n             \"#D0BBFF\", \"#FFFEA3\", \"#B9F2F0\"],\n    bright=[\"#023EFF\", \"#FF7C00\", \"#1AC938\", \"#E8000B\", \"#8B2BE2\",\n            \"#9F4800\", \"#F14CC1\", \"#A3A3A3\", \"#FFC400\", \"#00D7FF\"],\n    bright6=[\"#023EFF\", \"#1AC938\", \"#E8000B\",\n             \"#8B2BE2\", \"#FFC400\", \"#00D7FF\"],\n    dark=[\"#001C7F\", \"#B1400D\", \"#12711C\", \"#8C0800\", \"#591E71\",\n          \"#592F0D\", \"#A23582\", \"#3C3C3C\", \"#B8850A\", \"#006374\"],\n    dark6=[\"#001C7F\", \"#12711C\", \"#8C0800\",\n           \"#591E71\", \"#B8850A\", \"#006374\"],\n    colorblind=[\"#0173B2\", \"#DE8F05\", \"#029E73\", \"#D55E00\", \"#CC78BC\",\n                \"#CA9161\", \"#FBAFE4\", \"#949494\", \"#ECE133\", \"#56B4E9\"],\n    colorblind6=[\"#0173B2\", \"#029E73\", \"#D55E00\",\n                 \"#CC78BC\", \"#ECE133\", \"#56B4E9\"]\n)\n\n\nMPL_QUAL_PALS = {\n    \"tab10\": 10, \"tab20\": 20, \"tab20b\": 20, \"tab20c\": 20,\n    \"Set1\": 9, \"Set2\": 8, \"Set3\": 12,\n    \"Accent\": 8, \"Paired\": 12,\n    \"Pastel1\": 9, \"Pastel2\": 8, \"Dark2\": 8,\n}\n\n\nQUAL_PALETTE_SIZES = MPL_QUAL_PALS.copy()\nQUAL_PALETTE_SIZES.update({k: len(v) for k, v in SEABORN_PALETTES.items()})\nQUAL_PALETTES = list(QUAL_PALETTE_SIZES.keys())\n\n\nclass _ColorPalette(list):\n    \"\"\"Set the color palette in a with statement, otherwise be a list.\"\"\"\n    def __enter__(self):\n        \"\"\"Open the context.\"\"\"\n        from .rcmod import set_palette\n        self._orig_palette = color_palette()\n        set_palette(self)\n        return self\n\n    def __exit__(self, *args):\n        \"\"\"Close the context.\"\"\"\n        from .rcmod import set_palette\n        set_palette(self._orig_palette)\n\n    def as_hex(self):\n        \"\"\"Return a color palette with hex codes instead of RGB values.\"\"\"\n        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]\n        return _ColorPalette(hex)\n\n    def _repr_html_(self):\n        \"\"\"Rich display of the color palette in an HTML frontend.\"\"\"\n        s = 55\n        n = len(self)\n        html = f''\n        for i, c in enumerate(self.as_hex()):\n            html += (\n                f''\n            )\n        html += ''\n        return html\n\n\ndef _patch_colormap_display():\n    \"\"\"Simplify the rich display of matplotlib color maps in a notebook.\"\"\"\n    def _repr_png_(self):\n        \"\"\"Generate a PNG representation of the Colormap.\"\"\"\n        import io\n        from PIL import Image\n        import numpy as np\n        IMAGE_SIZE = (400, 50)\n        X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1))\n        pixels = self(X, bytes=True)\n        png_bytes = io.BytesIO()\n        Image.fromarray(pixels).save(png_bytes, format='png')\n        return png_bytes.getvalue()\n\n    def _repr_html_(self):\n        \"\"\"Generate an HTML representation of the Colormap.\"\"\"\n        import base64\n        png_bytes = self._repr_png_()\n        png_base64 = base64.b64encode(png_bytes).decode('ascii')\n        return ('')\n\n    mpl.colors.Colormap._repr_png_ = _repr_png_\n    mpl.colors.Colormap._repr_html_ = _repr_html_\n\n\ndef color_palette(palette=None, n_colors=None, desat=None, as_cmap=False):\n    \"\"\"Return a list of colors or continuous colormap defining a palette.\n\n    Possible ``palette`` values include:\n        - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)\n        - Name of matplotlib colormap\n        - 'husl' or 'hls'\n        - 'ch:'\n        - 'light:', 'dark:', 'blend:,',\n        - A sequence of colors in any format matplotlib accepts\n\n    Calling this function with ``palette=None`` will return the current\n    matplotlib color cycle.\n\n    This function can also be used in a ``with`` statement to temporarily\n    set the color cycle for a plot or set of plots.\n\n    See the :ref:`tutorial ` for more information.\n\n    Parameters\n    ----------\n    palette : None, string, or sequence, optional\n        Name of palette or None to return current palette. If a sequence, input\n        colors are used but possibly cycled and desaturated.\n    n_colors : int, optional\n        Number of colors in the palette. If ``None``, the default will depend\n        on how ``palette`` is specified. Named palettes default to 6 colors,\n        but grabbing the current palette or passing in a list of colors will\n        not change the number of colors unless this is specified. Asking for\n        more colors than exist in the palette will cause it to cycle. Ignored\n        when ``as_cmap`` is True.\n    desat : float, optional\n        Proportion to desaturate each color by.\n    as_cmap : bool\n        If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n    Returns\n    -------\n    list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    set_palette : Set the default color cycle for all plots.\n    set_color_codes : Reassign color codes like ``\"b\"``, ``\"g\"``, etc. to\n                      colors from one of the seaborn palettes.\n\n    Examples\n    --------\n\n    .. include:: ../docstrings/color_palette.rst\n\n    \"\"\"\n    if palette is None:\n        palette = get_color_cycle()\n        if n_colors is None:\n            n_colors = len(palette)\n\n    elif not isinstance(palette, str):\n        palette = palette\n        if n_colors is None:\n            n_colors = len(palette)\n    else:\n\n        if n_colors is None:\n            # Use all colors in a qualitative palette or 6 of another kind\n            n_colors = QUAL_PALETTE_SIZES.get(palette, 6)\n\n        if palette in SEABORN_PALETTES:\n            # Named \"seaborn variant\" of matplotlib default color cycle\n            palette = SEABORN_PALETTES[palette]\n\n        elif palette == \"hls\":\n            # Evenly spaced colors in cylindrical RGB space\n            palette = hls_palette(n_colors, as_cmap=as_cmap)\n\n        elif palette == \"husl\":\n            # Evenly spaced colors in cylindrical Lab space\n            palette = husl_palette(n_colors, as_cmap=as_cmap)\n\n        elif palette.lower() == \"jet\":\n            # Paternalism\n            raise ValueError(\"No.\")\n\n        elif palette.startswith(\"ch:\"):\n            # Cubehelix palette with params specified in string\n            args, kwargs = _parse_cubehelix_args(palette)\n            palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap)\n\n        elif palette.startswith(\"light:\"):\n            # light palette to color specified in string\n            _, color = palette.split(\":\")\n            reverse = color.endswith(\"_r\")\n            if reverse:\n                color = color[:-2]\n            palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)\n\n        elif palette.startswith(\"dark:\"):\n            # light palette to color specified in string\n            _, color = palette.split(\":\")\n            reverse = color.endswith(\"_r\")\n            if reverse:\n                color = color[:-2]\n            palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)\n\n        elif palette.startswith(\"blend:\"):\n            # blend palette between colors specified in string\n            _, colors = palette.split(\":\")\n            colors = colors.split(\",\")\n            palette = blend_palette(colors, n_colors, as_cmap=as_cmap)\n\n        else:\n            try:\n                # Perhaps a named matplotlib colormap?\n                palette = mpl_palette(palette, n_colors, as_cmap=as_cmap)\n            except (ValueError, KeyError):  # Error class changed in mpl36\n                raise ValueError(f\"{palette} is not a valid palette name\")\n\n    if desat is not None:\n        palette = [desaturate(c, desat) for c in palette]\n\n    if not as_cmap:\n\n        # Always return as many colors as we asked for\n        pal_cycle = cycle(palette)\n        palette = [next(pal_cycle) for _ in range(n_colors)]\n\n        # Always return in r, g, b tuple format\n        try:\n            palette = map(mpl.colors.colorConverter.to_rgb, palette)\n            palette = _ColorPalette(palette)\n        except ValueError:\n            raise ValueError(f\"Could not generate a palette for {palette}\")\n\n    return palette\n\n\ndef hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False):  # noqa\n    \"\"\"\n    Return hues with constant lightness and saturation in the HLS system.\n\n    The hues are evenly sampled along a circular path. The resulting palette will be\n    appropriate for categorical or cyclical data.\n\n    The `h`, `l`, and `s` values should be between 0 and 1.\n\n    .. note::\n        While the separation of the resulting colors will be mathematically\n        constant, the HLS system does not construct a perceptually-uniform space,\n        so their apparent intensity will vary.\n\n    Parameters\n    ----------\n    n_colors : int\n        Number of colors in the palette.\n    h : float\n        The value of the first hue.\n    l : float\n        The lightness value.\n    s : float\n        The saturation intensity.\n    as_cmap : bool\n        If True, return a matplotlib colormap object.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    husl_palette : Make a palette using evenly spaced hues in the HUSL system.\n\n    Examples\n    --------\n    .. include:: ../docstrings/hls_palette.rst\n\n    \"\"\"\n    if as_cmap:\n        n_colors = 256\n    hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]\n    hues += h\n    hues %= 1\n    hues -= hues.astype(int)\n    palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]\n    if as_cmap:\n        return mpl.colors.ListedColormap(palette, \"hls\")\n    else:\n        return _ColorPalette(palette)\n\n\ndef husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False):  # noqa\n    \"\"\"\n    Return hues with constant lightness and saturation in the HUSL system.\n\n    The hues are evenly sampled along a circular path. The resulting palette will be\n    appropriate for categorical or cyclical data.\n\n    The `h`, `l`, and `s` values should be between 0 and 1.\n\n    This function is similar to :func:`hls_palette`, but it uses a nonlinear color\n    space that is more perceptually uniform.\n\n    Parameters\n    ----------\n    n_colors : int\n        Number of colors in the palette.\n    h : float\n        The value of the first hue.\n    l : float\n        The lightness value.\n    s : float\n        The saturation intensity.\n    as_cmap : bool\n        If True, return a matplotlib colormap object.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    hls_palette : Make a palette using evenly spaced hues in the HSL system.\n\n    Examples\n    --------\n    .. include:: ../docstrings/husl_palette.rst\n\n    \"\"\"\n    if as_cmap:\n        n_colors = 256\n    hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]\n    hues += h\n    hues %= 1\n    hues *= 359\n    s *= 99\n    l *= 99  # noqa\n    palette = [_color_to_rgb((h_i, s, l), input=\"husl\") for h_i in hues]\n    if as_cmap:\n        return mpl.colors.ListedColormap(palette, \"hsl\")\n    else:\n        return _ColorPalette(palette)\n\n\ndef mpl_palette(name, n_colors=6, as_cmap=False):\n    \"\"\"\n    Return a palette or colormap from the matplotlib registry.\n\n    For continuous palettes, evenly-spaced discrete samples are chosen while\n    excluding the minimum and maximum value in the colormap to provide better\n    contrast at the extremes.\n\n    For qualitative palettes (e.g. those from colorbrewer), exact values are\n    indexed (rather than interpolated), but fewer than `n_colors` can be returned\n    if the palette does not define that many.\n\n    Parameters\n    ----------\n    name : string\n        Name of the palette. This should be a named matplotlib colormap.\n    n_colors : int\n        Number of discrete colors in the palette.\n\n    Returns\n    -------\n    list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    Examples\n    --------\n    .. include: ../docstrings/mpl_palette.rst\n\n    \"\"\"\n    if name.endswith(\"_d\"):\n        sub_name = name[:-2]\n        if sub_name.endswith(\"_r\"):\n            reverse = True\n            sub_name = sub_name[:-2]\n        else:\n            reverse = False\n        pal = color_palette(sub_name, 2) + [\"#333333\"]\n        if reverse:\n            pal = pal[::-1]\n        cmap = blend_palette(pal, n_colors, as_cmap=True)\n    else:\n        cmap = get_colormap(name)\n\n    if name in MPL_QUAL_PALS:\n        bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors]\n    else:\n        bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1]\n    palette = list(map(tuple, cmap(bins)[:, :3]))\n\n    if as_cmap:\n        return cmap\n    else:\n        return _ColorPalette(palette)\n\n\ndef _color_to_rgb(color, input):\n    \"\"\"Add some more flexibility to color choices.\"\"\"\n    if input == \"hls\":\n        color = colorsys.hls_to_rgb(*color)\n    elif input == \"husl\":\n        color = husl.husl_to_rgb(*color)\n        color = tuple(np.clip(color, 0, 1))\n    elif input == \"xkcd\":\n        color = xkcd_rgb[color]\n\n    return mpl.colors.to_rgb(color)\n\n\ndef dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input=\"rgb\"):\n    \"\"\"Make a sequential palette that blends from dark to ``color``.\n\n    This kind of palette is good for data that range between relatively\n    uninteresting low values and interesting high values.\n\n    The ``color`` parameter can be specified in a number of ways, including\n    all options for defining a color in matplotlib and several additional\n    color spaces that are handled by seaborn. You can also use the database\n    of named colors from the XKCD color survey.\n\n    If you are using the IPython notebook, you can also choose this palette\n    interactively with the :func:`choose_dark_palette` function.\n\n    Parameters\n    ----------\n    color : base color for high values\n        hex, rgb-tuple, or html color name\n    n_colors : int, optional\n        number of colors in the palette\n    reverse : bool, optional\n        if True, reverse the direction of the blend\n    as_cmap : bool, optional\n        If True, return a :class:`matplotlib.colors.ListedColormap`.\n    input : {'rgb', 'hls', 'husl', xkcd'}\n        Color space to interpret the input color. The first three options\n        apply to tuple inputs and the latter applies to string inputs.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    light_palette : Create a sequential palette with bright low values.\n    diverging_palette : Create a diverging palette with two colors.\n\n    Examples\n    --------\n    .. include:: ../docstrings/dark_palette.rst\n\n    \"\"\"\n    rgb = _color_to_rgb(color, input)\n    h, s, l = husl.rgb_to_husl(*rgb)\n    gray_s, gray_l = .15 * s, 15\n    gray = _color_to_rgb((h, gray_s, gray_l), input=\"husl\")\n    colors = [rgb, gray] if reverse else [gray, rgb]\n    return blend_palette(colors, n_colors, as_cmap)\n\n\ndef light_palette(color, n_colors=6, reverse=False, as_cmap=False, input=\"rgb\"):\n    \"\"\"Make a sequential palette that blends from light to ``color``.\n\n    The ``color`` parameter can be specified in a number of ways, including\n    all options for defining a color in matplotlib and several additional\n    color spaces that are handled by seaborn. You can also use the database\n    of named colors from the XKCD color survey.\n\n    If you are using a Jupyter notebook, you can also choose this palette\n    interactively with the :func:`choose_light_palette` function.\n\n    Parameters\n    ----------\n    color : base color for high values\n        hex code, html color name, or tuple in `input` space.\n    n_colors : int, optional\n        number of colors in the palette\n    reverse : bool, optional\n        if True, reverse the direction of the blend\n    as_cmap : bool, optional\n        If True, return a :class:`matplotlib.colors.ListedColormap`.\n    input : {'rgb', 'hls', 'husl', xkcd'}\n        Color space to interpret the input color. The first three options\n        apply to tuple inputs and the latter applies to string inputs.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    dark_palette : Create a sequential palette with dark low values.\n    diverging_palette : Create a diverging palette with two colors.\n\n    Examples\n    --------\n    .. include:: ../docstrings/light_palette.rst\n\n    \"\"\"\n    rgb = _color_to_rgb(color, input)\n    h, s, l = husl.rgb_to_husl(*rgb)\n    gray_s, gray_l = .15 * s, 95\n    gray = _color_to_rgb((h, gray_s, gray_l), input=\"husl\")\n    colors = [rgb, gray] if reverse else [gray, rgb]\n    return blend_palette(colors, n_colors, as_cmap)\n\n\ndef diverging_palette(h_neg, h_pos, s=75, l=50, sep=1, n=6,  # noqa\n                      center=\"light\", as_cmap=False):\n    \"\"\"Make a diverging palette between two HUSL colors.\n\n    If you are using the IPython notebook, you can also choose this palette\n    interactively with the :func:`choose_diverging_palette` function.\n\n    Parameters\n    ----------\n    h_neg, h_pos : float in [0, 359]\n        Anchor hues for negative and positive extents of the map.\n    s : float in [0, 100], optional\n        Anchor saturation for both extents of the map.\n    l : float in [0, 100], optional\n        Anchor lightness for both extents of the map.\n    sep : int, optional\n        Size of the intermediate region.\n    n : int, optional\n        Number of colors in the palette (if not returning a cmap)\n    center : {\"light\", \"dark\"}, optional\n        Whether the center of the palette is light or dark\n    as_cmap : bool, optional\n        If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    dark_palette : Create a sequential palette with dark values.\n    light_palette : Create a sequential palette with light values.\n\n    Examples\n    --------\n    .. include: ../docstrings/diverging_palette.rst\n\n    \"\"\"\n    palfunc = dict(dark=dark_palette, light=light_palette)[center]\n    n_half = int(128 - (sep // 2))\n    neg = palfunc((h_neg, s, l), n_half, reverse=True, input=\"husl\")\n    pos = palfunc((h_pos, s, l), n_half, input=\"husl\")\n    midpoint = dict(light=[(.95, .95, .95)], dark=[(.133, .133, .133)])[center]\n    mid = midpoint * sep\n    pal = blend_palette(np.concatenate([neg, mid, pos]), n, as_cmap=as_cmap)\n    return pal\n\n\ndef blend_palette(colors, n_colors=6, as_cmap=False, input=\"rgb\"):\n    \"\"\"Make a palette that blends between a list of colors.\n\n    Parameters\n    ----------\n    colors : sequence of colors in various formats interpreted by `input`\n        hex code, html color name, or tuple in `input` space.\n    n_colors : int, optional\n        Number of colors in the palette.\n    as_cmap : bool, optional\n        If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    Examples\n    --------\n    .. include: ../docstrings/blend_palette.rst\n\n    \"\"\"\n    colors = [_color_to_rgb(color, input) for color in colors]\n    name = \"blend\"\n    pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)\n    if not as_cmap:\n        rgb_array = pal(np.linspace(0, 1, int(n_colors)))[:, :3]  # no alpha\n        pal = _ColorPalette(map(tuple, rgb_array))\n    return pal\n\n\ndef xkcd_palette(colors):\n    \"\"\"Make a palette with color names from the xkcd color survey.\n\n    See xkcd for the full list of colors: https://xkcd.com/color/rgb/\n\n    This is just a simple wrapper around the `seaborn.xkcd_rgb` dictionary.\n\n    Parameters\n    ----------\n    colors : list of strings\n        List of keys in the `seaborn.xkcd_rgb` dictionary.\n\n    Returns\n    -------\n    palette\n        A list of colors as RGB tuples.\n\n    See Also\n    --------\n    crayon_palette : Make a palette with Crayola crayon colors.\n\n    \"\"\"\n    palette = [xkcd_rgb[name] for name in colors]\n    return color_palette(palette, len(palette))\n\n\ndef crayon_palette(colors):\n    \"\"\"Make a palette with color names from Crayola crayons.\n\n    Colors are taken from here:\n    https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors\n\n    This is just a simple wrapper around the `seaborn.crayons` dictionary.\n\n    Parameters\n    ----------\n    colors : list of strings\n        List of keys in the `seaborn.crayons` dictionary.\n\n    Returns\n    -------\n    palette\n        A list of colors as RGB tuples.\n\n    See Also\n    --------\n    xkcd_palette : Make a palette with named colors from the XKCD color survey.\n\n    \"\"\"\n    palette = [crayons[name] for name in colors]\n    return color_palette(palette, len(palette))\n\n\ndef cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,\n                      light=.85, dark=.15, reverse=False, as_cmap=False):\n    \"\"\"Make a sequential palette from the cubehelix system.\n\n    This produces a colormap with linearly-decreasing (or increasing)\n    brightness. That means that information will be preserved if printed to\n    black and white or viewed by someone who is colorblind.  \"cubehelix\" is\n    also available as a matplotlib-based palette, but this function gives the\n    user more control over the look of the palette and has a different set of\n    defaults.\n\n    In addition to using this function, it is also possible to generate a\n    cubehelix palette generally in seaborn using a string starting with\n    `ch:` and containing other parameters (e.g. `\"ch:s=.25,r=-.5\"`).\n\n    Parameters\n    ----------\n    n_colors : int\n        Number of colors in the palette.\n    start : float, 0 <= start <= 3\n        The hue value at the start of the helix.\n    rot : float\n        Rotations around the hue wheel over the range of the palette.\n    gamma : float 0 <= gamma\n        Nonlinearity to emphasize dark (gamma < 1) or light (gamma > 1) colors.\n    hue : float, 0 <= hue <= 1\n        Saturation of the colors.\n    dark : float 0 <= dark <= 1\n        Intensity of the darkest color in the palette.\n    light : float 0 <= light <= 1\n        Intensity of the lightest color in the palette.\n    reverse : bool\n        If True, the palette will go from dark to light.\n    as_cmap : bool\n        If True, return a :class:`matplotlib.colors.ListedColormap`.\n\n    Returns\n    -------\n    palette\n        list of RGB tuples or :class:`matplotlib.colors.ListedColormap`\n\n    See Also\n    --------\n    choose_cubehelix_palette : Launch an interactive widget to select cubehelix\n                               palette parameters.\n    dark_palette : Create a sequential palette with dark low values.\n    light_palette : Create a sequential palette with bright low values.\n\n    References\n    ----------\n    Green, D. A. (2011). \"A colour scheme for the display of astronomical\n    intensity images\". Bulletin of the Astromical Society of India, Vol. 39,\n    p. 289-295.\n\n    Examples\n    --------\n    .. include:: ../docstrings/cubehelix_palette.rst\n\n    \"\"\"\n    def get_color_function(p0, p1):\n        # Copied from matplotlib because it lives in private module\n        def color(x):\n            # Apply gamma factor to emphasise low or high intensity values\n            xg = x ** gamma\n\n            # Calculate amplitude and angle of deviation from the black\n            # to white diagonal in the plane of constant\n            # perceived intensity.\n            a = hue * xg * (1 - xg) / 2\n\n            phi = 2 * np.pi * (start / 3 + rot * x)\n\n            return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))\n        return color\n\n    cdict = {\n        \"red\": get_color_function(-0.14861, 1.78277),\n        \"green\": get_color_function(-0.29227, -0.90649),\n        \"blue\": get_color_function(1.97294, 0.0),\n    }\n\n    cmap = mpl.colors.LinearSegmentedColormap(\"cubehelix\", cdict)\n\n    x = np.linspace(light, dark, int(n_colors))\n    pal = cmap(x)[:, :3].tolist()\n    if reverse:\n        pal = pal[::-1]\n\n    if as_cmap:\n        x_256 = np.linspace(light, dark, 256)\n        if reverse:\n            x_256 = x_256[::-1]\n        pal_256 = cmap(x_256)\n        cmap = mpl.colors.ListedColormap(pal_256, \"seaborn_cubehelix\")\n        return cmap\n    else:\n        return _ColorPalette(pal)\n\n\ndef _parse_cubehelix_args(argstr):\n    \"\"\"Turn stringified cubehelix params into args/kwargs.\"\"\"\n\n    if argstr.startswith(\"ch:\"):\n        argstr = argstr[3:]\n\n    if argstr.endswith(\"_r\"):\n        reverse = True\n        argstr = argstr[:-2]\n    else:\n        reverse = False\n\n    if not argstr:\n        return [], {\"reverse\": reverse}\n\n    all_args = argstr.split(\",\")\n\n    args = [float(a.strip(\" \")) for a in all_args if \"=\" not in a]\n\n    kwargs = [a.split(\"=\") for a in all_args if \"=\" in a]\n    kwargs = {k.strip(\" \"): float(v.strip(\" \")) for k, v in kwargs}\n\n    kwarg_map = dict(\n        s=\"start\", r=\"rot\", g=\"gamma\",\n        h=\"hue\", l=\"light\", d=\"dark\",  # noqa: E741\n    )\n\n    kwargs = {kwarg_map.get(k, k): v for k, v in kwargs.items()}\n\n    if reverse:\n        kwargs[\"reverse\"] = True\n\n    return args, kwargs\n\n\ndef set_color_codes(palette=\"deep\"):\n    \"\"\"Change how matplotlib color shorthands are interpreted.\n\n    Calling this will change how shorthand codes like \"b\" or \"g\"\n    are interpreted by matplotlib in subsequent plots.\n\n    Parameters\n    ----------\n    palette : {deep, muted, pastel, dark, bright, colorblind}\n        Named seaborn palette to use as the source of colors.\n\n    See Also\n    --------\n    set : Color codes can be set through the high-level seaborn style\n          manager.\n    set_palette : Color codes can also be set through the function that\n                  sets the matplotlib color cycle.\n\n    \"\"\"\n    if palette == \"reset\":\n        colors = [\n            (0., 0., 1.),\n            (0., .5, 0.),\n            (1., 0., 0.),\n            (.75, 0., .75),\n            (.75, .75, 0.),\n            (0., .75, .75),\n            (0., 0., 0.)\n        ]\n    elif not isinstance(palette, str):\n        err = \"set_color_codes requires a named seaborn palette\"\n        raise TypeError(err)\n    elif palette in SEABORN_PALETTES:\n        if not palette.endswith(\"6\"):\n            palette = palette + \"6\"\n        colors = SEABORN_PALETTES[palette] + [(.1, .1, .1)]\n    else:\n        err = f\"Cannot set colors with palette '{palette}'\"\n        raise ValueError(err)\n\n    for code, color in zip(\"bgrmyck\", colors):\n        rgb = mpl.colors.colorConverter.to_rgb(color)\n        mpl.colors.colorConverter.colors[code] = rgb\n        mpl.colors.colorConverter.cache[code] = rgb\n"},{"className":"cycle","col":0,"comment":"null","endLoc":44,"id":3163,"nodeType":"Class","startLoc":41,"text":"class cycle(Iterator[_T]):\n    def __init__(self, iterable: Iterable[_T], /) -> None: ...\n    def __next__(self) -> _T: ...\n    def __iter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":43,"header":"def __next__(self) -> _T","id":3164,"name":"__next__","nodeType":"Function","startLoc":43,"text":"def __next__(self) -> _T: ..."},{"col":4,"comment":"null","endLoc":44,"header":"def __iter__(self) -> Self","id":3165,"name":"__iter__","nodeType":"Function","startLoc":44,"text":"def __iter__(self) -> Self: ..."},{"className":"cycle","col":0,"comment":" Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. ","endLoc":300,"id":3166,"nodeType":"Class","startLoc":272,"text":"class cycle(object):\n    \"\"\" Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. \"\"\"\n    def __getattribute__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Return getattr(self, name). \"\"\"\n        pass\n\n    def __init__(self, *args, **kwargs): # real signature unknown\n        pass\n\n    def __iter__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Implement iter(self). \"\"\"\n        pass\n\n    @staticmethod # known case of __new__\n    def __new__(*args, **kwargs): # real signature unknown\n        \"\"\" Create and return a new object.  See help(type) for accurate signature. \"\"\"\n        pass\n\n    def __next__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Implement next(self). \"\"\"\n        pass\n\n    def __reduce__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Return state information for pickling. \"\"\"\n        pass\n\n    def __setstate__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Set state information for unpickling. \"\"\"\n        pass"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":276,"header":"def __getattribute__(self, *args, **kwargs)","id":3167,"name":"__getattribute__","nodeType":"Function","startLoc":274,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Return getattr(self, name). \"\"\"\n        pass"},{"col":4,"comment":"null","endLoc":279,"header":"def __init__(self, *args, **kwargs)","id":3168,"name":"__init__","nodeType":"Function","startLoc":278,"text":"def __init__(self, *args, **kwargs): # real signature unknown\n        pass"},{"col":4,"comment":" Implement iter(self). ","endLoc":283,"header":"def __iter__(self, *args, **kwargs)","id":3169,"name":"__iter__","nodeType":"Function","startLoc":281,"text":"def __iter__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Implement iter(self). \"\"\"\n        pass"},{"col":4,"comment":" Create and return a new object.  See help(type) for accurate signature. ","endLoc":288,"header":"@staticmethod # known case of __new__\n    def __new__(*args, **kwargs)","id":3170,"name":"__new__","nodeType":"Function","startLoc":285,"text":"@staticmethod # known case of __new__\n    def __new__(*args, **kwargs): # real signature unknown\n        \"\"\" Create and return a new object.  See help(type) for accurate signature. \"\"\"\n        pass"},{"col":4,"comment":" Implement next(self). ","endLoc":292,"header":"def __next__(self, *args, **kwargs)","id":3171,"name":"__next__","nodeType":"Function","startLoc":290,"text":"def __next__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Implement next(self). \"\"\"\n        pass"},{"col":4,"comment":" Return state information for pickling. ","endLoc":296,"header":"def __reduce__(self, *args, **kwargs)","id":3172,"name":"__reduce__","nodeType":"Function","startLoc":294,"text":"def __reduce__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Return state information for pickling. \"\"\"\n        pass"},{"col":4,"comment":" Set state information for unpickling. ","endLoc":300,"header":"def __setstate__(self, *args, **kwargs)","id":3173,"name":"__setstate__","nodeType":"Function","startLoc":298,"text":"def __setstate__(self, *args, **kwargs): # real signature unknown\n        \"\"\" Set state information for unpickling. \"\"\"\n        pass"},{"className":"_ColorPalette","col":0,"comment":"Set the color palette in a with statement, otherwise be a list.","endLoc":91,"id":3174,"nodeType":"Class","startLoc":61,"text":"class _ColorPalette(list):\n    \"\"\"Set the color palette in a with statement, otherwise be a list.\"\"\"\n    def __enter__(self):\n        \"\"\"Open the context.\"\"\"\n        from .rcmod import set_palette\n        self._orig_palette = color_palette()\n        set_palette(self)\n        return self\n\n    def __exit__(self, *args):\n        \"\"\"Close the context.\"\"\"\n        from .rcmod import set_palette\n        set_palette(self._orig_palette)\n\n    def as_hex(self):\n        \"\"\"Return a color palette with hex codes instead of RGB values.\"\"\"\n        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]\n        return _ColorPalette(hex)\n\n    def _repr_html_(self):\n        \"\"\"Rich display of the color palette in an HTML frontend.\"\"\"\n        s = 55\n        n = len(self)\n        html = f''\n        for i, c in enumerate(self.as_hex()):\n            html += (\n                f''\n            )\n        html += ''\n        return html"},{"className":"list","col":0,"comment":"null","endLoc":1061,"id":3175,"nodeType":"Class","startLoc":1008,"text":"class list(MutableSequence[_T], Generic[_T]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, __iterable: Iterable[_T]) -> None: ...\n    def copy(self) -> list[_T]: ...\n    def append(self, __object: _T) -> None: ...\n    def extend(self, __iterable: Iterable[_T]) -> None: ...\n    def pop(self, __index: SupportsIndex = -1) -> _T: ...\n    # Signature of `list.index` should be kept in line with `collections.UserList.index()`\n    # and multiprocessing.managers.ListProxy.index()\n    def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ...\n    def count(self, __value: _T) -> int: ...\n    def insert(self, __index: SupportsIndex, __object: _T) -> None: ...\n    def remove(self, __value: _T) -> None: ...\n    # Signature of `list.sort` should be kept inline with `collections.UserList.sort()`\n    # and multiprocessing.managers.ListProxy.sort()\n    #\n    # Use list[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison]\n    # to work around invariance\n    @overload\n    def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ...\n    @overload\n    def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ...\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[_T]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    @overload\n    def __getitem__(self, __i: SupportsIndex) -> _T: ...\n    @overload\n    def __getitem__(self, __s: slice) -> list[_T]: ...\n    @overload\n    def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ...\n    @overload\n    def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ...\n    def __delitem__(self, __key: SupportsIndex | slice) -> None: ...\n    # Overloading looks unnecessary, but is needed to work around complex mypy problems\n    @overload\n    def __add__(self, __value: list[_T]) -> list[_T]: ...\n    @overload\n    def __add__(self, __value: list[_S]) -> list[_S | _T]: ...\n    def __iadd__(self, __value: Iterable[_T]) -> Self: ...  # type: ignore[misc]\n    def __mul__(self, __value: SupportsIndex) -> list[_T]: ...\n    def __rmul__(self, __value: SupportsIndex) -> list[_T]: ...\n    def __imul__(self, __value: SupportsIndex) -> Self: ...\n    def __contains__(self, __key: object) -> bool: ...\n    def __reversed__(self) -> Iterator[_T]: ...\n    def __gt__(self, __value: list[_T]) -> bool: ...\n    def __ge__(self, __value: list[_T]) -> bool: ...\n    def __lt__(self, __value: list[_T]) -> bool: ...\n    def __le__(self, __value: list[_T]) -> bool: ...\n    def __eq__(self, __value: object) -> bool: ...\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, __item: Any) -> GenericAlias: ..."},{"col":4,"comment":"null","endLoc":1013,"header":"def copy(self) -> list[_T]","id":3176,"name":"copy","nodeType":"Function","startLoc":1013,"text":"def copy(self) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1016,"header":"def pop(self, __index: SupportsIndex = -1) -> _T","id":3177,"name":"pop","nodeType":"Function","startLoc":1016,"text":"def pop(self, __index: SupportsIndex = -1) -> _T: ..."},{"col":4,"comment":"null","endLoc":1020,"header":"def count(self, __value: _T) -> int","id":3178,"name":"count","nodeType":"Function","startLoc":1020,"text":"def count(self, __value: _T) -> int: ..."},{"col":4,"comment":"null","endLoc":1022,"header":"def remove(self, __value: _T) -> None","id":3179,"name":"remove","nodeType":"Function","startLoc":1022,"text":"def remove(self, __value: _T) -> None: ..."},{"col":4,"comment":"null","endLoc":1029,"header":"@overload\n    def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None","id":3180,"name":"sort","nodeType":"Function","startLoc":1028,"text":"@overload\n    def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":1031,"header":"@overload\n    def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None","id":3181,"name":"sort","nodeType":"Function","startLoc":1030,"text":"@overload\n    def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":1032,"header":"def __len__(self) -> int","id":3182,"name":"__len__","nodeType":"Function","startLoc":1032,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1033,"header":"def __iter__(self) -> Iterator[_T]","id":3183,"name":"__iter__","nodeType":"Function","startLoc":1033,"text":"def __iter__(self) -> Iterator[_T]: ..."},{"col":4,"comment":"null","endLoc":1036,"header":"@overload\n    def __getitem__(self, __i: SupportsIndex) -> _T","id":3184,"name":"__getitem__","nodeType":"Function","startLoc":1035,"text":"@overload\n    def __getitem__(self, __i: SupportsIndex) -> _T: ..."},{"col":4,"comment":"null","endLoc":1038,"header":"@overload\n    def __getitem__(self, __s: slice) -> list[_T]","id":3185,"name":"__getitem__","nodeType":"Function","startLoc":1037,"text":"@overload\n    def __getitem__(self, __s: slice) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1040,"header":"@overload\n    def __setitem__(self, __key: SupportsIndex, __value: _T) -> None","id":3186,"name":"__setitem__","nodeType":"Function","startLoc":1039,"text":"@overload\n    def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ..."},{"col":4,"comment":"null","endLoc":1042,"header":"@overload\n    def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None","id":3187,"name":"__setitem__","nodeType":"Function","startLoc":1041,"text":"@overload\n    def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ..."},{"col":4,"comment":"null","endLoc":1043,"header":"def __delitem__(self, __key: SupportsIndex | slice) -> None","id":3188,"name":"__delitem__","nodeType":"Function","startLoc":1043,"text":"def __delitem__(self, __key: SupportsIndex | slice) -> None: ..."},{"col":4,"comment":"null","endLoc":1046,"header":"@overload\n    def __add__(self, __value: list[_T]) -> list[_T]","id":3189,"name":"__add__","nodeType":"Function","startLoc":1045,"text":"@overload\n    def __add__(self, __value: list[_T]) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1048,"header":"@overload\n    def __add__(self, __value: list[_S]) -> list[_S | _T]","id":3190,"name":"__add__","nodeType":"Function","startLoc":1047,"text":"@overload\n    def __add__(self, __value: list[_S]) -> list[_S | _T]: ..."},{"col":4,"comment":"null","endLoc":1049,"header":"def __iadd__(self, __value: Iterable[_T]) -> Self","id":3191,"name":"__iadd__","nodeType":"Function","startLoc":1049,"text":"def __iadd__(self, __value: Iterable[_T]) -> Self: ...  # type: ignore[misc]"},{"col":4,"comment":"null","endLoc":1050,"header":"def __mul__(self, __value: SupportsIndex) -> list[_T]","id":3192,"name":"__mul__","nodeType":"Function","startLoc":1050,"text":"def __mul__(self, __value: SupportsIndex) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1051,"header":"def __rmul__(self, __value: SupportsIndex) -> list[_T]","id":3193,"name":"__rmul__","nodeType":"Function","startLoc":1051,"text":"def __rmul__(self, __value: SupportsIndex) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1052,"header":"def __imul__(self, __value: SupportsIndex) -> Self","id":3194,"name":"__imul__","nodeType":"Function","startLoc":1052,"text":"def __imul__(self, __value: SupportsIndex) -> Self: ..."},{"col":4,"comment":"null","endLoc":1053,"header":"def __contains__(self, __key: object) -> bool","id":3195,"name":"__contains__","nodeType":"Function","startLoc":1053,"text":"def __contains__(self, __key: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":1054,"header":"def __reversed__(self) -> Iterator[_T]","id":3196,"name":"__reversed__","nodeType":"Function","startLoc":1054,"text":"def __reversed__(self) -> Iterator[_T]: ..."},{"col":4,"comment":"null","endLoc":1055,"header":"def __gt__(self, __value: list[_T]) -> bool","id":3197,"name":"__gt__","nodeType":"Function","startLoc":1055,"text":"def __gt__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1056,"header":"def __ge__(self, __value: list[_T]) -> bool","id":3198,"name":"__ge__","nodeType":"Function","startLoc":1056,"text":"def __ge__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1057,"header":"def __lt__(self, __value: list[_T]) -> bool","id":3199,"name":"__lt__","nodeType":"Function","startLoc":1057,"text":"def __lt__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1058,"header":"def __le__(self, __value: list[_T]) -> bool","id":3200,"name":"__le__","nodeType":"Function","startLoc":1058,"text":"def __le__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1059,"header":"def __eq__(self, __value: object) -> bool","id":3201,"name":"__eq__","nodeType":"Function","startLoc":1059,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":8,"comment":"null","endLoc":1061,"header":"def __class_getitem__(cls, __item: Any) -> GenericAlias","id":3202,"name":"__class_getitem__","nodeType":"Function","startLoc":1061,"text":"def __class_getitem__(cls, __item: Any) -> GenericAlias: ..."},{"attributeType":"None","col":4,"comment":"null","endLoc":1034,"id":3203,"name":"__hash__","nodeType":"Attribute","startLoc":1034,"text":"__hash__"},{"col":4,"comment":"Open the context.","endLoc":68,"header":"def __enter__(self)","id":3204,"name":"__enter__","nodeType":"Function","startLoc":63,"text":"def __enter__(self):\n        \"\"\"Open the context.\"\"\"\n        from .rcmod import set_palette\n        self._orig_palette = color_palette()\n        set_palette(self)\n        return self"},{"col":4,"comment":"Close the context.","endLoc":73,"header":"def __exit__(self, *args)","id":3205,"name":"__exit__","nodeType":"Function","startLoc":70,"text":"def __exit__(self, *args):\n        \"\"\"Close the context.\"\"\"\n        from .rcmod import set_palette\n        set_palette(self._orig_palette)"},{"col":4,"comment":"Return a color palette with hex codes instead of RGB values.","endLoc":78,"header":"def as_hex(self)","id":3206,"name":"as_hex","nodeType":"Function","startLoc":75,"text":"def as_hex(self):\n        \"\"\"Return a color palette with hex codes instead of RGB values.\"\"\"\n        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]\n        return _ColorPalette(hex)"},{"col":4,"comment":"null","endLoc":126,"header":"def test_bw_adjust(self, rng)","id":3207,"name":"test_bw_adjust","nodeType":"Function","startLoc":117,"text":"def test_bw_adjust(self, rng):\n\n        x = rng.normal(0, 3, 100)\n        kde1 = KDE(bw_adjust=.2)\n        kde2 = KDE(bw_adjust=2)\n\n        d1, _ = kde1(x)\n        d2, _ = kde2(x)\n\n        assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()"},{"className":"_PlottingContext","col":0,"comment":"Light wrapper on a dict to set context temporarily.","endLoc":499,"id":3208,"nodeType":"Class","startLoc":496,"text":"class _PlottingContext(_RCAesthetics):\n    \"\"\"Light wrapper on a dict to set context temporarily.\"\"\"\n    _keys = _context_keys\n    _set = staticmethod(set_context)"},{"col":4,"comment":"null","endLoc":106,"header":"def test_other_props_direct(self)","id":3209,"name":"test_other_props_direct","nodeType":"Function","startLoc":96,"text":"def test_other_props_direct(self):\n\n        x = y = [1, 2, 3]\n        m = Path(marker=\"s\", linestyle=\"--\", linewidth=3, pointsize=10, edgewidth=1)\n        p = Plot(x=x, y=y).add(m).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert line.get_marker() == m.marker\n        assert line.get_linestyle() == m.linestyle\n        assert line.get_linewidth() == m.linewidth\n        assert line.get_markersize() == m.pointsize\n        assert line.get_markeredgewidth() == m.edgewidth"},{"attributeType":"list","col":4,"comment":"null","endLoc":498,"id":3210,"name":"_keys","nodeType":"Attribute","startLoc":498,"text":"_keys"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":499,"id":3211,"name":"_set","nodeType":"Attribute","startLoc":499,"text":"_set"},{"col":4,"comment":"null","endLoc":137,"header":"def test_bivariate_grid(self, rng)","id":3212,"name":"test_bivariate_grid","nodeType":"Function","startLoc":128,"text":"def test_bivariate_grid(self, rng):\n\n        n = 100\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=n)\n        density, (xx, yy) = kde(x, y)\n\n        assert density.shape == (n, n)\n        assert xx.size == n\n        assert yy.size == n"},{"col":4,"comment":"null","endLoc":149,"header":"def test_bivariate_normalization(self, rng)","id":3213,"name":"test_bivariate_normalization","nodeType":"Function","startLoc":139,"text":"def test_bivariate_normalization(self, rng):\n\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=100)\n        density, (xx, yy) = kde(x, y)\n\n        dx = xx[1] - xx[0]\n        dy = yy[1] - yy[0]\n\n        total = density.sum() * (dx * dy)\n        assert total == pytest.approx(1, abs=1e-2)"},{"attributeType":"null","col":0,"comment":"null","endLoc":8,"id":3214,"name":"__all__","nodeType":"Attribute","startLoc":8,"text":"__all__"},{"attributeType":"list","col":0,"comment":"null","endLoc":13,"id":3215,"name":"_style_keys","nodeType":"Attribute","startLoc":13,"text":"_style_keys"},{"attributeType":"list","col":0,"comment":"null","endLoc":53,"id":3216,"name":"_context_keys","nodeType":"Attribute","startLoc":53,"text":"_context_keys"},{"col":0,"comment":"","endLoc":1,"header":"rcmod.py#","id":3217,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Control plot style and scaling using the matplotlib rcParams interface.\"\"\"\n\n__all__ = [\"set_theme\", \"set\", \"reset_defaults\", \"reset_orig\",\n           \"axes_style\", \"set_style\", \"plotting_context\", \"set_context\",\n           \"set_palette\"]\n\n_style_keys = [\n\n    \"axes.facecolor\",\n    \"axes.edgecolor\",\n    \"axes.grid\",\n    \"axes.axisbelow\",\n    \"axes.labelcolor\",\n\n    \"figure.facecolor\",\n\n    \"grid.color\",\n    \"grid.linestyle\",\n\n    \"text.color\",\n\n    \"xtick.color\",\n    \"ytick.color\",\n    \"xtick.direction\",\n    \"ytick.direction\",\n    \"lines.solid_capstyle\",\n\n    \"patch.edgecolor\",\n    \"patch.force_edgecolor\",\n\n    \"image.cmap\",\n    \"font.family\",\n    \"font.sans-serif\",\n\n    \"xtick.bottom\",\n    \"xtick.top\",\n    \"ytick.left\",\n    \"ytick.right\",\n\n    \"axes.spines.left\",\n    \"axes.spines.bottom\",\n    \"axes.spines.right\",\n    \"axes.spines.top\",\n\n]\n\n_context_keys = [\n\n    \"font.size\",\n    \"axes.labelsize\",\n    \"axes.titlesize\",\n    \"xtick.labelsize\",\n    \"ytick.labelsize\",\n    \"legend.fontsize\",\n    \"legend.title_fontsize\",\n\n    \"axes.linewidth\",\n    \"grid.linewidth\",\n    \"lines.linewidth\",\n    \"lines.markersize\",\n    \"patch.linewidth\",\n\n    \"xtick.major.width\",\n    \"ytick.major.width\",\n    \"xtick.minor.width\",\n    \"ytick.minor.width\",\n\n    \"xtick.major.size\",\n    \"ytick.major.size\",\n    \"xtick.minor.size\",\n    \"ytick.minor.size\",\n\n]"},{"id":3218,"name":"v0.5.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.5.1 (November 2014)\n----------------------\n\nThis is a bugfix release that includes a workaround for an issue in matplotlib 1.4.2 and fixes for two bugs in functions that were new in 0.5.0.\n\n- Implemented a workaround for a bug in matplotlib 1.4.2 that prevented point markers from being drawn when the seaborn styles had been set. See this `github issue `_ for more information.\n\n- Fixed a bug in :func:`heatmap` where the mask was vertically reversed relative to the data.\n\n- Fixed a bug in :func:`clustermap` when using nested lists of side colors.\n"},{"col":4,"comment":"null","endLoc":118,"header":"def test_other_props_mapped(self)","id":3219,"name":"test_other_props_mapped","nodeType":"Function","startLoc":108,"text":"def test_other_props_mapped(self):\n\n        x = y = [1, 2, 3, 4]\n        g = [\"a\", \"a\", \"b\", \"b\"]\n        m = Path()\n        p = Plot(x=x, y=y, marker=g, linestyle=g, pointsize=g).add(m).plot()\n        line1, line2 = p._figure.axes[0].get_lines()\n        assert line1.get_marker() != line2.get_marker()\n        # Matplotlib bug in storing linestyle from dash pattern\n        # assert line1.get_linestyle() != line2.get_linestyle()\n        assert line1.get_markersize() != line2.get_markersize()"},{"col":4,"comment":"null","endLoc":159,"header":"@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_bivariate_cumulative(self, rng)","id":3220,"name":"test_bivariate_cumulative","nodeType":"Function","startLoc":151,"text":"@pytest.mark.skipif(_no_scipy, reason=\"Test requires scipy\")\n    def test_bivariate_cumulative(self, rng):\n\n        x, y = rng.normal(0, 3, (2, 50))\n        kde = KDE(gridsize=100, cumulative=True)\n        density, _ = kde(x, y)\n\n        assert density[0, 0] == pytest.approx(0, abs=1e-2)\n        assert density[-1, -1] == pytest.approx(1, abs=1e-2)"},{"fileName":"__init__.py","filePath":"seaborn","id":3221,"nodeType":"File","text":"# Import seaborn objects\nfrom .rcmod import *  # noqa: F401,F403\nfrom .utils import *  # noqa: F401,F403\nfrom .palettes import *  # noqa: F401,F403\nfrom .relational import *  # noqa: F401,F403\nfrom .regression import *  # noqa: F401,F403\nfrom .categorical import *  # noqa: F401,F403\nfrom .distributions import *  # noqa: F401,F403\nfrom .matrix import *  # noqa: F401,F403\nfrom .miscplot import *  # noqa: F401,F403\nfrom .axisgrid import *  # noqa: F401,F403\nfrom .widgets import *  # noqa: F401,F403\nfrom .colors import xkcd_rgb, crayons  # noqa: F401\nfrom . import cm  # noqa: F401\n\n# Capture the original matplotlib rcParams\nimport matplotlib as mpl\n_orig_rc_params = mpl.rcParams.copy()\n\n# Define the seaborn version\n__version__ = \"0.12.1.dev0\"\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":18,"id":3222,"name":"_orig_rc_params","nodeType":"Attribute","startLoc":18,"text":"_orig_rc_params"},{"attributeType":"str","col":0,"comment":"null","endLoc":21,"id":3223,"name":"__version__","nodeType":"Attribute","startLoc":21,"text":"__version__"},{"col":0,"comment":"","endLoc":2,"header":"__init__.py#","id":3224,"name":"","nodeType":"Function","startLoc":2,"text":"_orig_rc_params = mpl.rcParams.copy()\n\n__version__ = \"0.12.1.dev0\""},{"fileName":"__init__.py","filePath":"seaborn/external","id":3225,"nodeType":"File","text":""},{"className":"TestHistogram","col":0,"comment":"null","endLoc":421,"id":3226,"nodeType":"Class","startLoc":162,"text":"class TestHistogram(DistributionFixtures):\n\n    def test_string_bins(self, x):\n\n        h = Histogram(bins=\"sqrt\")\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min(), x.max())\n        assert bin_kws[\"bins\"] == int(np.sqrt(len(x)))\n\n    def test_int_bins(self, x):\n\n        n = 24\n        h = Histogram(bins=n)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min(), x.max())\n        assert bin_kws[\"bins\"] == n\n\n    def test_array_bins(self, x):\n\n        bins = [-3, -2, 1, 2, 3]\n        h = Histogram(bins=bins)\n        bin_kws = h.define_bin_params(x)\n        assert_array_equal(bin_kws[\"bins\"], bins)\n\n    def test_bivariate_string_bins(self, x, y):\n\n        s1, s2 = \"sqrt\", \"fd\"\n\n        h = Histogram(bins=s1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, np.histogram_bin_edges(x, s1))\n        assert_array_equal(e2, np.histogram_bin_edges(y, s1))\n\n        h = Histogram(bins=(s1, s2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, np.histogram_bin_edges(x, s1))\n        assert_array_equal(e2, np.histogram_bin_edges(y, s2))\n\n    def test_bivariate_int_bins(self, x, y):\n\n        b1, b2 = 5, 10\n\n        h = Histogram(bins=b1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert len(e1) == b1 + 1\n        assert len(e2) == b1 + 1\n\n        h = Histogram(bins=(b1, b2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert len(e1) == b1 + 1\n        assert len(e2) == b2 + 1\n\n    def test_bivariate_array_bins(self, x, y):\n\n        b1 = [-3, -2, 1, 2, 3]\n        b2 = [-5, -2, 3, 6]\n\n        h = Histogram(bins=b1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, b1)\n        assert_array_equal(e2, b1)\n\n        h = Histogram(bins=(b1, b2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, b1)\n        assert_array_equal(e2, b2)\n\n    def test_binwidth(self, x):\n\n        binwidth = .5\n        h = Histogram(binwidth=binwidth)\n        bin_kws = h.define_bin_params(x)\n        n_bins = bin_kws[\"bins\"]\n        left, right = bin_kws[\"range\"]\n        assert (right - left) / n_bins == pytest.approx(binwidth)\n\n    def test_bivariate_binwidth(self, x, y):\n\n        w1, w2 = .5, 1\n\n        h = Histogram(binwidth=w1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert np.all(np.diff(e1) == w1)\n        assert np.all(np.diff(e2) == w1)\n\n        h = Histogram(binwidth=(w1, w2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert np.all(np.diff(e1) == w1)\n        assert np.all(np.diff(e2) == w2)\n\n    def test_binrange(self, x):\n\n        binrange = (-4, 4)\n        h = Histogram(binrange=binrange)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == binrange\n\n    def test_bivariate_binrange(self, x, y):\n\n        r1, r2 = (-4, 4), (-10, 10)\n\n        h = Histogram(binrange=r1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert e1.min() == r1[0]\n        assert e1.max() == r1[1]\n        assert e2.min() == r1[0]\n        assert e2.max() == r1[1]\n\n        h = Histogram(binrange=(r1, r2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert e1.min() == r1[0]\n        assert e1.max() == r1[1]\n        assert e2.min() == r2[0]\n        assert e2.max() == r2[1]\n\n    def test_discrete_bins(self, rng):\n\n        x = rng.binomial(20, .5, 100)\n        h = Histogram(discrete=True)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n        assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)\n\n    def test_odd_single_observation(self):\n        # GH2721\n        x = np.array([0.49928])\n        h, e = Histogram(binwidth=0.03)(x)\n        assert len(h) == 1\n        assert (e[1] - e[0]) == pytest.approx(.03)\n\n    def test_binwidth_roundoff(self):\n        # GH2785\n        x = np.array([2.4, 2.5, 2.6])\n        h, e = Histogram(binwidth=0.01)(x)\n        assert h.sum() == 3\n\n    def test_histogram(self, x):\n\n        h = Histogram()\n        heights, edges = h(x)\n        heights_mpl, edges_mpl = np.histogram(x, bins=\"auto\")\n\n        assert_array_equal(heights, heights_mpl)\n        assert_array_equal(edges, edges_mpl)\n\n    def test_count_stat(self, x):\n\n        h = Histogram(stat=\"count\")\n        heights, _ = h(x)\n        assert heights.sum() == len(x)\n\n    def test_density_stat(self, x):\n\n        h = Histogram(stat=\"density\")\n        heights, edges = h(x)\n        assert (heights * np.diff(edges)).sum() == 1\n\n    def test_probability_stat(self, x):\n\n        h = Histogram(stat=\"probability\")\n        heights, _ = h(x)\n        assert heights.sum() == 1\n\n    def test_frequency_stat(self, x):\n\n        h = Histogram(stat=\"frequency\")\n        heights, edges = h(x)\n        assert (heights * np.diff(edges)).sum() == len(x)\n\n    def test_cumulative_count(self, x):\n\n        h = Histogram(stat=\"count\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == len(x)\n\n    def test_cumulative_density(self, x):\n\n        h = Histogram(stat=\"density\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == 1\n\n    def test_cumulative_probability(self, x):\n\n        h = Histogram(stat=\"probability\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == 1\n\n    def test_cumulative_frequency(self, x):\n\n        h = Histogram(stat=\"frequency\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == len(x)\n\n    def test_bivariate_histogram(self, x, y):\n\n        h = Histogram()\n        heights, edges = h(x, y)\n        bins_mpl = (\n            np.histogram_bin_edges(x, \"auto\"),\n            np.histogram_bin_edges(y, \"auto\"),\n        )\n        heights_mpl, *edges_mpl = np.histogram2d(x, y, bins_mpl)\n        assert_array_equal(heights, heights_mpl)\n        assert_array_equal(edges[0], edges_mpl[0])\n        assert_array_equal(edges[1], edges_mpl[1])\n\n    def test_bivariate_count_stat(self, x, y):\n\n        h = Histogram(stat=\"count\")\n        heights, _ = h(x, y)\n        assert heights.sum() == len(x)\n\n    def test_bivariate_density_stat(self, x, y):\n\n        h = Histogram(stat=\"density\")\n        heights, (edges_x, edges_y) = h(x, y)\n        areas = np.outer(np.diff(edges_x), np.diff(edges_y))\n        assert (heights * areas).sum() == pytest.approx(1)\n\n    def test_bivariate_probability_stat(self, x, y):\n\n        h = Histogram(stat=\"probability\")\n        heights, _ = h(x, y)\n        assert heights.sum() == 1\n\n    def test_bivariate_frequency_stat(self, x, y):\n\n        h = Histogram(stat=\"frequency\")\n        heights, (x_edges, y_edges) = h(x, y)\n        area = np.outer(np.diff(x_edges), np.diff(y_edges))\n        assert (heights * area).sum() == len(x)\n\n    def test_bivariate_cumulative_count(self, x, y):\n\n        h = Histogram(stat=\"count\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == len(x)\n\n    def test_bivariate_cumulative_density(self, x, y):\n\n        h = Histogram(stat=\"density\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == pytest.approx(1)\n\n    def test_bivariate_cumulative_frequency(self, x, y):\n\n        h = Histogram(stat=\"frequency\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == len(x)\n\n    def test_bivariate_cumulative_probability(self, x, y):\n\n        h = Histogram(stat=\"probability\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == pytest.approx(1)\n\n    def test_bad_stat(self):\n\n        with pytest.raises(ValueError):\n            Histogram(stat=\"invalid\")"},{"col":4,"comment":"null","endLoc":169,"header":"def test_string_bins(self, x)","id":3227,"name":"test_string_bins","nodeType":"Function","startLoc":164,"text":"def test_string_bins(self, x):\n\n        h = Histogram(bins=\"sqrt\")\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min(), x.max())\n        assert bin_kws[\"bins\"] == int(np.sqrt(len(x)))"},{"fileName":"test_miscplot.py","filePath":"tests","id":3228,"nodeType":"File","text":"import matplotlib.pyplot as plt\n\nfrom seaborn import miscplot as misc\nfrom seaborn.palettes import color_palette\nfrom .test_utils import _network\n\n\nclass TestPalPlot:\n    \"\"\"Test the function that visualizes a color palette.\"\"\"\n    def test_palplot_size(self):\n\n        pal4 = color_palette(\"husl\", 4)\n        misc.palplot(pal4)\n        size4 = plt.gcf().get_size_inches()\n        assert tuple(size4) == (4, 1)\n\n        pal5 = color_palette(\"husl\", 5)\n        misc.palplot(pal5)\n        size5 = plt.gcf().get_size_inches()\n        assert tuple(size5) == (5, 1)\n\n        palbig = color_palette(\"husl\", 3)\n        misc.palplot(palbig, 2)\n        sizebig = plt.gcf().get_size_inches()\n        assert tuple(sizebig) == (6, 2)\n\n\nclass TestDogPlot:\n\n    @_network(url=\"https://github.com/mwaskom/seaborn-data\")\n    def test_dogplot(self):\n        misc.dogplot()\n        ax = plt.gca()\n        assert len(ax.images) == 1\n"},{"col":4,"comment":"null","endLoc":135,"header":"def test_capstyle(self)","id":3229,"name":"test_capstyle","nodeType":"Function","startLoc":120,"text":"def test_capstyle(self):\n\n        x = y = [1, 2]\n        rc = {\"lines.solid_capstyle\": \"projecting\", \"lines.dash_capstyle\": \"round\"}\n\n        p = Plot(x, y).add(Path()).theme(rc).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert line.get_dash_capstyle() == \"projecting\"\n\n        p = Plot(x, y).add(Path(linestyle=\"--\")).theme(rc).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert line.get_dash_capstyle() == \"round\"\n\n        p = Plot(x, y).add(Path({\"solid_capstyle\": \"butt\"})).theme(rc).plot()\n        line, = p._figure.axes[0].get_lines()\n        assert line.get_solid_capstyle() == \"butt\""},{"col":0,"comment":"\n    Decorator that will skip a test if `url` is unreachable.\n\n    Parameters\n    ----------\n    t : function, optional\n    url : str, optional\n\n    ","endLoc":60,"header":"def _network(t=None, url=\"https://github.com\")","id":3230,"name":"_network","nodeType":"Function","startLoc":38,"text":"def _network(t=None, url=\"https://github.com\"):\n    \"\"\"\n    Decorator that will skip a test if `url` is unreachable.\n\n    Parameters\n    ----------\n    t : function, optional\n    url : str, optional\n\n    \"\"\"\n    if t is None:\n        return lambda x: _network(x, url=url)\n\n    def wrapper(*args, **kwargs):\n        # attempt to connect\n        try:\n            f = urlopen(url)\n        except (OSError, HTTPException):\n            pytest.skip(\"No internet connection\")\n        else:\n            f.close()\n            return t(*args, **kwargs)\n    return wrapper"},{"col":4,"comment":"null","endLoc":2288,"header":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", bw_adjust=.5),\n            dict(x=\"x\", weights=\"f\"),\n            dict(x=\"x\", color=\"green\", linewidth=2),\n            dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n            dict(x=\"x\", hue=\"a\", fill=True),\n            dict(x=\"y\", hue=\"a\", fill=False),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n            dict(x=\"x\", y=\"y\"),\n        ],\n    )\n    def test_versus_single_kdeplot(self, long_df, kwargs)","id":3231,"name":"test_versus_single_kdeplot","nodeType":"Function","startLoc":2260,"text":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", bw_adjust=.5),\n            dict(x=\"x\", weights=\"f\"),\n            dict(x=\"x\", color=\"green\", linewidth=2),\n            dict(x=\"x\", hue=\"a\", multiple=\"stack\"),\n            dict(x=\"x\", hue=\"a\", fill=True),\n            dict(x=\"y\", hue=\"a\", fill=False),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n            dict(x=\"x\", y=\"y\"),\n        ],\n    )\n    def test_versus_single_kdeplot(self, long_df, kwargs):\n\n        ax = kdeplot(data=long_df, **kwargs)\n        g = displot(long_df, kind=\"kde\", **kwargs)\n        assert_plots_equal(ax, g.ax)\n\n        if ax.legend_ is not None:\n            assert_legends_equal(ax.legend_, g._legend)\n\n        if kwargs:\n            long_df[\"_\"] = \"_\"\n            g2 = displot(long_df, kind=\"kde\", col=\"_\", **kwargs)\n            assert_plots_equal(ax, g2.ax)"},{"col":4,"comment":"Rich display of the color palette in an HTML frontend.","endLoc":91,"header":"def _repr_html_(self)","id":3232,"name":"_repr_html_","nodeType":"Function","startLoc":80,"text":"def _repr_html_(self):\n        \"\"\"Rich display of the color palette in an HTML frontend.\"\"\"\n        s = 55\n        n = len(self)\n        html = f''\n        for i, c in enumerate(self.as_hex()):\n            html += (\n                f''\n            )\n        html += ''\n        return html"},{"col":4,"comment":"null","endLoc":494,"header":"def _str_section(self, name)","id":3233,"name":"_str_section","nodeType":"Function","startLoc":488,"text":"def _str_section(self, name):\n        out = []\n        if self[name]:\n            out += self._str_header(name)\n            out += self[name]\n            out += ['']\n        return out"},{"col":4,"comment":"null","endLoc":526,"header":"def _str_see_also(self, func_role)","id":3234,"name":"_str_see_also","nodeType":"Function","startLoc":496,"text":"def _str_see_also(self, func_role):\n        if not self['See Also']:\n            return []\n        out = []\n        out += self._str_header(\"See Also\")\n        out += ['']\n        last_had_desc = True\n        for funcs, desc in self['See Also']:\n            assert isinstance(funcs, list)\n            links = []\n            for func, role in funcs:\n                if role:\n                    link = f':{role}:`{func}`'\n                elif func_role:\n                    link = f':{func_role}:`{func}`'\n                else:\n                    link = f\"`{func}`_\"\n                links.append(link)\n            link = ', '.join(links)\n            out += [link]\n            if desc:\n                out += self._str_indent([' '.join(desc)])\n                last_had_desc = True\n            else:\n                last_had_desc = False\n                out += self._str_indent([self.empty_description])\n\n        if last_had_desc:\n            out += ['']\n        out += ['']\n        return out"},{"col":15,"endLoc":49,"id":3235,"nodeType":"Lambda","startLoc":49,"text":"lambda x: _network(x, url=url)"},{"className":"TestPalPlot","col":0,"comment":"Test the function that visualizes a color palette.","endLoc":25,"id":3236,"nodeType":"Class","startLoc":8,"text":"class TestPalPlot:\n    \"\"\"Test the function that visualizes a color palette.\"\"\"\n    def test_palplot_size(self):\n\n        pal4 = color_palette(\"husl\", 4)\n        misc.palplot(pal4)\n        size4 = plt.gcf().get_size_inches()\n        assert tuple(size4) == (4, 1)\n\n        pal5 = color_palette(\"husl\", 5)\n        misc.palplot(pal5)\n        size5 = plt.gcf().get_size_inches()\n        assert tuple(size5) == (5, 1)\n\n        palbig = color_palette(\"husl\", 3)\n        misc.palplot(palbig, 2)\n        sizebig = plt.gcf().get_size_inches()\n        assert tuple(sizebig) == (6, 2)"},{"col":4,"comment":"null","endLoc":25,"header":"def test_palplot_size(self)","id":3237,"name":"test_palplot_size","nodeType":"Function","startLoc":10,"text":"def test_palplot_size(self):\n\n        pal4 = color_palette(\"husl\", 4)\n        misc.palplot(pal4)\n        size4 = plt.gcf().get_size_inches()\n        assert tuple(size4) == (4, 1)\n\n        pal5 = color_palette(\"husl\", 5)\n        misc.palplot(pal5)\n        size5 = plt.gcf().get_size_inches()\n        assert tuple(size5) == (5, 1)\n\n        palbig = color_palette(\"husl\", 3)\n        misc.palplot(palbig, 2)\n        sizebig = plt.gcf().get_size_inches()\n        assert tuple(sizebig) == (6, 2)"},{"col":4,"comment":"null","endLoc":544,"header":"def _str_index(self)","id":3238,"name":"_str_index","nodeType":"Function","startLoc":528,"text":"def _str_index(self):\n        idx = self['index']\n        out = []\n        output_index = False\n        default_index = idx.get('default', '')\n        if default_index:\n            output_index = True\n        out += [f'.. index:: {default_index}']\n        for section, references in idx.items():\n            if section == 'default':\n                continue\n            output_index = True\n            out += [f\"   :{section}: {', '.join(references)}\"]\n        if output_index:\n            return out\n        else:\n            return ''"},{"col":4,"comment":"null","endLoc":561,"header":"def __str__(self, func_role='')","id":3239,"name":"__str__","nodeType":"Function","startLoc":546,"text":"def __str__(self, func_role=''):\n        out = []\n        out += self._str_signature()\n        out += self._str_summary()\n        out += self._str_extended_summary()\n        for param_list in ('Parameters', 'Returns', 'Yields', 'Receives',\n                           'Other Parameters', 'Raises', 'Warns'):\n            out += self._str_param_list(param_list)\n        out += self._str_section('Warnings')\n        out += self._str_see_also(func_role)\n        for s in ('Notes', 'References', 'Examples'):\n            out += self._str_section(s)\n        for param_list in ('Attributes', 'Methods'):\n            out += self._str_param_list(param_list)\n        out += self._str_index()\n        return '\\n'.join(out)"},{"attributeType":"null","col":4,"comment":"null","endLoc":143,"id":3240,"name":"sections","nodeType":"Attribute","startLoc":143,"text":"sections"},{"attributeType":"null","col":4,"comment":"null","endLoc":279,"id":3241,"name":"_role","nodeType":"Attribute","startLoc":279,"text":"_role"},{"attributeType":"null","col":4,"comment":"null","endLoc":280,"id":3242,"name":"_funcbacktick","nodeType":"Attribute","startLoc":280,"text":"_funcbacktick"},{"attributeType":"null","col":4,"comment":"null","endLoc":281,"id":3243,"name":"_funcplain","nodeType":"Attribute","startLoc":281,"text":"_funcplain"},{"attributeType":"null","col":4,"comment":"null","endLoc":282,"id":3244,"name":"_funcname","nodeType":"Attribute","startLoc":282,"text":"_funcname"},{"attributeType":"null","col":4,"comment":"null","endLoc":283,"id":3245,"name":"_funcnamenext","nodeType":"Attribute","startLoc":283,"text":"_funcnamenext"},{"attributeType":"null","col":4,"comment":"null","endLoc":284,"id":3246,"name":"_funcnamenext","nodeType":"Attribute","startLoc":284,"text":"_funcnamenext"},{"attributeType":"null","col":4,"comment":"null","endLoc":285,"id":3247,"name":"_description","nodeType":"Attribute","startLoc":285,"text":"_description"},{"attributeType":"null","col":4,"comment":"null","endLoc":286,"id":3248,"name":"_func_rgx","nodeType":"Attribute","startLoc":286,"text":"_func_rgx"},{"attributeType":"null","col":4,"comment":"null","endLoc":287,"id":3249,"name":"_line_rgx","nodeType":"Attribute","startLoc":287,"text":"_line_rgx"},{"attributeType":"null","col":4,"comment":"null","endLoc":297,"id":3250,"name":"empty_description","nodeType":"Attribute","startLoc":297,"text":"empty_description"},{"attributeType":"null","col":8,"comment":"null","endLoc":168,"id":3251,"name":"_doc","nodeType":"Attribute","startLoc":168,"text":"self._doc"},{"col":4,"comment":"null","endLoc":177,"header":"def test_int_bins(self, x)","id":3252,"name":"test_int_bins","nodeType":"Function","startLoc":171,"text":"def test_int_bins(self, x):\n\n        n = 24\n        h = Histogram(bins=n)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min(), x.max())\n        assert bin_kws[\"bins\"] == n"},{"attributeType":"null","col":8,"comment":"null","endLoc":169,"id":3253,"name":"_parsed_data","nodeType":"Attribute","startLoc":169,"text":"self._parsed_data"},{"col":4,"comment":"null","endLoc":184,"header":"def test_array_bins(self, x)","id":3254,"name":"test_array_bins","nodeType":"Function","startLoc":179,"text":"def test_array_bins(self, x):\n\n        bins = [-3, -2, 1, 2, 3]\n        h = Histogram(bins=bins)\n        bin_kws = h.define_bin_params(x)\n        assert_array_equal(bin_kws[\"bins\"], bins)"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":69,"id":3255,"name":"_core_params","nodeType":"Attribute","startLoc":69,"text":"_core_params"},{"col":4,"comment":"null","endLoc":198,"header":"def test_bivariate_string_bins(self, x, y)","id":3256,"name":"test_bivariate_string_bins","nodeType":"Function","startLoc":186,"text":"def test_bivariate_string_bins(self, x, y):\n\n        s1, s2 = \"sqrt\", \"fd\"\n\n        h = Histogram(bins=s1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, np.histogram_bin_edges(x, s1))\n        assert_array_equal(e2, np.histogram_bin_edges(y, s1))\n\n        h = Histogram(bins=(s1, s2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, np.histogram_bin_edges(x, s1))\n        assert_array_equal(e2, np.histogram_bin_edges(y, s2))"},{"col":4,"comment":"Add legend artists / labels for one layer in the plot.","endLoc":1577,"header":"def _update_legend_contents(\n        self,\n        p: Plot,\n        mark: Mark,\n        data: PlotData,\n        scales: dict[str, Scale],\n    ) -> None","id":3257,"name":"_update_legend_contents","nodeType":"Function","startLoc":1531,"text":"def _update_legend_contents(\n        self,\n        p: Plot,\n        mark: Mark,\n        data: PlotData,\n        scales: dict[str, Scale],\n    ) -> None:\n        \"\"\"Add legend artists / labels for one layer in the plot.\"\"\"\n        if data.frame.empty and data.frames:\n            legend_vars: list[str] = []\n            for frame in data.frames.values():\n                frame_vars = frame.columns.intersection(list(scales))\n                legend_vars.extend(v for v in frame_vars if v not in legend_vars)\n        else:\n            legend_vars = list(data.frame.columns.intersection(list(scales)))\n\n        # First pass: Identify the values that will be shown for each variable\n        schema: list[tuple[\n            tuple[str, str | int], list[str], tuple[list, list[str]]\n        ]] = []\n        schema = []\n        for var in legend_vars:\n            var_legend = scales[var]._legend\n            if var_legend is not None:\n                values, labels = var_legend\n                for (_, part_id), part_vars, _ in schema:\n                    if data.ids[var] == part_id:\n                        # Allow multiple plot semantics to represent same data variable\n                        part_vars.append(var)\n                        break\n                else:\n                    title = self._resolve_label(p, var, data.names[var])\n                    entry = (title, data.ids[var]), [var], (values, labels)\n                    schema.append(entry)\n\n        # Second pass, generate an artist corresponding to each value\n        contents: list[tuple[tuple[str, str | int], Any, list[str]]] = []\n        for key, variables, (values, labels) in schema:\n            artists = []\n            for val in values:\n                artist = mark._legend_artist(variables, val, scales)\n                if artist is not None:\n                    artists.append(artist)\n            if artists:\n                contents.append((key, artists, labels))\n\n        self._legend_contents.extend(contents)"},{"col":4,"comment":"null","endLoc":212,"header":"def test_bivariate_int_bins(self, x, y)","id":3258,"name":"test_bivariate_int_bins","nodeType":"Function","startLoc":200,"text":"def test_bivariate_int_bins(self, x, y):\n\n        b1, b2 = 5, 10\n\n        h = Histogram(bins=b1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert len(e1) == b1 + 1\n        assert len(e2) == b1 + 1\n\n        h = Histogram(bins=(b1, b2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert len(e1) == b1 + 1\n        assert len(e2) == b2 + 1"},{"className":"TestLine","col":0,"comment":"null","endLoc":153,"id":3259,"nodeType":"Class","startLoc":138,"text":"class TestLine:\n\n    # Most behaviors shared with Path and covered by above tests\n\n    def test_xy_data(self):\n\n        x = [1, 5, 3, np.nan, 2]\n        y = [1, 4, 2, 5, 3]\n        g = [1, 2, 1, 1, 2]\n        p = Plot(x=x, y=y, group=g).add(Line()).plot()\n        line1, line2 = p._figure.axes[0].get_lines()\n\n        assert_array_equal(line1.get_xdata(), [1, 3])\n        assert_array_equal(line1.get_ydata(), [1, 2])\n        assert_array_equal(line2.get_xdata(), [2, 5])\n        assert_array_equal(line2.get_ydata(), [3, 4])"},{"col":4,"comment":"null","endLoc":153,"header":"def test_xy_data(self)","id":3260,"name":"test_xy_data","nodeType":"Function","startLoc":142,"text":"def test_xy_data(self):\n\n        x = [1, 5, 3, np.nan, 2]\n        y = [1, 4, 2, 5, 3]\n        g = [1, 2, 1, 1, 2]\n        p = Plot(x=x, y=y, group=g).add(Line()).plot()\n        line1, line2 = p._figure.axes[0].get_lines()\n\n        assert_array_equal(line1.get_xdata(), [1, 3])\n        assert_array_equal(line1.get_ydata(), [1, 2])\n        assert_array_equal(line2.get_xdata(), [2, 5])\n        assert_array_equal(line2.get_ydata(), [3, 4])"},{"col":4,"comment":"null","endLoc":1603,"header":"def test_axis_labels(self, long_df)","id":3261,"name":"test_axis_labels","nodeType":"Function","startLoc":1590,"text":"def test_axis_labels(self, long_df):\n\n        f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n        p = _ScatterPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n        p.plot(ax1, {})\n        assert ax1.get_xlabel() == \"x\"\n        assert ax1.get_ylabel() == \"y\"\n\n        p.plot(ax2, {})\n        assert ax2.get_xlabel() == \"x\"\n        assert ax2.get_ylabel() == \"y\"\n        assert not ax2.yaxis.label.get_visible()"},{"attributeType":"_ColorPalette | list | list | _ColorPalette","col":8,"comment":"null","endLoc":66,"id":3262,"name":"_orig_palette","nodeType":"Attribute","startLoc":66,"text":"self._orig_palette"},{"col":4,"comment":"null","endLoc":227,"header":"def test_bivariate_array_bins(self, x, y)","id":3263,"name":"test_bivariate_array_bins","nodeType":"Function","startLoc":214,"text":"def test_bivariate_array_bins(self, x, y):\n\n        b1 = [-3, -2, 1, 2, 3]\n        b2 = [-5, -2, 3, 6]\n\n        h = Histogram(bins=b1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, b1)\n        assert_array_equal(e2, b1)\n\n        h = Histogram(bins=(b1, b2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert_array_equal(e1, b1)\n        assert_array_equal(e2, b2)"},{"col":4,"comment":"null","endLoc":1614,"header":"def test_scatterplot_axes(self, wide_df)","id":3264,"name":"test_scatterplot_axes","nodeType":"Function","startLoc":1605,"text":"def test_scatterplot_axes(self, wide_df):\n\n        f1, ax1 = plt.subplots()\n        f2, ax2 = plt.subplots()\n\n        ax = scatterplot(data=wide_df)\n        assert ax is ax2\n\n        ax = scatterplot(data=wide_df, ax=ax1)\n        assert ax is ax1"},{"col":4,"comment":"null","endLoc":236,"header":"def test_binwidth(self, x)","id":3265,"name":"test_binwidth","nodeType":"Function","startLoc":229,"text":"def test_binwidth(self, x):\n\n        binwidth = .5\n        h = Histogram(binwidth=binwidth)\n        bin_kws = h.define_bin_params(x)\n        n_bins = bin_kws[\"bins\"]\n        left, right = bin_kws[\"range\"]\n        assert (right - left) / n_bins == pytest.approx(binwidth)"},{"col":4,"comment":"null","endLoc":1629,"header":"def test_literal_attribute_vectors(self)","id":3266,"name":"test_literal_attribute_vectors","nodeType":"Function","startLoc":1616,"text":"def test_literal_attribute_vectors(self):\n\n        f, ax = plt.subplots()\n\n        x = y = [1, 2, 3]\n        s = [5, 10, 15]\n        c = [(1, 1, 0, 1), (1, 0, 1, .5), (.5, 1, 0, 1)]\n\n        scatterplot(x=x, y=y, c=c, s=s, ax=ax)\n\n        points, = ax.collections\n\n        assert_array_equal(points.get_sizes().squeeze(), s)\n        assert_array_equal(points.get_facecolors(), c)"},{"col":4,"comment":"null","endLoc":250,"header":"def test_bivariate_binwidth(self, x, y)","id":3267,"name":"test_bivariate_binwidth","nodeType":"Function","startLoc":238,"text":"def test_bivariate_binwidth(self, x, y):\n\n        w1, w2 = .5, 1\n\n        h = Histogram(binwidth=w1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert np.all(np.diff(e1) == w1)\n        assert np.all(np.diff(e2) == w1)\n\n        h = Histogram(binwidth=(w1, w2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert np.all(np.diff(e1) == w1)\n        assert np.all(np.diff(e2) == w2)"},{"col":4,"comment":"null","endLoc":1020,"header":"def test_map_diag_color(self)","id":3268,"name":"test_map_diag_color","nodeType":"Function","startLoc":1004,"text":"def test_map_diag_color(self):\n\n        color = \"red\"\n\n        g1 = ag.PairGrid(self.df)\n        g1.map_diag(plt.hist, color=color)\n\n        for ax in g1.diag_axes:\n            for patch in ax.patches:\n                assert_colors_equal(patch.get_facecolor(), color)\n\n        g2 = ag.PairGrid(self.df)\n        g2.map_diag(kdeplot, color='red')\n\n        for ax in g2.diag_axes:\n            for line in ax.lines:\n                assert_colors_equal(line.get_color(), color)"},{"className":"TestPaths","col":0,"comment":"null","endLoc":228,"id":3269,"nodeType":"Class","startLoc":156,"text":"class TestPaths:\n\n    def test_xy_data(self):\n\n        x = [1, 5, 3, np.nan, 2]\n        y = [1, 4, 2, 5, 3]\n        g = [1, 2, 1, 1, 2]\n        p = Plot(x=x, y=y, group=g).add(Paths()).plot()\n        lines, = p._figure.axes[0].collections\n\n        verts = lines.get_paths()[0].vertices.T\n        assert_array_equal(verts[0], [1, 3, np.nan])\n        assert_array_equal(verts[1], [1, 2, np.nan])\n\n        verts = lines.get_paths()[1].vertices.T\n        assert_array_equal(verts[0], [5, 2])\n        assert_array_equal(verts[1], [4, 3])\n\n    def test_set_properties(self):\n\n        x = y = [1, 2, 3]\n        m = Paths(color=\".737\", linewidth=1, linestyle=(3, 1))\n        p = Plot(x=x, y=y).add(m).plot()\n        lines, = p._figure.axes[0].collections\n\n        assert same_color(lines.get_color().squeeze(), m.color)\n        assert lines.get_linewidth().item() == m.linewidth\n        assert lines.get_linestyle()[0] == (0, list(m.linestyle))\n\n    def test_mapped_properties(self):\n\n        x = y = [1, 2, 3, 4]\n        g = [\"a\", \"a\", \"b\", \"b\"]\n        p = Plot(x=x, y=y, color=g, linewidth=g, linestyle=g).add(Paths()).plot()\n        lines, = p._figure.axes[0].collections\n\n        assert not np.array_equal(lines.get_colors()[0], lines.get_colors()[1])\n        assert lines.get_linewidths()[0] != lines.get_linewidth()[1]\n        assert lines.get_linestyle()[0] != lines.get_linestyle()[1]\n\n    def test_color_with_alpha(self):\n\n        x = y = [1, 2, 3]\n        m = Paths(color=(.2, .6, .9, .5))\n        p = Plot(x=x, y=y).add(m).plot()\n        lines, = p._figure.axes[0].collections\n        assert same_color(lines.get_colors().squeeze(), m.color)\n\n    def test_color_and_alpha(self):\n\n        x = y = [1, 2, 3]\n        m = Paths(color=(.2, .6, .9), alpha=.5)\n        p = Plot(x=x, y=y).add(m).plot()\n        lines, = p._figure.axes[0].collections\n        assert same_color(lines.get_colors().squeeze(), to_rgba(m.color, m.alpha))\n\n    def test_capstyle(self):\n\n        x = y = [1, 2]\n        rc = {\"lines.solid_capstyle\": \"projecting\"}\n\n        with mpl.rc_context(rc):\n            p = Plot(x, y).add(Paths()).plot()\n            lines = p._figure.axes[0].collections[0]\n            assert lines.get_capstyle() == \"projecting\"\n\n            p = Plot(x, y).add(Paths(linestyle=\"--\")).plot()\n            lines = p._figure.axes[0].collections[0]\n            assert lines.get_capstyle() == \"projecting\"\n\n            p = Plot(x, y).add(Paths({\"capstyle\": \"butt\"})).plot()\n            lines = p._figure.axes[0].collections[0]\n            assert lines.get_capstyle() == \"butt\""},{"col":4,"comment":"null","endLoc":172,"header":"def test_xy_data(self)","id":3270,"name":"test_xy_data","nodeType":"Function","startLoc":158,"text":"def test_xy_data(self):\n\n        x = [1, 5, 3, np.nan, 2]\n        y = [1, 4, 2, 5, 3]\n        g = [1, 2, 1, 1, 2]\n        p = Plot(x=x, y=y, group=g).add(Paths()).plot()\n        lines, = p._figure.axes[0].collections\n\n        verts = lines.get_paths()[0].vertices.T\n        assert_array_equal(verts[0], [1, 3, np.nan])\n        assert_array_equal(verts[1], [1, 2, np.nan])\n\n        verts = lines.get_paths()[1].vertices.T\n        assert_array_equal(verts[0], [5, 2])\n        assert_array_equal(verts[1], [4, 3])"},{"col":4,"comment":"null","endLoc":1653,"header":"def test_supplied_color_array(self, long_df)","id":3271,"name":"test_supplied_color_array","nodeType":"Function","startLoc":1631,"text":"def test_supplied_color_array(self, long_df):\n\n        cmap = get_colormap(\"Blues\")\n        norm = mpl.colors.Normalize()\n        colors = cmap(norm(long_df[\"y\"].to_numpy()))\n\n        keys = [\"c\", \"facecolor\", \"facecolors\"]\n\n        if Version(mpl.__version__) >= Version(\"3.1.0\"):\n            # https://github.com/matplotlib/matplotlib/pull/12851\n            keys.append(\"fc\")\n\n        for key in keys:\n\n            ax = plt.figure().subplots()\n            scatterplot(data=long_df, x=\"x\", y=\"y\", **{key: colors})\n            _draw_figure(ax.figure)\n            assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n        ax = plt.figure().subplots()\n        scatterplot(data=long_df, x=\"x\", y=\"y\", c=long_df[\"y\"], cmap=cmap)\n        _draw_figure(ax.figure)\n        assert_array_equal(ax.collections[0].get_facecolors(), colors)"},{"col":4,"comment":"null","endLoc":1031,"header":"def test_map_diag_palette(self)","id":3272,"name":"test_map_diag_palette","nodeType":"Function","startLoc":1022,"text":"def test_map_diag_palette(self):\n\n        palette = \"muted\"\n        pal = color_palette(palette, n_colors=len(self.df.a.unique()))\n        g = ag.PairGrid(self.df, hue=\"a\", palette=palette)\n        g.map_diag(kdeplot)\n\n        for ax in g.diag_axes:\n            for line, color in zip(ax.lines[::-1], pal):\n                assert_colors_equal(line.get_color(), color)"},{"col":4,"comment":"null","endLoc":257,"header":"def test_binrange(self, x)","id":3273,"name":"test_binrange","nodeType":"Function","startLoc":252,"text":"def test_binrange(self, x):\n\n        binrange = (-4, 4)\n        h = Histogram(binrange=binrange)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == binrange"},{"col":4,"comment":"null","endLoc":275,"header":"def test_bivariate_binrange(self, x, y)","id":3274,"name":"test_bivariate_binrange","nodeType":"Function","startLoc":259,"text":"def test_bivariate_binrange(self, x, y):\n\n        r1, r2 = (-4, 4), (-10, 10)\n\n        h = Histogram(binrange=r1)\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert e1.min() == r1[0]\n        assert e1.max() == r1[1]\n        assert e2.min() == r1[0]\n        assert e2.max() == r1[1]\n\n        h = Histogram(binrange=(r1, r2))\n        e1, e2 = h.define_bin_params(x, y)[\"bins\"]\n        assert e1.min() == r1[0]\n        assert e1.max() == r1[1]\n        assert e2.min() == r2[0]\n        assert e2.max() == r2[1]"},{"className":"TestDogPlot","col":0,"comment":"null","endLoc":34,"id":3275,"nodeType":"Class","startLoc":28,"text":"class TestDogPlot:\n\n    @_network(url=\"https://github.com/mwaskom/seaborn-data\")\n    def test_dogplot(self):\n        misc.dogplot()\n        ax = plt.gca()\n        assert len(ax.images) == 1"},{"col":4,"comment":"null","endLoc":34,"header":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\n    def test_dogplot(self)","id":3276,"name":"test_dogplot","nodeType":"Function","startLoc":30,"text":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\n    def test_dogplot(self):\n        misc.dogplot()\n        ax = plt.gca()\n        assert len(ax.images) == 1"},{"col":4,"comment":"null","endLoc":183,"header":"def test_set_properties(self)","id":3277,"name":"test_set_properties","nodeType":"Function","startLoc":174,"text":"def test_set_properties(self):\n\n        x = y = [1, 2, 3]\n        m = Paths(color=\".737\", linewidth=1, linestyle=(3, 1))\n        p = Plot(x=x, y=y).add(m).plot()\n        lines, = p._figure.axes[0].collections\n\n        assert same_color(lines.get_color().squeeze(), m.color)\n        assert lines.get_linewidth().item() == m.linewidth\n        assert lines.get_linestyle()[0] == (0, list(m.linestyle))"},{"attributeType":"null","col":28,"comment":"null","endLoc":1,"id":3278,"name":"plt","nodeType":"Attribute","startLoc":1,"text":"plt"},{"attributeType":"null","col":32,"comment":"null","endLoc":3,"id":3279,"name":"misc","nodeType":"Attribute","startLoc":3,"text":"misc"},{"col":4,"comment":"null","endLoc":1061,"header":"def test_map_diag_and_offdiag(self)","id":3280,"name":"test_map_diag_and_offdiag","nodeType":"Function","startLoc":1033,"text":"def test_map_diag_and_offdiag(self):\n\n        vars = [\"x\", \"y\", \"z\"]\n        g = ag.PairGrid(self.df)\n        g.map_offdiag(plt.scatter)\n        g.map_diag(plt.hist)\n\n        for ax in g.diag_axes:\n            assert len(ax.patches) == 10\n\n        for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n        for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n        for i, j in zip(*np.diag_indices_from(g.axes)):\n            ax = g.axes[i, j]\n            assert len(ax.collections) == 0"},{"id":3281,"name":"index.rst","nodeType":"TextFile","path":"doc/whatsnew","text":".. _whatsnew:\n\nWhat's new in each version\n==========================\n\nv0.12\n-----\n.. toctree::\n   :maxdepth: 2\n\n   v0.12.1\n   v0.12.0\n\nv0.11\n-----\n.. toctree::\n   :maxdepth: 2\n\n   v0.11.2\n   v0.11.1\n   v0.11.0\n\nv0.10\n-----\n.. toctree::\n   :maxdepth: 2\n\n   v0.10.1\n   v0.10.0\n\nv0.9\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.9.1\n   v0.9.0\n\nv0.8\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.8.1\n   v0.8.0\n\nv0.7\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.7.1\n   v0.7.0\n\nv0.6\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.6.0\n\nv0.5\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.5.1\n   v0.5.0\n\nv0.4\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.4.0\n\nv0.3\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.3.1\n   v0.3.0\n\nv0.2\n----\n.. toctree::\n   :maxdepth: 2\n\n   v0.2.1\n   v0.2.0\n"},{"id":3282,"name":"blend_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8f97280e-cec8-42b2-a968-4fd4364594f8\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme()\\n\",\n    \"sns.palettes._patch_colormap_display()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"972edede-df1a-4010-9674-00b864d020e2\",\n   \"metadata\": {},\n   \"source\": [\n    \"Pass a list of two colors to interpolate between them:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e6ae2547-1042-4ac0-84ea-6f37a0229871\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.blend_palette([\\\"b\\\", \\\"r\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"1d983eac-2dd5-4746-b27f-4dfa19b5e091\",\n   \"metadata\": {},\n   \"source\": [\n    \"The color list can be arbitrarily long, and any color format can be used:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"846b78fd-30ce-4507-93f4-4274122c1987\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.blend_palette([\\\"#45a872\\\", \\\".8\\\", \\\"xkcd:golden\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"318fef32-1f83-44d9-9ff9-21fa0231b7c6\",\n   \"metadata\": {},\n   \"source\": [\n    \"Return a continuous colormap instead of a discrete palette:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f0a05bc3-c60b-47a1-b276-d2e28a4a8226\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.blend_palette([\\\"#bdc\\\", \\\"#7b9\\\", \\\"#47a\\\"], as_cmap=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"0473a402-0ec2-4877-81d2-ed6c57aefc77\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":283,"header":"def test_discrete_bins(self, rng)","id":3283,"name":"test_discrete_bins","nodeType":"Function","startLoc":277,"text":"def test_discrete_bins(self, rng):\n\n        x = rng.binomial(20, .5, 100)\n        h = Histogram(discrete=True)\n        bin_kws = h.define_bin_params(x)\n        assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n        assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)"},{"id":3284,"name":"displot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns; sns.set_theme(style=\\\"ticks\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The default plot kind is a histogram:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the ``kind`` parameter to select a different representation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", kind=\\\"kde\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"There are three main plot kinds; in addition to histograms and kernel density estimates (KDEs), you can also draw empirical cumulative distribution functions (ECDFs):\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", kind=\\\"ecdf\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"While in histogram mode, it is also possible to add a KDE curve:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", kde=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"To draw a bivariate plot, assign both ``x`` and ``y``:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Currently, bivariate plots are available only for histograms and KDEs:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", kind=\\\"kde\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"For each kind of plot, you can also show individual observations with a marginal \\\"rug\\\":\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", kind=\\\"kde\\\", rug=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Each kind of plot can be drawn separately for subsets of data using ``hue`` mapping:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", kind=\\\"kde\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Additional keyword arguments are passed to the appropriate underlying plotting function, allowing for further customization:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The figure is constructed using a :class:`FacetGrid`, meaning that you can also show subsets on distinct subplots, or \\\"facets\\\":\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", col=\\\"sex\\\", kind=\\\"kde\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Because the figure is drawn with a :class:`FacetGrid`, you control its size and shape with the ``height`` and ``aspect`` parameters:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(\\n\",\n    \"    data=penguins, y=\\\"flipper_length_mm\\\", hue=\\\"sex\\\", col=\\\"species\\\",\\n\",\n    \"    kind=\\\"ecdf\\\", height=4, aspect=.7,\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The function returns the :class:`FacetGrid` object with the plot, and you can use the methods on this object to customize it further:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.displot(\\n\",\n    \"    data=penguins, y=\\\"flipper_length_mm\\\", hue=\\\"sex\\\", col=\\\"species\\\",\\n\",\n    \"    kind=\\\"kde\\\", height=4, aspect=.7,\\n\",\n    \")\\n\",\n    \"g.set_axis_labels(\\\"Density (a.u.)\\\", \\\"Flipper length (mm)\\\")\\n\",\n    \"g.set_titles(\\\"{col_name} penguins\\\")\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":3285,"name":"clustermap.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ffc1e1d9-fa74-4121-aa87-e1a8665e4c2b\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"41b4f602-32af-44f8-bf1a-0f1695c9abbb\",\n   \"metadata\": {},\n   \"source\": [\n    \"Plot a heatmap with row and column clustering:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c715bd8f-cf5d-4caa-9244-336b3d0248a8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"iris = sns.load_dataset(\\\"iris\\\")\\n\",\n    \"species = iris.pop(\\\"species\\\")\\n\",\n    \"sns.clustermap(iris)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"1cc3134c-579a-442a-97d8-a878651ce90a\",\n   \"metadata\": {},\n   \"source\": [\n    \"Change the size and layout of the figure:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"fd33cf4b-9589-4b9a-a246-0b95bad28c51\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.clustermap(\\n\",\n    \"    iris,\\n\",\n    \"    figsize=(7, 5),\\n\",\n    \"    row_cluster=False,\\n\",\n    \"    dendrogram_ratio=(.1, .2),\\n\",\n    \"    cbar_pos=(0, .2, .03, .4)\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"c5d3408d-f5d6-4045-9d61-15573a981587\",\n   \"metadata\": {},\n   \"source\": [\n    \"Add colored labels to identify observations:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"79d3fe52-6146-4f33-a39a-1d4a47243ea5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"lut = dict(zip(species.unique(), \\\"rbg\\\"))\\n\",\n    \"row_colors = species.map(lut)\\n\",\n    \"sns.clustermap(iris, row_colors=row_colors)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"f2f944e2-36cd-4653-86b4-6d2affec13d6\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use a different colormap and adjust the limits of the color range:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6137c7ad-db92-47b8-9d00-3228c4e1f7df\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.clustermap(iris, cmap=\\\"mako\\\", vmin=0, vmax=10)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"93f96d1c-9d04-464f-93c9-4319caa8504a\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use differente clustering parameters:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f9e76bde-a222-4eca-971f-54f56ad53281\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.clustermap(iris, metric=\\\"correlation\\\", method=\\\"single\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"ea6ed3fd-188d-4244-adac-ec0169c02205\",\n   \"metadata\": {},\n   \"source\": [\n    \"Standardize the data within the columns:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e5f744c4-b959-4ed1-b2cf-6046c9214568\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.clustermap(iris, standard_scale=1)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"7ca72242-4eb0-4f8e-b0c0-d1ef7166b738\",\n   \"metadata\": {},\n   \"source\": [\n    \"Normalize the data within rows:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"33815c4c-9bae-4226-bd11-3dfdb7ecab2b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.clustermap(iris, z_score=0, cmap=\\\"vlag\\\", center=0)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"0f37d57a-b049-4665-9c24-4d5fbbca00ba\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":1663,"header":"def test_hue_order(self, long_df)","id":3286,"name":"test_hue_order","nodeType":"Function","startLoc":1655,"text":"def test_hue_order(self, long_df):\n\n        order = categorical_order(long_df[\"a\"])\n        unused = order.pop()\n\n        ax = scatterplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", hue_order=order)\n        points = ax.collections[0]\n        assert (points.get_facecolors()[long_df[\"a\"] == unused] == 0).all()\n        assert [t.get_text() for t in ax.legend_.texts] == order"},{"col":4,"comment":"null","endLoc":290,"header":"def test_odd_single_observation(self)","id":3287,"name":"test_odd_single_observation","nodeType":"Function","startLoc":285,"text":"def test_odd_single_observation(self):\n        # GH2721\n        x = np.array([0.49928])\n        h, e = Histogram(binwidth=0.03)(x)\n        assert len(h) == 1\n        assert (e[1] - e[0]) == pytest.approx(.03)"},{"col":4,"comment":"null","endLoc":1695,"header":"def test_linewidths(self, long_df)","id":3288,"name":"test_linewidths","nodeType":"Function","startLoc":1665,"text":"def test_linewidths(self, long_df):\n\n        f, ax = plt.subplots()\n\n        scatterplot(data=long_df, x=\"x\", y=\"y\", s=10)\n        scatterplot(data=long_df, x=\"x\", y=\"y\", s=20)\n        points1, points2 = ax.collections\n        assert (\n            points1.get_linewidths().item() < points2.get_linewidths().item()\n        )\n\n        ax.clear()\n        scatterplot(data=long_df, x=\"x\", y=\"y\", s=long_df[\"x\"])\n        scatterplot(data=long_df, x=\"x\", y=\"y\", s=long_df[\"x\"] * 2)\n        points1, points2 = ax.collections\n        assert (\n            points1.get_linewidths().item() < points2.get_linewidths().item()\n        )\n\n        ax.clear()\n        scatterplot(data=long_df, x=\"x\", y=\"y\", size=long_df[\"x\"])\n        scatterplot(data=long_df, x=\"x\", y=\"y\", size=long_df[\"x\"] * 2)\n        points1, points2, *_ = ax.collections\n        assert (\n            points1.get_linewidths().item() < points2.get_linewidths().item()\n        )\n\n        ax.clear()\n        lw = 2\n        scatterplot(data=long_df, x=\"x\", y=\"y\", linewidth=lw)\n        assert ax.collections[0].get_linewidths().item() == lw"},{"col":4,"comment":"null","endLoc":1068,"header":"def test_diag_sharey(self)","id":3289,"name":"test_diag_sharey","nodeType":"Function","startLoc":1063,"text":"def test_diag_sharey(self):\n\n        g = ag.PairGrid(self.df, diag_sharey=True)\n        g.map_diag(kdeplot)\n        for ax in g.diag_axes[1:]:\n            assert ax.get_ylim() == g.diag_axes[0].get_ylim()"},{"col":4,"comment":"null","endLoc":194,"header":"def test_mapped_properties(self)","id":3290,"name":"test_mapped_properties","nodeType":"Function","startLoc":185,"text":"def test_mapped_properties(self):\n\n        x = y = [1, 2, 3, 4]\n        g = [\"a\", \"a\", \"b\", \"b\"]\n        p = Plot(x=x, y=y, color=g, linewidth=g, linestyle=g).add(Paths()).plot()\n        lines, = p._figure.axes[0].collections\n\n        assert not np.array_equal(lines.get_colors()[0], lines.get_colors()[1])\n        assert lines.get_linewidths()[0] != lines.get_linewidth()[1]\n        assert lines.get_linestyle()[0] != lines.get_linestyle()[1]"},{"col":4,"comment":"null","endLoc":296,"header":"def test_binwidth_roundoff(self)","id":3291,"name":"test_binwidth_roundoff","nodeType":"Function","startLoc":292,"text":"def test_binwidth_roundoff(self):\n        # GH2785\n        x = np.array([2.4, 2.5, 2.6])\n        h, e = Histogram(binwidth=0.01)(x)\n        assert h.sum() == 3"},{"col":4,"comment":"null","endLoc":1729,"header":"def test_size_norm_extrapolation(self)","id":3292,"name":"test_size_norm_extrapolation","nodeType":"Function","startLoc":1697,"text":"def test_size_norm_extrapolation(self):\n\n        # https://github.com/mwaskom/seaborn/issues/2539\n        x = np.arange(0, 20, 2)\n        f, axs = plt.subplots(1, 2, sharex=True, sharey=True)\n\n        slc = 5\n        kws = dict(sizes=(50, 200), size_norm=(0, x.max()), legend=\"brief\")\n\n        scatterplot(x=x, y=x, size=x, ax=axs[0], **kws)\n        scatterplot(x=x[:slc], y=x[:slc], size=x[:slc], ax=axs[1], **kws)\n\n        assert np.allclose(\n            axs[0].collections[0].get_sizes()[:slc],\n            axs[1].collections[0].get_sizes()\n        )\n\n        legends = [ax.legend_ for ax in axs]\n        legend_data = [\n            {\n                label.get_text(): handle.get_sizes().item()\n                for label, handle in zip(legend.get_texts(), legend.legendHandles)\n            } for legend in legends\n        ]\n\n        for key in set(legend_data[0]) & set(legend_data[1]):\n            if key == \"y\":\n                # At some point (circa 3.0) matplotlib auto-added pandas series\n                # with a valid name into the legend, which messes up this test.\n                # I can't track down when that was added (or removed), so let's\n                # just anticipate and ignore it here.\n                continue\n            assert legend_data[0][key] == legend_data[1][key]"},{"col":4,"comment":"null","endLoc":202,"header":"def test_color_with_alpha(self)","id":3293,"name":"test_color_with_alpha","nodeType":"Function","startLoc":196,"text":"def test_color_with_alpha(self):\n\n        x = y = [1, 2, 3]\n        m = Paths(color=(.2, .6, .9, .5))\n        p = Plot(x=x, y=y).add(m).plot()\n        lines, = p._figure.axes[0].collections\n        assert same_color(lines.get_colors().squeeze(), m.color)"},{"col":4,"comment":"null","endLoc":305,"header":"def test_histogram(self, x)","id":3294,"name":"test_histogram","nodeType":"Function","startLoc":298,"text":"def test_histogram(self, x):\n\n        h = Histogram()\n        heights, edges = h(x)\n        heights_mpl, edges_mpl = np.histogram(x, bins=\"auto\")\n\n        assert_array_equal(heights, heights_mpl)\n        assert_array_equal(edges, edges_mpl)"},{"col":4,"comment":"null","endLoc":311,"header":"def test_count_stat(self, x)","id":3295,"name":"test_count_stat","nodeType":"Function","startLoc":307,"text":"def test_count_stat(self, x):\n\n        h = Histogram(stat=\"count\")\n        heights, _ = h(x)\n        assert heights.sum() == len(x)"},{"col":4,"comment":"null","endLoc":1082,"header":"def test_map_diag_matplotlib(self)","id":3296,"name":"test_map_diag_matplotlib","nodeType":"Function","startLoc":1070,"text":"def test_map_diag_matplotlib(self):\n\n        bins = 10\n        g = ag.PairGrid(self.df)\n        g.map_diag(plt.hist, bins=bins)\n        for ax in g.diag_axes:\n            assert len(ax.patches) == bins\n\n        levels = len(self.df[\"a\"].unique())\n        g = ag.PairGrid(self.df, hue=\"a\")\n        g.map_diag(plt.hist, bins=bins)\n        for ax in g.diag_axes:\n            assert len(ax.patches) == (bins * levels)"},{"col":4,"comment":"null","endLoc":317,"header":"def test_density_stat(self, x)","id":3297,"name":"test_density_stat","nodeType":"Function","startLoc":313,"text":"def test_density_stat(self, x):\n\n        h = Histogram(stat=\"density\")\n        heights, edges = h(x)\n        assert (heights * np.diff(edges)).sum() == 1"},{"col":4,"comment":"null","endLoc":323,"header":"def test_probability_stat(self, x)","id":3298,"name":"test_probability_stat","nodeType":"Function","startLoc":319,"text":"def test_probability_stat(self, x):\n\n        h = Histogram(stat=\"probability\")\n        heights, _ = h(x)\n        assert heights.sum() == 1"},{"col":4,"comment":"null","endLoc":329,"header":"def test_frequency_stat(self, x)","id":3299,"name":"test_frequency_stat","nodeType":"Function","startLoc":325,"text":"def test_frequency_stat(self, x):\n\n        h = Histogram(stat=\"frequency\")\n        heights, edges = h(x)\n        assert (heights * np.diff(edges)).sum() == len(x)"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":114,"id":3300,"name":"_core_returns","nodeType":"Attribute","startLoc":114,"text":"_core_returns"},{"col":4,"comment":"null","endLoc":2316,"header":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", weights=\"f\"),\n            dict(y=\"x\"),\n            dict(x=\"x\", color=\"green\", linewidth=2),\n            dict(x=\"x\", hue=\"a\", complementary=True),\n            dict(x=\"x\", hue=\"a\", stat=\"count\"),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n        ],\n    )\n    def test_versus_single_ecdfplot(self, long_df, kwargs)","id":3301,"name":"test_versus_single_ecdfplot","nodeType":"Function","startLoc":2290,"text":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(),\n            dict(x=\"x\"),\n            dict(x=\"t\"),\n            dict(x=\"z\", log_scale=True),\n            dict(x=\"x\", weights=\"f\"),\n            dict(y=\"x\"),\n            dict(x=\"x\", color=\"green\", linewidth=2),\n            dict(x=\"x\", hue=\"a\", complementary=True),\n            dict(x=\"x\", hue=\"a\", stat=\"count\"),\n            dict(x=\"x\", hue=\"a\", palette=\"muted\"),\n        ],\n    )\n    def test_versus_single_ecdfplot(self, long_df, kwargs):\n\n        ax = ecdfplot(data=long_df, **kwargs)\n        g = displot(long_df, kind=\"ecdf\", **kwargs)\n        assert_plots_equal(ax, g.ax)\n\n        if ax.legend_ is not None:\n            assert_legends_equal(ax.legend_, g._legend)\n\n        if kwargs:\n            long_df[\"_\"] = \"_\"\n            g2 = displot(long_df, kind=\"ecdf\", col=\"_\", **kwargs)\n            assert_plots_equal(ax, g2.ax)"},{"col":4,"comment":"null","endLoc":335,"header":"def test_cumulative_count(self, x)","id":3302,"name":"test_cumulative_count","nodeType":"Function","startLoc":331,"text":"def test_cumulative_count(self, x):\n\n        h = Histogram(stat=\"count\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == len(x)"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":137,"id":3303,"name":"_seealso_blurbs","nodeType":"Attribute","startLoc":137,"text":"_seealso_blurbs"},{"col":4,"comment":"null","endLoc":341,"header":"def test_cumulative_density(self, x)","id":3304,"name":"test_cumulative_density","nodeType":"Function","startLoc":337,"text":"def test_cumulative_density(self, x):\n\n        h = Histogram(stat=\"density\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == 1"},{"col":4,"comment":"null","endLoc":347,"header":"def test_cumulative_probability(self, x)","id":3305,"name":"test_cumulative_probability","nodeType":"Function","startLoc":343,"text":"def test_cumulative_probability(self, x):\n\n        h = Histogram(stat=\"probability\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == 1"},{"col":4,"comment":"Draw a line to mark a single observation.","endLoc":1325,"header":"def draw_single_observation(self, ax, at_group, at_quant, density)","id":3306,"name":"draw_single_observation","nodeType":"Function","startLoc":1313,"text":"def draw_single_observation(self, ax, at_group, at_quant, density):\n        \"\"\"Draw a line to mark a single observation.\"\"\"\n        d_width = density * self.dwidth\n        if self.orient == \"v\":\n            ax.plot([at_group - d_width, at_group + d_width],\n                    [at_quant, at_quant],\n                    color=self.gray,\n                    linewidth=self.linewidth)\n        else:\n            ax.plot([at_quant, at_quant],\n                    [at_group - d_width, at_group + d_width],\n                    color=self.gray,\n                    linewidth=self.linewidth)"},{"col":4,"comment":"null","endLoc":1105,"header":"def test_palette(self)","id":3307,"name":"test_palette","nodeType":"Function","startLoc":1084,"text":"def test_palette(self):\n\n        rcmod.set()\n\n        g = ag.PairGrid(self.df, hue=\"a\")\n        assert g.palette == color_palette(n_colors=len(self.df.a.unique()))\n\n        g = ag.PairGrid(self.df, hue=\"b\")\n        assert g.palette == color_palette(\"husl\", len(self.df.b.unique()))\n\n        g = ag.PairGrid(self.df, hue=\"a\", palette=\"Set2\")\n        assert g.palette == color_palette(\"Set2\", len(self.df.a.unique()))\n\n        dict_pal = dict(a=\"red\", b=\"green\", c=\"blue\")\n        list_pal = color_palette([\"red\", \"green\", \"blue\"])\n        g = ag.PairGrid(self.df, hue=\"a\", palette=dict_pal)\n        assert g.palette == list_pal\n\n        list_pal = color_palette([\"blue\", \"red\", \"green\"])\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=list(\"cab\"),\n                        palette=dict_pal)\n        assert g.palette == list_pal"},{"col":4,"comment":"null","endLoc":210,"header":"def test_color_and_alpha(self)","id":3308,"name":"test_color_and_alpha","nodeType":"Function","startLoc":204,"text":"def test_color_and_alpha(self):\n\n        x = y = [1, 2, 3]\n        m = Paths(color=(.2, .6, .9), alpha=.5)\n        p = Plot(x=x, y=y).add(m).plot()\n        lines, = p._figure.axes[0].collections\n        assert same_color(lines.get_colors().squeeze(), to_rgba(m.color, m.alpha))"},{"col":4,"comment":"null","endLoc":353,"header":"def test_cumulative_frequency(self, x)","id":3309,"name":"test_cumulative_frequency","nodeType":"Function","startLoc":349,"text":"def test_cumulative_frequency(self, x):\n\n        h = Histogram(stat=\"frequency\", cumulative=True)\n        heights, _ = h(x)\n        assert heights[-1] == len(x)"},{"col":4,"comment":"null","endLoc":228,"header":"def test_capstyle(self)","id":3310,"name":"test_capstyle","nodeType":"Function","startLoc":212,"text":"def test_capstyle(self):\n\n        x = y = [1, 2]\n        rc = {\"lines.solid_capstyle\": \"projecting\"}\n\n        with mpl.rc_context(rc):\n            p = Plot(x, y).add(Paths()).plot()\n            lines = p._figure.axes[0].collections[0]\n            assert lines.get_capstyle() == \"projecting\"\n\n            p = Plot(x, y).add(Paths(linestyle=\"--\")).plot()\n            lines = p._figure.axes[0].collections[0]\n            assert lines.get_capstyle() == \"projecting\"\n\n            p = Plot(x, y).add(Paths({\"capstyle\": \"butt\"})).plot()\n            lines = p._figure.axes[0].collections[0]\n            assert lines.get_capstyle() == \"butt\""},{"col":4,"comment":"null","endLoc":366,"header":"def test_bivariate_histogram(self, x, y)","id":3311,"name":"test_bivariate_histogram","nodeType":"Function","startLoc":355,"text":"def test_bivariate_histogram(self, x, y):\n\n        h = Histogram()\n        heights, edges = h(x, y)\n        bins_mpl = (\n            np.histogram_bin_edges(x, \"auto\"),\n            np.histogram_bin_edges(y, \"auto\"),\n        )\n        heights_mpl, *edges_mpl = np.histogram2d(x, y, bins_mpl)\n        assert_array_equal(heights, heights_mpl)\n        assert_array_equal(edges[0], edges_mpl[0])\n        assert_array_equal(edges[1], edges_mpl[1])"},{"col":0,"comment":"","endLoc":1,"header":"_docstrings.py#","id":3312,"name":"","nodeType":"Function","startLoc":1,"text":"_core_params = dict(\n    data=\"\"\"\ndata : :class:`pandas.DataFrame`, :class:`numpy.ndarray`, mapping, or sequence\n    Input data structure. Either a long-form collection of vectors that can be\n    assigned to named variables or a wide-form dataset that will be internally\n    reshaped.\n    \"\"\",  # TODO add link to user guide narrative when exists\n    xy=\"\"\"\nx, y : vectors or keys in ``data``\n    Variables that specify positions on the x and y axes.\n    \"\"\",\n    hue=\"\"\"\nhue : vector or key in ``data``\n    Semantic variable that is mapped to determine the color of plot elements.\n    \"\"\",\n    palette=\"\"\"\npalette : string, list, dict, or :class:`matplotlib.colors.Colormap`\n    Method for choosing the colors to use when mapping the ``hue`` semantic.\n    String values are passed to :func:`color_palette`. List or dict values\n    imply categorical mapping, while a colormap object implies numeric mapping.\n    \"\"\",  # noqa: E501\n    hue_order=\"\"\"\nhue_order : vector of strings\n    Specify the order of processing and plotting for categorical levels of the\n    ``hue`` semantic.\n    \"\"\",\n    hue_norm=\"\"\"\nhue_norm : tuple or :class:`matplotlib.colors.Normalize`\n    Either a pair of values that set the normalization range in data units\n    or an object that will map from data units into a [0, 1] interval. Usage\n    implies numeric mapping.\n    \"\"\",\n    color=\"\"\"\ncolor : :mod:`matplotlib color `\n    Single color specification for when hue mapping is not used. Otherwise, the\n    plot will try to hook into the matplotlib property cycle.\n    \"\"\",\n    ax=\"\"\"\nax : :class:`matplotlib.axes.Axes`\n    Pre-existing axes for the plot. Otherwise, call :func:`matplotlib.pyplot.gca`\n    internally.\n    \"\"\",  # noqa: E501\n)\n\n_core_returns = dict(\n    ax=\"\"\"\n:class:`matplotlib.axes.Axes`\n    The matplotlib axes containing the plot.\n    \"\"\",\n    facetgrid=\"\"\"\n:class:`FacetGrid`\n    An object managing one or more subplots that correspond to conditional data\n    subsets with convenient methods for batch-setting of axes attributes.\n    \"\"\",\n    jointgrid=\"\"\"\n:class:`JointGrid`\n    An object managing multiple subplots that correspond to joint and marginal axes\n    for plotting a bivariate relationship or distribution.\n    \"\"\",\n    pairgrid=\"\"\"\n:class:`PairGrid`\n    An object managing multiple subplots that correspond to joint and marginal axes\n    for pairwise combinations of multiple variables in a dataset.\n    \"\"\",\n)\n\n_seealso_blurbs = dict(\n\n    # Relational plots\n    scatterplot=\"\"\"\nscatterplot : Plot data using points.\n    \"\"\",\n    lineplot=\"\"\"\nlineplot : Plot data using lines.\n    \"\"\",\n\n    # Distribution plots\n    displot=\"\"\"\ndisplot : Figure-level interface to distribution plot functions.\n    \"\"\",\n    histplot=\"\"\"\nhistplot : Plot a histogram of binned counts with optional normalization or smoothing.\n    \"\"\",\n    kdeplot=\"\"\"\nkdeplot : Plot univariate or bivariate distributions using kernel density estimation.\n    \"\"\",\n    ecdfplot=\"\"\"\necdfplot : Plot empirical cumulative distribution functions.\n    \"\"\",\n    rugplot=\"\"\"\nrugplot : Plot a tick at each observation value along the x and/or y axes.\n    \"\"\",\n\n    # Categorical plots\n    stripplot=\"\"\"\nstripplot : Plot a categorical scatter with jitter.\n    \"\"\",\n    swarmplot=\"\"\"\nswarmplot : Plot a categorical scatter with non-overlapping points.\n    \"\"\",\n    violinplot=\"\"\"\nviolinplot : Draw an enhanced boxplot using kernel density estimation.\n    \"\"\",\n    pointplot=\"\"\"\npointplot : Plot point estimates and CIs using markers and lines.\n    \"\"\",\n\n    # Multiples\n    jointplot=\"\"\"\njointplot : Draw a bivariate plot with univariate marginal distributions.\n    \"\"\",\n    pairplot=\"\"\"\njointplot : Draw multiple bivariate plots with univariate marginal distributions.\n    \"\"\",\n    jointgrid=\"\"\"\nJointGrid : Set up a figure with joint and marginal views on bivariate data.\n    \"\"\",\n    pairgrid=\"\"\"\nPairGrid : Set up a figure with joint and marginal views on multiple variables.\n    \"\"\",\n)\n\n_core_docs = dict(\n    params=DocstringComponents(_core_params),\n    returns=DocstringComponents(_core_returns),\n    seealso=DocstringComponents(_seealso_blurbs),\n)"},{"col":4,"comment":"null","endLoc":372,"header":"def test_bivariate_count_stat(self, x, y)","id":3313,"name":"test_bivariate_count_stat","nodeType":"Function","startLoc":368,"text":"def test_bivariate_count_stat(self, x, y):\n\n        h = Histogram(stat=\"count\")\n        heights, _ = h(x, y)\n        assert heights.sum() == len(x)"},{"id":3314,"name":"object.rst","nodeType":"TextFile","path":"doc/_templates/autosummary","text":"{{ fullname | escape | underline}}\n\n.. currentmodule:: {{ module }}\n\n.. autoclass:: {{ objname }}\n"},{"col":4,"comment":"null","endLoc":379,"header":"def test_bivariate_density_stat(self, x, y)","id":3315,"name":"test_bivariate_density_stat","nodeType":"Function","startLoc":374,"text":"def test_bivariate_density_stat(self, x, y):\n\n        h = Histogram(stat=\"density\")\n        heights, (edges_x, edges_y) = h(x, y)\n        areas = np.outer(np.diff(edges_x), np.diff(edges_y))\n        assert (heights * areas).sum() == pytest.approx(1)"},{"fileName":"faceted_histogram.py","filePath":"examples","id":3316,"nodeType":"File","text":"\"\"\"\nFacetting histograms by subsets of data\n=======================================\n\n_thumb: .33, .57\n\"\"\"\nimport seaborn as sns\n\nsns.set_theme(style=\"darkgrid\")\ndf = sns.load_dataset(\"penguins\")\nsns.displot(\n    df, x=\"flipper_length_mm\", col=\"species\", row=\"sex\",\n    binwidth=3, height=3, facet_kws=dict(margin_titles=True),\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3317,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":3318,"name":"df","nodeType":"Attribute","startLoc":10,"text":"df"},{"col":4,"comment":"Create the legend artist(s) and add onto the figure.","endLoc":1626,"header":"def _make_legend(self, p: Plot) -> None","id":3319,"name":"_make_legend","nodeType":"Function","startLoc":1579,"text":"def _make_legend(self, p: Plot) -> None:\n        \"\"\"Create the legend artist(s) and add onto the figure.\"\"\"\n        # Combine artists representing same information across layers\n        # Input list has an entry for each distinct variable in each layer\n        # Output dict has an entry for each distinct variable\n        merged_contents: dict[\n            tuple[str, str | int], tuple[list[Artist], list[str]],\n        ] = {}\n        for key, new_artists, labels in self._legend_contents:\n            # Key is (name, id); we need the id to resolve variable uniqueness,\n            # but will need the name in the next step to title the legend\n            if key in merged_contents:\n                # Copy so inplace updates don't propagate back to legend_contents\n                existing_artists = merged_contents[key][0]\n                for i, artist in enumerate(existing_artists):\n                    # Matplotlib accepts a tuple of artists and will overlay them\n                    if isinstance(artist, tuple):\n                        artist += new_artists[i],\n                    else:\n                        existing_artists[i] = artist, new_artists[i]\n            else:\n                merged_contents[key] = new_artists.copy(), labels\n\n        # TODO explain\n        loc = \"center right\" if self._pyplot else \"center left\"\n\n        base_legend = None\n        for (name, _), (handles, labels) in merged_contents.items():\n\n            legend = mpl.legend.Legend(\n                self._figure,\n                handles,\n                labels,\n                title=name,\n                loc=loc,\n                bbox_to_anchor=(.98, .55),\n            )\n\n            if base_legend:\n                # Matplotlib has no public API for this so it is a bit of a hack.\n                # Ideally we'd define our own legend class with more flexibility,\n                # but that is a lot of work!\n                base_legend_box = base_legend.get_children()[0]\n                this_legend_box = legend.get_children()[0]\n                base_legend_box.get_children().extend(this_legend_box.get_children())\n            else:\n                base_legend = legend\n                self._figure.legends.append(legend)"},{"col":4,"comment":"null","endLoc":385,"header":"def test_bivariate_probability_stat(self, x, y)","id":3320,"name":"test_bivariate_probability_stat","nodeType":"Function","startLoc":381,"text":"def test_bivariate_probability_stat(self, x, y):\n\n        h = Histogram(stat=\"probability\")\n        heights, _ = h(x, y)\n        assert heights.sum() == 1"},{"col":0,"comment":"","endLoc":6,"header":"faceted_histogram.py#","id":3321,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nFacetting histograms by subsets of data\n=======================================\n\n_thumb: .33, .57\n\"\"\"\n\nsns.set_theme(style=\"darkgrid\")\n\ndf = sns.load_dataset(\"penguins\")\n\nsns.displot(\n    df, x=\"flipper_length_mm\", col=\"species\", row=\"sex\",\n    binwidth=3, height=3, facet_kws=dict(margin_titles=True),\n)"},{"col":4,"comment":"null","endLoc":392,"header":"def test_bivariate_frequency_stat(self, x, y)","id":3322,"name":"test_bivariate_frequency_stat","nodeType":"Function","startLoc":387,"text":"def test_bivariate_frequency_stat(self, x, y):\n\n        h = Histogram(stat=\"frequency\")\n        heights, (x_edges, y_edges) = h(x, y)\n        area = np.outer(np.diff(x_edges), np.diff(y_edges))\n        assert (heights * area).sum() == len(x)"},{"col":4,"comment":"null","endLoc":1121,"header":"def test_hue_kws(self)","id":3323,"name":"test_hue_kws","nodeType":"Function","startLoc":1107,"text":"def test_hue_kws(self):\n\n        kws = dict(marker=[\"o\", \"s\", \"d\", \"+\"])\n        g = ag.PairGrid(self.df, hue=\"a\", hue_kws=kws)\n        g.map(plt.plot)\n\n        for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n            assert line.get_marker() == marker\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_kws=kws,\n                        hue_order=list(\"dcab\"))\n        g.map(plt.plot)\n\n        for line, marker in zip(g.axes[0, 0].lines, kws[\"marker\"]):\n            assert line.get_marker() == marker"},{"col":4,"comment":"null","endLoc":398,"header":"def test_bivariate_cumulative_count(self, x, y)","id":3324,"name":"test_bivariate_cumulative_count","nodeType":"Function","startLoc":394,"text":"def test_bivariate_cumulative_count(self, x, y):\n\n        h = Histogram(stat=\"count\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == len(x)"},{"col":4,"comment":"Draw boxplot information at center of the density.","endLoc":1359,"header":"def draw_box_lines(self, ax, data, center)","id":3325,"name":"draw_box_lines","nodeType":"Function","startLoc":1327,"text":"def draw_box_lines(self, ax, data, center):\n        \"\"\"Draw boxplot information at center of the density.\"\"\"\n        # Compute the boxplot statistics\n        q25, q50, q75 = np.percentile(data, [25, 50, 75])\n        whisker_lim = 1.5 * (q75 - q25)\n        h1 = np.min(data[data >= (q25 - whisker_lim)])\n        h2 = np.max(data[data <= (q75 + whisker_lim)])\n\n        # Draw a boxplot using lines and a point\n        if self.orient == \"v\":\n            ax.plot([center, center], [h1, h2],\n                    linewidth=self.linewidth,\n                    color=self.gray)\n            ax.plot([center, center], [q25, q75],\n                    linewidth=self.linewidth * 3,\n                    color=self.gray)\n            ax.scatter(center, q50,\n                       zorder=3,\n                       color=\"white\",\n                       edgecolor=self.gray,\n                       s=np.square(self.linewidth * 2))\n        else:\n            ax.plot([h1, h2], [center, center],\n                    linewidth=self.linewidth,\n                    color=self.gray)\n            ax.plot([q25, q75], [center, center],\n                    linewidth=self.linewidth * 3,\n                    color=self.gray)\n            ax.scatter(q50, center,\n                       zorder=3,\n                       color=\"white\",\n                       edgecolor=self.gray,\n                       s=np.square(self.linewidth * 2))"},{"className":"TestLines","col":0,"comment":"null","endLoc":256,"id":3326,"nodeType":"Class","startLoc":231,"text":"class TestLines:\n\n    def test_xy_data(self):\n\n        x = [1, 5, 3, np.nan, 2]\n        y = [1, 4, 2, 5, 3]\n        g = [1, 2, 1, 1, 2]\n        p = Plot(x=x, y=y, group=g).add(Lines()).plot()\n        lines, = p._figure.axes[0].collections\n\n        verts = lines.get_paths()[0].vertices.T\n        assert_array_equal(verts[0], [1, 3])\n        assert_array_equal(verts[1], [1, 2])\n\n        verts = lines.get_paths()[1].vertices.T\n        assert_array_equal(verts[0], [2, 5])\n        assert_array_equal(verts[1], [3, 4])\n\n    def test_single_orient_value(self):\n\n        x = [1, 1, 1]\n        y = [1, 2, 3]\n        p = Plot(x, y).add(Lines()).plot()\n        lines, = p._figure.axes[0].collections\n        paths, = lines.get_paths()\n        assert paths.vertices.shape == (0, 2)"},{"col":4,"comment":"null","endLoc":404,"header":"def test_bivariate_cumulative_density(self, x, y)","id":3327,"name":"test_bivariate_cumulative_density","nodeType":"Function","startLoc":400,"text":"def test_bivariate_cumulative_density(self, x, y):\n\n        h = Histogram(stat=\"density\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":247,"header":"def test_xy_data(self)","id":3328,"name":"test_xy_data","nodeType":"Function","startLoc":233,"text":"def test_xy_data(self):\n\n        x = [1, 5, 3, np.nan, 2]\n        y = [1, 4, 2, 5, 3]\n        g = [1, 2, 1, 1, 2]\n        p = Plot(x=x, y=y, group=g).add(Lines()).plot()\n        lines, = p._figure.axes[0].collections\n\n        verts = lines.get_paths()[0].vertices.T\n        assert_array_equal(verts[0], [1, 3])\n        assert_array_equal(verts[1], [1, 2])\n\n        verts = lines.get_paths()[1].vertices.T\n        assert_array_equal(verts[0], [2, 5])\n        assert_array_equal(verts[1], [3, 4])"},{"col":4,"comment":"null","endLoc":410,"header":"def test_bivariate_cumulative_frequency(self, x, y)","id":3329,"name":"test_bivariate_cumulative_frequency","nodeType":"Function","startLoc":406,"text":"def test_bivariate_cumulative_frequency(self, x, y):\n\n        h = Histogram(stat=\"frequency\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == len(x)"},{"col":4,"comment":"null","endLoc":416,"header":"def test_bivariate_cumulative_probability(self, x, y)","id":3330,"name":"test_bivariate_cumulative_probability","nodeType":"Function","startLoc":412,"text":"def test_bivariate_cumulative_probability(self, x, y):\n\n        h = Histogram(stat=\"probability\", cumulative=True)\n        heights, _ = h(x, y)\n        assert heights[-1, -1] == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":421,"header":"def test_bad_stat(self)","id":3331,"name":"test_bad_stat","nodeType":"Function","startLoc":418,"text":"def test_bad_stat(self):\n\n        with pytest.raises(ValueError):\n            Histogram(stat=\"invalid\")"},{"className":"TestECDF","col":0,"comment":"null","endLoc":484,"id":3332,"nodeType":"Class","startLoc":424,"text":"class TestECDF(DistributionFixtures):\n\n    def test_univariate_proportion(self, x):\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x)\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], np.linspace(0, 1, len(x) + 1)[1:])\n        assert stat[0] == 0\n\n    def test_univariate_count(self, x):\n\n        ecdf = ECDF(stat=\"count\")\n        stat, vals = ecdf(x)\n\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], np.arange(len(x)) + 1)\n        assert stat[0] == 0\n\n    def test_univariate_proportion_weights(self, x, weights):\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x, weights=weights)\n        assert_array_equal(vals[1:], np.sort(x))\n        expected_stats = weights[x.argsort()].cumsum() / weights.sum()\n        assert_array_almost_equal(stat[1:], expected_stats)\n        assert stat[0] == 0\n\n    def test_univariate_count_weights(self, x, weights):\n\n        ecdf = ECDF(stat=\"count\")\n        stat, vals = ecdf(x, weights=weights)\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], weights[x.argsort()].cumsum())\n        assert stat[0] == 0\n\n    @pytest.mark.skipif(smdist is None, reason=\"Requires statsmodels\")\n    def test_against_statsmodels(self, x):\n\n        sm_ecdf = smdist.empirical_distribution.ECDF(x)\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x)\n        assert_array_equal(vals, sm_ecdf.x)\n        assert_array_almost_equal(stat, sm_ecdf.y)\n\n        ecdf = ECDF(complementary=True)\n        stat, vals = ecdf(x)\n        assert_array_equal(vals, sm_ecdf.x)\n        assert_array_almost_equal(stat, sm_ecdf.y[::-1])\n\n    def test_invalid_stat(self, x):\n\n        with pytest.raises(ValueError, match=\"`stat` must be one of\"):\n            ECDF(stat=\"density\")\n\n    def test_bivariate_error(self, x, y):\n\n        with pytest.raises(NotImplementedError, match=\"Bivariate ECDF\"):\n            ecdf = ECDF()\n            ecdf(x, y)"},{"col":4,"comment":"null","endLoc":432,"header":"def test_univariate_proportion(self, x)","id":3333,"name":"test_univariate_proportion","nodeType":"Function","startLoc":426,"text":"def test_univariate_proportion(self, x):\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x)\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], np.linspace(0, 1, len(x) + 1)[1:])\n        assert stat[0] == 0"},{"col":4,"comment":"Draw the quartiles as lines at width of density.","endLoc":1373,"header":"def draw_quartiles(self, ax, data, support, density, center, split=False)","id":3334,"name":"draw_quartiles","nodeType":"Function","startLoc":1361,"text":"def draw_quartiles(self, ax, data, support, density, center, split=False):\n        \"\"\"Draw the quartiles as lines at width of density.\"\"\"\n        q25, q50, q75 = np.percentile(data, [25, 50, 75])\n\n        self.draw_to_density(ax, center, q25, support, density, split,\n                             linewidth=self.linewidth,\n                             dashes=[self.linewidth * 1.5] * 2)\n        self.draw_to_density(ax, center, q50, support, density, split,\n                             linewidth=self.linewidth,\n                             dashes=[self.linewidth * 3] * 2)\n        self.draw_to_density(ax, center, q75, support, density, split,\n                             linewidth=self.linewidth,\n                             dashes=[self.linewidth * 1.5] * 2)"},{"col":4,"comment":"Draw a line orthogonal to the value axis at width of density.","endLoc":1415,"header":"def draw_to_density(self, ax, center, val, support, density, split, **kws)","id":3335,"name":"draw_to_density","nodeType":"Function","startLoc":1395,"text":"def draw_to_density(self, ax, center, val, support, density, split, **kws):\n        \"\"\"Draw a line orthogonal to the value axis at width of density.\"\"\"\n        idx = np.argmin(np.abs(support - val))\n        width = self.dwidth * density[idx] * .99\n\n        kws[\"color\"] = self.gray\n\n        if self.orient == \"v\":\n            if split == \"left\":\n                ax.plot([center - width, center], [val, val], **kws)\n            elif split == \"right\":\n                ax.plot([center, center + width], [val, val], **kws)\n            else:\n                ax.plot([center - width, center + width], [val, val], **kws)\n        else:\n            if split == \"left\":\n                ax.plot([val, val], [center - width, center], **kws)\n            elif split == \"right\":\n                ax.plot([val, val], [center, center + width], **kws)\n            else:\n                ax.plot([val, val], [center - width, center + width], **kws)"},{"col":4,"comment":"Draw individual observations as sticks at width of density.","endLoc":1393,"header":"def draw_stick_lines(self, ax, data, support, density,\n                         center, split=False)","id":3336,"name":"draw_stick_lines","nodeType":"Function","startLoc":1388,"text":"def draw_stick_lines(self, ax, data, support, density,\n                         center, split=False):\n        \"\"\"Draw individual observations as sticks at width of density.\"\"\"\n        for val in data:\n            self.draw_to_density(ax, center, val, support, density, split,\n                                 linewidth=self.linewidth * .5)"},{"col":4,"comment":"null","endLoc":441,"header":"def test_univariate_count(self, x)","id":3337,"name":"test_univariate_count","nodeType":"Function","startLoc":434,"text":"def test_univariate_count(self, x):\n\n        ecdf = ECDF(stat=\"count\")\n        stat, vals = ecdf(x)\n\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], np.arange(len(x)) + 1)\n        assert stat[0] == 0"},{"col":4,"comment":"null","endLoc":256,"header":"def test_single_orient_value(self)","id":3338,"name":"test_single_orient_value","nodeType":"Function","startLoc":249,"text":"def test_single_orient_value(self):\n\n        x = [1, 1, 1]\n        y = [1, 2, 3]\n        p = Plot(x, y).add(Lines()).plot()\n        lines, = p._figure.axes[0].collections\n        paths, = lines.get_paths()\n        assert paths.vertices.shape == (0, 2)"},{"col":4,"comment":"null","endLoc":450,"header":"def test_univariate_proportion_weights(self, x, weights)","id":3339,"name":"test_univariate_proportion_weights","nodeType":"Function","startLoc":443,"text":"def test_univariate_proportion_weights(self, x, weights):\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x, weights=weights)\n        assert_array_equal(vals[1:], np.sort(x))\n        expected_stats = weights[x.argsort()].cumsum() / weights.sum()\n        assert_array_almost_equal(stat[1:], expected_stats)\n        assert stat[0] == 0"},{"col":4,"comment":"Draw individual observations as points at middle of the violin.","endLoc":1386,"header":"def draw_points(self, ax, data, center)","id":3340,"name":"draw_points","nodeType":"Function","startLoc":1375,"text":"def draw_points(self, ax, data, center):\n        \"\"\"Draw individual observations as points at middle of the violin.\"\"\"\n        kws = dict(s=np.square(self.linewidth * 2),\n                   color=self.gray,\n                   edgecolor=self.gray)\n\n        grid = np.ones(len(data)) * center\n\n        if self.orient == \"v\":\n            ax.scatter(grid, data, **kws)\n        else:\n            ax.scatter(data, grid, **kws)"},{"col":4,"comment":"null","endLoc":458,"header":"def test_univariate_count_weights(self, x, weights)","id":3341,"name":"test_univariate_count_weights","nodeType":"Function","startLoc":452,"text":"def test_univariate_count_weights(self, x, weights):\n\n        ecdf = ECDF(stat=\"count\")\n        stat, vals = ecdf(x, weights=weights)\n        assert_array_equal(vals[1:], np.sort(x))\n        assert_array_almost_equal(stat[1:], weights[x.argsort()].cumsum())\n        assert stat[0] == 0"},{"col":4,"comment":"null","endLoc":473,"header":"@pytest.mark.skipif(smdist is None, reason=\"Requires statsmodels\")\n    def test_against_statsmodels(self, x)","id":3342,"name":"test_against_statsmodels","nodeType":"Function","startLoc":460,"text":"@pytest.mark.skipif(smdist is None, reason=\"Requires statsmodels\")\n    def test_against_statsmodels(self, x):\n\n        sm_ecdf = smdist.empirical_distribution.ECDF(x)\n\n        ecdf = ECDF()\n        stat, vals = ecdf(x)\n        assert_array_equal(vals, sm_ecdf.x)\n        assert_array_almost_equal(stat, sm_ecdf.y)\n\n        ecdf = ECDF(complementary=True)\n        stat, vals = ecdf(x)\n        assert_array_equal(vals, sm_ecdf.x)\n        assert_array_almost_equal(stat, sm_ecdf.y[::-1])"},{"col":4,"comment":"null","endLoc":478,"header":"def test_invalid_stat(self, x)","id":3343,"name":"test_invalid_stat","nodeType":"Function","startLoc":475,"text":"def test_invalid_stat(self, x):\n\n        with pytest.raises(ValueError, match=\"`stat` must be one of\"):\n            ECDF(stat=\"density\")"},{"col":4,"comment":"null","endLoc":484,"header":"def test_bivariate_error(self, x, y)","id":3344,"name":"test_bivariate_error","nodeType":"Function","startLoc":480,"text":"def test_bivariate_error(self, x, y):\n\n        with pytest.raises(NotImplementedError, match=\"Bivariate ECDF\"):\n            ecdf = ECDF()\n            ecdf(x, y)"},{"className":"TestEstimateAggregator","col":0,"comment":"null","endLoc":618,"id":3345,"nodeType":"Class","startLoc":487,"text":"class TestEstimateAggregator:\n\n    def test_func_estimator(self, long_df):\n\n        func = np.mean\n        agg = EstimateAggregator(func)\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == func(long_df[\"x\"])\n\n    def test_name_estimator(self, long_df):\n\n        agg = EstimateAggregator(\"mean\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n\n    def test_custom_func_estimator(self, long_df):\n\n        def func(x):\n            return np.asarray(x).min()\n\n        agg = EstimateAggregator(func)\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == func(long_df[\"x\"])\n\n    def test_se_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"se\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - long_df[\"x\"].sem())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + long_df[\"x\"].sem())\n\n        agg = EstimateAggregator(\"mean\", (\"se\", 2))\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - 2 * long_df[\"x\"].sem())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + 2 * long_df[\"x\"].sem())\n\n    def test_sd_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"sd\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - long_df[\"x\"].std())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + long_df[\"x\"].std())\n\n        agg = EstimateAggregator(\"mean\", (\"sd\", 2))\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - 2 * long_df[\"x\"].std())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + 2 * long_df[\"x\"].std())\n\n    def test_pi_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"pi\")\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == np.percentile(long_df[\"y\"], 2.5)\n        assert out[\"ymax\"] == np.percentile(long_df[\"y\"], 97.5)\n\n        agg = EstimateAggregator(\"mean\", (\"pi\", 50))\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == np.percentile(long_df[\"y\"], 25)\n        assert out[\"ymax\"] == np.percentile(long_df[\"y\"], 75)\n\n    def test_ci_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"ci\", n_boot=100000, seed=0)\n        out = agg(long_df, \"y\")\n\n        agg_ref = EstimateAggregator(\"mean\", (\"se\", 1.96))\n        out_ref = agg_ref(long_df, \"y\")\n\n        assert out[\"ymin\"] == pytest.approx(out_ref[\"ymin\"], abs=1e-2)\n        assert out[\"ymax\"] == pytest.approx(out_ref[\"ymax\"], abs=1e-2)\n\n        agg = EstimateAggregator(\"mean\", (\"ci\", 68), n_boot=100000, seed=0)\n        out = agg(long_df, \"y\")\n\n        agg_ref = EstimateAggregator(\"mean\", (\"se\", 1))\n        out_ref = agg_ref(long_df, \"y\")\n\n        assert out[\"ymin\"] == pytest.approx(out_ref[\"ymin\"], abs=1e-2)\n        assert out[\"ymax\"] == pytest.approx(out_ref[\"ymax\"], abs=1e-2)\n\n        agg = EstimateAggregator(\"mean\", \"ci\", seed=0)\n        out_orig = agg_ref(long_df, \"y\")\n        out_test = agg_ref(long_df, \"y\")\n        assert_array_equal(out_orig, out_test)\n\n    def test_custom_errorbars(self, long_df):\n\n        f = lambda x: (x.min(), x.max())  # noqa: E731\n        agg = EstimateAggregator(\"mean\", f)\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == long_df[\"y\"].min()\n        assert out[\"ymax\"] == long_df[\"y\"].max()\n\n    def test_singleton_errorbars(self):\n\n        agg = EstimateAggregator(\"mean\", \"ci\")\n        val = 7\n        out = agg(pd.DataFrame(dict(y=[val])), \"y\")\n        assert out[\"y\"] == val\n        assert pd.isna(out[\"ymin\"])\n        assert pd.isna(out[\"ymax\"])\n\n    def test_errorbar_validation(self):\n\n        method, level = _validate_errorbar_arg((\"ci\", 99))\n        assert method == \"ci\"\n        assert level == 99\n\n        method, level = _validate_errorbar_arg(\"sd\")\n        assert method == \"sd\"\n        assert level == 1\n\n        f = lambda x: (x.min(), x.max())  # noqa: E731\n        method, level = _validate_errorbar_arg(f)\n        assert method is f\n        assert level is None\n\n        bad_args = [\n            (\"sem\", ValueError),\n            ((\"std\", 2), ValueError),\n            ((\"pi\", 5, 95), ValueError),\n            (95, TypeError),\n            ((\"ci\", \"large\"), TypeError),\n        ]\n\n        for arg, exception in bad_args:\n            with pytest.raises(exception, match=\"`errorbar` must be\"):\n                _validate_errorbar_arg(arg)"},{"col":4,"comment":"null","endLoc":494,"header":"def test_func_estimator(self, long_df)","id":3346,"name":"test_func_estimator","nodeType":"Function","startLoc":489,"text":"def test_func_estimator(self, long_df):\n\n        func = np.mean\n        agg = EstimateAggregator(func)\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == func(long_df[\"x\"])"},{"col":4,"comment":"null","endLoc":500,"header":"def test_name_estimator(self, long_df)","id":3347,"name":"test_name_estimator","nodeType":"Function","startLoc":496,"text":"def test_name_estimator(self, long_df):\n\n        agg = EstimateAggregator(\"mean\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()"},{"col":4,"comment":"null","endLoc":509,"header":"def test_custom_func_estimator(self, long_df)","id":3348,"name":"test_custom_func_estimator","nodeType":"Function","startLoc":502,"text":"def test_custom_func_estimator(self, long_df):\n\n        def func(x):\n            return np.asarray(x).min()\n\n        agg = EstimateAggregator(func)\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == func(long_df[\"x\"])"},{"col":4,"comment":"null","endLoc":523,"header":"def test_se_errorbars(self, long_df)","id":3350,"name":"test_se_errorbars","nodeType":"Function","startLoc":511,"text":"def test_se_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"se\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - long_df[\"x\"].sem())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + long_df[\"x\"].sem())\n\n        agg = EstimateAggregator(\"mean\", (\"se\", 2))\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - 2 * long_df[\"x\"].sem())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + 2 * long_df[\"x\"].sem())"},{"className":"TestRange","col":0,"comment":"null","endLoc":315,"id":3351,"nodeType":"Class","startLoc":259,"text":"class TestRange:\n\n    def test_xy_data(self):\n\n        x = [1, 2]\n        ymin = [1, 4]\n        ymax = [2, 3]\n\n        p = Plot(x=x, ymin=ymin, ymax=ymax).add(Range()).plot()\n        lines, = p._figure.axes[0].collections\n\n        for i, path in enumerate(lines.get_paths()):\n            verts = path.vertices.T\n            assert_array_equal(verts[0], [x[i], x[i]])\n            assert_array_equal(verts[1], [ymin[i], ymax[i]])\n\n    def test_auto_range(self):\n\n        x = [1, 1, 2, 2, 2]\n        y = [1, 2, 3, 4, 5]\n\n        p = Plot(x=x, y=y).add(Range()).plot()\n        lines, = p._figure.axes[0].collections\n        paths = lines.get_paths()\n        assert_array_equal(paths[0].vertices, [(1, 1), (1, 2)])\n        assert_array_equal(paths[1].vertices, [(2, 3), (2, 5)])\n\n    def test_mapped_color(self):\n\n        x = [1, 2, 1, 2]\n        ymin = [1, 4, 3, 2]\n        ymax = [2, 3, 1, 4]\n        group = [\"a\", \"a\", \"b\", \"b\"]\n\n        p = Plot(x=x, ymin=ymin, ymax=ymax, color=group).add(Range()).plot()\n        lines, = p._figure.axes[0].collections\n        colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n        for i, path in enumerate(lines.get_paths()):\n            verts = path.vertices.T\n            assert_array_equal(verts[0], [x[i], x[i]])\n            assert_array_equal(verts[1], [ymin[i], ymax[i]])\n            assert same_color(lines.get_colors()[i], colors[i // 2])\n\n    def test_direct_properties(self):\n\n        x = [1, 2]\n        ymin = [1, 4]\n        ymax = [2, 3]\n\n        m = Range(color=\".654\", linewidth=4)\n        p = Plot(x=x, ymin=ymin, ymax=ymax).add(m).plot()\n        lines, = p._figure.axes[0].collections\n\n        for i, path in enumerate(lines.get_paths()):\n            assert same_color(lines.get_colors()[i], m.color)\n            assert lines.get_linewidths()[i] == m.linewidth"},{"col":4,"comment":"null","endLoc":273,"header":"def test_xy_data(self)","id":3352,"name":"test_xy_data","nodeType":"Function","startLoc":261,"text":"def test_xy_data(self):\n\n        x = [1, 2]\n        ymin = [1, 4]\n        ymax = [2, 3]\n\n        p = Plot(x=x, ymin=ymin, ymax=ymax).add(Range()).plot()\n        lines, = p._figure.axes[0].collections\n\n        for i, path in enumerate(lines.get_paths()):\n            verts = path.vertices.T\n            assert_array_equal(verts[0], [x[i], x[i]])\n            assert_array_equal(verts[1], [ymin[i], ymax[i]])"},{"col":4,"comment":"null","endLoc":1164,"header":"def test_hue_order(self)","id":3353,"name":"test_hue_order","nodeType":"Function","startLoc":1123,"text":"def test_hue_order(self):\n\n        order = list(\"dcab\")\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map(plt.plot)\n\n        for line, level in zip(g.axes[1, 0].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n        plt.close(\"all\")\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map_diag(plt.plot)\n\n        for line, level in zip(g.axes[0, 0].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n        plt.close(\"all\")\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map_lower(plt.plot)\n\n        for line, level in zip(g.axes[1, 0].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n        plt.close(\"all\")\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map_upper(plt.plot)\n\n        for line, level in zip(g.axes[0, 1].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"y\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n        plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":537,"header":"def test_sd_errorbars(self, long_df)","id":3354,"name":"test_sd_errorbars","nodeType":"Function","startLoc":525,"text":"def test_sd_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"sd\")\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - long_df[\"x\"].std())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + long_df[\"x\"].std())\n\n        agg = EstimateAggregator(\"mean\", (\"sd\", 2))\n        out = agg(long_df, \"x\")\n        assert out[\"x\"] == long_df[\"x\"].mean()\n        assert out[\"xmin\"] == (long_df[\"x\"].mean() - 2 * long_df[\"x\"].std())\n        assert out[\"xmax\"] == (long_df[\"x\"].mean() + 2 * long_df[\"x\"].std())"},{"col":4,"comment":"null","endLoc":284,"header":"def test_auto_range(self)","id":3355,"name":"test_auto_range","nodeType":"Function","startLoc":275,"text":"def test_auto_range(self):\n\n        x = [1, 1, 2, 2, 2]\n        y = [1, 2, 3, 4, 5]\n\n        p = Plot(x=x, y=y).add(Range()).plot()\n        lines, = p._figure.axes[0].collections\n        paths = lines.get_paths()\n        assert_array_equal(paths[0].vertices, [(1, 1), (1, 2)])\n        assert_array_equal(paths[1].vertices, [(2, 3), (2, 5)])"},{"col":4,"comment":"null","endLoc":549,"header":"def test_pi_errorbars(self, long_df)","id":3356,"name":"test_pi_errorbars","nodeType":"Function","startLoc":539,"text":"def test_pi_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"pi\")\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == np.percentile(long_df[\"y\"], 2.5)\n        assert out[\"ymax\"] == np.percentile(long_df[\"y\"], 97.5)\n\n        agg = EstimateAggregator(\"mean\", (\"pi\", 50))\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == np.percentile(long_df[\"y\"], 25)\n        assert out[\"ymax\"] == np.percentile(long_df[\"y\"], 75)"},{"col":4,"comment":"null","endLoc":1736,"header":"def test_datetime_scale(self, long_df)","id":3357,"name":"test_datetime_scale","nodeType":"Function","startLoc":1731,"text":"def test_datetime_scale(self, long_df):\n\n        ax = scatterplot(data=long_df, x=\"t\", y=\"y\")\n        # Check that we avoid weird matplotlib default auto scaling\n        # https://github.com/matplotlib/matplotlib/issues/17586\n        ax.get_xlim()[0] > ax.xaxis.convert_units(np.datetime64(\"2002-01-01\"))"},{"col":4,"comment":"null","endLoc":1742,"header":"def test_unfilled_marker_edgecolor_warning(self, long_df)","id":3358,"name":"test_unfilled_marker_edgecolor_warning","nodeType":"Function","startLoc":1738,"text":"def test_unfilled_marker_edgecolor_warning(self, long_df):  # GH2636\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"error\")\n            scatterplot(data=long_df, x=\"x\", y=\"y\", marker=\"+\")"},{"col":4,"comment":"null","endLoc":574,"header":"def test_ci_errorbars(self, long_df)","id":3359,"name":"test_ci_errorbars","nodeType":"Function","startLoc":551,"text":"def test_ci_errorbars(self, long_df):\n\n        agg = EstimateAggregator(\"mean\", \"ci\", n_boot=100000, seed=0)\n        out = agg(long_df, \"y\")\n\n        agg_ref = EstimateAggregator(\"mean\", (\"se\", 1.96))\n        out_ref = agg_ref(long_df, \"y\")\n\n        assert out[\"ymin\"] == pytest.approx(out_ref[\"ymin\"], abs=1e-2)\n        assert out[\"ymax\"] == pytest.approx(out_ref[\"ymax\"], abs=1e-2)\n\n        agg = EstimateAggregator(\"mean\", (\"ci\", 68), n_boot=100000, seed=0)\n        out = agg(long_df, \"y\")\n\n        agg_ref = EstimateAggregator(\"mean\", (\"se\", 1))\n        out_ref = agg_ref(long_df, \"y\")\n\n        assert out[\"ymin\"] == pytest.approx(out_ref[\"ymin\"], abs=1e-2)\n        assert out[\"ymax\"] == pytest.approx(out_ref[\"ymax\"], abs=1e-2)\n\n        agg = EstimateAggregator(\"mean\", \"ci\", seed=0)\n        out_orig = agg_ref(long_df, \"y\")\n        out_test = agg_ref(long_df, \"y\")\n        assert_array_equal(out_orig, out_test)"},{"col":4,"comment":"null","endLoc":2338,"header":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(x=\"x\"),\n            dict(x=\"x\", y=\"y\"),\n            dict(x=\"x\", hue=\"a\"),\n        ]\n    )\n    def test_with_rug(self, long_df, kwargs)","id":3360,"name":"test_with_rug","nodeType":"Function","startLoc":2318,"text":"@pytest.mark.parametrize(\n        \"kwargs\", [\n            dict(x=\"x\"),\n            dict(x=\"x\", y=\"y\"),\n            dict(x=\"x\", hue=\"a\"),\n        ]\n    )\n    def test_with_rug(self, long_df, kwargs):\n\n        ax = plt.figure().subplots()\n        histplot(data=long_df, **kwargs, ax=ax)\n        rugplot(data=long_df, **kwargs, ax=ax)\n\n        g = displot(long_df, rug=True, **kwargs)\n\n        assert_plots_equal(ax, g.ax, labels=False)\n\n        long_df[\"_\"] = \"_\"\n        g2 = displot(long_df, col=\"_\", rug=True, **kwargs)\n\n        assert_plots_equal(ax, g2.ax, labels=False)"},{"col":4,"comment":"null","endLoc":301,"header":"def test_mapped_color(self)","id":3361,"name":"test_mapped_color","nodeType":"Function","startLoc":286,"text":"def test_mapped_color(self):\n\n        x = [1, 2, 1, 2]\n        ymin = [1, 4, 3, 2]\n        ymax = [2, 3, 1, 4]\n        group = [\"a\", \"a\", \"b\", \"b\"]\n\n        p = Plot(x=x, ymin=ymin, ymax=ymax, color=group).add(Range()).plot()\n        lines, = p._figure.axes[0].collections\n        colors = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n        for i, path in enumerate(lines.get_paths()):\n            verts = path.vertices.T\n            assert_array_equal(verts[0], [x[i], x[i]])\n            assert_array_equal(verts[1], [ymin[i], ymax[i]])\n            assert same_color(lines.get_colors()[i], colors[i // 2])"},{"col":4,"comment":"null","endLoc":1207,"header":"def test_hue_order_missing_level(self)","id":3362,"name":"test_hue_order_missing_level","nodeType":"Function","startLoc":1166,"text":"def test_hue_order_missing_level(self):\n\n        order = list(\"dcaeb\")\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map(plt.plot)\n\n        for line, level in zip(g.axes[1, 0].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n        plt.close(\"all\")\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map_diag(plt.plot)\n\n        for line, level in zip(g.axes[0, 0].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n        plt.close(\"all\")\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map_lower(plt.plot)\n\n        for line, level in zip(g.axes[1, 0].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"x\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"y\"])\n\n        plt.close(\"all\")\n\n        g = ag.PairGrid(self.df, hue=\"a\", hue_order=order)\n        g.map_upper(plt.plot)\n\n        for line, level in zip(g.axes[0, 1].lines, order):\n            x, y = line.get_xydata().T\n            npt.assert_array_equal(x, self.df.loc[self.df.a == level, \"y\"])\n            npt.assert_array_equal(y, self.df.loc[self.df.a == level, \"x\"])\n\n        plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1215,"header":"def test_hue_in_map(self, long_df)","id":3363,"name":"test_hue_in_map","nodeType":"Function","startLoc":1209,"text":"def test_hue_in_map(self, long_df):\n\n        g = ag.PairGrid(long_df, vars=[\"x\", \"y\"])\n        g.map(scatterplot, hue=long_df[\"a\"])\n        ax = g.axes.flat[0]\n        points = ax.collections[0]\n        assert len(set(map(tuple, points.get_facecolors()))) == 3"},{"col":4,"comment":"null","endLoc":582,"header":"def test_custom_errorbars(self, long_df)","id":3364,"name":"test_custom_errorbars","nodeType":"Function","startLoc":576,"text":"def test_custom_errorbars(self, long_df):\n\n        f = lambda x: (x.min(), x.max())  # noqa: E731\n        agg = EstimateAggregator(\"mean\", f)\n        out = agg(long_df, \"y\")\n        assert out[\"ymin\"] == long_df[\"y\"].min()\n        assert out[\"ymax\"] == long_df[\"y\"].max()"},{"col":12,"endLoc":578,"id":3365,"nodeType":"Lambda","startLoc":578,"text":"lambda x: (x.min(), x.max())"},{"col":4,"comment":"null","endLoc":591,"header":"def test_singleton_errorbars(self)","id":3366,"name":"test_singleton_errorbars","nodeType":"Function","startLoc":584,"text":"def test_singleton_errorbars(self):\n\n        agg = EstimateAggregator(\"mean\", \"ci\")\n        val = 7\n        out = agg(pd.DataFrame(dict(y=[val])), \"y\")\n        assert out[\"y\"] == val\n        assert pd.isna(out[\"ymin\"])\n        assert pd.isna(out[\"ymax\"])"},{"col":4,"comment":"null","endLoc":2357,"header":"@pytest.mark.parametrize(\n        \"facet_var\", [\"col\", \"row\"],\n    )\n    def test_facets(self, long_df, facet_var)","id":3367,"name":"test_facets","nodeType":"Function","startLoc":2340,"text":"@pytest.mark.parametrize(\n        \"facet_var\", [\"col\", \"row\"],\n    )\n    def test_facets(self, long_df, facet_var):\n\n        kwargs = {facet_var: \"a\"}\n        ax = kdeplot(data=long_df, x=\"x\", hue=\"a\")\n        g = displot(long_df, x=\"x\", kind=\"kde\", **kwargs)\n\n        legend_texts = ax.legend_.get_texts()\n\n        for i, line in enumerate(ax.lines[::-1]):\n            facet_ax = g.axes.flat[i]\n            facet_line = facet_ax.lines[0]\n            assert_array_equal(line.get_xydata(), facet_line.get_xydata())\n\n            text = legend_texts[i].get_text()\n            assert text in facet_ax.get_title()"},{"col":4,"comment":"null","endLoc":315,"header":"def test_direct_properties(self)","id":3368,"name":"test_direct_properties","nodeType":"Function","startLoc":303,"text":"def test_direct_properties(self):\n\n        x = [1, 2]\n        ymin = [1, 4]\n        ymax = [2, 3]\n\n        m = Range(color=\".654\", linewidth=4)\n        p = Plot(x=x, ymin=ymin, ymax=ymax).add(m).plot()\n        lines, = p._figure.axes[0].collections\n\n        for i, path in enumerate(lines.get_paths()):\n            assert same_color(lines.get_colors()[i], m.color)\n            assert lines.get_linewidths()[i] == m.linewidth"},{"col":4,"comment":"null","endLoc":2374,"header":"@pytest.mark.parametrize(\"multiple\", [\"dodge\", \"stack\", \"fill\"])\n    def test_facet_multiple(self, long_df, multiple)","id":3369,"name":"test_facet_multiple","nodeType":"Function","startLoc":2359,"text":"@pytest.mark.parametrize(\"multiple\", [\"dodge\", \"stack\", \"fill\"])\n    def test_facet_multiple(self, long_df, multiple):\n\n        bins = np.linspace(0, 20, 5)\n        ax = histplot(\n            data=long_df[long_df[\"c\"] == 0],\n            x=\"x\", hue=\"a\", hue_order=[\"a\", \"b\", \"c\"],\n            multiple=multiple, bins=bins,\n        )\n\n        g = displot(\n            data=long_df, x=\"x\", hue=\"a\", col=\"c\", hue_order=[\"a\", \"b\", \"c\"],\n            multiple=multiple, bins=bins,\n        )\n\n        assert_plots_equal(ax, g.axes_dict[0])"},{"col":4,"comment":"null","endLoc":2380,"header":"def test_ax_warning(self, long_df)","id":3370,"name":"test_ax_warning","nodeType":"Function","startLoc":2376,"text":"def test_ax_warning(self, long_df):\n\n        ax = plt.figure().subplots()\n        with pytest.warns(UserWarning, match=\"`displot` is a figure-level\"):\n            displot(long_df, x=\"x\", ax=ax)"},{"col":4,"comment":"null","endLoc":2390,"header":"@pytest.mark.parametrize(\"key\", [\"col\", \"row\"])\n    def test_array_faceting(self, long_df, key)","id":3371,"name":"test_array_faceting","nodeType":"Function","startLoc":2382,"text":"@pytest.mark.parametrize(\"key\", [\"col\", \"row\"])\n    def test_array_faceting(self, long_df, key):\n\n        a = long_df[\"a\"].to_numpy()\n        vals = categorical_order(a)\n        g = displot(long_df, x=\"x\", **{key: a})\n        assert len(g.axes.flat) == len(vals)\n        for ax, val in zip(g.axes.flat, vals):\n            assert val in ax.get_title()"},{"col":4,"comment":"null","endLoc":1245,"header":"def test_nondefault_index(self)","id":3372,"name":"test_nondefault_index","nodeType":"Function","startLoc":1217,"text":"def test_nondefault_index(self):\n\n        df = self.df.copy().set_index(\"b\")\n\n        plot_vars = [\"x\", \"y\", \"z\"]\n        g1 = ag.PairGrid(df)\n        g1.map(plt.scatter)\n\n        for i, axes_i in enumerate(g1.axes):\n            for j, ax in enumerate(axes_i):\n                x_in = self.df[plot_vars[j]]\n                y_in = self.df[plot_vars[i]]\n                x_out, y_out = ax.collections[0].get_offsets().T\n                npt.assert_array_equal(x_in, x_out)\n                npt.assert_array_equal(y_in, y_out)\n\n        g2 = ag.PairGrid(df, hue=\"a\")\n        g2.map(plt.scatter)\n\n        for i, axes_i in enumerate(g2.axes):\n            for j, ax in enumerate(axes_i):\n                x_in = self.df[plot_vars[j]]\n                y_in = self.df[plot_vars[i]]\n                for k, k_level in enumerate(self.df.a.unique()):\n                    x_in_k = x_in[self.df.a == k_level]\n                    y_in_k = y_in[self.df.a == k_level]\n                    x_out, y_out = ax.collections[k].get_offsets().T\n                    npt.assert_array_equal(x_in_k, x_out)\n                    npt.assert_array_equal(y_in_k, y_out)"},{"col":4,"comment":"null","endLoc":1649,"header":"def _finalize_figure(self, p: Plot) -> None","id":3373,"name":"_finalize_figure","nodeType":"Function","startLoc":1628,"text":"def _finalize_figure(self, p: Plot) -> None:\n\n        for sub in self._subplots:\n            ax = sub[\"ax\"]\n            for axis in \"xy\":\n                axis_key = sub[axis]\n\n                # Axis limits\n                if axis_key in p._limits:\n                    convert_units = getattr(ax, f\"{axis}axis\").convert_units\n                    a, b = p._limits[axis_key]\n                    lo = a if a is None else convert_units(a)\n                    hi = b if b is None else convert_units(b)\n                    if isinstance(a, str):\n                        lo = cast(float, lo) - 0.5\n                    if isinstance(b, str):\n                        hi = cast(float, hi) + 0.5\n                    ax.set(**{f\"{axis}lim\": (lo, hi)})\n\n        engine_default = None if p._target is not None else \"tight\"\n        layout_engine = p._layout_spec.get(\"engine\", engine_default)\n        set_layout_engine(self._figure, layout_engine)"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":3374,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":3,"id":3375,"name":"mpl","nodeType":"Attribute","startLoc":3,"text":"mpl"},{"attributeType":"PlotData","col":4,"comment":"null","endLoc":870,"id":3376,"name":"_data","nodeType":"Attribute","startLoc":870,"text":"_data"},{"attributeType":"list","col":4,"comment":"null","endLoc":871,"id":3377,"name":"_layers","nodeType":"Attribute","startLoc":871,"text":"_layers"},{"attributeType":"null","col":4,"comment":"null","endLoc":872,"id":3378,"name":"_figure","nodeType":"Attribute","startLoc":872,"text":"_figure"},{"attributeType":"bool","col":8,"comment":"null","endLoc":876,"id":3379,"name":"_pyplot","nodeType":"Attribute","startLoc":876,"text":"self._pyplot"},{"attributeType":"dict","col":8,"comment":"null","endLoc":877,"id":3380,"name":"_theme","nodeType":"Attribute","startLoc":877,"text":"self._theme"},{"col":4,"comment":"Make the violin plot.","endLoc":1422,"header":"def plot(self, ax)","id":3381,"name":"plot","nodeType":"Function","startLoc":1417,"text":"def plot(self, ax):\n        \"\"\"Make the violin plot.\"\"\"\n        self.draw_violins(ax)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"attributeType":"null","col":8,"comment":"null","endLoc":999,"id":3382,"name":"_figure","nodeType":"Attribute","startLoc":999,"text":"self._figure"},{"attributeType":"dict","col":8,"comment":"null","endLoc":881,"id":3383,"name":"_scales","nodeType":"Attribute","startLoc":881,"text":"self._scales"},{"attributeType":"list","col":8,"comment":"null","endLoc":878,"id":3384,"name":"_legend_contents","nodeType":"Attribute","startLoc":878,"text":"self._legend_contents"},{"attributeType":"Subplots","col":8,"comment":"null","endLoc":996,"id":3385,"name":"_subplots","nodeType":"Attribute","startLoc":996,"text":"self._subplots"},{"col":0,"comment":"Temporarily modify specifc matplotlib rcParams.","endLoc":110,"header":"@contextmanager\ndef theme_context(params: dict[str, Any]) -> Generator","id":3386,"name":"theme_context","nodeType":"Function","startLoc":92,"text":"@contextmanager\ndef theme_context(params: dict[str, Any]) -> Generator:\n    \"\"\"Temporarily modify specifc matplotlib rcParams.\"\"\"\n    orig_params = {k: mpl.rcParams[k] for k in params}\n    color_codes = \"bgrmyck\"\n    nice_colors = [*color_palette(\"deep6\"), (.15, .15, .15)]\n    orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes]\n    # TODO how to allow this to reflect the color cycle when relevant?\n    try:\n        mpl.rcParams.update(params)\n        for (code, color) in zip(color_codes, nice_colors):\n            mpl.colors.colorConverter.colors[code] = color\n            mpl.colors.colorConverter.cache[code] = color\n        yield\n    finally:\n        mpl.rcParams.update(orig_params)\n        for (code, color) in zip(color_codes, orig_colors):\n            mpl.colors.colorConverter.colors[code] = color\n            mpl.colors.colorConverter.cache[code] = color"},{"col":4,"comment":"null","endLoc":2395,"header":"def test_legend(self, long_df)","id":3387,"name":"test_legend","nodeType":"Function","startLoc":2392,"text":"def test_legend(self, long_df):\n\n        g = displot(long_df, x=\"x\", hue=\"a\")\n        assert g._legend is not None"},{"col":4,"comment":"null","endLoc":2400,"header":"def test_empty(self)","id":3388,"name":"test_empty","nodeType":"Function","startLoc":2397,"text":"def test_empty(self):\n\n        g = displot(x=[], y=[])\n        assert isinstance(g, FacetGrid)"},{"col":4,"comment":"null","endLoc":2405,"header":"def test_bivariate_ecdf_error(self, long_df)","id":3389,"name":"test_bivariate_ecdf_error","nodeType":"Function","startLoc":2402,"text":"def test_bivariate_ecdf_error(self, long_df):\n\n        with pytest.raises(NotImplementedError):\n            displot(long_df, x=\"x\", y=\"y\", kind=\"ecdf\")"},{"col":4,"comment":"null","endLoc":2420,"header":"def test_bivariate_kde_norm(self, rng)","id":3390,"name":"test_bivariate_kde_norm","nodeType":"Function","startLoc":2407,"text":"def test_bivariate_kde_norm(self, rng):\n\n        x, y = rng.normal(0, 1, (2, 100))\n        z = [0] * 80 + [1] * 20\n\n        g = displot(x=x, y=y, col=z, kind=\"kde\", levels=10)\n        l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)\n        l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)\n        assert l1 > l2\n\n        g = displot(x=x, y=y, col=z, kind=\"kde\", levels=10, common_norm=False)\n        l1 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[0].collections)\n        l2 = sum(bool(get_contour_coords(c)) for c in g.axes.flat[1].collections)\n        assert l1 == l2"},{"attributeType":"null","col":8,"comment":"null","endLoc":907,"id":3391,"name":"dodge","nodeType":"Attribute","startLoc":907,"text":"self.dodge"},{"col":4,"comment":"null","endLoc":1274,"header":"@pytest.mark.parametrize(\"func\", [scatterplot, plt.scatter])\n    def test_dropna(self, func)","id":3392,"name":"test_dropna","nodeType":"Function","startLoc":1247,"text":"@pytest.mark.parametrize(\"func\", [scatterplot, plt.scatter])\n    def test_dropna(self, func):\n\n        df = self.df.copy()\n        n_null = 20\n        df.loc[np.arange(n_null), \"x\"] = np.nan\n\n        plot_vars = [\"x\", \"y\", \"z\"]\n\n        g1 = ag.PairGrid(df, vars=plot_vars, dropna=True)\n        g1.map(func)\n\n        for i, axes_i in enumerate(g1.axes):\n            for j, ax in enumerate(axes_i):\n                x_in = df[plot_vars[j]]\n                y_in = df[plot_vars[i]]\n                x_out, y_out = ax.collections[0].get_offsets().T\n\n                n_valid = (x_in * y_in).notnull().sum()\n\n                assert n_valid == len(x_out)\n                assert n_valid == len(y_out)\n\n        g1.map_diag(histplot)\n        for i, ax in enumerate(g1.diag_axes):\n            var = plot_vars[i]\n            count = sum(p.get_height() for p in ax.patches)\n            assert count == df[var].notna().sum()"},{"attributeType":"null","col":8,"comment":"null","endLoc":921,"id":3393,"name":"split","nodeType":"Attribute","startLoc":921,"text":"self.split"},{"attributeType":"null","col":8,"comment":"null","endLoc":905,"id":3394,"name":"gridsize","nodeType":"Attribute","startLoc":905,"text":"self.gridsize"},{"attributeType":"list | list","col":8,"comment":"null","endLoc":1050,"id":3395,"name":"density","nodeType":"Attribute","startLoc":1050,"text":"self.density"},{"attributeType":"null","col":8,"comment":"null","endLoc":906,"id":3396,"name":"width","nodeType":"Attribute","startLoc":906,"text":"self.width"},{"attributeType":"None","col":8,"comment":"null","endLoc":916,"id":3397,"name":"inner","nodeType":"Attribute","startLoc":916,"text":"self.inner"},{"attributeType":"null","col":8,"comment":"null","endLoc":925,"id":3398,"name":"linewidth","nodeType":"Attribute","startLoc":925,"text":"self.linewidth"},{"attributeType":"list | list","col":8,"comment":"null","endLoc":1049,"id":3399,"name":"support","nodeType":"Attribute","startLoc":1049,"text":"self.support"},{"className":"_CategoricalStatPlotter","col":0,"comment":"null","endLoc":1520,"id":3400,"nodeType":"Class","startLoc":1425,"text":"class _CategoricalStatPlotter(_CategoricalPlotter):\n\n    require_numeric = True\n\n    @property\n    def nested_width(self):\n        \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n        if self.dodge:\n            width = self.width / len(self.hue_names)\n        else:\n            width = self.width\n        return width\n\n    def estimate_statistic(self, estimator, errorbar, n_boot, seed):\n\n        if self.hue_names is None:\n            statistic = []\n            confint = []\n        else:\n            statistic = [[] for _ in self.plot_data]\n            confint = [[] for _ in self.plot_data]\n\n        var = {\"v\": \"y\", \"h\": \"x\"}[self.orient]\n\n        agg = EstimateAggregator(estimator, errorbar, n_boot=n_boot, seed=seed)\n\n        for i, group_data in enumerate(self.plot_data):\n\n            # Option 1: we have a single layer of grouping\n            # --------------------------------------------\n            if self.plot_hues is None:\n\n                df = pd.DataFrame({var: group_data})\n                if self.plot_units is not None:\n                    df[\"units\"] = self.plot_units[i]\n\n                res = agg(df, var)\n\n                statistic.append(res[var])\n                if errorbar is not None:\n                    confint.append((res[f\"{var}min\"], res[f\"{var}max\"]))\n\n            # Option 2: we are grouping by a hue layer\n            # ----------------------------------------\n\n            else:\n                for hue_level in self.hue_names:\n\n                    if not self.plot_hues[i].size:\n                        statistic[i].append(np.nan)\n                        if errorbar is not None:\n                            confint[i].append((np.nan, np.nan))\n                        continue\n\n                    hue_mask = self.plot_hues[i] == hue_level\n                    df = pd.DataFrame({var: group_data[hue_mask]})\n                    if self.plot_units is not None:\n                        df[\"units\"] = self.plot_units[i][hue_mask]\n\n                    res = agg(df, var)\n\n                    statistic[i].append(res[var])\n                    if errorbar is not None:\n                        confint[i].append((res[f\"{var}min\"], res[f\"{var}max\"]))\n\n        # Save the resulting values for plotting\n        self.statistic = np.array(statistic)\n        self.confint = np.array(confint)\n\n    def draw_confints(self, ax, at_group, confint, colors,\n                      errwidth=None, capsize=None, **kws):\n\n        if errwidth is not None:\n            kws.setdefault(\"lw\", errwidth)\n        else:\n            kws.setdefault(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.8)\n\n        for at, (ci_low, ci_high), color in zip(at_group,\n                                                confint,\n                                                colors):\n            if self.orient == \"v\":\n                ax.plot([at, at], [ci_low, ci_high], color=color, **kws)\n                if capsize is not None:\n                    ax.plot([at - capsize / 2, at + capsize / 2],\n                            [ci_low, ci_low], color=color, **kws)\n                    ax.plot([at - capsize / 2, at + capsize / 2],\n                            [ci_high, ci_high], color=color, **kws)\n            else:\n                ax.plot([ci_low, ci_high], [at, at], color=color, **kws)\n                if capsize is not None:\n                    ax.plot([ci_low, ci_low],\n                            [at - capsize / 2, at + capsize / 2],\n                            color=color, **kws)\n                    ax.plot([ci_high, ci_high],\n                            [at - capsize / 2, at + capsize / 2],\n                            color=color, **kws)"},{"col":4,"comment":"A float with the width of plot elements when hue nesting is used.","endLoc":1436,"header":"@property\n    def nested_width(self)","id":3401,"name":"nested_width","nodeType":"Function","startLoc":1429,"text":"@property\n    def nested_width(self):\n        \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n        if self.dodge:\n            width = self.width / len(self.hue_names)\n        else:\n            width = self.width\n        return width"},{"col":4,"comment":"null","endLoc":2435,"header":"def test_bivariate_hist_norm(self, rng)","id":3402,"name":"test_bivariate_hist_norm","nodeType":"Function","startLoc":2422,"text":"def test_bivariate_hist_norm(self, rng):\n\n        x, y = rng.normal(0, 1, (2, 100))\n        z = [0] * 80 + [1] * 20\n\n        g = displot(x=x, y=y, col=z, kind=\"hist\")\n        clim1 = g.axes.flat[0].collections[0].get_clim()\n        clim2 = g.axes.flat[1].collections[0].get_clim()\n        assert clim1 == clim2\n\n        g = displot(x=x, y=y, col=z, kind=\"hist\", common_norm=False)\n        clim1 = g.axes.flat[0].collections[0].get_clim()\n        clim2 = g.axes.flat[1].collections[0].get_clim()\n        assert clim1[1] > clim2[1]"},{"col":4,"comment":"null","endLoc":1520,"header":"def draw_confints(self, ax, at_group, confint, colors,\n                      errwidth=None, capsize=None, **kws)","id":3403,"name":"draw_confints","nodeType":"Function","startLoc":1494,"text":"def draw_confints(self, ax, at_group, confint, colors,\n                      errwidth=None, capsize=None, **kws):\n\n        if errwidth is not None:\n            kws.setdefault(\"lw\", errwidth)\n        else:\n            kws.setdefault(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.8)\n\n        for at, (ci_low, ci_high), color in zip(at_group,\n                                                confint,\n                                                colors):\n            if self.orient == \"v\":\n                ax.plot([at, at], [ci_low, ci_high], color=color, **kws)\n                if capsize is not None:\n                    ax.plot([at - capsize / 2, at + capsize / 2],\n                            [ci_low, ci_low], color=color, **kws)\n                    ax.plot([at - capsize / 2, at + capsize / 2],\n                            [ci_high, ci_high], color=color, **kws)\n            else:\n                ax.plot([ci_low, ci_high], [at, at], color=color, **kws)\n                if capsize is not None:\n                    ax.plot([ci_low, ci_low],\n                            [at - capsize / 2, at + capsize / 2],\n                            color=color, **kws)\n                    ax.plot([ci_high, ci_high],\n                            [at - capsize / 2, at + capsize / 2],\n                            color=color, **kws)"},{"id":3404,"name":"seaborn/colors","nodeType":"Package"},{"fileName":"xkcd_rgb.py","filePath":"seaborn/colors","id":3405,"nodeType":"File","text":"xkcd_rgb = {'acid green': '#8ffe09',\n            'adobe': '#bd6c48',\n            'algae': '#54ac68',\n            'algae green': '#21c36f',\n            'almost black': '#070d0d',\n            'amber': '#feb308',\n            'amethyst': '#9b5fc0',\n            'apple': '#6ecb3c',\n            'apple green': '#76cd26',\n            'apricot': '#ffb16d',\n            'aqua': '#13eac9',\n            'aqua blue': '#02d8e9',\n            'aqua green': '#12e193',\n            'aqua marine': '#2ee8bb',\n            'aquamarine': '#04d8b2',\n            'army green': '#4b5d16',\n            'asparagus': '#77ab56',\n            'aubergine': '#3d0734',\n            'auburn': '#9a3001',\n            'avocado': '#90b134',\n            'avocado green': '#87a922',\n            'azul': '#1d5dec',\n            'azure': '#069af3',\n            'baby blue': '#a2cffe',\n            'baby green': '#8cff9e',\n            'baby pink': '#ffb7ce',\n            'baby poo': '#ab9004',\n            'baby poop': '#937c00',\n            'baby poop green': '#8f9805',\n            'baby puke green': '#b6c406',\n            'baby purple': '#ca9bf7',\n            'baby shit brown': '#ad900d',\n            'baby shit green': '#889717',\n            'banana': '#ffff7e',\n            'banana yellow': '#fafe4b',\n            'barbie pink': '#fe46a5',\n            'barf green': '#94ac02',\n            'barney': '#ac1db8',\n            'barney purple': '#a00498',\n            'battleship grey': '#6b7c85',\n            'beige': '#e6daa6',\n            'berry': '#990f4b',\n            'bile': '#b5c306',\n            'black': '#000000',\n            'bland': '#afa88b',\n            'blood': '#770001',\n            'blood orange': '#fe4b03',\n            'blood red': '#980002',\n            'blue': '#0343df',\n            'blue blue': '#2242c7',\n            'blue green': '#137e6d',\n            'blue grey': '#607c8e',\n            'blue purple': '#5729ce',\n            'blue violet': '#5d06e9',\n            'blue with a hint of purple': '#533cc6',\n            'blue/green': '#0f9b8e',\n            'blue/grey': '#758da3',\n            'blue/purple': '#5a06ef',\n            'blueberry': '#464196',\n            'bluegreen': '#017a79',\n            'bluegrey': '#85a3b2',\n            'bluey green': '#2bb179',\n            'bluey grey': '#89a0b0',\n            'bluey purple': '#6241c7',\n            'bluish': '#2976bb',\n            'bluish green': '#10a674',\n            'bluish grey': '#748b97',\n            'bluish purple': '#703be7',\n            'blurple': '#5539cc',\n            'blush': '#f29e8e',\n            'blush pink': '#fe828c',\n            'booger': '#9bb53c',\n            'booger green': '#96b403',\n            'bordeaux': '#7b002c',\n            'boring green': '#63b365',\n            'bottle green': '#044a05',\n            'brick': '#a03623',\n            'brick orange': '#c14a09',\n            'brick red': '#8f1402',\n            'bright aqua': '#0bf9ea',\n            'bright blue': '#0165fc',\n            'bright cyan': '#41fdfe',\n            'bright green': '#01ff07',\n            'bright lavender': '#c760ff',\n            'bright light blue': '#26f7fd',\n            'bright light green': '#2dfe54',\n            'bright lilac': '#c95efb',\n            'bright lime': '#87fd05',\n            'bright lime green': '#65fe08',\n            'bright magenta': '#ff08e8',\n            'bright olive': '#9cbb04',\n            'bright orange': '#ff5b00',\n            'bright pink': '#fe01b1',\n            'bright purple': '#be03fd',\n            'bright red': '#ff000d',\n            'bright sea green': '#05ffa6',\n            'bright sky blue': '#02ccfe',\n            'bright teal': '#01f9c6',\n            'bright turquoise': '#0ffef9',\n            'bright violet': '#ad0afd',\n            'bright yellow': '#fffd01',\n            'bright yellow green': '#9dff00',\n            'british racing green': '#05480d',\n            'bronze': '#a87900',\n            'brown': '#653700',\n            'brown green': '#706c11',\n            'brown grey': '#8d8468',\n            'brown orange': '#b96902',\n            'brown red': '#922b05',\n            'brown yellow': '#b29705',\n            'brownish': '#9c6d57',\n            'brownish green': '#6a6e09',\n            'brownish grey': '#86775f',\n            'brownish orange': '#cb7723',\n            'brownish pink': '#c27e79',\n            'brownish purple': '#76424e',\n            'brownish red': '#9e3623',\n            'brownish yellow': '#c9b003',\n            'browny green': '#6f6c0a',\n            'browny orange': '#ca6b02',\n            'bruise': '#7e4071',\n            'bubble gum pink': '#ff69af',\n            'bubblegum': '#ff6cb5',\n            'bubblegum pink': '#fe83cc',\n            'buff': '#fef69e',\n            'burgundy': '#610023',\n            'burnt orange': '#c04e01',\n            'burnt red': '#9f2305',\n            'burnt siena': '#b75203',\n            'burnt sienna': '#b04e0f',\n            'burnt umber': '#a0450e',\n            'burnt yellow': '#d5ab09',\n            'burple': '#6832e3',\n            'butter': '#ffff81',\n            'butter yellow': '#fffd74',\n            'butterscotch': '#fdb147',\n            'cadet blue': '#4e7496',\n            'camel': '#c69f59',\n            'camo': '#7f8f4e',\n            'camo green': '#526525',\n            'camouflage green': '#4b6113',\n            'canary': '#fdff63',\n            'canary yellow': '#fffe40',\n            'candy pink': '#ff63e9',\n            'caramel': '#af6f09',\n            'carmine': '#9d0216',\n            'carnation': '#fd798f',\n            'carnation pink': '#ff7fa7',\n            'carolina blue': '#8ab8fe',\n            'celadon': '#befdb7',\n            'celery': '#c1fd95',\n            'cement': '#a5a391',\n            'cerise': '#de0c62',\n            'cerulean': '#0485d1',\n            'cerulean blue': '#056eee',\n            'charcoal': '#343837',\n            'charcoal grey': '#3c4142',\n            'chartreuse': '#c1f80a',\n            'cherry': '#cf0234',\n            'cherry red': '#f7022a',\n            'chestnut': '#742802',\n            'chocolate': '#3d1c02',\n            'chocolate brown': '#411900',\n            'cinnamon': '#ac4f06',\n            'claret': '#680018',\n            'clay': '#b66a50',\n            'clay brown': '#b2713d',\n            'clear blue': '#247afd',\n            'cloudy blue': '#acc2d9',\n            'cobalt': '#1e488f',\n            'cobalt blue': '#030aa7',\n            'cocoa': '#875f42',\n            'coffee': '#a6814c',\n            'cool blue': '#4984b8',\n            'cool green': '#33b864',\n            'cool grey': '#95a3a6',\n            'copper': '#b66325',\n            'coral': '#fc5a50',\n            'coral pink': '#ff6163',\n            'cornflower': '#6a79f7',\n            'cornflower blue': '#5170d7',\n            'cranberry': '#9e003a',\n            'cream': '#ffffc2',\n            'creme': '#ffffb6',\n            'crimson': '#8c000f',\n            'custard': '#fffd78',\n            'cyan': '#00ffff',\n            'dandelion': '#fedf08',\n            'dark': '#1b2431',\n            'dark aqua': '#05696b',\n            'dark aquamarine': '#017371',\n            'dark beige': '#ac9362',\n            'dark blue': '#00035b',\n            'dark blue green': '#005249',\n            'dark blue grey': '#1f3b4d',\n            'dark brown': '#341c02',\n            'dark coral': '#cf524e',\n            'dark cream': '#fff39a',\n            'dark cyan': '#0a888a',\n            'dark forest green': '#002d04',\n            'dark fuchsia': '#9d0759',\n            'dark gold': '#b59410',\n            'dark grass green': '#388004',\n            'dark green': '#033500',\n            'dark green blue': '#1f6357',\n            'dark grey': '#363737',\n            'dark grey blue': '#29465b',\n            'dark hot pink': '#d90166',\n            'dark indigo': '#1f0954',\n            'dark khaki': '#9b8f55',\n            'dark lavender': '#856798',\n            'dark lilac': '#9c6da5',\n            'dark lime': '#84b701',\n            'dark lime green': '#7ebd01',\n            'dark magenta': '#960056',\n            'dark maroon': '#3c0008',\n            'dark mauve': '#874c62',\n            'dark mint': '#48c072',\n            'dark mint green': '#20c073',\n            'dark mustard': '#a88905',\n            'dark navy': '#000435',\n            'dark navy blue': '#00022e',\n            'dark olive': '#373e02',\n            'dark olive green': '#3c4d03',\n            'dark orange': '#c65102',\n            'dark pastel green': '#56ae57',\n            'dark peach': '#de7e5d',\n            'dark periwinkle': '#665fd1',\n            'dark pink': '#cb416b',\n            'dark plum': '#3f012c',\n            'dark purple': '#35063e',\n            'dark red': '#840000',\n            'dark rose': '#b5485d',\n            'dark royal blue': '#02066f',\n            'dark sage': '#598556',\n            'dark salmon': '#c85a53',\n            'dark sand': '#a88f59',\n            'dark sea green': '#11875d',\n            'dark seafoam': '#1fb57a',\n            'dark seafoam green': '#3eaf76',\n            'dark sky blue': '#448ee4',\n            'dark slate blue': '#214761',\n            'dark tan': '#af884a',\n            'dark taupe': '#7f684e',\n            'dark teal': '#014d4e',\n            'dark turquoise': '#045c5a',\n            'dark violet': '#34013f',\n            'dark yellow': '#d5b60a',\n            'dark yellow green': '#728f02',\n            'darkblue': '#030764',\n            'darkgreen': '#054907',\n            'darkish blue': '#014182',\n            'darkish green': '#287c37',\n            'darkish pink': '#da467d',\n            'darkish purple': '#751973',\n            'darkish red': '#a90308',\n            'deep aqua': '#08787f',\n            'deep blue': '#040273',\n            'deep brown': '#410200',\n            'deep green': '#02590f',\n            'deep lavender': '#8d5eb7',\n            'deep lilac': '#966ebd',\n            'deep magenta': '#a0025c',\n            'deep orange': '#dc4d01',\n            'deep pink': '#cb0162',\n            'deep purple': '#36013f',\n            'deep red': '#9a0200',\n            'deep rose': '#c74767',\n            'deep sea blue': '#015482',\n            'deep sky blue': '#0d75f8',\n            'deep teal': '#00555a',\n            'deep turquoise': '#017374',\n            'deep violet': '#490648',\n            'denim': '#3b638c',\n            'denim blue': '#3b5b92',\n            'desert': '#ccad60',\n            'diarrhea': '#9f8303',\n            'dirt': '#8a6e45',\n            'dirt brown': '#836539',\n            'dirty blue': '#3f829d',\n            'dirty green': '#667e2c',\n            'dirty orange': '#c87606',\n            'dirty pink': '#ca7b80',\n            'dirty purple': '#734a65',\n            'dirty yellow': '#cdc50a',\n            'dodger blue': '#3e82fc',\n            'drab': '#828344',\n            'drab green': '#749551',\n            'dried blood': '#4b0101',\n            'duck egg blue': '#c3fbf4',\n            'dull blue': '#49759c',\n            'dull brown': '#876e4b',\n            'dull green': '#74a662',\n            'dull orange': '#d8863b',\n            'dull pink': '#d5869d',\n            'dull purple': '#84597e',\n            'dull red': '#bb3f3f',\n            'dull teal': '#5f9e8f',\n            'dull yellow': '#eedc5b',\n            'dusk': '#4e5481',\n            'dusk blue': '#26538d',\n            'dusky blue': '#475f94',\n            'dusky pink': '#cc7a8b',\n            'dusky purple': '#895b7b',\n            'dusky rose': '#ba6873',\n            'dust': '#b2996e',\n            'dusty blue': '#5a86ad',\n            'dusty green': '#76a973',\n            'dusty lavender': '#ac86a8',\n            'dusty orange': '#f0833a',\n            'dusty pink': '#d58a94',\n            'dusty purple': '#825f87',\n            'dusty red': '#b9484e',\n            'dusty rose': '#c0737a',\n            'dusty teal': '#4c9085',\n            'earth': '#a2653e',\n            'easter green': '#8cfd7e',\n            'easter purple': '#c071fe',\n            'ecru': '#feffca',\n            'egg shell': '#fffcc4',\n            'eggplant': '#380835',\n            'eggplant purple': '#430541',\n            'eggshell': '#ffffd4',\n            'eggshell blue': '#c4fff7',\n            'electric blue': '#0652ff',\n            'electric green': '#21fc0d',\n            'electric lime': '#a8ff04',\n            'electric pink': '#ff0490',\n            'electric purple': '#aa23ff',\n            'emerald': '#01a049',\n            'emerald green': '#028f1e',\n            'evergreen': '#05472a',\n            'faded blue': '#658cbb',\n            'faded green': '#7bb274',\n            'faded orange': '#f0944d',\n            'faded pink': '#de9dac',\n            'faded purple': '#916e99',\n            'faded red': '#d3494e',\n            'faded yellow': '#feff7f',\n            'fawn': '#cfaf7b',\n            'fern': '#63a950',\n            'fern green': '#548d44',\n            'fire engine red': '#fe0002',\n            'flat blue': '#3c73a8',\n            'flat green': '#699d4c',\n            'fluorescent green': '#08ff08',\n            'fluro green': '#0aff02',\n            'foam green': '#90fda9',\n            'forest': '#0b5509',\n            'forest green': '#06470c',\n            'forrest green': '#154406',\n            'french blue': '#436bad',\n            'fresh green': '#69d84f',\n            'frog green': '#58bc08',\n            'fuchsia': '#ed0dd9',\n            'gold': '#dbb40c',\n            'golden': '#f5bf03',\n            'golden brown': '#b27a01',\n            'golden rod': '#f9bc08',\n            'golden yellow': '#fec615',\n            'goldenrod': '#fac205',\n            'grape': '#6c3461',\n            'grape purple': '#5d1451',\n            'grapefruit': '#fd5956',\n            'grass': '#5cac2d',\n            'grass green': '#3f9b0b',\n            'grassy green': '#419c03',\n            'green': '#15b01a',\n            'green apple': '#5edc1f',\n            'green blue': '#06b48b',\n            'green brown': '#544e03',\n            'green grey': '#77926f',\n            'green teal': '#0cb577',\n            'green yellow': '#c9ff27',\n            'green/blue': '#01c08d',\n            'green/yellow': '#b5ce08',\n            'greenblue': '#23c48b',\n            'greenish': '#40a368',\n            'greenish beige': '#c9d179',\n            'greenish blue': '#0b8b87',\n            'greenish brown': '#696112',\n            'greenish cyan': '#2afeb7',\n            'greenish grey': '#96ae8d',\n            'greenish tan': '#bccb7a',\n            'greenish teal': '#32bf84',\n            'greenish turquoise': '#00fbb0',\n            'greenish yellow': '#cdfd02',\n            'greeny blue': '#42b395',\n            'greeny brown': '#696006',\n            'greeny grey': '#7ea07a',\n            'greeny yellow': '#c6f808',\n            'grey': '#929591',\n            'grey blue': '#6b8ba4',\n            'grey brown': '#7f7053',\n            'grey green': '#789b73',\n            'grey pink': '#c3909b',\n            'grey purple': '#826d8c',\n            'grey teal': '#5e9b8a',\n            'grey/blue': '#647d8e',\n            'grey/green': '#86a17d',\n            'greyblue': '#77a1b5',\n            'greyish': '#a8a495',\n            'greyish blue': '#5e819d',\n            'greyish brown': '#7a6a4f',\n            'greyish green': '#82a67d',\n            'greyish pink': '#c88d94',\n            'greyish purple': '#887191',\n            'greyish teal': '#719f91',\n            'gross green': '#a0bf16',\n            'gunmetal': '#536267',\n            'hazel': '#8e7618',\n            'heather': '#a484ac',\n            'heliotrope': '#d94ff5',\n            'highlighter green': '#1bfc06',\n            'hospital green': '#9be5aa',\n            'hot green': '#25ff29',\n            'hot magenta': '#f504c9',\n            'hot pink': '#ff028d',\n            'hot purple': '#cb00f5',\n            'hunter green': '#0b4008',\n            'ice': '#d6fffa',\n            'ice blue': '#d7fffe',\n            'icky green': '#8fae22',\n            'indian red': '#850e04',\n            'indigo': '#380282',\n            'indigo blue': '#3a18b1',\n            'iris': '#6258c4',\n            'irish green': '#019529',\n            'ivory': '#ffffcb',\n            'jade': '#1fa774',\n            'jade green': '#2baf6a',\n            'jungle green': '#048243',\n            'kelley green': '#009337',\n            'kelly green': '#02ab2e',\n            'kermit green': '#5cb200',\n            'key lime': '#aeff6e',\n            'khaki': '#aaa662',\n            'khaki green': '#728639',\n            'kiwi': '#9cef43',\n            'kiwi green': '#8ee53f',\n            'lavender': '#c79fef',\n            'lavender blue': '#8b88f8',\n            'lavender pink': '#dd85d7',\n            'lawn green': '#4da409',\n            'leaf': '#71aa34',\n            'leaf green': '#5ca904',\n            'leafy green': '#51b73b',\n            'leather': '#ac7434',\n            'lemon': '#fdff52',\n            'lemon green': '#adf802',\n            'lemon lime': '#bffe28',\n            'lemon yellow': '#fdff38',\n            'lichen': '#8fb67b',\n            'light aqua': '#8cffdb',\n            'light aquamarine': '#7bfdc7',\n            'light beige': '#fffeb6',\n            'light blue': '#95d0fc',\n            'light blue green': '#7efbb3',\n            'light blue grey': '#b7c9e2',\n            'light bluish green': '#76fda8',\n            'light bright green': '#53fe5c',\n            'light brown': '#ad8150',\n            'light burgundy': '#a8415b',\n            'light cyan': '#acfffc',\n            'light eggplant': '#894585',\n            'light forest green': '#4f9153',\n            'light gold': '#fddc5c',\n            'light grass green': '#9af764',\n            'light green': '#96f97b',\n            'light green blue': '#56fca2',\n            'light greenish blue': '#63f7b4',\n            'light grey': '#d8dcd6',\n            'light grey blue': '#9dbcd4',\n            'light grey green': '#b7e1a1',\n            'light indigo': '#6d5acf',\n            'light khaki': '#e6f2a2',\n            'light lavendar': '#efc0fe',\n            'light lavender': '#dfc5fe',\n            'light light blue': '#cafffb',\n            'light light green': '#c8ffb0',\n            'light lilac': '#edc8ff',\n            'light lime': '#aefd6c',\n            'light lime green': '#b9ff66',\n            'light magenta': '#fa5ff7',\n            'light maroon': '#a24857',\n            'light mauve': '#c292a1',\n            'light mint': '#b6ffbb',\n            'light mint green': '#a6fbb2',\n            'light moss green': '#a6c875',\n            'light mustard': '#f7d560',\n            'light navy': '#155084',\n            'light navy blue': '#2e5a88',\n            'light neon green': '#4efd54',\n            'light olive': '#acbf69',\n            'light olive green': '#a4be5c',\n            'light orange': '#fdaa48',\n            'light pastel green': '#b2fba5',\n            'light pea green': '#c4fe82',\n            'light peach': '#ffd8b1',\n            'light periwinkle': '#c1c6fc',\n            'light pink': '#ffd1df',\n            'light plum': '#9d5783',\n            'light purple': '#bf77f6',\n            'light red': '#ff474c',\n            'light rose': '#ffc5cb',\n            'light royal blue': '#3a2efe',\n            'light sage': '#bcecac',\n            'light salmon': '#fea993',\n            'light sea green': '#98f6b0',\n            'light seafoam': '#a0febf',\n            'light seafoam green': '#a7ffb5',\n            'light sky blue': '#c6fcff',\n            'light tan': '#fbeeac',\n            'light teal': '#90e4c1',\n            'light turquoise': '#7ef4cc',\n            'light urple': '#b36ff6',\n            'light violet': '#d6b4fc',\n            'light yellow': '#fffe7a',\n            'light yellow green': '#ccfd7f',\n            'light yellowish green': '#c2ff89',\n            'lightblue': '#7bc8f6',\n            'lighter green': '#75fd63',\n            'lighter purple': '#a55af4',\n            'lightgreen': '#76ff7b',\n            'lightish blue': '#3d7afd',\n            'lightish green': '#61e160',\n            'lightish purple': '#a552e6',\n            'lightish red': '#fe2f4a',\n            'lilac': '#cea2fd',\n            'liliac': '#c48efd',\n            'lime': '#aaff32',\n            'lime green': '#89fe05',\n            'lime yellow': '#d0fe1d',\n            'lipstick': '#d5174e',\n            'lipstick red': '#c0022f',\n            'macaroni and cheese': '#efb435',\n            'magenta': '#c20078',\n            'mahogany': '#4a0100',\n            'maize': '#f4d054',\n            'mango': '#ffa62b',\n            'manilla': '#fffa86',\n            'marigold': '#fcc006',\n            'marine': '#042e60',\n            'marine blue': '#01386a',\n            'maroon': '#650021',\n            'mauve': '#ae7181',\n            'medium blue': '#2c6fbb',\n            'medium brown': '#7f5112',\n            'medium green': '#39ad48',\n            'medium grey': '#7d7f7c',\n            'medium pink': '#f36196',\n            'medium purple': '#9e43a2',\n            'melon': '#ff7855',\n            'merlot': '#730039',\n            'metallic blue': '#4f738e',\n            'mid blue': '#276ab3',\n            'mid green': '#50a747',\n            'midnight': '#03012d',\n            'midnight blue': '#020035',\n            'midnight purple': '#280137',\n            'military green': '#667c3e',\n            'milk chocolate': '#7f4e1e',\n            'mint': '#9ffeb0',\n            'mint green': '#8fff9f',\n            'minty green': '#0bf77d',\n            'mocha': '#9d7651',\n            'moss': '#769958',\n            'moss green': '#658b38',\n            'mossy green': '#638b27',\n            'mud': '#735c12',\n            'mud brown': '#60460f',\n            'mud green': '#606602',\n            'muddy brown': '#886806',\n            'muddy green': '#657432',\n            'muddy yellow': '#bfac05',\n            'mulberry': '#920a4e',\n            'murky green': '#6c7a0e',\n            'mushroom': '#ba9e88',\n            'mustard': '#ceb301',\n            'mustard brown': '#ac7e04',\n            'mustard green': '#a8b504',\n            'mustard yellow': '#d2bd0a',\n            'muted blue': '#3b719f',\n            'muted green': '#5fa052',\n            'muted pink': '#d1768f',\n            'muted purple': '#805b87',\n            'nasty green': '#70b23f',\n            'navy': '#01153e',\n            'navy blue': '#001146',\n            'navy green': '#35530a',\n            'neon blue': '#04d9ff',\n            'neon green': '#0cff0c',\n            'neon pink': '#fe019a',\n            'neon purple': '#bc13fe',\n            'neon red': '#ff073a',\n            'neon yellow': '#cfff04',\n            'nice blue': '#107ab0',\n            'night blue': '#040348',\n            'ocean': '#017b92',\n            'ocean blue': '#03719c',\n            'ocean green': '#3d9973',\n            'ocher': '#bf9b0c',\n            'ochre': '#bf9005',\n            'ocre': '#c69c04',\n            'off blue': '#5684ae',\n            'off green': '#6ba353',\n            'off white': '#ffffe4',\n            'off yellow': '#f1f33f',\n            'old pink': '#c77986',\n            'old rose': '#c87f89',\n            'olive': '#6e750e',\n            'olive brown': '#645403',\n            'olive drab': '#6f7632',\n            'olive green': '#677a04',\n            'olive yellow': '#c2b709',\n            'orange': '#f97306',\n            'orange brown': '#be6400',\n            'orange pink': '#ff6f52',\n            'orange red': '#fd411e',\n            'orange yellow': '#ffad01',\n            'orangeish': '#fd8d49',\n            'orangered': '#fe420f',\n            'orangey brown': '#b16002',\n            'orangey red': '#fa4224',\n            'orangey yellow': '#fdb915',\n            'orangish': '#fc824a',\n            'orangish brown': '#b25f03',\n            'orangish red': '#f43605',\n            'orchid': '#c875c4',\n            'pale': '#fff9d0',\n            'pale aqua': '#b8ffeb',\n            'pale blue': '#d0fefe',\n            'pale brown': '#b1916e',\n            'pale cyan': '#b7fffa',\n            'pale gold': '#fdde6c',\n            'pale green': '#c7fdb5',\n            'pale grey': '#fdfdfe',\n            'pale lavender': '#eecffe',\n            'pale light green': '#b1fc99',\n            'pale lilac': '#e4cbff',\n            'pale lime': '#befd73',\n            'pale lime green': '#b1ff65',\n            'pale magenta': '#d767ad',\n            'pale mauve': '#fed0fc',\n            'pale olive': '#b9cc81',\n            'pale olive green': '#b1d27b',\n            'pale orange': '#ffa756',\n            'pale peach': '#ffe5ad',\n            'pale pink': '#ffcfdc',\n            'pale purple': '#b790d4',\n            'pale red': '#d9544d',\n            'pale rose': '#fdc1c5',\n            'pale salmon': '#ffb19a',\n            'pale sky blue': '#bdf6fe',\n            'pale teal': '#82cbb2',\n            'pale turquoise': '#a5fbd5',\n            'pale violet': '#ceaefa',\n            'pale yellow': '#ffff84',\n            'parchment': '#fefcaf',\n            'pastel blue': '#a2bffe',\n            'pastel green': '#b0ff9d',\n            'pastel orange': '#ff964f',\n            'pastel pink': '#ffbacd',\n            'pastel purple': '#caa0ff',\n            'pastel red': '#db5856',\n            'pastel yellow': '#fffe71',\n            'pea': '#a4bf20',\n            'pea green': '#8eab12',\n            'pea soup': '#929901',\n            'pea soup green': '#94a617',\n            'peach': '#ffb07c',\n            'peachy pink': '#ff9a8a',\n            'peacock blue': '#016795',\n            'pear': '#cbf85f',\n            'periwinkle': '#8e82fe',\n            'periwinkle blue': '#8f99fb',\n            'perrywinkle': '#8f8ce7',\n            'petrol': '#005f6a',\n            'pig pink': '#e78ea5',\n            'pine': '#2b5d34',\n            'pine green': '#0a481e',\n            'pink': '#ff81c0',\n            'pink purple': '#db4bda',\n            'pink red': '#f5054f',\n            'pink/purple': '#ef1de7',\n            'pinkish': '#d46a7e',\n            'pinkish brown': '#b17261',\n            'pinkish grey': '#c8aca9',\n            'pinkish orange': '#ff724c',\n            'pinkish purple': '#d648d7',\n            'pinkish red': '#f10c45',\n            'pinkish tan': '#d99b82',\n            'pinky': '#fc86aa',\n            'pinky purple': '#c94cbe',\n            'pinky red': '#fc2647',\n            'piss yellow': '#ddd618',\n            'pistachio': '#c0fa8b',\n            'plum': '#580f41',\n            'plum purple': '#4e0550',\n            'poison green': '#40fd14',\n            'poo': '#8f7303',\n            'poo brown': '#885f01',\n            'poop': '#7f5e00',\n            'poop brown': '#7a5901',\n            'poop green': '#6f7c00',\n            'powder blue': '#b1d1fc',\n            'powder pink': '#ffb2d0',\n            'primary blue': '#0804f9',\n            'prussian blue': '#004577',\n            'puce': '#a57e52',\n            'puke': '#a5a502',\n            'puke brown': '#947706',\n            'puke green': '#9aae07',\n            'puke yellow': '#c2be0e',\n            'pumpkin': '#e17701',\n            'pumpkin orange': '#fb7d07',\n            'pure blue': '#0203e2',\n            'purple': '#7e1e9c',\n            'purple blue': '#632de9',\n            'purple brown': '#673a3f',\n            'purple grey': '#866f85',\n            'purple pink': '#e03fd8',\n            'purple red': '#990147',\n            'purple/blue': '#5d21d0',\n            'purple/pink': '#d725de',\n            'purpleish': '#98568d',\n            'purpleish blue': '#6140ef',\n            'purpleish pink': '#df4ec8',\n            'purpley': '#8756e4',\n            'purpley blue': '#5f34e7',\n            'purpley grey': '#947e94',\n            'purpley pink': '#c83cb9',\n            'purplish': '#94568c',\n            'purplish blue': '#601ef9',\n            'purplish brown': '#6b4247',\n            'purplish grey': '#7a687f',\n            'purplish pink': '#ce5dae',\n            'purplish red': '#b0054b',\n            'purply': '#983fb2',\n            'purply blue': '#661aee',\n            'purply pink': '#f075e6',\n            'putty': '#beae8a',\n            'racing green': '#014600',\n            'radioactive green': '#2cfa1f',\n            'raspberry': '#b00149',\n            'raw sienna': '#9a6200',\n            'raw umber': '#a75e09',\n            'really light blue': '#d4ffff',\n            'red': '#e50000',\n            'red brown': '#8b2e16',\n            'red orange': '#fd3c06',\n            'red pink': '#fa2a55',\n            'red purple': '#820747',\n            'red violet': '#9e0168',\n            'red wine': '#8c0034',\n            'reddish': '#c44240',\n            'reddish brown': '#7f2b0a',\n            'reddish grey': '#997570',\n            'reddish orange': '#f8481c',\n            'reddish pink': '#fe2c54',\n            'reddish purple': '#910951',\n            'reddy brown': '#6e1005',\n            'rich blue': '#021bf9',\n            'rich purple': '#720058',\n            'robin egg blue': '#8af1fe',\n            \"robin's egg\": '#6dedfd',\n            \"robin's egg blue\": '#98eff9',\n            'rosa': '#fe86a4',\n            'rose': '#cf6275',\n            'rose pink': '#f7879a',\n            'rose red': '#be013c',\n            'rosy pink': '#f6688e',\n            'rouge': '#ab1239',\n            'royal': '#0c1793',\n            'royal blue': '#0504aa',\n            'royal purple': '#4b006e',\n            'ruby': '#ca0147',\n            'russet': '#a13905',\n            'rust': '#a83c09',\n            'rust brown': '#8b3103',\n            'rust orange': '#c45508',\n            'rust red': '#aa2704',\n            'rusty orange': '#cd5909',\n            'rusty red': '#af2f0d',\n            'saffron': '#feb209',\n            'sage': '#87ae73',\n            'sage green': '#88b378',\n            'salmon': '#ff796c',\n            'salmon pink': '#fe7b7c',\n            'sand': '#e2ca76',\n            'sand brown': '#cba560',\n            'sand yellow': '#fce166',\n            'sandstone': '#c9ae74',\n            'sandy': '#f1da7a',\n            'sandy brown': '#c4a661',\n            'sandy yellow': '#fdee73',\n            'sap green': '#5c8b15',\n            'sapphire': '#2138ab',\n            'scarlet': '#be0119',\n            'sea': '#3c9992',\n            'sea blue': '#047495',\n            'sea green': '#53fca1',\n            'seafoam': '#80f9ad',\n            'seafoam blue': '#78d1b6',\n            'seafoam green': '#7af9ab',\n            'seaweed': '#18d17b',\n            'seaweed green': '#35ad6b',\n            'sepia': '#985e2b',\n            'shamrock': '#01b44c',\n            'shamrock green': '#02c14d',\n            'shit': '#7f5f00',\n            'shit brown': '#7b5804',\n            'shit green': '#758000',\n            'shocking pink': '#fe02a2',\n            'sick green': '#9db92c',\n            'sickly green': '#94b21c',\n            'sickly yellow': '#d0e429',\n            'sienna': '#a9561e',\n            'silver': '#c5c9c7',\n            'sky': '#82cafc',\n            'sky blue': '#75bbfd',\n            'slate': '#516572',\n            'slate blue': '#5b7c99',\n            'slate green': '#658d6d',\n            'slate grey': '#59656d',\n            'slime green': '#99cc04',\n            'snot': '#acbb0d',\n            'snot green': '#9dc100',\n            'soft blue': '#6488ea',\n            'soft green': '#6fc276',\n            'soft pink': '#fdb0c0',\n            'soft purple': '#a66fb5',\n            'spearmint': '#1ef876',\n            'spring green': '#a9f971',\n            'spruce': '#0a5f38',\n            'squash': '#f2ab15',\n            'steel': '#738595',\n            'steel blue': '#5a7d9a',\n            'steel grey': '#6f828a',\n            'stone': '#ada587',\n            'stormy blue': '#507b9c',\n            'straw': '#fcf679',\n            'strawberry': '#fb2943',\n            'strong blue': '#0c06f7',\n            'strong pink': '#ff0789',\n            'sun yellow': '#ffdf22',\n            'sunflower': '#ffc512',\n            'sunflower yellow': '#ffda03',\n            'sunny yellow': '#fff917',\n            'sunshine yellow': '#fffd37',\n            'swamp': '#698339',\n            'swamp green': '#748500',\n            'tan': '#d1b26f',\n            'tan brown': '#ab7e4c',\n            'tan green': '#a9be70',\n            'tangerine': '#ff9408',\n            'taupe': '#b9a281',\n            'tea': '#65ab7c',\n            'tea green': '#bdf8a3',\n            'teal': '#029386',\n            'teal blue': '#01889f',\n            'teal green': '#25a36f',\n            'tealish': '#24bca8',\n            'tealish green': '#0cdc73',\n            'terra cotta': '#c9643b',\n            'terracota': '#cb6843',\n            'terracotta': '#ca6641',\n            'tiffany blue': '#7bf2da',\n            'tomato': '#ef4026',\n            'tomato red': '#ec2d01',\n            'topaz': '#13bbaf',\n            'toupe': '#c7ac7d',\n            'toxic green': '#61de2a',\n            'tree green': '#2a7e19',\n            'true blue': '#010fcc',\n            'true green': '#089404',\n            'turquoise': '#06c2ac',\n            'turquoise blue': '#06b1c4',\n            'turquoise green': '#04f489',\n            'turtle green': '#75b84f',\n            'twilight': '#4e518b',\n            'twilight blue': '#0a437a',\n            'ugly blue': '#31668a',\n            'ugly brown': '#7d7103',\n            'ugly green': '#7a9703',\n            'ugly pink': '#cd7584',\n            'ugly purple': '#a442a0',\n            'ugly yellow': '#d0c101',\n            'ultramarine': '#2000b1',\n            'ultramarine blue': '#1805db',\n            'umber': '#b26400',\n            'velvet': '#750851',\n            'vermillion': '#f4320c',\n            'very dark blue': '#000133',\n            'very dark brown': '#1d0200',\n            'very dark green': '#062e03',\n            'very dark purple': '#2a0134',\n            'very light blue': '#d5ffff',\n            'very light brown': '#d3b683',\n            'very light green': '#d1ffbd',\n            'very light pink': '#fff4f2',\n            'very light purple': '#f6cefc',\n            'very pale blue': '#d6fffe',\n            'very pale green': '#cffdbc',\n            'vibrant blue': '#0339f8',\n            'vibrant green': '#0add08',\n            'vibrant purple': '#ad03de',\n            'violet': '#9a0eea',\n            'violet blue': '#510ac9',\n            'violet pink': '#fb5ffc',\n            'violet red': '#a50055',\n            'viridian': '#1e9167',\n            'vivid blue': '#152eff',\n            'vivid green': '#2fef10',\n            'vivid purple': '#9900fa',\n            'vomit': '#a2a415',\n            'vomit green': '#89a203',\n            'vomit yellow': '#c7c10c',\n            'warm blue': '#4b57db',\n            'warm brown': '#964e02',\n            'warm grey': '#978a84',\n            'warm pink': '#fb5581',\n            'warm purple': '#952e8f',\n            'washed out green': '#bcf5a6',\n            'water blue': '#0e87cc',\n            'watermelon': '#fd4659',\n            'weird green': '#3ae57f',\n            'wheat': '#fbdd7e',\n            'white': '#ffffff',\n            'windows blue': '#3778bf',\n            'wine': '#80013f',\n            'wine red': '#7b0323',\n            'wintergreen': '#20f986',\n            'wisteria': '#a87dc2',\n            'yellow': '#ffff14',\n            'yellow brown': '#b79400',\n            'yellow green': '#c0fb2d',\n            'yellow ochre': '#cb9d06',\n            'yellow orange': '#fcb001',\n            'yellow tan': '#ffe36e',\n            'yellow/green': '#c8fd3d',\n            'yellowgreen': '#bbf90f',\n            'yellowish': '#faee66',\n            'yellowish brown': '#9b7a01',\n            'yellowish green': '#b0dd16',\n            'yellowish orange': '#ffab0f',\n            'yellowish tan': '#fcfc81',\n            'yellowy brown': '#ae8b0c',\n            'yellowy green': '#bff128'}\n"},{"col":0,"comment":"","endLoc":949,"header":"xkcd_rgb.py#","id":3406,"name":"","nodeType":"Function","startLoc":1,"text":"xkcd_rgb = {'acid green': '#8ffe09',\n            'adobe': '#bd6c48',\n            'algae': '#54ac68',\n            'algae green': '#21c36f',\n            'almost black': '#070d0d',\n            'amber': '#feb308',\n            'amethyst': '#9b5fc0',\n            'apple': '#6ecb3c',\n            'apple green': '#76cd26',\n            'apricot': '#ffb16d',\n            'aqua': '#13eac9',\n            'aqua blue': '#02d8e9',\n            'aqua green': '#12e193',\n            'aqua marine': '#2ee8bb',\n            'aquamarine': '#04d8b2',\n            'army green': '#4b5d16',\n            'asparagus': '#77ab56',\n            'aubergine': '#3d0734',\n            'auburn': '#9a3001',\n            'avocado': '#90b134',\n            'avocado green': '#87a922',\n            'azul': '#1d5dec',\n            'azure': '#069af3',\n            'baby blue': '#a2cffe',\n            'baby green': '#8cff9e',\n            'baby pink': '#ffb7ce',\n            'baby poo': '#ab9004',\n            'baby poop': '#937c00',\n            'baby poop green': '#8f9805',\n            'baby puke green': '#b6c406',\n            'baby purple': '#ca9bf7',\n            'baby shit brown': '#ad900d',\n            'baby shit green': '#889717',\n            'banana': '#ffff7e',\n            'banana yellow': '#fafe4b',\n            'barbie pink': '#fe46a5',\n            'barf green': '#94ac02',\n            'barney': '#ac1db8',\n            'barney purple': '#a00498',\n            'battleship grey': '#6b7c85',\n            'beige': '#e6daa6',\n            'berry': '#990f4b',\n            'bile': '#b5c306',\n            'black': '#000000',\n            'bland': '#afa88b',\n            'blood': '#770001',\n            'blood orange': '#fe4b03',\n            'blood red': '#980002',\n            'blue': '#0343df',\n            'blue blue': '#2242c7',\n            'blue green': '#137e6d',\n            'blue grey': '#607c8e',\n            'blue purple': '#5729ce',\n            'blue violet': '#5d06e9',\n            'blue with a hint of purple': '#533cc6',\n            'blue/green': '#0f9b8e',\n            'blue/grey': '#758da3',\n            'blue/purple': '#5a06ef',\n            'blueberry': '#464196',\n            'bluegreen': '#017a79',\n            'bluegrey': '#85a3b2',\n            'bluey green': '#2bb179',\n            'bluey grey': '#89a0b0',\n            'bluey purple': '#6241c7',\n            'bluish': '#2976bb',\n            'bluish green': '#10a674',\n            'bluish grey': '#748b97',\n            'bluish purple': '#703be7',\n            'blurple': '#5539cc',\n            'blush': '#f29e8e',\n            'blush pink': '#fe828c',\n            'booger': '#9bb53c',\n            'booger green': '#96b403',\n            'bordeaux': '#7b002c',\n            'boring green': '#63b365',\n            'bottle green': '#044a05',\n            'brick': '#a03623',\n            'brick orange': '#c14a09',\n            'brick red': '#8f1402',\n            'bright aqua': '#0bf9ea',\n            'bright blue': '#0165fc',\n            'bright cyan': '#41fdfe',\n            'bright green': '#01ff07',\n            'bright lavender': '#c760ff',\n            'bright light blue': '#26f7fd',\n            'bright light green': '#2dfe54',\n            'bright lilac': '#c95efb',\n            'bright lime': '#87fd05',\n            'bright lime green': '#65fe08',\n            'bright magenta': '#ff08e8',\n            'bright olive': '#9cbb04',\n            'bright orange': '#ff5b00',\n            'bright pink': '#fe01b1',\n            'bright purple': '#be03fd',\n            'bright red': '#ff000d',\n            'bright sea green': '#05ffa6',\n            'bright sky blue': '#02ccfe',\n            'bright teal': '#01f9c6',\n            'bright turquoise': '#0ffef9',\n            'bright violet': '#ad0afd',\n            'bright yellow': '#fffd01',\n            'bright yellow green': '#9dff00',\n            'british racing green': '#05480d',\n            'bronze': '#a87900',\n            'brown': '#653700',\n            'brown green': '#706c11',\n            'brown grey': '#8d8468',\n            'brown orange': '#b96902',\n            'brown red': '#922b05',\n            'brown yellow': '#b29705',\n            'brownish': '#9c6d57',\n            'brownish green': '#6a6e09',\n            'brownish grey': '#86775f',\n            'brownish orange': '#cb7723',\n            'brownish pink': '#c27e79',\n            'brownish purple': '#76424e',\n            'brownish red': '#9e3623',\n            'brownish yellow': '#c9b003',\n            'browny green': '#6f6c0a',\n            'browny orange': '#ca6b02',\n            'bruise': '#7e4071',\n            'bubble gum pink': '#ff69af',\n            'bubblegum': '#ff6cb5',\n            'bubblegum pink': '#fe83cc',\n            'buff': '#fef69e',\n            'burgundy': '#610023',\n            'burnt orange': '#c04e01',\n            'burnt red': '#9f2305',\n            'burnt siena': '#b75203',\n            'burnt sienna': '#b04e0f',\n            'burnt umber': '#a0450e',\n            'burnt yellow': '#d5ab09',\n            'burple': '#6832e3',\n            'butter': '#ffff81',\n            'butter yellow': '#fffd74',\n            'butterscotch': '#fdb147',\n            'cadet blue': '#4e7496',\n            'camel': '#c69f59',\n            'camo': '#7f8f4e',\n            'camo green': '#526525',\n            'camouflage green': '#4b6113',\n            'canary': '#fdff63',\n            'canary yellow': '#fffe40',\n            'candy pink': '#ff63e9',\n            'caramel': '#af6f09',\n            'carmine': '#9d0216',\n            'carnation': '#fd798f',\n            'carnation pink': '#ff7fa7',\n            'carolina blue': '#8ab8fe',\n            'celadon': '#befdb7',\n            'celery': '#c1fd95',\n            'cement': '#a5a391',\n            'cerise': '#de0c62',\n            'cerulean': '#0485d1',\n            'cerulean blue': '#056eee',\n            'charcoal': '#343837',\n            'charcoal grey': '#3c4142',\n            'chartreuse': '#c1f80a',\n            'cherry': '#cf0234',\n            'cherry red': '#f7022a',\n            'chestnut': '#742802',\n            'chocolate': '#3d1c02',\n            'chocolate brown': '#411900',\n            'cinnamon': '#ac4f06',\n            'claret': '#680018',\n            'clay': '#b66a50',\n            'clay brown': '#b2713d',\n            'clear blue': '#247afd',\n            'cloudy blue': '#acc2d9',\n            'cobalt': '#1e488f',\n            'cobalt blue': '#030aa7',\n            'cocoa': '#875f42',\n            'coffee': '#a6814c',\n            'cool blue': '#4984b8',\n            'cool green': '#33b864',\n            'cool grey': '#95a3a6',\n            'copper': '#b66325',\n            'coral': '#fc5a50',\n            'coral pink': '#ff6163',\n            'cornflower': '#6a79f7',\n            'cornflower blue': '#5170d7',\n            'cranberry': '#9e003a',\n            'cream': '#ffffc2',\n            'creme': '#ffffb6',\n            'crimson': '#8c000f',\n            'custard': '#fffd78',\n            'cyan': '#00ffff',\n            'dandelion': '#fedf08',\n            'dark': '#1b2431',\n            'dark aqua': '#05696b',\n            'dark aquamarine': '#017371',\n            'dark beige': '#ac9362',\n            'dark blue': '#00035b',\n            'dark blue green': '#005249',\n            'dark blue grey': '#1f3b4d',\n            'dark brown': '#341c02',\n            'dark coral': '#cf524e',\n            'dark cream': '#fff39a',\n            'dark cyan': '#0a888a',\n            'dark forest green': '#002d04',\n            'dark fuchsia': '#9d0759',\n            'dark gold': '#b59410',\n            'dark grass green': '#388004',\n            'dark green': '#033500',\n            'dark green blue': '#1f6357',\n            'dark grey': '#363737',\n            'dark grey blue': '#29465b',\n            'dark hot pink': '#d90166',\n            'dark indigo': '#1f0954',\n            'dark khaki': '#9b8f55',\n            'dark lavender': '#856798',\n            'dark lilac': '#9c6da5',\n            'dark lime': '#84b701',\n            'dark lime green': '#7ebd01',\n            'dark magenta': '#960056',\n            'dark maroon': '#3c0008',\n            'dark mauve': '#874c62',\n            'dark mint': '#48c072',\n            'dark mint green': '#20c073',\n            'dark mustard': '#a88905',\n            'dark navy': '#000435',\n            'dark navy blue': '#00022e',\n            'dark olive': '#373e02',\n            'dark olive green': '#3c4d03',\n            'dark orange': '#c65102',\n            'dark pastel green': '#56ae57',\n            'dark peach': '#de7e5d',\n            'dark periwinkle': '#665fd1',\n            'dark pink': '#cb416b',\n            'dark plum': '#3f012c',\n            'dark purple': '#35063e',\n            'dark red': '#840000',\n            'dark rose': '#b5485d',\n            'dark royal blue': '#02066f',\n            'dark sage': '#598556',\n            'dark salmon': '#c85a53',\n            'dark sand': '#a88f59',\n            'dark sea green': '#11875d',\n            'dark seafoam': '#1fb57a',\n            'dark seafoam green': '#3eaf76',\n            'dark sky blue': '#448ee4',\n            'dark slate blue': '#214761',\n            'dark tan': '#af884a',\n            'dark taupe': '#7f684e',\n            'dark teal': '#014d4e',\n            'dark turquoise': '#045c5a',\n            'dark violet': '#34013f',\n            'dark yellow': '#d5b60a',\n            'dark yellow green': '#728f02',\n            'darkblue': '#030764',\n            'darkgreen': '#054907',\n            'darkish blue': '#014182',\n            'darkish green': '#287c37',\n            'darkish pink': '#da467d',\n            'darkish purple': '#751973',\n            'darkish red': '#a90308',\n            'deep aqua': '#08787f',\n            'deep blue': '#040273',\n            'deep brown': '#410200',\n            'deep green': '#02590f',\n            'deep lavender': '#8d5eb7',\n            'deep lilac': '#966ebd',\n            'deep magenta': '#a0025c',\n            'deep orange': '#dc4d01',\n            'deep pink': '#cb0162',\n            'deep purple': '#36013f',\n            'deep red': '#9a0200',\n            'deep rose': '#c74767',\n            'deep sea blue': '#015482',\n            'deep sky blue': '#0d75f8',\n            'deep teal': '#00555a',\n            'deep turquoise': '#017374',\n            'deep violet': '#490648',\n            'denim': '#3b638c',\n            'denim blue': '#3b5b92',\n            'desert': '#ccad60',\n            'diarrhea': '#9f8303',\n            'dirt': '#8a6e45',\n            'dirt brown': '#836539',\n            'dirty blue': '#3f829d',\n            'dirty green': '#667e2c',\n            'dirty orange': '#c87606',\n            'dirty pink': '#ca7b80',\n            'dirty purple': '#734a65',\n            'dirty yellow': '#cdc50a',\n            'dodger blue': '#3e82fc',\n            'drab': '#828344',\n            'drab green': '#749551',\n            'dried blood': '#4b0101',\n            'duck egg blue': '#c3fbf4',\n            'dull blue': '#49759c',\n            'dull brown': '#876e4b',\n            'dull green': '#74a662',\n            'dull orange': '#d8863b',\n            'dull pink': '#d5869d',\n            'dull purple': '#84597e',\n            'dull red': '#bb3f3f',\n            'dull teal': '#5f9e8f',\n            'dull yellow': '#eedc5b',\n            'dusk': '#4e5481',\n            'dusk blue': '#26538d',\n            'dusky blue': '#475f94',\n            'dusky pink': '#cc7a8b',\n            'dusky purple': '#895b7b',\n            'dusky rose': '#ba6873',\n            'dust': '#b2996e',\n            'dusty blue': '#5a86ad',\n            'dusty green': '#76a973',\n            'dusty lavender': '#ac86a8',\n            'dusty orange': '#f0833a',\n            'dusty pink': '#d58a94',\n            'dusty purple': '#825f87',\n            'dusty red': '#b9484e',\n            'dusty rose': '#c0737a',\n            'dusty teal': '#4c9085',\n            'earth': '#a2653e',\n            'easter green': '#8cfd7e',\n            'easter purple': '#c071fe',\n            'ecru': '#feffca',\n            'egg shell': '#fffcc4',\n            'eggplant': '#380835',\n            'eggplant purple': '#430541',\n            'eggshell': '#ffffd4',\n            'eggshell blue': '#c4fff7',\n            'electric blue': '#0652ff',\n            'electric green': '#21fc0d',\n            'electric lime': '#a8ff04',\n            'electric pink': '#ff0490',\n            'electric purple': '#aa23ff',\n            'emerald': '#01a049',\n            'emerald green': '#028f1e',\n            'evergreen': '#05472a',\n            'faded blue': '#658cbb',\n            'faded green': '#7bb274',\n            'faded orange': '#f0944d',\n            'faded pink': '#de9dac',\n            'faded purple': '#916e99',\n            'faded red': '#d3494e',\n            'faded yellow': '#feff7f',\n            'fawn': '#cfaf7b',\n            'fern': '#63a950',\n            'fern green': '#548d44',\n            'fire engine red': '#fe0002',\n            'flat blue': '#3c73a8',\n            'flat green': '#699d4c',\n            'fluorescent green': '#08ff08',\n            'fluro green': '#0aff02',\n            'foam green': '#90fda9',\n            'forest': '#0b5509',\n            'forest green': '#06470c',\n            'forrest green': '#154406',\n            'french blue': '#436bad',\n            'fresh green': '#69d84f',\n            'frog green': '#58bc08',\n            'fuchsia': '#ed0dd9',\n            'gold': '#dbb40c',\n            'golden': '#f5bf03',\n            'golden brown': '#b27a01',\n            'golden rod': '#f9bc08',\n            'golden yellow': '#fec615',\n            'goldenrod': '#fac205',\n            'grape': '#6c3461',\n            'grape purple': '#5d1451',\n            'grapefruit': '#fd5956',\n            'grass': '#5cac2d',\n            'grass green': '#3f9b0b',\n            'grassy green': '#419c03',\n            'green': '#15b01a',\n            'green apple': '#5edc1f',\n            'green blue': '#06b48b',\n            'green brown': '#544e03',\n            'green grey': '#77926f',\n            'green teal': '#0cb577',\n            'green yellow': '#c9ff27',\n            'green/blue': '#01c08d',\n            'green/yellow': '#b5ce08',\n            'greenblue': '#23c48b',\n            'greenish': '#40a368',\n            'greenish beige': '#c9d179',\n            'greenish blue': '#0b8b87',\n            'greenish brown': '#696112',\n            'greenish cyan': '#2afeb7',\n            'greenish grey': '#96ae8d',\n            'greenish tan': '#bccb7a',\n            'greenish teal': '#32bf84',\n            'greenish turquoise': '#00fbb0',\n            'greenish yellow': '#cdfd02',\n            'greeny blue': '#42b395',\n            'greeny brown': '#696006',\n            'greeny grey': '#7ea07a',\n            'greeny yellow': '#c6f808',\n            'grey': '#929591',\n            'grey blue': '#6b8ba4',\n            'grey brown': '#7f7053',\n            'grey green': '#789b73',\n            'grey pink': '#c3909b',\n            'grey purple': '#826d8c',\n            'grey teal': '#5e9b8a',\n            'grey/blue': '#647d8e',\n            'grey/green': '#86a17d',\n            'greyblue': '#77a1b5',\n            'greyish': '#a8a495',\n            'greyish blue': '#5e819d',\n            'greyish brown': '#7a6a4f',\n            'greyish green': '#82a67d',\n            'greyish pink': '#c88d94',\n            'greyish purple': '#887191',\n            'greyish teal': '#719f91',\n            'gross green': '#a0bf16',\n            'gunmetal': '#536267',\n            'hazel': '#8e7618',\n            'heather': '#a484ac',\n            'heliotrope': '#d94ff5',\n            'highlighter green': '#1bfc06',\n            'hospital green': '#9be5aa',\n            'hot green': '#25ff29',\n            'hot magenta': '#f504c9',\n            'hot pink': '#ff028d',\n            'hot purple': '#cb00f5',\n            'hunter green': '#0b4008',\n            'ice': '#d6fffa',\n            'ice blue': '#d7fffe',\n            'icky green': '#8fae22',\n            'indian red': '#850e04',\n            'indigo': '#380282',\n            'indigo blue': '#3a18b1',\n            'iris': '#6258c4',\n            'irish green': '#019529',\n            'ivory': '#ffffcb',\n            'jade': '#1fa774',\n            'jade green': '#2baf6a',\n            'jungle green': '#048243',\n            'kelley green': '#009337',\n            'kelly green': '#02ab2e',\n            'kermit green': '#5cb200',\n            'key lime': '#aeff6e',\n            'khaki': '#aaa662',\n            'khaki green': '#728639',\n            'kiwi': '#9cef43',\n            'kiwi green': '#8ee53f',\n            'lavender': '#c79fef',\n            'lavender blue': '#8b88f8',\n            'lavender pink': '#dd85d7',\n            'lawn green': '#4da409',\n            'leaf': '#71aa34',\n            'leaf green': '#5ca904',\n            'leafy green': '#51b73b',\n            'leather': '#ac7434',\n            'lemon': '#fdff52',\n            'lemon green': '#adf802',\n            'lemon lime': '#bffe28',\n            'lemon yellow': '#fdff38',\n            'lichen': '#8fb67b',\n            'light aqua': '#8cffdb',\n            'light aquamarine': '#7bfdc7',\n            'light beige': '#fffeb6',\n            'light blue': '#95d0fc',\n            'light blue green': '#7efbb3',\n            'light blue grey': '#b7c9e2',\n            'light bluish green': '#76fda8',\n            'light bright green': '#53fe5c',\n            'light brown': '#ad8150',\n            'light burgundy': '#a8415b',\n            'light cyan': '#acfffc',\n            'light eggplant': '#894585',\n            'light forest green': '#4f9153',\n            'light gold': '#fddc5c',\n            'light grass green': '#9af764',\n            'light green': '#96f97b',\n            'light green blue': '#56fca2',\n            'light greenish blue': '#63f7b4',\n            'light grey': '#d8dcd6',\n            'light grey blue': '#9dbcd4',\n            'light grey green': '#b7e1a1',\n            'light indigo': '#6d5acf',\n            'light khaki': '#e6f2a2',\n            'light lavendar': '#efc0fe',\n            'light lavender': '#dfc5fe',\n            'light light blue': '#cafffb',\n            'light light green': '#c8ffb0',\n            'light lilac': '#edc8ff',\n            'light lime': '#aefd6c',\n            'light lime green': '#b9ff66',\n            'light magenta': '#fa5ff7',\n            'light maroon': '#a24857',\n            'light mauve': '#c292a1',\n            'light mint': '#b6ffbb',\n            'light mint green': '#a6fbb2',\n            'light moss green': '#a6c875',\n            'light mustard': '#f7d560',\n            'light navy': '#155084',\n            'light navy blue': '#2e5a88',\n            'light neon green': '#4efd54',\n            'light olive': '#acbf69',\n            'light olive green': '#a4be5c',\n            'light orange': '#fdaa48',\n            'light pastel green': '#b2fba5',\n            'light pea green': '#c4fe82',\n            'light peach': '#ffd8b1',\n            'light periwinkle': '#c1c6fc',\n            'light pink': '#ffd1df',\n            'light plum': '#9d5783',\n            'light purple': '#bf77f6',\n            'light red': '#ff474c',\n            'light rose': '#ffc5cb',\n            'light royal blue': '#3a2efe',\n            'light sage': '#bcecac',\n            'light salmon': '#fea993',\n            'light sea green': '#98f6b0',\n            'light seafoam': '#a0febf',\n            'light seafoam green': '#a7ffb5',\n            'light sky blue': '#c6fcff',\n            'light tan': '#fbeeac',\n            'light teal': '#90e4c1',\n            'light turquoise': '#7ef4cc',\n            'light urple': '#b36ff6',\n            'light violet': '#d6b4fc',\n            'light yellow': '#fffe7a',\n            'light yellow green': '#ccfd7f',\n            'light yellowish green': '#c2ff89',\n            'lightblue': '#7bc8f6',\n            'lighter green': '#75fd63',\n            'lighter purple': '#a55af4',\n            'lightgreen': '#76ff7b',\n            'lightish blue': '#3d7afd',\n            'lightish green': '#61e160',\n            'lightish purple': '#a552e6',\n            'lightish red': '#fe2f4a',\n            'lilac': '#cea2fd',\n            'liliac': '#c48efd',\n            'lime': '#aaff32',\n            'lime green': '#89fe05',\n            'lime yellow': '#d0fe1d',\n            'lipstick': '#d5174e',\n            'lipstick red': '#c0022f',\n            'macaroni and cheese': '#efb435',\n            'magenta': '#c20078',\n            'mahogany': '#4a0100',\n            'maize': '#f4d054',\n            'mango': '#ffa62b',\n            'manilla': '#fffa86',\n            'marigold': '#fcc006',\n            'marine': '#042e60',\n            'marine blue': '#01386a',\n            'maroon': '#650021',\n            'mauve': '#ae7181',\n            'medium blue': '#2c6fbb',\n            'medium brown': '#7f5112',\n            'medium green': '#39ad48',\n            'medium grey': '#7d7f7c',\n            'medium pink': '#f36196',\n            'medium purple': '#9e43a2',\n            'melon': '#ff7855',\n            'merlot': '#730039',\n            'metallic blue': '#4f738e',\n            'mid blue': '#276ab3',\n            'mid green': '#50a747',\n            'midnight': '#03012d',\n            'midnight blue': '#020035',\n            'midnight purple': '#280137',\n            'military green': '#667c3e',\n            'milk chocolate': '#7f4e1e',\n            'mint': '#9ffeb0',\n            'mint green': '#8fff9f',\n            'minty green': '#0bf77d',\n            'mocha': '#9d7651',\n            'moss': '#769958',\n            'moss green': '#658b38',\n            'mossy green': '#638b27',\n            'mud': '#735c12',\n            'mud brown': '#60460f',\n            'mud green': '#606602',\n            'muddy brown': '#886806',\n            'muddy green': '#657432',\n            'muddy yellow': '#bfac05',\n            'mulberry': '#920a4e',\n            'murky green': '#6c7a0e',\n            'mushroom': '#ba9e88',\n            'mustard': '#ceb301',\n            'mustard brown': '#ac7e04',\n            'mustard green': '#a8b504',\n            'mustard yellow': '#d2bd0a',\n            'muted blue': '#3b719f',\n            'muted green': '#5fa052',\n            'muted pink': '#d1768f',\n            'muted purple': '#805b87',\n            'nasty green': '#70b23f',\n            'navy': '#01153e',\n            'navy blue': '#001146',\n            'navy green': '#35530a',\n            'neon blue': '#04d9ff',\n            'neon green': '#0cff0c',\n            'neon pink': '#fe019a',\n            'neon purple': '#bc13fe',\n            'neon red': '#ff073a',\n            'neon yellow': '#cfff04',\n            'nice blue': '#107ab0',\n            'night blue': '#040348',\n            'ocean': '#017b92',\n            'ocean blue': '#03719c',\n            'ocean green': '#3d9973',\n            'ocher': '#bf9b0c',\n            'ochre': '#bf9005',\n            'ocre': '#c69c04',\n            'off blue': '#5684ae',\n            'off green': '#6ba353',\n            'off white': '#ffffe4',\n            'off yellow': '#f1f33f',\n            'old pink': '#c77986',\n            'old rose': '#c87f89',\n            'olive': '#6e750e',\n            'olive brown': '#645403',\n            'olive drab': '#6f7632',\n            'olive green': '#677a04',\n            'olive yellow': '#c2b709',\n            'orange': '#f97306',\n            'orange brown': '#be6400',\n            'orange pink': '#ff6f52',\n            'orange red': '#fd411e',\n            'orange yellow': '#ffad01',\n            'orangeish': '#fd8d49',\n            'orangered': '#fe420f',\n            'orangey brown': '#b16002',\n            'orangey red': '#fa4224',\n            'orangey yellow': '#fdb915',\n            'orangish': '#fc824a',\n            'orangish brown': '#b25f03',\n            'orangish red': '#f43605',\n            'orchid': '#c875c4',\n            'pale': '#fff9d0',\n            'pale aqua': '#b8ffeb',\n            'pale blue': '#d0fefe',\n            'pale brown': '#b1916e',\n            'pale cyan': '#b7fffa',\n            'pale gold': '#fdde6c',\n            'pale green': '#c7fdb5',\n            'pale grey': '#fdfdfe',\n            'pale lavender': '#eecffe',\n            'pale light green': '#b1fc99',\n            'pale lilac': '#e4cbff',\n            'pale lime': '#befd73',\n            'pale lime green': '#b1ff65',\n            'pale magenta': '#d767ad',\n            'pale mauve': '#fed0fc',\n            'pale olive': '#b9cc81',\n            'pale olive green': '#b1d27b',\n            'pale orange': '#ffa756',\n            'pale peach': '#ffe5ad',\n            'pale pink': '#ffcfdc',\n            'pale purple': '#b790d4',\n            'pale red': '#d9544d',\n            'pale rose': '#fdc1c5',\n            'pale salmon': '#ffb19a',\n            'pale sky blue': '#bdf6fe',\n            'pale teal': '#82cbb2',\n            'pale turquoise': '#a5fbd5',\n            'pale violet': '#ceaefa',\n            'pale yellow': '#ffff84',\n            'parchment': '#fefcaf',\n            'pastel blue': '#a2bffe',\n            'pastel green': '#b0ff9d',\n            'pastel orange': '#ff964f',\n            'pastel pink': '#ffbacd',\n            'pastel purple': '#caa0ff',\n            'pastel red': '#db5856',\n            'pastel yellow': '#fffe71',\n            'pea': '#a4bf20',\n            'pea green': '#8eab12',\n            'pea soup': '#929901',\n            'pea soup green': '#94a617',\n            'peach': '#ffb07c',\n            'peachy pink': '#ff9a8a',\n            'peacock blue': '#016795',\n            'pear': '#cbf85f',\n            'periwinkle': '#8e82fe',\n            'periwinkle blue': '#8f99fb',\n            'perrywinkle': '#8f8ce7',\n            'petrol': '#005f6a',\n            'pig pink': '#e78ea5',\n            'pine': '#2b5d34',\n            'pine green': '#0a481e',\n            'pink': '#ff81c0',\n            'pink purple': '#db4bda',\n            'pink red': '#f5054f',\n            'pink/purple': '#ef1de7',\n            'pinkish': '#d46a7e',\n            'pinkish brown': '#b17261',\n            'pinkish grey': '#c8aca9',\n            'pinkish orange': '#ff724c',\n            'pinkish purple': '#d648d7',\n            'pinkish red': '#f10c45',\n            'pinkish tan': '#d99b82',\n            'pinky': '#fc86aa',\n            'pinky purple': '#c94cbe',\n            'pinky red': '#fc2647',\n            'piss yellow': '#ddd618',\n            'pistachio': '#c0fa8b',\n            'plum': '#580f41',\n            'plum purple': '#4e0550',\n            'poison green': '#40fd14',\n            'poo': '#8f7303',\n            'poo brown': '#885f01',\n            'poop': '#7f5e00',\n            'poop brown': '#7a5901',\n            'poop green': '#6f7c00',\n            'powder blue': '#b1d1fc',\n            'powder pink': '#ffb2d0',\n            'primary blue': '#0804f9',\n            'prussian blue': '#004577',\n            'puce': '#a57e52',\n            'puke': '#a5a502',\n            'puke brown': '#947706',\n            'puke green': '#9aae07',\n            'puke yellow': '#c2be0e',\n            'pumpkin': '#e17701',\n            'pumpkin orange': '#fb7d07',\n            'pure blue': '#0203e2',\n            'purple': '#7e1e9c',\n            'purple blue': '#632de9',\n            'purple brown': '#673a3f',\n            'purple grey': '#866f85',\n            'purple pink': '#e03fd8',\n            'purple red': '#990147',\n            'purple/blue': '#5d21d0',\n            'purple/pink': '#d725de',\n            'purpleish': '#98568d',\n            'purpleish blue': '#6140ef',\n            'purpleish pink': '#df4ec8',\n            'purpley': '#8756e4',\n            'purpley blue': '#5f34e7',\n            'purpley grey': '#947e94',\n            'purpley pink': '#c83cb9',\n            'purplish': '#94568c',\n            'purplish blue': '#601ef9',\n            'purplish brown': '#6b4247',\n            'purplish grey': '#7a687f',\n            'purplish pink': '#ce5dae',\n            'purplish red': '#b0054b',\n            'purply': '#983fb2',\n            'purply blue': '#661aee',\n            'purply pink': '#f075e6',\n            'putty': '#beae8a',\n            'racing green': '#014600',\n            'radioactive green': '#2cfa1f',\n            'raspberry': '#b00149',\n            'raw sienna': '#9a6200',\n            'raw umber': '#a75e09',\n            'really light blue': '#d4ffff',\n            'red': '#e50000',\n            'red brown': '#8b2e16',\n            'red orange': '#fd3c06',\n            'red pink': '#fa2a55',\n            'red purple': '#820747',\n            'red violet': '#9e0168',\n            'red wine': '#8c0034',\n            'reddish': '#c44240',\n            'reddish brown': '#7f2b0a',\n            'reddish grey': '#997570',\n            'reddish orange': '#f8481c',\n            'reddish pink': '#fe2c54',\n            'reddish purple': '#910951',\n            'reddy brown': '#6e1005',\n            'rich blue': '#021bf9',\n            'rich purple': '#720058',\n            'robin egg blue': '#8af1fe',\n            \"robin's egg\": '#6dedfd',\n            \"robin's egg blue\": '#98eff9',\n            'rosa': '#fe86a4',\n            'rose': '#cf6275',\n            'rose pink': '#f7879a',\n            'rose red': '#be013c',\n            'rosy pink': '#f6688e',\n            'rouge': '#ab1239',\n            'royal': '#0c1793',\n            'royal blue': '#0504aa',\n            'royal purple': '#4b006e',\n            'ruby': '#ca0147',\n            'russet': '#a13905',\n            'rust': '#a83c09',\n            'rust brown': '#8b3103',\n            'rust orange': '#c45508',\n            'rust red': '#aa2704',\n            'rusty orange': '#cd5909',\n            'rusty red': '#af2f0d',\n            'saffron': '#feb209',\n            'sage': '#87ae73',\n            'sage green': '#88b378',\n            'salmon': '#ff796c',\n            'salmon pink': '#fe7b7c',\n            'sand': '#e2ca76',\n            'sand brown': '#cba560',\n            'sand yellow': '#fce166',\n            'sandstone': '#c9ae74',\n            'sandy': '#f1da7a',\n            'sandy brown': '#c4a661',\n            'sandy yellow': '#fdee73',\n            'sap green': '#5c8b15',\n            'sapphire': '#2138ab',\n            'scarlet': '#be0119',\n            'sea': '#3c9992',\n            'sea blue': '#047495',\n            'sea green': '#53fca1',\n            'seafoam': '#80f9ad',\n            'seafoam blue': '#78d1b6',\n            'seafoam green': '#7af9ab',\n            'seaweed': '#18d17b',\n            'seaweed green': '#35ad6b',\n            'sepia': '#985e2b',\n            'shamrock': '#01b44c',\n            'shamrock green': '#02c14d',\n            'shit': '#7f5f00',\n            'shit brown': '#7b5804',\n            'shit green': '#758000',\n            'shocking pink': '#fe02a2',\n            'sick green': '#9db92c',\n            'sickly green': '#94b21c',\n            'sickly yellow': '#d0e429',\n            'sienna': '#a9561e',\n            'silver': '#c5c9c7',\n            'sky': '#82cafc',\n            'sky blue': '#75bbfd',\n            'slate': '#516572',\n            'slate blue': '#5b7c99',\n            'slate green': '#658d6d',\n            'slate grey': '#59656d',\n            'slime green': '#99cc04',\n            'snot': '#acbb0d',\n            'snot green': '#9dc100',\n            'soft blue': '#6488ea',\n            'soft green': '#6fc276',\n            'soft pink': '#fdb0c0',\n            'soft purple': '#a66fb5',\n            'spearmint': '#1ef876',\n            'spring green': '#a9f971',\n            'spruce': '#0a5f38',\n            'squash': '#f2ab15',\n            'steel': '#738595',\n            'steel blue': '#5a7d9a',\n            'steel grey': '#6f828a',\n            'stone': '#ada587',\n            'stormy blue': '#507b9c',\n            'straw': '#fcf679',\n            'strawberry': '#fb2943',\n            'strong blue': '#0c06f7',\n            'strong pink': '#ff0789',\n            'sun yellow': '#ffdf22',\n            'sunflower': '#ffc512',\n            'sunflower yellow': '#ffda03',\n            'sunny yellow': '#fff917',\n            'sunshine yellow': '#fffd37',\n            'swamp': '#698339',\n            'swamp green': '#748500',\n            'tan': '#d1b26f',\n            'tan brown': '#ab7e4c',\n            'tan green': '#a9be70',\n            'tangerine': '#ff9408',\n            'taupe': '#b9a281',\n            'tea': '#65ab7c',\n            'tea green': '#bdf8a3',\n            'teal': '#029386',\n            'teal blue': '#01889f',\n            'teal green': '#25a36f',\n            'tealish': '#24bca8',\n            'tealish green': '#0cdc73',\n            'terra cotta': '#c9643b',\n            'terracota': '#cb6843',\n            'terracotta': '#ca6641',\n            'tiffany blue': '#7bf2da',\n            'tomato': '#ef4026',\n            'tomato red': '#ec2d01',\n            'topaz': '#13bbaf',\n            'toupe': '#c7ac7d',\n            'toxic green': '#61de2a',\n            'tree green': '#2a7e19',\n            'true blue': '#010fcc',\n            'true green': '#089404',\n            'turquoise': '#06c2ac',\n            'turquoise blue': '#06b1c4',\n            'turquoise green': '#04f489',\n            'turtle green': '#75b84f',\n            'twilight': '#4e518b',\n            'twilight blue': '#0a437a',\n            'ugly blue': '#31668a',\n            'ugly brown': '#7d7103',\n            'ugly green': '#7a9703',\n            'ugly pink': '#cd7584',\n            'ugly purple': '#a442a0',\n            'ugly yellow': '#d0c101',\n            'ultramarine': '#2000b1',\n            'ultramarine blue': '#1805db',\n            'umber': '#b26400',\n            'velvet': '#750851',\n            'vermillion': '#f4320c',\n            'very dark blue': '#000133',\n            'very dark brown': '#1d0200',\n            'very dark green': '#062e03',\n            'very dark purple': '#2a0134',\n            'very light blue': '#d5ffff',\n            'very light brown': '#d3b683',\n            'very light green': '#d1ffbd',\n            'very light pink': '#fff4f2',\n            'very light purple': '#f6cefc',\n            'very pale blue': '#d6fffe',\n            'very pale green': '#cffdbc',\n            'vibrant blue': '#0339f8',\n            'vibrant green': '#0add08',\n            'vibrant purple': '#ad03de',\n            'violet': '#9a0eea',\n            'violet blue': '#510ac9',\n            'violet pink': '#fb5ffc',\n            'violet red': '#a50055',\n            'viridian': '#1e9167',\n            'vivid blue': '#152eff',\n            'vivid green': '#2fef10',\n            'vivid purple': '#9900fa',\n            'vomit': '#a2a415',\n            'vomit green': '#89a203',\n            'vomit yellow': '#c7c10c',\n            'warm blue': '#4b57db',\n            'warm brown': '#964e02',\n            'warm grey': '#978a84',\n            'warm pink': '#fb5581',\n            'warm purple': '#952e8f',\n            'washed out green': '#bcf5a6',\n            'water blue': '#0e87cc',\n            'watermelon': '#fd4659',\n            'weird green': '#3ae57f',\n            'wheat': '#fbdd7e',\n            'white': '#ffffff',\n            'windows blue': '#3778bf',\n            'wine': '#80013f',\n            'wine red': '#7b0323',\n            'wintergreen': '#20f986',\n            'wisteria': '#a87dc2',\n            'yellow': '#ffff14',\n            'yellow brown': '#b79400',\n            'yellow green': '#c0fb2d',\n            'yellow ochre': '#cb9d06',\n            'yellow orange': '#fcb001',\n            'yellow tan': '#ffe36e',\n            'yellow/green': '#c8fd3d',\n            'yellowgreen': '#bbf90f',\n            'yellowish': '#faee66',\n            'yellowish brown': '#9b7a01',\n            'yellowish green': '#b0dd16',\n            'yellowish orange': '#ffab0f',\n            'yellowish tan': '#fcfc81',\n            'yellowy brown': '#ae8b0c',\n            'yellowy green': '#bff128'}"},{"col":4,"comment":"null","endLoc":2448,"header":"def test_facetgrid_data(self, long_df)","id":3407,"name":"test_facetgrid_data","nodeType":"Function","startLoc":2437,"text":"def test_facetgrid_data(self, long_df):\n\n        g = displot(\n            data=long_df.to_dict(orient=\"list\"),\n            x=\"z\",\n            hue=long_df[\"a\"].rename(\"hue_var\"),\n            col=long_df[\"c\"].to_numpy(),\n        )\n        expected_cols = set(long_df.columns.to_list() + [\"hue_var\", \"_col_\"])\n        assert set(g.data.columns) == expected_cols\n        assert_array_equal(g.data[\"hue_var\"], long_df[\"a\"])\n        assert_array_equal(g.data[\"_col_\"], long_df[\"c\"])"},{"attributeType":"null","col":16,"comment":"null","endLoc":4,"id":3408,"name":"np","nodeType":"Attribute","startLoc":4,"text":"np"},{"id":3409,"name":"getmsfonts.sh","nodeType":"TextFile","path":"ci","text":"echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections\napt-get install msttcorefonts -qq\n"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":3410,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":6,"id":3411,"name":"plt","nodeType":"Attribute","startLoc":6,"text":"plt"},{"attributeType":"null","col":37,"comment":"null","endLoc":12,"id":3412,"name":"dist","nodeType":"Attribute","startLoc":12,"text":"dist"},{"fileName":"generate_logos.py","filePath":"doc/tools","id":3413,"nodeType":"File","text":"import numpy as np\nimport seaborn as sns\nfrom matplotlib import patches\nimport matplotlib.pyplot as plt\nfrom scipy.signal import gaussian\nfrom scipy.spatial import distance\n\n\nXY_CACHE = {}\n\nSTATIC_DIR = \"_static\"\nplt.rcParams[\"savefig.dpi\"] = 300\n\n\ndef poisson_disc_sample(array_radius, pad_radius, candidates=100, d=2, seed=None):\n    \"\"\"Find positions using poisson-disc sampling.\"\"\"\n    # See http://bost.ocks.org/mike/algorithms/\n    rng = np.random.default_rng(seed)\n    uniform = rng.uniform\n    randint = rng.integers\n\n    # Cache the results\n    key = array_radius, pad_radius, seed\n    if key in XY_CACHE:\n        return XY_CACHE[key]\n\n    # Start at a fixed point we know will work\n    start = np.zeros(d)\n    samples = [start]\n    queue = [start]\n\n    while queue:\n\n        # Pick a sample to expand from\n        s_idx = randint(len(queue))\n        s = queue[s_idx]\n\n        for i in range(candidates):\n            # Generate a candidate from this sample\n            coords = uniform(s - 2 * pad_radius, s + 2 * pad_radius, d)\n\n            # Check the three conditions to accept the candidate\n            in_array = np.sqrt(np.sum(coords ** 2)) < array_radius\n            in_ring = np.all(distance.cdist(samples, [coords]) > pad_radius)\n\n            if in_array and in_ring:\n                # Accept the candidate\n                samples.append(coords)\n                queue.append(coords)\n                break\n\n        if (i + 1) == candidates:\n            # We've exhausted the particular sample\n            queue.pop(s_idx)\n\n    samples = np.array(samples)\n    XY_CACHE[key] = samples\n    return samples\n\n\ndef logo(\n    ax,\n    color_kws, ring, ring_idx, edge,\n    pdf_means, pdf_sigma, dy, y0, w, h,\n    hist_mean, hist_sigma, hist_y0, lw, skip,\n    scatter, pad, scale,\n):\n\n    # Square, invisible axes with specified limits to center the logo\n    ax.set(xlim=(35 + w, 95 - w), ylim=(-3, 53))\n    ax.set_axis_off()\n    ax.set_aspect('equal')\n\n    # Magic numbers for the logo circle\n    radius = 27\n    center = 65, 25\n\n    # Full x and y grids for a gaussian curve\n    x = np.arange(101)\n    y = gaussian(x.size, pdf_sigma)\n\n    x0 = 30  # Magic number\n    xx = x[x0:]\n\n    # Vertical distances between the PDF curves\n    n = len(pdf_means)\n    dys = np.linspace(0, (n - 1) * dy, n) - (n * dy / 2)\n    dys -= dys.mean()\n\n    # Compute the PDF curves with vertical offsets\n    pdfs = [h * (y[x0 - m:-m] + y0 + dy) for m, dy in zip(pdf_means, dys)]\n\n    # Add in constants to fill from bottom and to top\n    pdfs.insert(0, np.full(xx.shape, -h))\n    pdfs.append(np.full(xx.shape, 50 + h))\n\n    # Color gradient\n    colors = sns.cubehelix_palette(n + 1 + bool(hist_mean), **color_kws)\n\n    # White fill between curves and around edges\n    bg = patches.Circle(\n        center, radius=radius - 1 + ring, color=\"white\",\n        transform=ax.transData, zorder=0,\n    )\n    ax.add_artist(bg)\n\n    # Clipping artist (not shown) for the interior elements\n    fg = patches.Circle(center, radius=radius - edge, transform=ax.transData)\n\n    # Ring artist to surround the circle (optional)\n    if ring:\n        wedge = patches.Wedge(\n            center, r=radius + edge / 2, theta1=0, theta2=360, width=edge / 2,\n            transform=ax.transData, color=colors[ring_idx], alpha=1\n        )\n        ax.add_artist(wedge)\n\n    # Add histogram bars\n    if hist_mean:\n        hist_color = colors.pop(0)\n        hist_y = gaussian(x.size, hist_sigma)\n        hist = 1.1 * h * (hist_y[x0 - hist_mean:-hist_mean] + hist_y0)\n        dx = x[skip] - x[0]\n        hist_x = xx[::skip]\n        hist_h = h + hist[::skip]\n        # Magic number to avoid tiny sliver of bar on edge\n        use = hist_x < center[0] + radius * .5\n        bars = ax.bar(\n            hist_x[use], hist_h[use], bottom=-h, width=dx,\n            align=\"edge\", color=hist_color, ec=\"w\", lw=lw,\n            zorder=3,\n        )\n        for bar in bars:\n            bar.set_clip_path(fg)\n\n    # Add each smooth PDF \"wave\"\n    for i, pdf in enumerate(pdfs[1:], 1):\n        u = ax.fill_between(xx, pdfs[i - 1] + w, pdf, color=colors[i - 1], lw=0)\n        u.set_clip_path(fg)\n\n    # Add scatterplot in top wave area\n    if scatter:\n        seed = sum(map(ord, \"seaborn logo\"))\n        xy = poisson_disc_sample(radius - edge - ring, pad, seed=seed)\n        clearance = distance.cdist(xy + center, np.c_[xx, pdfs[-2]])\n        use = clearance.min(axis=1) > pad / 1.8\n        x, y = xy[use].T\n        sizes = (x - y) % 9\n\n        points = ax.scatter(\n            x + center[0], y + center[1], s=scale * (10 + sizes * 5),\n            zorder=5, color=colors[-1], ec=\"w\", lw=scale / 2,\n        )\n        path = u.get_paths()[0]\n        points.set_clip_path(path, transform=u.get_transform())\n        u.set_visible(False)\n\n\ndef savefig(fig, shape, variant):\n\n    fig.subplots_adjust(0, 0, 1, 1, 0, 0)\n\n    facecolor = (1, 1, 1, 1) if bg == \"white\" else (1, 1, 1, 0)\n\n    for ext in [\"png\", \"svg\"]:\n        fig.savefig(f\"{STATIC_DIR}/logo-{shape}-{variant}bg.{ext}\", facecolor=facecolor)\n\n\nif __name__ == \"__main__\":\n\n    for bg in [\"white\", \"light\", \"dark\"]:\n\n        color_idx = -1 if bg == \"dark\" else 0\n\n        kwargs = dict(\n            color_kws=dict(start=.3, rot=-.4, light=.8, dark=.3, reverse=True),\n            ring=True, ring_idx=color_idx, edge=1,\n            pdf_means=[8, 24], pdf_sigma=16,\n            dy=1, y0=1.8, w=.5, h=12,\n            hist_mean=2, hist_sigma=10, hist_y0=.6, lw=1, skip=6,\n            scatter=True, pad=1.8, scale=.5,\n        )\n        color = sns.cubehelix_palette(**kwargs[\"color_kws\"])[color_idx]\n\n        # ------------------------------------------------------------------------ #\n\n        fig, ax = plt.subplots(figsize=(2, 2), facecolor=\"w\", dpi=100)\n        logo(ax, **kwargs)\n        savefig(fig, \"mark\", bg)\n\n        # ------------------------------------------------------------------------ #\n\n        fig, axs = plt.subplots(1, 2, figsize=(8, 2), dpi=100,\n                                gridspec_kw=dict(width_ratios=[1, 3]))\n        logo(axs[0], **kwargs)\n\n        font = {\n            \"family\": \"avenir\",\n            \"color\": color,\n            \"weight\": \"regular\",\n            \"size\": 120,\n        }\n        axs[1].text(.01, .35, \"seaborn\", ha=\"left\", va=\"center\",\n                    fontdict=font, transform=axs[1].transAxes)\n        axs[1].set_axis_off()\n        savefig(fig, \"wide\", bg)\n\n        # ------------------------------------------------------------------------ #\n\n        fig, axs = plt.subplots(2, 1, figsize=(2, 2.5), dpi=100,\n                                gridspec_kw=dict(height_ratios=[4, 1]))\n\n        logo(axs[0], **kwargs)\n\n        font = {\n            \"family\": \"avenir\",\n            \"color\": color,\n            \"weight\": \"regular\",\n            \"size\": 34,\n        }\n        axs[1].text(.5, 1, \"seaborn\", ha=\"center\", va=\"top\",\n                    fontdict=font, transform=axs[1].transAxes)\n        axs[1].set_axis_off()\n        savefig(fig, \"tall\", bg)\n"},{"col":0,"comment":"Find positions using poisson-disc sampling.","endLoc":58,"header":"def poisson_disc_sample(array_radius, pad_radius, candidates=100, d=2, seed=None)","id":3414,"name":"poisson_disc_sample","nodeType":"Function","startLoc":15,"text":"def poisson_disc_sample(array_radius, pad_radius, candidates=100, d=2, seed=None):\n    \"\"\"Find positions using poisson-disc sampling.\"\"\"\n    # See http://bost.ocks.org/mike/algorithms/\n    rng = np.random.default_rng(seed)\n    uniform = rng.uniform\n    randint = rng.integers\n\n    # Cache the results\n    key = array_radius, pad_radius, seed\n    if key in XY_CACHE:\n        return XY_CACHE[key]\n\n    # Start at a fixed point we know will work\n    start = np.zeros(d)\n    samples = [start]\n    queue = [start]\n\n    while queue:\n\n        # Pick a sample to expand from\n        s_idx = randint(len(queue))\n        s = queue[s_idx]\n\n        for i in range(candidates):\n            # Generate a candidate from this sample\n            coords = uniform(s - 2 * pad_radius, s + 2 * pad_radius, d)\n\n            # Check the three conditions to accept the candidate\n            in_array = np.sqrt(np.sum(coords ** 2)) < array_radius\n            in_ring = np.all(distance.cdist(samples, [coords]) > pad_radius)\n\n            if in_array and in_ring:\n                # Accept the candidate\n                samples.append(coords)\n                queue.append(coords)\n                break\n\n        if (i + 1) == candidates:\n            # We've exhausted the particular sample\n            queue.pop(s_idx)\n\n    samples = np.array(samples)\n    XY_CACHE[key] = samples\n    return samples"},{"col":4,"comment":"null","endLoc":1283,"header":"def test_histplot_legend(self)","id":3415,"name":"test_histplot_legend","nodeType":"Function","startLoc":1276,"text":"def test_histplot_legend(self):\n\n        # Tests _extract_legend_handles\n        g = ag.PairGrid(self.df, vars=[\"x\", \"y\"], hue=\"a\")\n        g.map_offdiag(histplot)\n        g.add_legend()\n\n        assert len(g._legend.legendHandles) == len(self.df[\"a\"].unique())"},{"col":4,"comment":"null","endLoc":1317,"header":"def test_pairplot(self)","id":3416,"name":"test_pairplot","nodeType":"Function","startLoc":1285,"text":"def test_pairplot(self):\n\n        vars = [\"x\", \"y\", \"z\"]\n        g = ag.pairplot(self.df)\n\n        for ax in g.diag_axes:\n            assert len(ax.patches) > 1\n\n        for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n        for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n        for i, j in zip(*np.diag_indices_from(g.axes)):\n            ax = g.axes[i, j]\n            assert len(ax.collections) == 0\n\n        g = ag.pairplot(self.df, hue=\"a\")\n        n = len(self.df.a.unique())\n\n        for ax in g.diag_axes:\n            assert len(ax.collections) == n"},{"col":0,"comment":"\n    Decorator function for giving Plot a useful signature.\n\n    Currently this mostly saves us some duplicated typing, but we would\n    like eventually to have a way of registering new semantic properties,\n    at which point dynamic signature generation would become more important.\n\n    ","endLoc":142,"header":"def build_plot_signature(cls)","id":3417,"name":"build_plot_signature","nodeType":"Function","startLoc":113,"text":"def build_plot_signature(cls):\n    \"\"\"\n    Decorator function for giving Plot a useful signature.\n\n    Currently this mostly saves us some duplicated typing, but we would\n    like eventually to have a way of registering new semantic properties,\n    at which point dynamic signature generation would become more important.\n\n    \"\"\"\n    sig = inspect.signature(cls)\n    params = [\n        inspect.Parameter(\"args\", inspect.Parameter.VAR_POSITIONAL),\n        inspect.Parameter(\"data\", inspect.Parameter.KEYWORD_ONLY, default=None)\n    ]\n    params.extend([\n        inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None)\n        for name in PROPERTIES\n    ])\n    new_sig = sig.replace(parameters=params)\n    cls.__signature__ = new_sig\n\n    known_properties = textwrap.fill(\n        \", \".join([f\"|{p}|\" for p in PROPERTIES]),\n        width=78, subsequent_indent=\" \" * 8,\n    )\n\n    if cls.__doc__ is not None:  # support python -OO mode\n        cls.__doc__ = cls.__doc__.format(known_properties=known_properties)\n\n    return cls"},{"col":4,"comment":"null","endLoc":1351,"header":"def test_pairplot_reg(self)","id":3419,"name":"test_pairplot_reg","nodeType":"Function","startLoc":1319,"text":"def test_pairplot_reg(self):\n\n        vars = [\"x\", \"y\", \"z\"]\n        g = ag.pairplot(self.df, diag_kind=\"hist\", kind=\"reg\")\n\n        for ax in g.diag_axes:\n            assert len(ax.patches)\n\n        for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n            assert len(ax.lines) == 1\n            assert len(ax.collections) == 2\n\n        for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n            assert len(ax.lines) == 1\n            assert len(ax.collections) == 2\n\n        for i, j in zip(*np.diag_indices_from(g.axes)):\n            ax = g.axes[i, j]\n            assert len(ax.collections) == 0"},{"fileName":"test_dot.py","filePath":"tests/_marks","id":3420,"nodeType":"File","text":"from matplotlib.colors import to_rgba, to_rgba_array\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn.palettes import color_palette\nfrom seaborn._core.plot import Plot\nfrom seaborn._marks.dot import Dot, Dots\n\n\n@pytest.fixture(autouse=True)\ndef default_palette():\n    with color_palette(\"deep\"):\n        yield\n\n\nclass DotBase:\n\n    def check_offsets(self, points, x, y):\n\n        offsets = points.get_offsets().T\n        assert_array_equal(offsets[0], x)\n        assert_array_equal(offsets[1], y)\n\n    def check_colors(self, part, points, colors, alpha=None):\n\n        rgba = to_rgba_array(colors, alpha)\n\n        getter = getattr(points, f\"get_{part}colors\")\n        assert_array_equal(getter(), rgba)\n\n\nclass TestDot(DotBase):\n\n    def test_simple(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        p = Plot(x=x, y=y).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0] * 3, 1)\n        self.check_colors(\"edge\", points, [C0] * 3, 1)\n\n    def test_filled_unfilled_mix(self):\n\n        x = [1, 2]\n        y = [4, 5]\n        marker = [\"a\", \"b\"]\n        shapes = [\"o\", \"x\"]\n\n        mark = Dot(edgecolor=\"w\", stroke=2, edgewidth=1)\n        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, to_rgba(C0, 0)], None)\n        self.check_colors(\"edge\", points, [\"w\", C0], 1)\n\n        expected = [mark.edgewidth, mark.stroke]\n        assert_array_equal(points.get_linewidths(), expected)\n\n    def test_missing_coordinate_data(self):\n\n        x = [1, float(\"nan\"), 3]\n        y = [5, 3, 4]\n\n        p = Plot(x=x, y=y).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, [1, 3], [5, 4])\n\n    @pytest.mark.parametrize(\"prop\", [\"color\", \"fill\", \"marker\", \"pointsize\"])\n    def test_missing_semantic_data(self, prop):\n\n        x = [1, 2, 3]\n        y = [5, 3, 4]\n        z = [\"a\", float(\"nan\"), \"b\"]\n\n        p = Plot(x=x, y=y, **{prop: z}).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, [1, 3], [5, 4])\n\n\nclass TestDots(DotBase):\n\n    def test_simple(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        p = Plot(x=x, y=y).add(Dots()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0] * 3, .2)\n        self.check_colors(\"edge\", points, [C0] * 3, 1)\n\n    def test_set_color(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        m = Dots(color=\".25\")\n        p = Plot(x=x, y=y).add(m).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [m.color] * 3, .2)\n        self.check_colors(\"edge\", points, [m.color] * 3, 1)\n\n    def test_map_color(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        c = [\"a\", \"b\", \"a\"]\n        p = Plot(x=x, y=y, color=c).add(Dots()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, C1, C0], .2)\n        self.check_colors(\"edge\", points, [C0, C1, C0], 1)\n\n    def test_fill(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        c = [\"a\", \"b\", \"a\"]\n        p = Plot(x=x, y=y, color=c).add(Dots(fill=False)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, C1, C0], 0)\n        self.check_colors(\"edge\", points, [C0, C1, C0], 1)\n\n    def test_pointsize(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        s = 3\n        p = Plot(x=x, y=y).add(Dots(pointsize=s)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        assert_array_equal(points.get_sizes(), [s ** 2] * 3)\n\n    def test_stroke(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        s = 3\n        p = Plot(x=x, y=y).add(Dots(stroke=s)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        assert_array_equal(points.get_linewidths(), [s] * 3)\n\n    def test_filled_unfilled_mix(self):\n\n        x = [1, 2]\n        y = [4, 5]\n        marker = [\"a\", \"b\"]\n        shapes = [\"o\", \"x\"]\n\n        mark = Dots(stroke=2)\n        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [to_rgba(C0, .2), to_rgba(C0, 0)], None)\n        self.check_colors(\"edge\", points, [C0, C0], 1)\n        assert_array_equal(points.get_linewidths(), [mark.stroke] * 2)\n"},{"className":"DotBase","col":0,"comment":"null","endLoc":30,"id":3421,"nodeType":"Class","startLoc":17,"text":"class DotBase:\n\n    def check_offsets(self, points, x, y):\n\n        offsets = points.get_offsets().T\n        assert_array_equal(offsets[0], x)\n        assert_array_equal(offsets[1], y)\n\n    def check_colors(self, part, points, colors, alpha=None):\n\n        rgba = to_rgba_array(colors, alpha)\n\n        getter = getattr(points, f\"get_{part}colors\")\n        assert_array_equal(getter(), rgba)"},{"col":4,"comment":"null","endLoc":23,"header":"def check_offsets(self, points, x, y)","id":3422,"name":"check_offsets","nodeType":"Function","startLoc":19,"text":"def check_offsets(self, points, x, y):\n\n        offsets = points.get_offsets().T\n        assert_array_equal(offsets[0], x)\n        assert_array_equal(offsets[1], y)"},{"col":4,"comment":"null","endLoc":30,"header":"def check_colors(self, part, points, colors, alpha=None)","id":3423,"name":"check_colors","nodeType":"Function","startLoc":25,"text":"def check_colors(self, part, points, colors, alpha=None):\n\n        rgba = to_rgba_array(colors, alpha)\n\n        getter = getattr(points, f\"get_{part}colors\")\n        assert_array_equal(getter(), rgba)"},{"col":4,"comment":"null","endLoc":618,"header":"def test_errorbar_validation(self)","id":3424,"name":"test_errorbar_validation","nodeType":"Function","startLoc":593,"text":"def test_errorbar_validation(self):\n\n        method, level = _validate_errorbar_arg((\"ci\", 99))\n        assert method == \"ci\"\n        assert level == 99\n\n        method, level = _validate_errorbar_arg(\"sd\")\n        assert method == \"sd\"\n        assert level == 1\n\n        f = lambda x: (x.min(), x.max())  # noqa: E731\n        method, level = _validate_errorbar_arg(f)\n        assert method is f\n        assert level is None\n\n        bad_args = [\n            (\"sem\", ValueError),\n            ((\"std\", 2), ValueError),\n            ((\"pi\", 5, 95), ValueError),\n            (95, TypeError),\n            ((\"ci\", \"large\"), TypeError),\n        ]\n\n        for arg, exception in bad_args:\n            with pytest.raises(exception, match=\"`errorbar` must be\"):\n                _validate_errorbar_arg(arg)"},{"col":12,"endLoc":603,"id":3425,"nodeType":"Lambda","startLoc":603,"text":"lambda x: (x.min(), x.max())"},{"col":0,"comment":"","endLoc":1,"header":"test_statistics.py#","id":3426,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n    import statsmodels.distributions as smdist\nexcept ImportError:\n    smdist = None"},{"col":4,"comment":"null","endLoc":1365,"header":"def test_pairplot_reg_hue(self)","id":3427,"name":"test_pairplot_reg_hue","nodeType":"Function","startLoc":1353,"text":"def test_pairplot_reg_hue(self):\n\n        markers = [\"o\", \"s\", \"d\"]\n        g = ag.pairplot(self.df, kind=\"reg\", hue=\"a\", markers=markers)\n\n        ax = g.axes[-1, 0]\n        c1 = ax.collections[0]\n        c2 = ax.collections[2]\n\n        assert not np.array_equal(c1.get_facecolor(), c2.get_facecolor())\n        assert not np.array_equal(\n            c1.get_paths()[0].vertices, c2.get_paths()[0].vertices,\n        )"},{"fileName":"check_gallery.py","filePath":"ci","id":3428,"nodeType":"File","text":"\"\"\"Execute the scripts that comprise the example gallery in the online docs.\"\"\"\nfrom glob import glob\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n\n    fnames = sorted(glob(\"examples/*.py\"))\n\n    for fname in fnames:\n\n        print(f\"- {fname}\")\n        with open(fname) as fid:\n            exec(fid.read())\n        plt.close(\"all\")\n"},{"attributeType":"Default","col":0,"comment":"null","endLoc":56,"id":3430,"name":"default","nodeType":"Attribute","startLoc":56,"text":"default"},{"col":0,"comment":"","endLoc":1,"header":"plot.py#","id":3431,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"The classes for specifying and compiling a declarative visualization.\"\"\"\n\nif TYPE_CHECKING:\n    from matplotlib.figure import SubFigure\n\nif sys.version_info >= (3, 8):\n    from typing import TypedDict\nelse:\n    from typing_extensions import TypedDict\n\ndefault = Default()"},{"fileName":"logistic_regression.py","filePath":"examples","id":3432,"nodeType":"File","text":"\"\"\"\nFaceted logistic regression\n===========================\n\n_thumb: .58, .5\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"darkgrid\")\n\n# Load the example Titanic dataset\ndf = sns.load_dataset(\"titanic\")\n\n# Make a custom palette with gendered colors\npal = dict(male=\"#6495ED\", female=\"#F08080\")\n\n# Show the survival probability as a function of age and sex\ng = sns.lmplot(x=\"age\", y=\"survived\", col=\"sex\", hue=\"sex\", data=df,\n               palette=pal, y_jitter=.02, logistic=True, truncate=False)\ng.set(xlim=(0, 80), ylim=(-.05, 1.05))\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3433,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3434,"name":"df","nodeType":"Attribute","startLoc":11,"text":"df"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":14,"id":3435,"name":"pal","nodeType":"Attribute","startLoc":14,"text":"pal"},{"col":4,"comment":"null","endLoc":41,"header":"def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]","id":3436,"name":"glob","nodeType":"Function","startLoc":41,"text":"def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]: ..."},{"col":4,"comment":"null","endLoc":1754,"header":"def test_scatterplot_vs_relplot(self, long_df, long_semantics)","id":3437,"name":"test_scatterplot_vs_relplot","nodeType":"Function","startLoc":1744,"text":"def test_scatterplot_vs_relplot(self, long_df, long_semantics):\n\n        ax = scatterplot(data=long_df, **long_semantics)\n        g = relplot(data=long_df, kind=\"scatter\", **long_semantics)\n\n        for s_pts, r_pts in zip(ax.collections, g.ax.collections):\n\n            assert_array_equal(s_pts.get_offsets(), r_pts.get_offsets())\n            assert_array_equal(s_pts.get_sizes(), r_pts.get_sizes())\n            assert_array_equal(s_pts.get_facecolors(), r_pts.get_facecolors())\n            assert self.paths_equal(s_pts.get_paths(), r_pts.get_paths())"},{"attributeType":"null","col":28,"comment":"null","endLoc":3,"id":3438,"name":"plt","nodeType":"Attribute","startLoc":3,"text":"plt"},{"col":4,"comment":"null","endLoc":1393,"header":"def test_pairplot_diag_kde(self)","id":3439,"name":"test_pairplot_diag_kde","nodeType":"Function","startLoc":1367,"text":"def test_pairplot_diag_kde(self):\n\n        vars = [\"x\", \"y\", \"z\"]\n        g = ag.pairplot(self.df, diag_kind=\"kde\")\n\n        for ax in g.diag_axes:\n            assert len(ax.collections) == 1\n\n        for i, j in zip(*np.triu_indices_from(g.axes, 1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n        for i, j in zip(*np.tril_indices_from(g.axes, -1)):\n            ax = g.axes[i, j]\n            x_in = self.df[vars[j]]\n            y_in = self.df[vars[i]]\n            x_out, y_out = ax.collections[0].get_offsets().T\n            npt.assert_array_equal(x_in, x_out)\n            npt.assert_array_equal(y_in, y_out)\n\n        for i, j in zip(*np.diag_indices_from(g.axes)):\n            ax = g.axes[i, j]\n            assert len(ax.collections) == 0"},{"attributeType":"list","col":4,"comment":"null","endLoc":7,"id":3440,"name":"fnames","nodeType":"Attribute","startLoc":7,"text":"fnames"},{"className":"TestDot","col":0,"comment":"null","endLoc":86,"id":3441,"nodeType":"Class","startLoc":33,"text":"class TestDot(DotBase):\n\n    def test_simple(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        p = Plot(x=x, y=y).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0] * 3, 1)\n        self.check_colors(\"edge\", points, [C0] * 3, 1)\n\n    def test_filled_unfilled_mix(self):\n\n        x = [1, 2]\n        y = [4, 5]\n        marker = [\"a\", \"b\"]\n        shapes = [\"o\", \"x\"]\n\n        mark = Dot(edgecolor=\"w\", stroke=2, edgewidth=1)\n        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, to_rgba(C0, 0)], None)\n        self.check_colors(\"edge\", points, [\"w\", C0], 1)\n\n        expected = [mark.edgewidth, mark.stroke]\n        assert_array_equal(points.get_linewidths(), expected)\n\n    def test_missing_coordinate_data(self):\n\n        x = [1, float(\"nan\"), 3]\n        y = [5, 3, 4]\n\n        p = Plot(x=x, y=y).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, [1, 3], [5, 4])\n\n    @pytest.mark.parametrize(\"prop\", [\"color\", \"fill\", \"marker\", \"pointsize\"])\n    def test_missing_semantic_data(self, prop):\n\n        x = [1, 2, 3]\n        y = [5, 3, 4]\n        z = [\"a\", float(\"nan\"), \"b\"]\n\n        p = Plot(x=x, y=y, **{prop: z}).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, [1, 3], [5, 4])"},{"col":4,"comment":"null","endLoc":45,"header":"def test_simple(self)","id":3442,"name":"test_simple","nodeType":"Function","startLoc":35,"text":"def test_simple(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        p = Plot(x=x, y=y).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0] * 3, 1)\n        self.check_colors(\"edge\", points, [C0] * 3, 1)"},{"fileName":"test_order.py","filePath":"tests/_stats","id":3443,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.order import Perc\nfrom seaborn.external.version import Version\n\n\nclass Fixtures:\n\n    @pytest.fixture\n    def df(self, rng):\n        return pd.DataFrame(dict(x=\"\", y=rng.normal(size=30)))\n\n    def get_groupby(self, df, orient):\n        # TODO note, copied from aggregation\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        cols = [c for c in df if c != other]\n        return GroupBy(cols)\n\n\nclass TestPerc(Fixtures):\n\n    def test_int_k(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        res = Perc(3)(df, gb, ori, {})\n        percentiles = [0, 50, 100]\n        assert_array_equal(res[\"percentile\"], percentiles)\n        assert_array_equal(res[\"y\"], np.percentile(df[\"y\"], percentiles))\n\n    def test_list_k(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        percentiles = [0, 20, 100]\n        res = Perc(k=percentiles)(df, gb, ori, {})\n        assert_array_equal(res[\"percentile\"], percentiles)\n        assert_array_equal(res[\"y\"], np.percentile(df[\"y\"], percentiles))\n\n    def test_orientation(self, df):\n\n        df = df.rename(columns={\"x\": \"y\", \"y\": \"x\"})\n        ori = \"y\"\n        gb = self.get_groupby(df, ori)\n        res = Perc(k=3)(df, gb, ori, {})\n        assert_array_equal(res[\"x\"], np.percentile(df[\"x\"], [0, 50, 100]))\n\n    def test_method(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        method = \"nearest\"\n        res = Perc(k=5, method=method)(df, gb, ori, {})\n        percentiles = [0, 25, 50, 75, 100]\n        if Version(np.__version__) < Version(\"1.22.0\"):\n            expected = np.percentile(df[\"y\"], percentiles, interpolation=method)\n        else:\n            expected = np.percentile(df[\"y\"], percentiles, method=method)\n        assert_array_equal(res[\"y\"], expected)\n\n    def test_grouped(self, df, rng):\n\n        ori = \"x\"\n        df = df.assign(x=rng.choice([\"a\", \"b\", \"c\"], len(df)))\n        gb = self.get_groupby(df, ori)\n        k = [10, 90]\n        res = Perc(k)(df, gb, ori, {})\n        for x, res_x in res.groupby(\"x\"):\n            assert_array_equal(res_x[\"percentile\"], k)\n            expected = np.percentile(df.loc[df[\"x\"] == x, \"y\"], k)\n            assert_array_equal(res_x[\"y\"], expected)\n\n    def test_with_na(self, df):\n\n        ori = \"x\"\n        df.loc[:5, \"y\"] = np.nan\n        gb = self.get_groupby(df, ori)\n        k = [10, 90]\n        res = Perc(k)(df, gb, ori, {})\n        expected = np.percentile(df[\"y\"].dropna(), k)\n        assert_array_equal(res[\"y\"], expected)\n"},{"className":"Fixtures","col":0,"comment":"null","endLoc":23,"id":3444,"nodeType":"Class","startLoc":13,"text":"class Fixtures:\n\n    @pytest.fixture\n    def df(self, rng):\n        return pd.DataFrame(dict(x=\"\", y=rng.normal(size=30)))\n\n    def get_groupby(self, df, orient):\n        # TODO note, copied from aggregation\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        cols = [c for c in df if c != other]\n        return GroupBy(cols)"},{"col":4,"comment":"null","endLoc":17,"header":"@pytest.fixture\n    def df(self, rng)","id":3445,"name":"df","nodeType":"Function","startLoc":15,"text":"@pytest.fixture\n    def df(self, rng):\n        return pd.DataFrame(dict(x=\"\", y=rng.normal(size=30)))"},{"col":4,"comment":"null","endLoc":23,"header":"def get_groupby(self, df, orient)","id":3446,"name":"get_groupby","nodeType":"Function","startLoc":19,"text":"def get_groupby(self, df, orient):\n        # TODO note, copied from aggregation\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        cols = [c for c in df if c != other]\n        return GroupBy(cols)"},{"className":"TestPerc","col":0,"comment":"null","endLoc":87,"id":3447,"nodeType":"Class","startLoc":26,"text":"class TestPerc(Fixtures):\n\n    def test_int_k(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        res = Perc(3)(df, gb, ori, {})\n        percentiles = [0, 50, 100]\n        assert_array_equal(res[\"percentile\"], percentiles)\n        assert_array_equal(res[\"y\"], np.percentile(df[\"y\"], percentiles))\n\n    def test_list_k(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        percentiles = [0, 20, 100]\n        res = Perc(k=percentiles)(df, gb, ori, {})\n        assert_array_equal(res[\"percentile\"], percentiles)\n        assert_array_equal(res[\"y\"], np.percentile(df[\"y\"], percentiles))\n\n    def test_orientation(self, df):\n\n        df = df.rename(columns={\"x\": \"y\", \"y\": \"x\"})\n        ori = \"y\"\n        gb = self.get_groupby(df, ori)\n        res = Perc(k=3)(df, gb, ori, {})\n        assert_array_equal(res[\"x\"], np.percentile(df[\"x\"], [0, 50, 100]))\n\n    def test_method(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        method = \"nearest\"\n        res = Perc(k=5, method=method)(df, gb, ori, {})\n        percentiles = [0, 25, 50, 75, 100]\n        if Version(np.__version__) < Version(\"1.22.0\"):\n            expected = np.percentile(df[\"y\"], percentiles, interpolation=method)\n        else:\n            expected = np.percentile(df[\"y\"], percentiles, method=method)\n        assert_array_equal(res[\"y\"], expected)\n\n    def test_grouped(self, df, rng):\n\n        ori = \"x\"\n        df = df.assign(x=rng.choice([\"a\", \"b\", \"c\"], len(df)))\n        gb = self.get_groupby(df, ori)\n        k = [10, 90]\n        res = Perc(k)(df, gb, ori, {})\n        for x, res_x in res.groupby(\"x\"):\n            assert_array_equal(res_x[\"percentile\"], k)\n            expected = np.percentile(df.loc[df[\"x\"] == x, \"y\"], k)\n            assert_array_equal(res_x[\"y\"], expected)\n\n    def test_with_na(self, df):\n\n        ori = \"x\"\n        df.loc[:5, \"y\"] = np.nan\n        gb = self.get_groupby(df, ori)\n        k = [10, 90]\n        res = Perc(k)(df, gb, ori, {})\n        expected = np.percentile(df[\"y\"].dropna(), k)\n        assert_array_equal(res[\"y\"], expected)"},{"col":4,"comment":"null","endLoc":35,"header":"def test_int_k(self, df)","id":3448,"name":"test_int_k","nodeType":"Function","startLoc":28,"text":"def test_int_k(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        res = Perc(3)(df, gb, ori, {})\n        percentiles = [0, 50, 100]\n        assert_array_equal(res[\"percentile\"], percentiles)\n        assert_array_equal(res[\"y\"], np.percentile(df[\"y\"], percentiles))"},{"col":4,"comment":"null","endLoc":44,"header":"def test_list_k(self, df)","id":3449,"name":"test_list_k","nodeType":"Function","startLoc":37,"text":"def test_list_k(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        percentiles = [0, 20, 100]\n        res = Perc(k=percentiles)(df, gb, ori, {})\n        assert_array_equal(res[\"percentile\"], percentiles)\n        assert_array_equal(res[\"y\"], np.percentile(df[\"y\"], percentiles))"},{"col":4,"comment":"null","endLoc":52,"header":"def test_orientation(self, df)","id":3450,"name":"test_orientation","nodeType":"Function","startLoc":46,"text":"def test_orientation(self, df):\n\n        df = df.rename(columns={\"x\": \"y\", \"y\": \"x\"})\n        ori = \"y\"\n        gb = self.get_groupby(df, ori)\n        res = Perc(k=3)(df, gb, ori, {})\n        assert_array_equal(res[\"x\"], np.percentile(df[\"x\"], [0, 50, 100]))"},{"col":4,"comment":"null","endLoc":65,"header":"def test_method(self, df)","id":3451,"name":"test_method","nodeType":"Function","startLoc":54,"text":"def test_method(self, df):\n\n        ori = \"x\"\n        gb = self.get_groupby(df, ori)\n        method = \"nearest\"\n        res = Perc(k=5, method=method)(df, gb, ori, {})\n        percentiles = [0, 25, 50, 75, 100]\n        if Version(np.__version__) < Version(\"1.22.0\"):\n            expected = np.percentile(df[\"y\"], percentiles, interpolation=method)\n        else:\n            expected = np.percentile(df[\"y\"], percentiles, method=method)\n        assert_array_equal(res[\"y\"], expected)"},{"col":0,"comment":"null","endLoc":156,"header":"def logo(\n    ax,\n    color_kws, ring, ring_idx, edge,\n    pdf_means, pdf_sigma, dy, y0, w, h,\n    hist_mean, hist_sigma, hist_y0, lw, skip,\n    scatter, pad, scale,\n)","id":3452,"name":"logo","nodeType":"Function","startLoc":61,"text":"def logo(\n    ax,\n    color_kws, ring, ring_idx, edge,\n    pdf_means, pdf_sigma, dy, y0, w, h,\n    hist_mean, hist_sigma, hist_y0, lw, skip,\n    scatter, pad, scale,\n):\n\n    # Square, invisible axes with specified limits to center the logo\n    ax.set(xlim=(35 + w, 95 - w), ylim=(-3, 53))\n    ax.set_axis_off()\n    ax.set_aspect('equal')\n\n    # Magic numbers for the logo circle\n    radius = 27\n    center = 65, 25\n\n    # Full x and y grids for a gaussian curve\n    x = np.arange(101)\n    y = gaussian(x.size, pdf_sigma)\n\n    x0 = 30  # Magic number\n    xx = x[x0:]\n\n    # Vertical distances between the PDF curves\n    n = len(pdf_means)\n    dys = np.linspace(0, (n - 1) * dy, n) - (n * dy / 2)\n    dys -= dys.mean()\n\n    # Compute the PDF curves with vertical offsets\n    pdfs = [h * (y[x0 - m:-m] + y0 + dy) for m, dy in zip(pdf_means, dys)]\n\n    # Add in constants to fill from bottom and to top\n    pdfs.insert(0, np.full(xx.shape, -h))\n    pdfs.append(np.full(xx.shape, 50 + h))\n\n    # Color gradient\n    colors = sns.cubehelix_palette(n + 1 + bool(hist_mean), **color_kws)\n\n    # White fill between curves and around edges\n    bg = patches.Circle(\n        center, radius=radius - 1 + ring, color=\"white\",\n        transform=ax.transData, zorder=0,\n    )\n    ax.add_artist(bg)\n\n    # Clipping artist (not shown) for the interior elements\n    fg = patches.Circle(center, radius=radius - edge, transform=ax.transData)\n\n    # Ring artist to surround the circle (optional)\n    if ring:\n        wedge = patches.Wedge(\n            center, r=radius + edge / 2, theta1=0, theta2=360, width=edge / 2,\n            transform=ax.transData, color=colors[ring_idx], alpha=1\n        )\n        ax.add_artist(wedge)\n\n    # Add histogram bars\n    if hist_mean:\n        hist_color = colors.pop(0)\n        hist_y = gaussian(x.size, hist_sigma)\n        hist = 1.1 * h * (hist_y[x0 - hist_mean:-hist_mean] + hist_y0)\n        dx = x[skip] - x[0]\n        hist_x = xx[::skip]\n        hist_h = h + hist[::skip]\n        # Magic number to avoid tiny sliver of bar on edge\n        use = hist_x < center[0] + radius * .5\n        bars = ax.bar(\n            hist_x[use], hist_h[use], bottom=-h, width=dx,\n            align=\"edge\", color=hist_color, ec=\"w\", lw=lw,\n            zorder=3,\n        )\n        for bar in bars:\n            bar.set_clip_path(fg)\n\n    # Add each smooth PDF \"wave\"\n    for i, pdf in enumerate(pdfs[1:], 1):\n        u = ax.fill_between(xx, pdfs[i - 1] + w, pdf, color=colors[i - 1], lw=0)\n        u.set_clip_path(fg)\n\n    # Add scatterplot in top wave area\n    if scatter:\n        seed = sum(map(ord, \"seaborn logo\"))\n        xy = poisson_disc_sample(radius - edge - ring, pad, seed=seed)\n        clearance = distance.cdist(xy + center, np.c_[xx, pdfs[-2]])\n        use = clearance.min(axis=1) > pad / 1.8\n        x, y = xy[use].T\n        sizes = (x - y) % 9\n\n        points = ax.scatter(\n            x + center[0], y + center[1], s=scale * (10 + sizes * 5),\n            zorder=5, color=colors[-1], ec=\"w\", lw=scale / 2,\n        )\n        path = u.get_paths()[0]\n        points.set_clip_path(path, transform=u.get_transform())\n        u.set_visible(False)"},{"col":4,"comment":"null","endLoc":1839,"header":"def test_scatterplot_smoke(\n        self,\n        wide_df, wide_array,\n        flat_series, flat_array, flat_list,\n        wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n        long_df, missing_df, object_df\n    )","id":3453,"name":"test_scatterplot_smoke","nodeType":"Function","startLoc":1756,"text":"def test_scatterplot_smoke(\n        self,\n        wide_df, wide_array,\n        flat_series, flat_array, flat_list,\n        wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,\n        long_df, missing_df, object_df\n    ):\n\n        f, ax = plt.subplots()\n\n        scatterplot(x=[], y=[])\n        ax.clear()\n\n        scatterplot(data=wide_df)\n        ax.clear()\n\n        scatterplot(data=wide_array)\n        ax.clear()\n\n        scatterplot(data=wide_list_of_series)\n        ax.clear()\n\n        scatterplot(data=wide_list_of_arrays)\n        ax.clear()\n\n        scatterplot(data=wide_list_of_lists)\n        ax.clear()\n\n        scatterplot(data=flat_series)\n        ax.clear()\n\n        scatterplot(data=flat_array)\n        ax.clear()\n\n        scatterplot(data=flat_list)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=long_df.x, y=long_df.y)\n        ax.clear()\n\n        scatterplot(x=long_df.x, y=\"y\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=long_df.y.to_numpy(), data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"a\", data=missing_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", style=\"b\", data=missing_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=long_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"a\", data=missing_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"a\", size=\"s\", data=missing_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"f\", data=object_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"c\", size=\"f\", data=object_df)\n        ax.clear()\n\n        scatterplot(x=\"x\", y=\"y\", hue=\"f\", size=\"s\", data=object_df)\n        ax.clear()"},{"col":4,"comment":"null","endLoc":1403,"header":"def test_pairplot_kde(self)","id":3454,"name":"test_pairplot_kde","nodeType":"Function","startLoc":1395,"text":"def test_pairplot_kde(self):\n\n        f, ax1 = plt.subplots()\n        kdeplot(data=self.df, x=\"x\", y=\"y\", ax=ax1)\n\n        g = ag.pairplot(self.df, kind=\"kde\")\n        ax2 = g.axes[1, 0]\n\n        assert_plots_equal(ax1, ax2, labels=False)"},{"col":4,"comment":"null","endLoc":1413,"header":"def test_pairplot_hist(self)","id":3455,"name":"test_pairplot_hist","nodeType":"Function","startLoc":1405,"text":"def test_pairplot_hist(self):\n\n        f, ax1 = plt.subplots()\n        histplot(data=self.df, x=\"x\", y=\"y\", ax=ax1)\n\n        g = ag.pairplot(self.df, kind=\"hist\")\n        ax2 = g.axes[1, 0]\n\n        assert_plots_equal(ax1, ax2, labels=False)"},{"col":4,"comment":"null","endLoc":1425,"header":"def test_pairplot_markers(self)","id":3456,"name":"test_pairplot_markers","nodeType":"Function","startLoc":1415,"text":"def test_pairplot_markers(self):\n\n        vars = [\"x\", \"y\", \"z\"]\n        markers = [\"o\", \"X\", \"s\"]\n        g = ag.pairplot(self.df, hue=\"a\", vars=vars, markers=markers)\n        m1 = g._legend.legendHandles[0].get_paths()[0]\n        m2 = g._legend.legendHandles[1].get_paths()[0]\n        assert m1 != m2\n\n        with pytest.warns(UserWarning):\n            g = ag.pairplot(self.df, hue=\"a\", vars=vars, markers=markers[:-2])"},{"col":4,"comment":"null","endLoc":77,"header":"def test_grouped(self, df, rng)","id":3457,"name":"test_grouped","nodeType":"Function","startLoc":67,"text":"def test_grouped(self, df, rng):\n\n        ori = \"x\"\n        df = df.assign(x=rng.choice([\"a\", \"b\", \"c\"], len(df)))\n        gb = self.get_groupby(df, ori)\n        k = [10, 90]\n        res = Perc(k)(df, gb, ori, {})\n        for x, res_x in res.groupby(\"x\"):\n            assert_array_equal(res_x[\"percentile\"], k)\n            expected = np.percentile(df.loc[df[\"x\"] == x, \"y\"], k)\n            assert_array_equal(res_x[\"y\"], expected)"},{"col":4,"comment":"null","endLoc":87,"header":"def test_with_na(self, df)","id":3458,"name":"test_with_na","nodeType":"Function","startLoc":79,"text":"def test_with_na(self, df):\n\n        ori = \"x\"\n        df.loc[:5, \"y\"] = np.nan\n        gb = self.get_groupby(df, ori)\n        k = [10, 90]\n        res = Perc(k)(df, gb, ori, {})\n        expected = np.percentile(df[\"y\"].dropna(), k)\n        assert_array_equal(res[\"y\"], expected)"},{"col":4,"comment":"null","endLoc":1431,"header":"def test_corner_despine(self)","id":3459,"name":"test_corner_despine","nodeType":"Function","startLoc":1427,"text":"def test_corner_despine(self):\n\n        g = ag.PairGrid(self.df, corner=True, despine=False)\n        g.map_diag(histplot)\n        assert g.axes[0, 0].spines[\"top\"].get_visible()"},{"col":4,"comment":"null","endLoc":1437,"header":"def test_corner_set(self)","id":3460,"name":"test_corner_set","nodeType":"Function","startLoc":1433,"text":"def test_corner_set(self):\n\n        g = ag.PairGrid(self.df, corner=True, despine=False)\n        g.set(xlim=(0, 10))\n        assert g.axes[-1, 0].get_xlim() == (0, 10)"},{"col":4,"comment":"null","endLoc":1445,"header":"def test_legend(self)","id":3461,"name":"test_legend","nodeType":"Function","startLoc":1439,"text":"def test_legend(self):\n\n        g1 = ag.pairplot(self.df, hue=\"a\")\n        assert isinstance(g1.legend, mpl.legend.Legend)\n\n        g2 = ag.pairplot(self.df)\n        assert g2.legend is None"},{"col":4,"comment":"null","endLoc":1458,"header":"def test_tick_params(self)","id":3462,"name":"test_tick_params","nodeType":"Function","startLoc":1447,"text":"def test_tick_params(self):\n\n        g = ag.PairGrid(self.df)\n        color = \"red\"\n        pad = 3\n        g.tick_params(pad=pad, color=color)\n        for ax in g.axes.flat:\n            for axis in [\"xaxis\", \"yaxis\"]:\n                for tick in getattr(ax, axis).get_major_ticks():\n                    assert mpl.colors.same_color(tick.tick1line.get_color(), color)\n                    assert mpl.colors.same_color(tick.tick2line.get_color(), color)\n                    assert tick.get_pad() == pad"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":1297,"id":3463,"name":"func","nodeType":"Attribute","startLoc":1297,"text":"func"},{"col":0,"comment":"null","endLoc":45,"header":"@pytest.fixture(params=[\n    dict(x=\"x\", y=\"y\"),\n    dict(x=\"t\", y=\"y\"),\n    dict(x=\"a\", y=\"y\"),\n    dict(x=\"x\", y=\"y\", hue=\"y\"),\n    dict(x=\"x\", y=\"y\", hue=\"a\"),\n    dict(x=\"x\", y=\"y\", size=\"a\"),\n    dict(x=\"x\", y=\"y\", style=\"a\"),\n    dict(x=\"x\", y=\"y\", hue=\"s\"),\n    dict(x=\"x\", y=\"y\", size=\"s\"),\n    dict(x=\"x\", y=\"y\", style=\"s\"),\n    dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n    dict(x=\"x\", y=\"y\", hue=\"a\", size=\"b\", style=\"b\"),\n])\ndef long_semantics(request)","id":3464,"name":"long_semantics","nodeType":"Function","startLoc":30,"text":"@pytest.fixture(params=[\n    dict(x=\"x\", y=\"y\"),\n    dict(x=\"t\", y=\"y\"),\n    dict(x=\"a\", y=\"y\"),\n    dict(x=\"x\", y=\"y\", hue=\"y\"),\n    dict(x=\"x\", y=\"y\", hue=\"a\"),\n    dict(x=\"x\", y=\"y\", size=\"a\"),\n    dict(x=\"x\", y=\"y\", style=\"a\"),\n    dict(x=\"x\", y=\"y\", hue=\"s\"),\n    dict(x=\"x\", y=\"y\", size=\"s\"),\n    dict(x=\"x\", y=\"y\", style=\"s\"),\n    dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n    dict(x=\"x\", y=\"y\", hue=\"a\", size=\"b\", style=\"b\"),\n])\ndef long_semantics(request):\n    return request.param"},{"attributeType":"null","col":4,"comment":"null","endLoc":715,"id":3465,"name":"rs","nodeType":"Attribute","startLoc":715,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":716,"id":3466,"name":"df","nodeType":"Attribute","startLoc":716,"text":"df"},{"className":"TestJointGrid","col":0,"comment":"null","endLoc":1669,"id":3467,"nodeType":"Class","startLoc":1461,"text":"class TestJointGrid:\n\n    rs = np.random.RandomState(sum(map(ord, \"JointGrid\")))\n    x = rs.randn(100)\n    y = rs.randn(100)\n    x_na = x.copy()\n    x_na[10] = np.nan\n    x_na[20] = np.nan\n    data = pd.DataFrame(dict(x=x, y=y, x_na=x_na))\n\n    def test_margin_grid_from_lists(self):\n\n        g = ag.JointGrid(x=self.x.tolist(), y=self.y.tolist())\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)\n\n    def test_margin_grid_from_arrays(self):\n\n        g = ag.JointGrid(x=self.x, y=self.y)\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)\n\n    def test_margin_grid_from_series(self):\n\n        g = ag.JointGrid(x=self.data.x, y=self.data.y)\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)\n\n    def test_margin_grid_from_dataframe(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)\n\n    def test_margin_grid_from_dataframe_bad_variable(self):\n\n        with pytest.raises(ValueError):\n            ag.JointGrid(x=\"x\", y=\"bad_column\", data=self.data)\n\n    def test_margin_grid_axis_labels(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n\n        xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()\n        assert xlabel == \"x\"\n        assert ylabel == \"y\"\n\n        g.set_axis_labels(\"x variable\", \"y variable\")\n        xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()\n        assert xlabel == \"x variable\"\n        assert ylabel == \"y variable\"\n\n    def test_dropna(self):\n\n        g = ag.JointGrid(x=\"x_na\", y=\"y\", data=self.data, dropna=False)\n        assert len(g.x) == len(self.x_na)\n\n        g = ag.JointGrid(x=\"x_na\", y=\"y\", data=self.data, dropna=True)\n        assert len(g.x) == pd.notnull(self.x_na).sum()\n\n    def test_axlims(self):\n\n        lim = (-3, 3)\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data, xlim=lim, ylim=lim)\n\n        assert g.ax_joint.get_xlim() == lim\n        assert g.ax_joint.get_ylim() == lim\n\n        assert g.ax_marg_x.get_xlim() == lim\n        assert g.ax_marg_y.get_ylim() == lim\n\n    def test_marginal_ticks(self):\n\n        g = ag.JointGrid(marginal_ticks=False)\n        assert not sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())\n        assert not sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())\n\n        g = ag.JointGrid(marginal_ticks=True)\n        assert sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())\n        assert sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())\n\n    def test_bivariate_plot(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n        g.plot_joint(plt.plot)\n\n        x, y = g.ax_joint.lines[0].get_xydata().T\n        npt.assert_array_equal(x, self.x)\n        npt.assert_array_equal(y, self.y)\n\n    def test_univariate_plot(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        g.plot_marginals(kdeplot)\n\n        _, y1 = g.ax_marg_x.lines[0].get_xydata().T\n        y2, _ = g.ax_marg_y.lines[0].get_xydata().T\n        npt.assert_array_equal(y1, y2)\n\n    def test_univariate_plot_distplot(self):\n\n        bins = 10\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        with pytest.warns(UserWarning):\n            g.plot_marginals(distplot, bins=bins)\n        assert len(g.ax_marg_x.patches) == bins\n        assert len(g.ax_marg_y.patches) == bins\n        for x, y in zip(g.ax_marg_x.patches, g.ax_marg_y.patches):\n            assert x.get_height() == y.get_width()\n\n    def test_univariate_plot_matplotlib(self):\n\n        bins = 10\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        g.plot_marginals(plt.hist, bins=bins)\n        assert len(g.ax_marg_x.patches) == bins\n        assert len(g.ax_marg_y.patches) == bins\n\n    def test_plot(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        g.plot(plt.plot, kdeplot)\n\n        x, y = g.ax_joint.lines[0].get_xydata().T\n        npt.assert_array_equal(x, self.x)\n        npt.assert_array_equal(y, self.x)\n\n        _, y1 = g.ax_marg_x.lines[0].get_xydata().T\n        y2, _ = g.ax_marg_y.lines[0].get_xydata().T\n        npt.assert_array_equal(y1, y2)\n\n    def test_space(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data, space=0)\n\n        joint_bounds = g.ax_joint.bbox.bounds\n        marg_x_bounds = g.ax_marg_x.bbox.bounds\n        marg_y_bounds = g.ax_marg_y.bbox.bounds\n\n        assert joint_bounds[2] == marg_x_bounds[2]\n        assert joint_bounds[3] == marg_y_bounds[3]\n\n    @pytest.mark.parametrize(\n        \"as_vector\", [True, False],\n    )\n    def test_hue(self, long_df, as_vector):\n\n        if as_vector:\n            data = None\n            x, y, hue = long_df[\"x\"], long_df[\"y\"], long_df[\"a\"]\n        else:\n            data = long_df\n            x, y, hue = \"x\", \"y\", \"a\"\n\n        g = ag.JointGrid(data=data, x=x, y=y, hue=hue)\n        g.plot_joint(scatterplot)\n        g.plot_marginals(histplot)\n\n        g2 = ag.JointGrid()\n        scatterplot(data=long_df, x=x, y=y, hue=hue, ax=g2.ax_joint)\n        histplot(data=long_df, x=x, hue=hue, ax=g2.ax_marg_x)\n        histplot(data=long_df, y=y, hue=hue, ax=g2.ax_marg_y)\n\n        assert_plots_equal(g.ax_joint, g2.ax_joint)\n        assert_plots_equal(g.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g.ax_marg_y, g2.ax_marg_y, labels=False)\n\n    def test_refline(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n        g.plot(scatterplot, histplot)\n        g.refline()\n        assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines\n\n        refx = refy = 0.5\n        hline = np.array([[0, refy], [1, refy]])\n        vline = np.array([[refx, 0], [refx, 1]])\n        g.refline(x=refx, y=refy, joint=False, marginal=False)\n        assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines\n\n        g.refline(x=refx, y=refy)\n        assert g.ax_joint.lines[0].get_color() == '.5'\n        assert g.ax_joint.lines[0].get_linestyle() == '--'\n        assert len(g.ax_joint.lines) == 2\n        assert len(g.ax_marg_x.lines) == 1\n        assert len(g.ax_marg_y.lines) == 1\n        npt.assert_array_equal(g.ax_joint.lines[0].get_xydata(), vline)\n        npt.assert_array_equal(g.ax_joint.lines[1].get_xydata(), hline)\n        npt.assert_array_equal(g.ax_marg_x.lines[0].get_xydata(), vline)\n        npt.assert_array_equal(g.ax_marg_y.lines[0].get_xydata(), hline)\n\n        color, linestyle = 'red', '-'\n        g.refline(x=refx, marginal=False, color=color, linestyle=linestyle)\n        npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), vline)\n        assert g.ax_joint.lines[-1].get_color() == color\n        assert g.ax_joint.lines[-1].get_linestyle() == linestyle\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n        g.refline(x=refx, joint=False)\n        npt.assert_array_equal(g.ax_marg_x.lines[-1].get_xydata(), vline)\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines) + 1\n\n        g.refline(y=refy, joint=False)\n        npt.assert_array_equal(g.ax_marg_y.lines[-1].get_xydata(), hline)\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n        g.refline(y=refy, marginal=False)\n        npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), hline)\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)"},{"col":4,"comment":"null","endLoc":1475,"header":"def test_margin_grid_from_lists(self)","id":3468,"name":"test_margin_grid_from_lists","nodeType":"Function","startLoc":1471,"text":"def test_margin_grid_from_lists(self):\n\n        g = ag.JointGrid(x=self.x.tolist(), y=self.y.tolist())\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":3469,"name":"__all__","nodeType":"Attribute","startLoc":14,"text":"__all__"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":20,"id":3470,"name":"SEABORN_PALETTES","nodeType":"Attribute","startLoc":20,"text":"SEABORN_PALETTES"},{"attributeType":"dict","col":0,"comment":"null","endLoc":48,"id":3471,"name":"MPL_QUAL_PALS","nodeType":"Attribute","startLoc":48,"text":"MPL_QUAL_PALS"},{"attributeType":"dict","col":0,"comment":"null","endLoc":56,"id":3472,"name":"QUAL_PALETTE_SIZES","nodeType":"Attribute","startLoc":56,"text":"QUAL_PALETTE_SIZES"},{"id":3473,"name":"Makefile","nodeType":"TextFile","path":"","text":"export SHELL := /bin/bash\n\ntest:\n\tpytest -n auto --cov=seaborn --cov=tests --cov-config=.coveragerc tests\n\nlint:\n\tflake8 seaborn\n\ntypecheck:\n\tmypy --follow-imports=skip seaborn/_core seaborn/_marks seaborn/_stats\n"},{"attributeType":"str","col":8,"comment":"null","endLoc":9,"id":3474,"name":"fname","nodeType":"Attribute","startLoc":9,"text":"fname"},{"fileName":"three_variable_histogram.py","filePath":"examples","id":3475,"nodeType":"File","text":"\"\"\"\nTrivariate histogram with two categorical variables\n===================================================\n\n_thumb: .32, .55\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"dark\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\nsns.displot(\n    data=diamonds, x=\"price\", y=\"color\", col=\"clarity\",\n    log_scale=(True, False), col_wrap=4, height=4, aspect=.7,\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":3476,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"bool","col":4,"comment":"null","endLoc":1427,"id":3477,"name":"require_numeric","nodeType":"Attribute","startLoc":1427,"text":"require_numeric"},{"attributeType":"null","col":8,"comment":"null","endLoc":1491,"id":3478,"name":"statistic","nodeType":"Attribute","startLoc":1491,"text":"self.statistic"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3479,"name":"diamonds","nodeType":"Attribute","startLoc":11,"text":"diamonds"},{"col":0,"comment":"","endLoc":7,"header":"three_variable_histogram.py#","id":3480,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nTrivariate histogram with two categorical variables\n===================================================\n\n_thumb: .32, .55\n\n\"\"\"\n\nsns.set_theme(style=\"dark\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\n\nsns.displot(\n    data=diamonds, x=\"price\", y=\"color\", col=\"clarity\",\n    log_scale=(True, False), col_wrap=4, height=4, aspect=.7,\n)"},{"id":3481,"name":"pairplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme(style=\\\"ticks\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The simplest invocation uses :func:`scatterplot` for each pairing of the variables and :func:`histplot` for the marginal plots along the diagonal:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n    \"sns.pairplot(penguins)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assigning a ``hue`` variable adds a semantic mapping and changes the default marginal plot to a layered kernel density estimate (KDE):\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, hue=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"It's possible to force marginal histograms:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, hue=\\\"species\\\", diag_kind=\\\"hist\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The ``kind`` parameter determines both the diagonal and off-diagonal plotting style. Several options are available, including using :func:`kdeplot` to draw KDEs:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, kind=\\\"kde\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Or :func:`histplot` to draw both bivariate and univariate histograms:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, kind=\\\"hist\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The ``markers`` parameter applies a style mapping on the off-diagonal axes. Currently, it will be redundant with the ``hue`` variable:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, hue=\\\"species\\\", markers=[\\\"o\\\", \\\"s\\\", \\\"D\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"As with other figure-level functions, the size of the figure is controlled by setting the ``height`` of each individual subplot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, height=1.5)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use ``vars`` or ``x_vars`` and ``y_vars`` to select the variables to plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(\\n\",\n    \"    penguins,\\n\",\n    \"    x_vars=[\\\"bill_length_mm\\\", \\\"bill_depth_mm\\\", \\\"flipper_length_mm\\\"],\\n\",\n    \"    y_vars=[\\\"bill_length_mm\\\", \\\"bill_depth_mm\\\"],\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Set ``corner=True`` to plot only the lower triangle:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(penguins, corner=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The ``plot_kws`` and ``diag_kws`` parameters accept dicts of keyword arguments to customize the off-diagonal and diagonal plots, respectively:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(\\n\",\n    \"    penguins,\\n\",\n    \"    plot_kws=dict(marker=\\\"+\\\", linewidth=1),\\n\",\n    \"    diag_kws=dict(fill=False),\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The return object is the underlying :class:`PairGrid`, which can be used to further customize the plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.pairplot(penguins, diag_kind=\\\"kde\\\")\\n\",\n    \"g.map_lower(sns.kdeplot, levels=4, color=\\\".2\\\")\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":3482,"name":".pre-commit-config.yaml","nodeType":"TextFile","path":"","text":"repos:\n-   repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.3.0\n    hooks:\n    -   id: check-yaml\n    -   id: end-of-file-fixer\n    -   id: trailing-whitespace\n        exclude: \\.svg$\n-   repo: https://github.com/pycqa/flake8\n    rev: 5.0.4\n    hooks:\n    -   id: flake8\n        exclude: seaborn/(cm\\.py|external/)\n        types: [file, python]\n-   repo: https://github.com/pre-commit/mirrors-mypy\n    rev: v0.971\n    hooks:\n     -  id: mypy\n        args: [--follow-imports=skip]\n        files: seaborn/_(core|marks|stats)/\n"},{"attributeType":"TextIO","col":28,"comment":"null","endLoc":12,"id":3483,"name":"fid","nodeType":"Attribute","startLoc":12,"text":"fid"},{"fileName":"test_decorators.py","filePath":"tests","id":3484,"nodeType":"File","text":"import inspect\nfrom seaborn._decorators import share_init_params_with_map\n\n\ndef test_share_init_params_with_map():\n\n    @share_init_params_with_map\n    class Thingie:\n\n        def map(cls, *args, **kwargs):\n            return cls(*args, **kwargs)\n\n        def __init__(self, a, b=1):\n            \"\"\"Make a new thingie.\"\"\"\n            self.a = a\n            self.b = b\n\n    thingie = Thingie.map(1, b=2)\n    assert thingie.a == 1\n    assert thingie.b == 2\n\n    assert \"a\" in inspect.signature(Thingie.map).parameters\n    assert \"b\" in inspect.signature(Thingie.map).parameters\n\n    assert Thingie.map.__doc__ == Thingie.__init__.__doc__\n"},{"col":0,"comment":"null","endLoc":25,"header":"def test_share_init_params_with_map()","id":3485,"name":"test_share_init_params_with_map","nodeType":"Function","startLoc":5,"text":"def test_share_init_params_with_map():\n\n    @share_init_params_with_map\n    class Thingie:\n\n        def map(cls, *args, **kwargs):\n            return cls(*args, **kwargs)\n\n        def __init__(self, a, b=1):\n            \"\"\"Make a new thingie.\"\"\"\n            self.a = a\n            self.b = b\n\n    thingie = Thingie.map(1, b=2)\n    assert thingie.a == 1\n    assert thingie.b == 2\n\n    assert \"a\" in inspect.signature(Thingie.map).parameters\n    assert \"b\" in inspect.signature(Thingie.map).parameters\n\n    assert Thingie.map.__doc__ == Thingie.__init__.__doc__"},{"col":4,"comment":"null","endLoc":1481,"header":"def test_margin_grid_from_arrays(self)","id":3487,"name":"test_margin_grid_from_arrays","nodeType":"Function","startLoc":1477,"text":"def test_margin_grid_from_arrays(self):\n\n        g = ag.JointGrid(x=self.x, y=self.y)\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)"},{"col":4,"comment":"null","endLoc":1487,"header":"def test_margin_grid_from_series(self)","id":3488,"name":"test_margin_grid_from_series","nodeType":"Function","startLoc":1483,"text":"def test_margin_grid_from_series(self):\n\n        g = ag.JointGrid(x=self.data.x, y=self.data.y)\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)"},{"col":4,"comment":"null","endLoc":64,"header":"def test_filled_unfilled_mix(self)","id":3489,"name":"test_filled_unfilled_mix","nodeType":"Function","startLoc":47,"text":"def test_filled_unfilled_mix(self):\n\n        x = [1, 2]\n        y = [4, 5]\n        marker = [\"a\", \"b\"]\n        shapes = [\"o\", \"x\"]\n\n        mark = Dot(edgecolor=\"w\", stroke=2, edgewidth=1)\n        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, to_rgba(C0, 0)], None)\n        self.check_colors(\"edge\", points, [\"w\", C0], 1)\n\n        expected = [mark.edgewidth, mark.stroke]\n        assert_array_equal(points.get_linewidths(), expected)"},{"col":4,"comment":"null","endLoc":1493,"header":"def test_margin_grid_from_dataframe(self)","id":3490,"name":"test_margin_grid_from_dataframe","nodeType":"Function","startLoc":1489,"text":"def test_margin_grid_from_dataframe(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n        npt.assert_array_equal(g.x, self.x)\n        npt.assert_array_equal(g.y, self.y)"},{"attributeType":"null","col":8,"comment":"null","endLoc":1492,"id":3491,"name":"confint","nodeType":"Attribute","startLoc":1492,"text":"self.confint"},{"col":4,"comment":"null","endLoc":1498,"header":"def test_margin_grid_from_dataframe_bad_variable(self)","id":3492,"name":"test_margin_grid_from_dataframe_bad_variable","nodeType":"Function","startLoc":1495,"text":"def test_margin_grid_from_dataframe_bad_variable(self):\n\n        with pytest.raises(ValueError):\n            ag.JointGrid(x=\"x\", y=\"bad_column\", data=self.data)"},{"className":"_BarPlotter","col":0,"comment":"null","endLoc":1589,"id":3493,"nodeType":"Class","startLoc":1523,"text":"class _BarPlotter(_CategoricalStatPlotter):\n\n    def __init__(self, x, y, hue, data, order, hue_order,\n                 estimator, errorbar, n_boot, units, seed,\n                 orient, color, palette, saturation, width,\n                 errcolor, errwidth, capsize, dodge):\n        \"\"\"Initialize the plotter.\"\"\"\n        self.establish_variables(x, y, hue, data, orient,\n                                 order, hue_order, units)\n        self.establish_colors(color, palette, saturation)\n        self.estimate_statistic(estimator, errorbar, n_boot, seed)\n\n        self.dodge = dodge\n        self.width = width\n\n        self.errcolor = errcolor\n        self.errwidth = errwidth\n        self.capsize = capsize\n\n    def draw_bars(self, ax, kws):\n        \"\"\"Draw the bars onto `ax`.\"\"\"\n        # Get the right matplotlib function depending on the orientation\n        barfunc = ax.bar if self.orient == \"v\" else ax.barh\n        barpos = np.arange(len(self.statistic))\n\n        if self.plot_hues is None:\n\n            # Draw the bars\n            barfunc(barpos, self.statistic, self.width,\n                    color=self.colors, align=\"center\", **kws)\n\n            # Draw the confidence intervals\n            errcolors = [self.errcolor] * len(barpos)\n            self.draw_confints(ax,\n                               barpos,\n                               self.confint,\n                               errcolors,\n                               self.errwidth,\n                               self.capsize)\n\n        else:\n\n            for j, hue_level in enumerate(self.hue_names):\n\n                # Draw the bars\n                offpos = barpos + self.hue_offsets[j]\n                barfunc(offpos, self.statistic[:, j], self.nested_width,\n                        color=self.colors[j], align=\"center\",\n                        label=hue_level, **kws)\n\n                # Draw the confidence intervals\n                if self.confint.size:\n                    confint = self.confint[:, j]\n                    errcolors = [self.errcolor] * len(offpos)\n                    self.draw_confints(ax,\n                                       offpos,\n                                       confint,\n                                       errcolors,\n                                       self.errwidth,\n                                       self.capsize)\n\n    def plot(self, ax, bar_kws):\n        \"\"\"Make the plot.\"\"\"\n        self.draw_bars(ax, bar_kws)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"col":4,"comment":"Draw the bars onto `ax`.","endLoc":1582,"header":"def draw_bars(self, ax, kws)","id":3494,"name":"draw_bars","nodeType":"Function","startLoc":1542,"text":"def draw_bars(self, ax, kws):\n        \"\"\"Draw the bars onto `ax`.\"\"\"\n        # Get the right matplotlib function depending on the orientation\n        barfunc = ax.bar if self.orient == \"v\" else ax.barh\n        barpos = np.arange(len(self.statistic))\n\n        if self.plot_hues is None:\n\n            # Draw the bars\n            barfunc(barpos, self.statistic, self.width,\n                    color=self.colors, align=\"center\", **kws)\n\n            # Draw the confidence intervals\n            errcolors = [self.errcolor] * len(barpos)\n            self.draw_confints(ax,\n                               barpos,\n                               self.confint,\n                               errcolors,\n                               self.errwidth,\n                               self.capsize)\n\n        else:\n\n            for j, hue_level in enumerate(self.hue_names):\n\n                # Draw the bars\n                offpos = barpos + self.hue_offsets[j]\n                barfunc(offpos, self.statistic[:, j], self.nested_width,\n                        color=self.colors[j], align=\"center\",\n                        label=hue_level, **kws)\n\n                # Draw the confidence intervals\n                if self.confint.size:\n                    confint = self.confint[:, j]\n                    errcolors = [self.errcolor] * len(offpos)\n                    self.draw_confints(ax,\n                                       offpos,\n                                       confint,\n                                       errcolors,\n                                       self.errwidth,\n                                       self.capsize)"},{"col":4,"comment":"null","endLoc":1511,"header":"def test_margin_grid_axis_labels(self)","id":3495,"name":"test_margin_grid_axis_labels","nodeType":"Function","startLoc":1500,"text":"def test_margin_grid_axis_labels(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n\n        xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()\n        assert xlabel == \"x\"\n        assert ylabel == \"y\"\n\n        g.set_axis_labels(\"x variable\", \"y variable\")\n        xlabel, ylabel = g.ax_joint.get_xlabel(), g.ax_joint.get_ylabel()\n        assert xlabel == \"x variable\"\n        assert ylabel == \"y variable\""},{"col":0,"comment":"","endLoc":1,"header":"palettes.py#","id":3496,"name":"","nodeType":"Function","startLoc":1,"text":"__all__ = [\"color_palette\", \"hls_palette\", \"husl_palette\", \"mpl_palette\",\n           \"dark_palette\", \"light_palette\", \"diverging_palette\",\n           \"blend_palette\", \"xkcd_palette\", \"crayon_palette\",\n           \"cubehelix_palette\", \"set_color_codes\"]\n\nSEABORN_PALETTES = dict(\n    deep=[\"#4C72B0\", \"#DD8452\", \"#55A868\", \"#C44E52\", \"#8172B3\",\n          \"#937860\", \"#DA8BC3\", \"#8C8C8C\", \"#CCB974\", \"#64B5CD\"],\n    deep6=[\"#4C72B0\", \"#55A868\", \"#C44E52\",\n           \"#8172B3\", \"#CCB974\", \"#64B5CD\"],\n    muted=[\"#4878D0\", \"#EE854A\", \"#6ACC64\", \"#D65F5F\", \"#956CB4\",\n           \"#8C613C\", \"#DC7EC0\", \"#797979\", \"#D5BB67\", \"#82C6E2\"],\n    muted6=[\"#4878D0\", \"#6ACC64\", \"#D65F5F\",\n            \"#956CB4\", \"#D5BB67\", \"#82C6E2\"],\n    pastel=[\"#A1C9F4\", \"#FFB482\", \"#8DE5A1\", \"#FF9F9B\", \"#D0BBFF\",\n            \"#DEBB9B\", \"#FAB0E4\", \"#CFCFCF\", \"#FFFEA3\", \"#B9F2F0\"],\n    pastel6=[\"#A1C9F4\", \"#8DE5A1\", \"#FF9F9B\",\n             \"#D0BBFF\", \"#FFFEA3\", \"#B9F2F0\"],\n    bright=[\"#023EFF\", \"#FF7C00\", \"#1AC938\", \"#E8000B\", \"#8B2BE2\",\n            \"#9F4800\", \"#F14CC1\", \"#A3A3A3\", \"#FFC400\", \"#00D7FF\"],\n    bright6=[\"#023EFF\", \"#1AC938\", \"#E8000B\",\n             \"#8B2BE2\", \"#FFC400\", \"#00D7FF\"],\n    dark=[\"#001C7F\", \"#B1400D\", \"#12711C\", \"#8C0800\", \"#591E71\",\n          \"#592F0D\", \"#A23582\", \"#3C3C3C\", \"#B8850A\", \"#006374\"],\n    dark6=[\"#001C7F\", \"#12711C\", \"#8C0800\",\n           \"#591E71\", \"#B8850A\", \"#006374\"],\n    colorblind=[\"#0173B2\", \"#DE8F05\", \"#029E73\", \"#D55E00\", \"#CC78BC\",\n                \"#CA9161\", \"#FBAFE4\", \"#949494\", \"#ECE133\", \"#56B4E9\"],\n    colorblind6=[\"#0173B2\", \"#029E73\", \"#D55E00\",\n                 \"#CC78BC\", \"#ECE133\", \"#56B4E9\"]\n)\n\nMPL_QUAL_PALS = {\n    \"tab10\": 10, \"tab20\": 20, \"tab20b\": 20, \"tab20c\": 20,\n    \"Set1\": 9, \"Set2\": 8, \"Set3\": 12,\n    \"Accent\": 8, \"Paired\": 12,\n    \"Pastel1\": 9, \"Pastel2\": 8, \"Dark2\": 8,\n}\n\nQUAL_PALETTE_SIZES = MPL_QUAL_PALS.copy()\n\nQUAL_PALETTE_SIZES.update({k: len(v) for k, v in SEABORN_PALETTES.items()})\n\nQUAL_PALETTES = list(QUAL_PALETTE_SIZES.keys())"},{"col":4,"comment":"Make the plot.","endLoc":1589,"header":"def plot(self, ax, bar_kws)","id":3497,"name":"plot","nodeType":"Function","startLoc":1584,"text":"def plot(self, ax, bar_kws):\n        \"\"\"Make the plot.\"\"\"\n        self.draw_bars(ax, bar_kws)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":3498,"name":"g","nodeType":"Attribute","startLoc":17,"text":"g"},{"col":0,"comment":"","endLoc":6,"header":"logistic_regression.py#","id":3499,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nFaceted logistic regression\n===========================\n\n_thumb: .58, .5\n\"\"\"\n\nsns.set_theme(style=\"darkgrid\")\n\ndf = sns.load_dataset(\"titanic\")\n\npal = dict(male=\"#6495ED\", female=\"#F08080\")\n\ng = sns.lmplot(x=\"age\", y=\"survived\", col=\"sex\", hue=\"sex\", data=df,\n               palette=pal, y_jitter=.02, logistic=True, truncate=False)\n\ng.set(xlim=(0, 80), ylim=(-.05, 1.05))"},{"attributeType":"null","col":8,"comment":"null","endLoc":1535,"id":3500,"name":"dodge","nodeType":"Attribute","startLoc":1535,"text":"self.dodge"},{"fileName":"appdirs.py","filePath":"seaborn/external","id":3501,"nodeType":"File","text":"#!/usr/bin/env python3\n# Copyright (c) 2005-2010 ActiveState Software Inc.\n# Copyright (c) 2013 Eddy Petrișor\n\n# flake8: noqa\n\n\"\"\"\nThis file is directly from\nhttps://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py\n\nThe license of https://github.com/ActiveState/appdirs copied below:\n\n\n# This is the MIT license\n\nCopyright (c) 2010 ActiveState Software Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\"\"\"Utilities for determining application-specific dirs.\n\nSee  for details and usage.\n\"\"\"\n# Dev Notes:\n# - MSDN on where to store app data files:\n#   http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120\n# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html\n# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html\n\n__version__ = \"1.4.4\"\n__version_info__ = tuple(int(segment) for segment in __version__.split(\".\"))\n\n\nimport sys\nimport os\n\nunicode = str\n\nif sys.platform.startswith('java'):\n    import platform\n    os_name = platform.java_ver()[3][0]\n    if os_name.startswith('Windows'): # \"Windows XP\", \"Windows 7\", etc.\n        system = 'win32'\n    elif os_name.startswith('Mac'): # \"Mac OS X\", etc.\n        system = 'darwin'\n    else: # \"Linux\", \"SunOS\", \"FreeBSD\", etc.\n        # Setting this to \"linux2\" is not ideal, but only Windows or Mac\n        # are actually checked for and the rest of the module expects\n        # *sys.platform* style strings.\n        system = 'linux2'\nelse:\n    system = sys.platform\n\n\ndef user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):\n    r\"\"\"Return full path to the user-specific cache dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \".\".\n            Only applied when appname is present.\n        \"opinion\" (boolean) can be False to disable the appending of\n            \"Cache\" to the base app data dir for Windows. See\n            discussion below.\n\n    Typical user cache directories are:\n        Mac OS X:   ~/Library/Caches/\n        Unix:       ~/.cache/ (XDG default)\n        Win XP:     C:\\Documents and Settings\\\\Local Settings\\Application Data\\\\\\Cache\n        Vista:      C:\\Users\\\\AppData\\Local\\\\\\Cache\n\n    On Windows the only suggestion in the MSDN docs is that local settings go in\n    the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming\n    app data dir (the default returned by `user_data_dir` above). Apps typically\n    put cache data somewhere *under* the given dir here. Some examples:\n        ...\\Mozilla\\Firefox\\Profiles\\\\Cache\n        ...\\Acme\\SuperApp\\Cache\\1.0\n    OPINION: This function appends \"Cache\" to the `CSIDL_LOCAL_APPDATA` value.\n    This can be disabled with the `opinion=False` option.\n    \"\"\"\n    if system == \"win32\":\n        if appauthor is None:\n            appauthor = appname\n        path = os.path.normpath(_get_win_folder(\"CSIDL_LOCAL_APPDATA\"))\n        if appname:\n            if appauthor is not False:\n                path = os.path.join(path, appauthor, appname)\n            else:\n                path = os.path.join(path, appname)\n            if opinion:\n                path = os.path.join(path, \"Cache\")\n    elif system == 'darwin':\n        path = os.path.expanduser('~/Library/Caches')\n        if appname:\n            path = os.path.join(path, appname)\n    else:\n        path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))\n        if appname:\n            path = os.path.join(path, appname)\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\n#---- internal support stuff\n\ndef _get_win_folder_from_registry(csidl_name):\n    \"\"\"This is a fallback technique at best. I'm not sure if using the\n    registry for this guarantees us the correct answer for all CSIDL_*\n    names.\n    \"\"\"\n    import winreg as _winreg\n\n    shell_folder_name = {\n        \"CSIDL_APPDATA\": \"AppData\",\n        \"CSIDL_COMMON_APPDATA\": \"Common AppData\",\n        \"CSIDL_LOCAL_APPDATA\": \"Local AppData\",\n    }[csidl_name]\n\n    key = _winreg.OpenKey(\n        _winreg.HKEY_CURRENT_USER,\n        r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"\n    )\n    dir, type = _winreg.QueryValueEx(key, shell_folder_name)\n    return dir\n\n\ndef _get_win_folder_with_pywin32(csidl_name):\n    from win32com.shell import shellcon, shell\n    dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)\n    # Try to make this a unicode path because SHGetFolderPath does\n    # not return unicode strings when there is unicode data in the\n    # path.\n    try:\n        dir = unicode(dir)\n\n        # Downgrade to short path name if have highbit chars. See\n        # .\n        has_high_char = False\n        for c in dir:\n            if ord(c) > 255:\n                has_high_char = True\n                break\n        if has_high_char:\n            try:\n                import win32api\n                dir = win32api.GetShortPathName(dir)\n            except ImportError:\n                pass\n    except UnicodeError:\n        pass\n    return dir\n\n\ndef _get_win_folder_with_ctypes(csidl_name):\n    import ctypes\n\n    csidl_const = {\n        \"CSIDL_APPDATA\": 26,\n        \"CSIDL_COMMON_APPDATA\": 35,\n        \"CSIDL_LOCAL_APPDATA\": 28,\n    }[csidl_name]\n\n    buf = ctypes.create_unicode_buffer(1024)\n    ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)\n\n    # Downgrade to short path name if have highbit chars. See\n    # .\n    has_high_char = False\n    for c in buf:\n        if ord(c) > 255:\n            has_high_char = True\n            break\n    if has_high_char:\n        buf2 = ctypes.create_unicode_buffer(1024)\n        if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):\n            buf = buf2\n\n    return buf.value\n\ndef _get_win_folder_with_jna(csidl_name):\n    import array\n    from com.sun import jna\n    from com.sun.jna.platform import win32\n\n    buf_size = win32.WinDef.MAX_PATH * 2\n    buf = array.zeros('c', buf_size)\n    shell = win32.Shell32.INSTANCE\n    shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)\n    dir = jna.Native.toString(buf.tostring()).rstrip(\"\\0\")\n\n    # Downgrade to short path name if have highbit chars. See\n    # .\n    has_high_char = False\n    for c in dir:\n        if ord(c) > 255:\n            has_high_char = True\n            break\n    if has_high_char:\n        buf = array.zeros('c', buf_size)\n        kernel = win32.Kernel32.INSTANCE\n        if kernel.GetShortPathName(dir, buf, buf_size):\n            dir = jna.Native.toString(buf.tostring()).rstrip(\"\\0\")\n\n    return dir\n\nif system == \"win32\":\n    try:\n        import win32com.shell\n        _get_win_folder = _get_win_folder_with_pywin32\n    except ImportError:\n        try:\n            from ctypes import windll\n            _get_win_folder = _get_win_folder_with_ctypes\n        except ImportError:\n            try:\n                import com.sun.jna\n                _get_win_folder = _get_win_folder_with_jna\n            except ImportError:\n                _get_win_folder = _get_win_folder_from_registry\n"},{"col":4,"comment":"null","endLoc":1519,"header":"def test_dropna(self)","id":3502,"name":"test_dropna","nodeType":"Function","startLoc":1513,"text":"def test_dropna(self):\n\n        g = ag.JointGrid(x=\"x_na\", y=\"y\", data=self.data, dropna=False)\n        assert len(g.x) == len(self.x_na)\n\n        g = ag.JointGrid(x=\"x_na\", y=\"y\", data=self.data, dropna=True)\n        assert len(g.x) == pd.notnull(self.x_na).sum()"},{"attributeType":"str","col":0,"comment":"null","endLoc":48,"id":3503,"name":"__version__","nodeType":"Attribute","startLoc":48,"text":"__version__"},{"attributeType":"(int, ...)","col":0,"comment":"null","endLoc":49,"id":3504,"name":"__version_info__","nodeType":"Attribute","startLoc":49,"text":"__version_info__"},{"id":3505,"name":"logo-tall-darkbg.svg","nodeType":"TextFile","path":"doc/_static","text":"\n\n\n\n \n  \n   \n    \n    2020-09-07T14:14:01.511527\n    image/svg+xml\n    \n     \n      Matplotlib v3.3.1, https://matplotlib.org/\n     \n    \n   \n  \n \n \n  \n \n \n  \n   \n  \n  \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n   \n   \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n   \n  \n  \n   \n    \n    \n     \n      \n      \n      \n      \n      \n      \n      \n     \n     \n     \n     \n     \n     \n     \n     \n    \n   \n  \n \n \n  \n   \n  \n  \n   \n  \n  \n   \n  \n \n\n"},{"fileName":"__init__.py","filePath":"seaborn/colors","id":3506,"nodeType":"File","text":"from .xkcd_rgb import xkcd_rgb  # noqa: F401\nfrom .crayons import crayons  # noqa: F401\n"},{"col":4,"comment":"null","endLoc":74,"header":"def test_missing_coordinate_data(self)","id":3507,"name":"test_missing_coordinate_data","nodeType":"Function","startLoc":66,"text":"def test_missing_coordinate_data(self):\n\n        x = [1, float(\"nan\"), 3]\n        y = [5, 3, 4]\n\n        p = Plot(x=x, y=y).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, [1, 3], [5, 4])"},{"attributeType":"null","col":8,"comment":"null","endLoc":1538,"id":3508,"name":"errcolor","nodeType":"Attribute","startLoc":1538,"text":"self.errcolor"},{"attributeType":"null","col":8,"comment":"null","endLoc":1539,"id":3509,"name":"errwidth","nodeType":"Attribute","startLoc":1539,"text":"self.errwidth"},{"attributeType":"null","col":8,"comment":"null","endLoc":1536,"id":3510,"name":"width","nodeType":"Attribute","startLoc":1536,"text":"self.width"},{"attributeType":"null","col":8,"comment":"null","endLoc":1540,"id":3511,"name":"capsize","nodeType":"Attribute","startLoc":1540,"text":"self.capsize"},{"attributeType":"null","col":16,"comment":"null","endLoc":4,"id":3512,"name":"np","nodeType":"Attribute","startLoc":4,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":3513,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":6,"id":3514,"name":"plt","nodeType":"Attribute","startLoc":6,"text":"plt"},{"fileName":"__init__.py","filePath":"seaborn/_stats","id":3515,"nodeType":"File","text":""},{"col":4,"comment":"null","endLoc":1530,"header":"def test_axlims(self)","id":3516,"name":"test_axlims","nodeType":"Function","startLoc":1521,"text":"def test_axlims(self):\n\n        lim = (-3, 3)\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data, xlim=lim, ylim=lim)\n\n        assert g.ax_joint.get_xlim() == lim\n        assert g.ax_joint.get_ylim() == lim\n\n        assert g.ax_marg_x.get_xlim() == lim\n        assert g.ax_marg_y.get_ylim() == lim"},{"className":"_PointPlotter","col":0,"comment":"null","endLoc":1737,"id":3517,"nodeType":"Class","startLoc":1592,"text":"class _PointPlotter(_CategoricalStatPlotter):\n\n    default_palette = \"dark\"\n\n    def __init__(self, x, y, hue, data, order, hue_order,\n                 estimator, errorbar, n_boot, units, seed,\n                 markers, linestyles, dodge, join, scale,\n                 orient, color, palette, errwidth=None, capsize=None):\n        \"\"\"Initialize the plotter.\"\"\"\n        self.establish_variables(x, y, hue, data, orient,\n                                 order, hue_order, units)\n        self.establish_colors(color, palette, 1)\n        self.estimate_statistic(estimator, errorbar, n_boot, seed)\n\n        # Override the default palette for single-color plots\n        if hue is None and color is None and palette is None:\n            self.colors = [color_palette()[0]] * len(self.colors)\n\n        # Don't join single-layer plots with different colors\n        if hue is None and palette is not None:\n            join = False\n\n        # Use a good default for `dodge=True`\n        if dodge is True and self.hue_names is not None:\n            dodge = .025 * len(self.hue_names)\n\n        # Make sure we have a marker for each hue level\n        if isinstance(markers, str):\n            markers = [markers] * len(self.colors)\n        self.markers = markers\n\n        # Make sure we have a line style for each hue level\n        if isinstance(linestyles, str):\n            linestyles = [linestyles] * len(self.colors)\n        self.linestyles = linestyles\n\n        # Set the other plot components\n        self.dodge = dodge\n        self.join = join\n        self.scale = scale\n        self.errwidth = errwidth\n        self.capsize = capsize\n\n    @property\n    def hue_offsets(self):\n        \"\"\"Offsets relative to the center position for each hue level.\"\"\"\n        if self.dodge:\n            offset = np.linspace(0, self.dodge, len(self.hue_names))\n            offset -= offset.mean()\n        else:\n            offset = np.zeros(len(self.hue_names))\n        return offset\n\n    def draw_points(self, ax):\n        \"\"\"Draw the main data components of the plot.\"\"\"\n        # Get the center positions on the categorical axis\n        pointpos = np.arange(len(self.statistic))\n\n        # Get the size of the plot elements\n        lw = mpl.rcParams[\"lines.linewidth\"] * 1.8 * self.scale\n        mew = lw * .75\n        markersize = np.pi * np.square(lw) * 2\n\n        if self.plot_hues is None:\n\n            # Draw lines joining each estimate point\n            if self.join:\n                color = self.colors[0]\n                ls = self.linestyles[0]\n                if self.orient == \"h\":\n                    ax.plot(self.statistic, pointpos,\n                            color=color, ls=ls, lw=lw)\n                else:\n                    ax.plot(pointpos, self.statistic,\n                            color=color, ls=ls, lw=lw)\n\n            # Draw the confidence intervals\n            self.draw_confints(ax, pointpos, self.confint, self.colors,\n                               self.errwidth, self.capsize)\n\n            # Draw the estimate points\n            marker = self.markers[0]\n            colors = [mpl.colors.colorConverter.to_rgb(c) for c in self.colors]\n            if self.orient == \"h\":\n                x, y = self.statistic, pointpos\n            else:\n                x, y = pointpos, self.statistic\n            ax.scatter(x, y,\n                       linewidth=mew, marker=marker, s=markersize,\n                       facecolor=colors, edgecolor=colors)\n\n        else:\n\n            offsets = self.hue_offsets\n            for j, hue_level in enumerate(self.hue_names):\n\n                # Determine the values to plot for this level\n                statistic = self.statistic[:, j]\n\n                # Determine the position on the categorical and z axes\n                offpos = pointpos + offsets[j]\n                z = j + 1\n\n                # Draw lines joining each estimate point\n                if self.join:\n                    color = self.colors[j]\n                    ls = self.linestyles[j]\n                    if self.orient == \"h\":\n                        ax.plot(statistic, offpos, color=color,\n                                zorder=z, ls=ls, lw=lw)\n                    else:\n                        ax.plot(offpos, statistic, color=color,\n                                zorder=z, ls=ls, lw=lw)\n\n                # Draw the confidence intervals\n                if self.confint.size:\n                    confint = self.confint[:, j]\n                    errcolors = [self.colors[j]] * len(offpos)\n                    self.draw_confints(ax, offpos, confint, errcolors,\n                                       self.errwidth, self.capsize,\n                                       zorder=z)\n\n                # Draw the estimate points\n                n_points = len(remove_na(offpos))\n                marker = self.markers[j]\n                color = mpl.colors.colorConverter.to_rgb(self.colors[j])\n\n                if self.orient == \"h\":\n                    x, y = statistic, offpos\n                else:\n                    x, y = offpos, statistic\n\n                if not len(remove_na(statistic)):\n                    x = y = [np.nan] * n_points\n\n                ax.scatter(x, y, label=hue_level,\n                           facecolor=color, edgecolor=color,\n                           linewidth=mew, marker=marker, s=markersize,\n                           zorder=z)\n\n    def plot(self, ax):\n        \"\"\"Make the plot.\"\"\"\n        self.draw_points(ax)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"col":4,"comment":"Offsets relative to the center position for each hue level.","endLoc":1643,"header":"@property\n    def hue_offsets(self)","id":3518,"name":"hue_offsets","nodeType":"Function","startLoc":1635,"text":"@property\n    def hue_offsets(self):\n        \"\"\"Offsets relative to the center position for each hue level.\"\"\"\n        if self.dodge:\n            offset = np.linspace(0, self.dodge, len(self.hue_names))\n            offset -= offset.mean()\n        else:\n            offset = np.zeros(len(self.hue_names))\n        return offset"},{"col":4,"comment":"null","endLoc":86,"header":"@pytest.mark.parametrize(\"prop\", [\"color\", \"fill\", \"marker\", \"pointsize\"])\n    def test_missing_semantic_data(self, prop)","id":3519,"name":"test_missing_semantic_data","nodeType":"Function","startLoc":76,"text":"@pytest.mark.parametrize(\"prop\", [\"color\", \"fill\", \"marker\", \"pointsize\"])\n    def test_missing_semantic_data(self, prop):\n\n        x = [1, 2, 3]\n        y = [5, 3, 4]\n        z = [\"a\", float(\"nan\"), \"b\"]\n\n        p = Plot(x=x, y=y, **{prop: z}).add(Dot()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, [1, 3], [5, 4])"},{"fileName":"extract_examples.py","filePath":"doc/tools","id":3520,"nodeType":"File","text":"\"\"\"Turn the examples section of a function docstring into a notebook.\"\"\"\nimport re\nimport sys\nimport pydoc\nimport seaborn\nfrom seaborn.external.docscrape import NumpyDocString\nimport nbformat\n\n\ndef line_type(line):\n\n    if line.startswith(\"    \"):\n        return \"code\"\n    else:\n        return \"markdown\"\n\n\ndef add_cell(nb, lines, cell_type):\n\n    cell_objs = {\n        \"code\": nbformat.v4.new_code_cell,\n        \"markdown\": nbformat.v4.new_markdown_cell,\n    }\n    text = \"\\n\".join(lines)\n    cell = cell_objs[cell_type](text)\n    nb[\"cells\"].append(cell)\n\n\nif __name__ == \"__main__\":\n\n    _, name = sys.argv\n\n    # Parse the docstring and get the examples section\n    obj = getattr(seaborn, name)\n    if obj.__class__.__name__ != \"function\":\n        obj = obj.__init__\n    lines = NumpyDocString(pydoc.getdoc(obj))[\"Examples\"]\n\n    # Remove code indentation, the prompt, and mpl return variable\n    pat = re.compile(r\"\\s{4}[>\\.]{3} (ax = ){0,1}(g = ){0,1}\")\n\n    nb = nbformat.v4.new_notebook()\n\n    # We always start with at least one line of text\n    cell_type = \"markdown\"\n    cell = []\n\n    for line in lines:\n\n        # Ignore matplotlib plot directive\n        if \".. plot\" in line or \":context:\" in line:\n            continue\n\n        # Ignore blank lines\n        if not line:\n            continue\n\n        if line_type(line) != cell_type:\n            # We are on the first line of the next cell,\n            # so package up the last cell\n            add_cell(nb, cell, cell_type)\n            cell_type = line_type(line)\n            cell = []\n\n        if line_type(line) == \"code\":\n            line = re.sub(pat, \"\", line)\n\n        cell.append(line)\n\n    # Package the final cell\n    add_cell(nb, cell, cell_type)\n\n    nbformat.write(nb, f\"docstrings/{name}.ipynb\")\n"},{"col":0,"comment":"null","endLoc":15,"header":"def line_type(line)","id":3521,"name":"line_type","nodeType":"Function","startLoc":10,"text":"def line_type(line):\n\n    if line.startswith(\"    \"):\n        return \"code\"\n    else:\n        return \"markdown\""},{"col":4,"comment":"null","endLoc":1540,"header":"def test_marginal_ticks(self)","id":3522,"name":"test_marginal_ticks","nodeType":"Function","startLoc":1532,"text":"def test_marginal_ticks(self):\n\n        g = ag.JointGrid(marginal_ticks=False)\n        assert not sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())\n        assert not sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())\n\n        g = ag.JointGrid(marginal_ticks=True)\n        assert sum(t.get_visible() for t in g.ax_marg_x.get_yticklabels())\n        assert sum(t.get_visible() for t in g.ax_marg_y.get_xticklabels())"},{"col":0,"comment":"null","endLoc":26,"header":"def add_cell(nb, lines, cell_type)","id":3523,"name":"add_cell","nodeType":"Function","startLoc":18,"text":"def add_cell(nb, lines, cell_type):\n\n    cell_objs = {\n        \"code\": nbformat.v4.new_code_cell,\n        \"markdown\": nbformat.v4.new_markdown_cell,\n    }\n    text = \"\\n\".join(lines)\n    cell = cell_objs[cell_type](text)\n    nb[\"cells\"].append(cell)"},{"col":4,"comment":"null","endLoc":1549,"header":"def test_bivariate_plot(self)","id":3524,"name":"test_bivariate_plot","nodeType":"Function","startLoc":1542,"text":"def test_bivariate_plot(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n        g.plot_joint(plt.plot)\n\n        x, y = g.ax_joint.lines[0].get_xydata().T\n        npt.assert_array_equal(x, self.x)\n        npt.assert_array_equal(y, self.y)"},{"col":4,"comment":"null","endLoc":1558,"header":"def test_univariate_plot(self)","id":3525,"name":"test_univariate_plot","nodeType":"Function","startLoc":1551,"text":"def test_univariate_plot(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        g.plot_marginals(kdeplot)\n\n        _, y1 = g.ax_marg_x.lines[0].get_xydata().T\n        y2, _ = g.ax_marg_y.lines[0].get_xydata().T\n        npt.assert_array_equal(y1, y2)"},{"col":4,"comment":"Draw the main data components of the plot.","endLoc":1730,"header":"def draw_points(self, ax)","id":3526,"name":"draw_points","nodeType":"Function","startLoc":1645,"text":"def draw_points(self, ax):\n        \"\"\"Draw the main data components of the plot.\"\"\"\n        # Get the center positions on the categorical axis\n        pointpos = np.arange(len(self.statistic))\n\n        # Get the size of the plot elements\n        lw = mpl.rcParams[\"lines.linewidth\"] * 1.8 * self.scale\n        mew = lw * .75\n        markersize = np.pi * np.square(lw) * 2\n\n        if self.plot_hues is None:\n\n            # Draw lines joining each estimate point\n            if self.join:\n                color = self.colors[0]\n                ls = self.linestyles[0]\n                if self.orient == \"h\":\n                    ax.plot(self.statistic, pointpos,\n                            color=color, ls=ls, lw=lw)\n                else:\n                    ax.plot(pointpos, self.statistic,\n                            color=color, ls=ls, lw=lw)\n\n            # Draw the confidence intervals\n            self.draw_confints(ax, pointpos, self.confint, self.colors,\n                               self.errwidth, self.capsize)\n\n            # Draw the estimate points\n            marker = self.markers[0]\n            colors = [mpl.colors.colorConverter.to_rgb(c) for c in self.colors]\n            if self.orient == \"h\":\n                x, y = self.statistic, pointpos\n            else:\n                x, y = pointpos, self.statistic\n            ax.scatter(x, y,\n                       linewidth=mew, marker=marker, s=markersize,\n                       facecolor=colors, edgecolor=colors)\n\n        else:\n\n            offsets = self.hue_offsets\n            for j, hue_level in enumerate(self.hue_names):\n\n                # Determine the values to plot for this level\n                statistic = self.statistic[:, j]\n\n                # Determine the position on the categorical and z axes\n                offpos = pointpos + offsets[j]\n                z = j + 1\n\n                # Draw lines joining each estimate point\n                if self.join:\n                    color = self.colors[j]\n                    ls = self.linestyles[j]\n                    if self.orient == \"h\":\n                        ax.plot(statistic, offpos, color=color,\n                                zorder=z, ls=ls, lw=lw)\n                    else:\n                        ax.plot(offpos, statistic, color=color,\n                                zorder=z, ls=ls, lw=lw)\n\n                # Draw the confidence intervals\n                if self.confint.size:\n                    confint = self.confint[:, j]\n                    errcolors = [self.colors[j]] * len(offpos)\n                    self.draw_confints(ax, offpos, confint, errcolors,\n                                       self.errwidth, self.capsize,\n                                       zorder=z)\n\n                # Draw the estimate points\n                n_points = len(remove_na(offpos))\n                marker = self.markers[j]\n                color = mpl.colors.colorConverter.to_rgb(self.colors[j])\n\n                if self.orient == \"h\":\n                    x, y = statistic, offpos\n                else:\n                    x, y = offpos, statistic\n\n                if not len(remove_na(statistic)):\n                    x = y = [np.nan] * n_points\n\n                ax.scatter(x, y, label=hue_level,\n                           facecolor=color, edgecolor=color,\n                           linewidth=mew, marker=marker, s=markersize,\n                           zorder=z)"},{"className":"TestDots","col":0,"comment":"null","endLoc":178,"id":3527,"nodeType":"Class","startLoc":89,"text":"class TestDots(DotBase):\n\n    def test_simple(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        p = Plot(x=x, y=y).add(Dots()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0] * 3, .2)\n        self.check_colors(\"edge\", points, [C0] * 3, 1)\n\n    def test_set_color(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        m = Dots(color=\".25\")\n        p = Plot(x=x, y=y).add(m).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [m.color] * 3, .2)\n        self.check_colors(\"edge\", points, [m.color] * 3, 1)\n\n    def test_map_color(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        c = [\"a\", \"b\", \"a\"]\n        p = Plot(x=x, y=y, color=c).add(Dots()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, C1, C0], .2)\n        self.check_colors(\"edge\", points, [C0, C1, C0], 1)\n\n    def test_fill(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        c = [\"a\", \"b\", \"a\"]\n        p = Plot(x=x, y=y, color=c).add(Dots(fill=False)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, C1, C0], 0)\n        self.check_colors(\"edge\", points, [C0, C1, C0], 1)\n\n    def test_pointsize(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        s = 3\n        p = Plot(x=x, y=y).add(Dots(pointsize=s)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        assert_array_equal(points.get_sizes(), [s ** 2] * 3)\n\n    def test_stroke(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        s = 3\n        p = Plot(x=x, y=y).add(Dots(stroke=s)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        assert_array_equal(points.get_linewidths(), [s] * 3)\n\n    def test_filled_unfilled_mix(self):\n\n        x = [1, 2]\n        y = [4, 5]\n        marker = [\"a\", \"b\"]\n        shapes = [\"o\", \"x\"]\n\n        mark = Dots(stroke=2)\n        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [to_rgba(C0, .2), to_rgba(C0, 0)], None)\n        self.check_colors(\"edge\", points, [C0, C0], 1)\n        assert_array_equal(points.get_linewidths(), [mark.stroke] * 2)"},{"col":4,"comment":"null","endLoc":1569,"header":"def test_univariate_plot_distplot(self)","id":3528,"name":"test_univariate_plot_distplot","nodeType":"Function","startLoc":1560,"text":"def test_univariate_plot_distplot(self):\n\n        bins = 10\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        with pytest.warns(UserWarning):\n            g.plot_marginals(distplot, bins=bins)\n        assert len(g.ax_marg_x.patches) == bins\n        assert len(g.ax_marg_y.patches) == bins\n        for x, y in zip(g.ax_marg_x.patches, g.ax_marg_y.patches):\n            assert x.get_height() == y.get_width()"},{"col":4,"comment":"null","endLoc":101,"header":"def test_simple(self)","id":3529,"name":"test_simple","nodeType":"Function","startLoc":91,"text":"def test_simple(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        p = Plot(x=x, y=y).add(Dots()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0] * 3, .2)\n        self.check_colors(\"edge\", points, [C0] * 3, 1)"},{"attributeType":"str","col":4,"comment":"null","endLoc":31,"id":3530,"name":"_","nodeType":"Attribute","startLoc":31,"text":"_"},{"col":0,"comment":"","endLoc":1,"header":"check_gallery.py#","id":3531,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Execute the scripts that comprise the example gallery in the online docs.\"\"\"\n\nif __name__ == \"__main__\":\n\n    fnames = sorted(glob(\"examples/*.py\"))\n\n    for fname in fnames:\n\n        print(f\"- {fname}\")\n        with open(fname) as fid:\n            exec(fid.read())\n        plt.close(\"all\")"},{"fileName":"test_moves.py","filePath":"tests/_core","id":3534,"nodeType":"File","text":"\nfrom itertools import product\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.testing import assert_series_equal\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom seaborn._core.moves import Dodge, Jitter, Shift, Stack, Norm\nfrom seaborn._core.rules import categorical_order\nfrom seaborn._core.groupby import GroupBy\n\nimport pytest\n\n\nclass MoveFixtures:\n\n    @pytest.fixture\n    def df(self, rng):\n\n        n = 50\n        data = {\n            \"x\": rng.choice([0., 1., 2., 3.], n),\n            \"y\": rng.normal(0, 1, n),\n            \"grp2\": rng.choice([\"a\", \"b\"], n),\n            \"grp3\": rng.choice([\"x\", \"y\", \"z\"], n),\n            \"width\": 0.8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)\n\n    @pytest.fixture\n    def toy_df(self):\n\n        data = {\n            \"x\": [0, 0, 1],\n            \"y\": [1, 2, 3],\n            \"grp\": [\"a\", \"b\", \"b\"],\n            \"width\": .8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)\n\n    @pytest.fixture\n    def toy_df_widths(self, toy_df):\n\n        toy_df[\"width\"] = [.8, .2, .4]\n        return toy_df\n\n    @pytest.fixture\n    def toy_df_facets(self):\n\n        data = {\n            \"x\": [0, 0, 1, 0, 1, 2],\n            \"y\": [1, 2, 3, 1, 2, 3],\n            \"grp\": [\"a\", \"b\", \"a\", \"b\", \"a\", \"b\"],\n            \"col\": [\"x\", \"x\", \"x\", \"y\", \"y\", \"y\"],\n            \"width\": .8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)\n\n\nclass TestJitter(MoveFixtures):\n\n    def get_groupby(self, data, orient):\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        variables = [v for v in data if v not in [other, \"width\"]]\n        return GroupBy(variables)\n\n    def check_same(self, res, df, *cols):\n        for col in cols:\n            assert_series_equal(res[col], df[col])\n\n    def check_pos(self, res, df, var, limit):\n\n        assert (res[var] != df[var]).all()\n        assert (res[var] < df[var] + limit / 2).all()\n        assert (res[var] > df[var] - limit / 2).all()\n\n    def test_default(self, df):\n\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter()(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", 0.2 * df[\"width\"])\n        assert (res[\"x\"] - df[\"x\"]).abs().min() > 0\n\n    def test_width(self, df):\n\n        width = .4\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(width=width)(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", width * df[\"width\"])\n\n    def test_x(self, df):\n\n        val = .2\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(x=val)(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", val)\n\n    def test_y(self, df):\n\n        val = .2\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(y=val)(df, groupby, orient, {})\n        self.check_same(res, df, \"x\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"y\", val)\n\n    def test_seed(self, df):\n\n        kws = dict(width=.2, y=.1, seed=0)\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res1 = Jitter(**kws)(df, groupby, orient, {})\n        res2 = Jitter(**kws)(df, groupby, orient, {})\n        for var in \"xy\":\n            assert_series_equal(res1[var], res2[var])\n\n\nclass TestDodge(MoveFixtures):\n\n    # First some very simple toy examples\n\n    def test_default(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge()(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3]),\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1.2])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])\n\n    def test_fill(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"fill\")(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3]),\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .8])\n\n    def test_drop(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(\"drop\")(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])\n\n    def test_gap(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(gap=.25)(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1.2])\n        assert_array_almost_equal(res[\"width\"], [.3, .3, .3])\n\n    def test_widths_default(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge()(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1.1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .2])\n\n    def test_widths_fill(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"fill\")(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .4])\n\n    def test_widths_drop(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"drop\")(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .2])\n\n    def test_faceted_default(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge()(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, .8, .2, .8, 2.2])\n        assert_array_almost_equal(res[\"width\"], [.4] * 6)\n\n    def test_faceted_fill(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge(empty=\"fill\")(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1, 0, 1, 2])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .8, .8, .8, .8])\n\n    def test_faceted_drop(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge(empty=\"drop\")(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1, 0, 1, 2])\n        assert_array_almost_equal(res[\"width\"], [.4] * 6)\n\n    def test_orient(self, toy_df):\n\n        df = toy_df.assign(x=toy_df[\"y\"], y=toy_df[\"x\"])\n\n        groupby = GroupBy([\"y\", \"grp\"])\n        res = Dodge(\"drop\")(df, groupby, \"y\", {})\n\n        assert_array_equal(res[\"x\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"y\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])\n\n    # Now tests with slightly more complicated data\n\n    @pytest.mark.parametrize(\"grp\", [\"grp2\", \"grp3\"])\n    def test_single_semantic(self, df, grp):\n\n        groupby = GroupBy([\"x\", grp])\n        res = Dodge()(df, groupby, \"x\", {})\n\n        levels = categorical_order(df[grp])\n        w, n = 0.8, len(levels)\n\n        shifts = np.linspace(0, w - w / n, n)\n        shifts -= shifts.mean()\n\n        assert_series_equal(res[\"y\"], df[\"y\"])\n        assert_series_equal(res[\"width\"], df[\"width\"] / n)\n\n        for val, shift in zip(levels, shifts):\n            rows = df[grp] == val\n            assert_series_equal(res.loc[rows, \"x\"], df.loc[rows, \"x\"] + shift)\n\n    def test_two_semantics(self, df):\n\n        groupby = GroupBy([\"x\", \"grp2\", \"grp3\"])\n        res = Dodge()(df, groupby, \"x\", {})\n\n        levels = categorical_order(df[\"grp2\"]), categorical_order(df[\"grp3\"])\n        w, n = 0.8, len(levels[0]) * len(levels[1])\n\n        shifts = np.linspace(0, w - w / n, n)\n        shifts -= shifts.mean()\n\n        assert_series_equal(res[\"y\"], df[\"y\"])\n        assert_series_equal(res[\"width\"], df[\"width\"] / n)\n\n        for (v2, v3), shift in zip(product(*levels), shifts):\n            rows = (df[\"grp2\"] == v2) & (df[\"grp3\"] == v3)\n            assert_series_equal(res.loc[rows, \"x\"], df.loc[rows, \"x\"] + shift)\n\n\nclass TestStack(MoveFixtures):\n\n    def test_basic(self, toy_df):\n\n        groupby = GroupBy([\"color\", \"group\"])\n        res = Stack()(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"x\"], [0, 0, 1])\n        assert_array_equal(res[\"y\"], [1, 3, 3])\n        assert_array_equal(res[\"baseline\"], [0, 1, 0])\n\n    def test_faceted(self, toy_df_facets):\n\n        groupby = GroupBy([\"color\", \"group\"])\n        res = Stack()(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"x\"], [0, 0, 1, 0, 1, 2])\n        assert_array_equal(res[\"y\"], [1, 3, 3, 1, 2, 3])\n        assert_array_equal(res[\"baseline\"], [0, 1, 0, 0, 0, 0])\n\n    def test_misssing_data(self, toy_df):\n\n        df = pd.DataFrame({\n            \"x\": [0, 0, 0],\n            \"y\": [2, np.nan, 1],\n            \"baseline\": [0, 0, 0],\n        })\n        res = Stack()(df, None, \"x\", {})\n        assert_array_equal(res[\"y\"], [2, np.nan, 3])\n        assert_array_equal(res[\"baseline\"], [0, np.nan, 2])\n\n    def test_baseline_homogeneity_check(self, toy_df):\n\n        toy_df[\"baseline\"] = [0, 1, 2]\n        groupby = GroupBy([\"color\", \"group\"])\n        move = Stack()\n        err = \"Stack move cannot be used when baselines\"\n        with pytest.raises(RuntimeError, match=err):\n            move(toy_df, groupby, \"x\", {})\n\n\nclass TestShift(MoveFixtures):\n\n    def test_default(self, toy_df):\n\n        gb = GroupBy([\"color\", \"group\"])\n        res = Shift()(toy_df, gb, \"x\", {})\n        for col in toy_df:\n            assert_series_equal(toy_df[col], res[col])\n\n    @pytest.mark.parametrize(\"x,y\", [(.3, 0), (0, .2), (.1, .3)])\n    def test_moves(self, toy_df, x, y):\n\n        gb = GroupBy([\"color\", \"group\"])\n        res = Shift(x=x, y=y)(toy_df, gb, \"x\", {})\n        assert_array_equal(res[\"x\"], toy_df[\"x\"] + x)\n        assert_array_equal(res[\"y\"], toy_df[\"y\"] + y)\n\n\nclass TestNorm(MoveFixtures):\n\n    @pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_no_groups(self, df, orient):\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        gb = GroupBy([\"null\"])\n        res = Norm()(df, gb, orient, {})\n        assert res[other].max() == pytest.approx(1)\n\n    @pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_groups(self, df, orient):\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        gb = GroupBy([\"grp2\"])\n        res = Norm()(df, gb, orient, {})\n        for _, grp in res.groupby(\"grp2\"):\n            assert grp[other].max() == pytest.approx(1)\n\n    def test_sum(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(\"sum\")(df, gb, \"x\", {})\n        assert res[\"y\"].sum() == pytest.approx(1)\n\n    def test_where(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(where=\"x == 2\")(df, gb, \"x\", {})\n        assert res.loc[res[\"x\"] == 2, \"y\"].max() == pytest.approx(1)\n\n    def test_percent(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(percent=True)(df, gb, \"x\", {})\n        assert res[\"y\"].max() == pytest.approx(100)\n"},{"className":"MoveFixtures","col":0,"comment":"null","endLoc":61,"id":3535,"nodeType":"Class","startLoc":16,"text":"class MoveFixtures:\n\n    @pytest.fixture\n    def df(self, rng):\n\n        n = 50\n        data = {\n            \"x\": rng.choice([0., 1., 2., 3.], n),\n            \"y\": rng.normal(0, 1, n),\n            \"grp2\": rng.choice([\"a\", \"b\"], n),\n            \"grp3\": rng.choice([\"x\", \"y\", \"z\"], n),\n            \"width\": 0.8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)\n\n    @pytest.fixture\n    def toy_df(self):\n\n        data = {\n            \"x\": [0, 0, 1],\n            \"y\": [1, 2, 3],\n            \"grp\": [\"a\", \"b\", \"b\"],\n            \"width\": .8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)\n\n    @pytest.fixture\n    def toy_df_widths(self, toy_df):\n\n        toy_df[\"width\"] = [.8, .2, .4]\n        return toy_df\n\n    @pytest.fixture\n    def toy_df_facets(self):\n\n        data = {\n            \"x\": [0, 0, 1, 0, 1, 2],\n            \"y\": [1, 2, 3, 1, 2, 3],\n            \"grp\": [\"a\", \"b\", \"a\", \"b\", \"a\", \"b\"],\n            \"col\": [\"x\", \"x\", \"x\", \"y\", \"y\", \"y\"],\n            \"width\": .8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)"},{"col":4,"comment":"null","endLoc":30,"header":"@pytest.fixture\n    def df(self, rng)","id":3536,"name":"df","nodeType":"Function","startLoc":18,"text":"@pytest.fixture\n    def df(self, rng):\n\n        n = 50\n        data = {\n            \"x\": rng.choice([0., 1., 2., 3.], n),\n            \"y\": rng.normal(0, 1, n),\n            \"grp2\": rng.choice([\"a\", \"b\"], n),\n            \"grp3\": rng.choice([\"x\", \"y\", \"z\"], n),\n            \"width\": 0.8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)"},{"col":4,"comment":"null","endLoc":42,"header":"@pytest.fixture\n    def toy_df(self)","id":3537,"name":"toy_df","nodeType":"Function","startLoc":32,"text":"@pytest.fixture\n    def toy_df(self):\n\n        data = {\n            \"x\": [0, 0, 1],\n            \"y\": [1, 2, 3],\n            \"grp\": [\"a\", \"b\", \"b\"],\n            \"width\": .8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)"},{"col":4,"comment":"null","endLoc":48,"header":"@pytest.fixture\n    def toy_df_widths(self, toy_df)","id":3538,"name":"toy_df_widths","nodeType":"Function","startLoc":44,"text":"@pytest.fixture\n    def toy_df_widths(self, toy_df):\n\n        toy_df[\"width\"] = [.8, .2, .4]\n        return toy_df"},{"col":4,"comment":"null","endLoc":61,"header":"@pytest.fixture\n    def toy_df_facets(self)","id":3539,"name":"toy_df_facets","nodeType":"Function","startLoc":50,"text":"@pytest.fixture\n    def toy_df_facets(self):\n\n        data = {\n            \"x\": [0, 0, 1, 0, 1, 2],\n            \"y\": [1, 2, 3, 1, 2, 3],\n            \"grp\": [\"a\", \"b\", \"a\", \"b\", \"a\", \"b\"],\n            \"col\": [\"x\", \"x\", \"x\", \"y\", \"y\", \"y\"],\n            \"width\": .8,\n            \"baseline\": 0,\n        }\n        return pd.DataFrame(data)"},{"className":"TestJitter","col":0,"comment":"null","endLoc":125,"id":3540,"nodeType":"Class","startLoc":64,"text":"class TestJitter(MoveFixtures):\n\n    def get_groupby(self, data, orient):\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        variables = [v for v in data if v not in [other, \"width\"]]\n        return GroupBy(variables)\n\n    def check_same(self, res, df, *cols):\n        for col in cols:\n            assert_series_equal(res[col], df[col])\n\n    def check_pos(self, res, df, var, limit):\n\n        assert (res[var] != df[var]).all()\n        assert (res[var] < df[var] + limit / 2).all()\n        assert (res[var] > df[var] - limit / 2).all()\n\n    def test_default(self, df):\n\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter()(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", 0.2 * df[\"width\"])\n        assert (res[\"x\"] - df[\"x\"]).abs().min() > 0\n\n    def test_width(self, df):\n\n        width = .4\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(width=width)(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", width * df[\"width\"])\n\n    def test_x(self, df):\n\n        val = .2\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(x=val)(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", val)\n\n    def test_y(self, df):\n\n        val = .2\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(y=val)(df, groupby, orient, {})\n        self.check_same(res, df, \"x\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"y\", val)\n\n    def test_seed(self, df):\n\n        kws = dict(width=.2, y=.1, seed=0)\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res1 = Jitter(**kws)(df, groupby, orient, {})\n        res2 = Jitter(**kws)(df, groupby, orient, {})\n        for var in \"xy\":\n            assert_series_equal(res1[var], res2[var])"},{"col":4,"comment":"null","endLoc":69,"header":"def get_groupby(self, data, orient)","id":3541,"name":"get_groupby","nodeType":"Function","startLoc":66,"text":"def get_groupby(self, data, orient):\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        variables = [v for v in data if v not in [other, \"width\"]]\n        return GroupBy(variables)"},{"col":4,"comment":"null","endLoc":73,"header":"def check_same(self, res, df, *cols)","id":3542,"name":"check_same","nodeType":"Function","startLoc":71,"text":"def check_same(self, res, df, *cols):\n        for col in cols:\n            assert_series_equal(res[col], df[col])"},{"col":4,"comment":"null","endLoc":79,"header":"def check_pos(self, res, df, var, limit)","id":3543,"name":"check_pos","nodeType":"Function","startLoc":75,"text":"def check_pos(self, res, df, var, limit):\n\n        assert (res[var] != df[var]).all()\n        assert (res[var] < df[var] + limit / 2).all()\n        assert (res[var] > df[var] - limit / 2).all()"},{"col":4,"comment":"null","endLoc":1577,"header":"def test_univariate_plot_matplotlib(self)","id":3544,"name":"test_univariate_plot_matplotlib","nodeType":"Function","startLoc":1571,"text":"def test_univariate_plot_matplotlib(self):\n\n        bins = 10\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        g.plot_marginals(plt.hist, bins=bins)\n        assert len(g.ax_marg_x.patches) == bins\n        assert len(g.ax_marg_y.patches) == bins"},{"col":4,"comment":"null","endLoc":1590,"header":"def test_plot(self)","id":3545,"name":"test_plot","nodeType":"Function","startLoc":1579,"text":"def test_plot(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"x\", data=self.data)\n        g.plot(plt.plot, kdeplot)\n\n        x, y = g.ax_joint.lines[0].get_xydata().T\n        npt.assert_array_equal(x, self.x)\n        npt.assert_array_equal(y, self.x)\n\n        _, y1 = g.ax_marg_x.lines[0].get_xydata().T\n        y2, _ = g.ax_marg_y.lines[0].get_xydata().T\n        npt.assert_array_equal(y1, y2)"},{"col":4,"comment":"null","endLoc":113,"header":"def test_set_color(self)","id":3546,"name":"test_set_color","nodeType":"Function","startLoc":103,"text":"def test_set_color(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        m = Dots(color=\".25\")\n        p = Plot(x=x, y=y).add(m).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [m.color] * 3, .2)\n        self.check_colors(\"edge\", points, [m.color] * 3, 1)"},{"col":4,"comment":"null","endLoc":1601,"header":"def test_space(self)","id":3547,"name":"test_space","nodeType":"Function","startLoc":1592,"text":"def test_space(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data, space=0)\n\n        joint_bounds = g.ax_joint.bbox.bounds\n        marg_x_bounds = g.ax_marg_x.bbox.bounds\n        marg_y_bounds = g.ax_marg_y.bbox.bounds\n\n        assert joint_bounds[2] == marg_x_bounds[2]\n        assert joint_bounds[3] == marg_y_bounds[3]"},{"col":4,"comment":"null","endLoc":1626,"header":"@pytest.mark.parametrize(\n        \"as_vector\", [True, False],\n    )\n    def test_hue(self, long_df, as_vector)","id":3548,"name":"test_hue","nodeType":"Function","startLoc":1603,"text":"@pytest.mark.parametrize(\n        \"as_vector\", [True, False],\n    )\n    def test_hue(self, long_df, as_vector):\n\n        if as_vector:\n            data = None\n            x, y, hue = long_df[\"x\"], long_df[\"y\"], long_df[\"a\"]\n        else:\n            data = long_df\n            x, y, hue = \"x\", \"y\", \"a\"\n\n        g = ag.JointGrid(data=data, x=x, y=y, hue=hue)\n        g.plot_joint(scatterplot)\n        g.plot_marginals(histplot)\n\n        g2 = ag.JointGrid()\n        scatterplot(data=long_df, x=x, y=y, hue=hue, ax=g2.ax_joint)\n        histplot(data=long_df, x=x, hue=hue, ax=g2.ax_marg_x)\n        histplot(data=long_df, y=y, hue=hue, ax=g2.ax_marg_y)\n\n        assert_plots_equal(g.ax_joint, g2.ax_joint)\n        assert_plots_equal(g.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g.ax_marg_y, g2.ax_marg_y, labels=False)"},{"attributeType":"str","col":7,"comment":"null","endLoc":31,"id":3549,"name":"name","nodeType":"Attribute","startLoc":31,"text":"name"},{"col":4,"comment":"null","endLoc":126,"header":"def test_map_color(self)","id":3552,"name":"test_map_color","nodeType":"Function","startLoc":115,"text":"def test_map_color(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        c = [\"a\", \"b\", \"a\"]\n        p = Plot(x=x, y=y, color=c).add(Dots()).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, C1, C0], .2)\n        self.check_colors(\"edge\", points, [C0, C1, C0], 1)"},{"col":4,"comment":"null","endLoc":88,"header":"def test_default(self, df)","id":3553,"name":"test_default","nodeType":"Function","startLoc":81,"text":"def test_default(self, df):\n\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter()(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", 0.2 * df[\"width\"])\n        assert (res[\"x\"] - df[\"x\"]).abs().min() > 0"},{"col":4,"comment":"null","endLoc":1669,"header":"def test_refline(self)","id":3554,"name":"test_refline","nodeType":"Function","startLoc":1628,"text":"def test_refline(self):\n\n        g = ag.JointGrid(x=\"x\", y=\"y\", data=self.data)\n        g.plot(scatterplot, histplot)\n        g.refline()\n        assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines\n\n        refx = refy = 0.5\n        hline = np.array([[0, refy], [1, refy]])\n        vline = np.array([[refx, 0], [refx, 1]])\n        g.refline(x=refx, y=refy, joint=False, marginal=False)\n        assert not g.ax_joint.lines and not g.ax_marg_x.lines and not g.ax_marg_y.lines\n\n        g.refline(x=refx, y=refy)\n        assert g.ax_joint.lines[0].get_color() == '.5'\n        assert g.ax_joint.lines[0].get_linestyle() == '--'\n        assert len(g.ax_joint.lines) == 2\n        assert len(g.ax_marg_x.lines) == 1\n        assert len(g.ax_marg_y.lines) == 1\n        npt.assert_array_equal(g.ax_joint.lines[0].get_xydata(), vline)\n        npt.assert_array_equal(g.ax_joint.lines[1].get_xydata(), hline)\n        npt.assert_array_equal(g.ax_marg_x.lines[0].get_xydata(), vline)\n        npt.assert_array_equal(g.ax_marg_y.lines[0].get_xydata(), hline)\n\n        color, linestyle = 'red', '-'\n        g.refline(x=refx, marginal=False, color=color, linestyle=linestyle)\n        npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), vline)\n        assert g.ax_joint.lines[-1].get_color() == color\n        assert g.ax_joint.lines[-1].get_linestyle() == linestyle\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n        g.refline(x=refx, joint=False)\n        npt.assert_array_equal(g.ax_marg_x.lines[-1].get_xydata(), vline)\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines) + 1\n\n        g.refline(y=refy, joint=False)\n        npt.assert_array_equal(g.ax_marg_y.lines[-1].get_xydata(), hline)\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)\n\n        g.refline(y=refy, marginal=False)\n        npt.assert_array_equal(g.ax_joint.lines[-1].get_xydata(), hline)\n        assert len(g.ax_marg_x.lines) == len(g.ax_marg_y.lines)"},{"attributeType":"str","col":0,"comment":"null","endLoc":55,"id":3555,"name":"unicode","nodeType":"Attribute","startLoc":55,"text":"unicode"},{"attributeType":"null","col":4,"comment":"null","endLoc":34,"id":3556,"name":"obj","nodeType":"Attribute","startLoc":34,"text":"obj"},{"attributeType":"str","col":4,"comment":"null","endLoc":59,"id":3557,"name":"os_name","nodeType":"Attribute","startLoc":59,"text":"os_name"},{"col":4,"comment":"null","endLoc":139,"header":"def test_fill(self)","id":3558,"name":"test_fill","nodeType":"Function","startLoc":128,"text":"def test_fill(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        c = [\"a\", \"b\", \"a\"]\n        p = Plot(x=x, y=y, color=c).add(Dots(fill=False)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [C0, C1, C0], 0)\n        self.check_colors(\"edge\", points, [C0, C1, C0], 1)"},{"col":4,"comment":"Make the plot.","endLoc":1737,"header":"def plot(self, ax)","id":3559,"name":"plot","nodeType":"Function","startLoc":1732,"text":"def plot(self, ax):\n        \"\"\"Make the plot.\"\"\"\n        self.draw_points(ax)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"attributeType":"null","col":8,"comment":"null","endLoc":36,"id":3560,"name":"obj","nodeType":"Attribute","startLoc":36,"text":"obj"},{"col":4,"comment":"null","endLoc":150,"header":"def test_pointsize(self)","id":3561,"name":"test_pointsize","nodeType":"Function","startLoc":141,"text":"def test_pointsize(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        s = 3\n        p = Plot(x=x, y=y).add(Dots(pointsize=s)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        assert_array_equal(points.get_sizes(), [s ** 2] * 3)"},{"attributeType":"null","col":4,"comment":"null","endLoc":37,"id":3562,"name":"lines","nodeType":"Attribute","startLoc":37,"text":"lines"},{"col":4,"comment":"null","endLoc":97,"header":"def test_width(self, df)","id":3563,"name":"test_width","nodeType":"Function","startLoc":90,"text":"def test_width(self, df):\n\n        width = .4\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(width=width)(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", width * df[\"width\"])"},{"col":4,"comment":"null","endLoc":106,"header":"def test_x(self, df)","id":3564,"name":"test_x","nodeType":"Function","startLoc":99,"text":"def test_x(self, df):\n\n        val = .2\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(x=val)(df, groupby, orient, {})\n        self.check_same(res, df, \"y\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"x\", val)"},{"col":4,"comment":"null","endLoc":161,"header":"def test_stroke(self)","id":3565,"name":"test_stroke","nodeType":"Function","startLoc":152,"text":"def test_stroke(self):\n\n        x = [1, 2, 3]\n        y = [4, 5, 2]\n        s = 3\n        p = Plot(x=x, y=y).add(Dots(stroke=s)).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        self.check_offsets(points, x, y)\n        assert_array_equal(points.get_linewidths(), [s] * 3)"},{"attributeType":"str","col":4,"comment":"null","endLoc":1594,"id":3566,"name":"default_palette","nodeType":"Attribute","startLoc":1594,"text":"default_palette"},{"attributeType":"float","col":8,"comment":"null","endLoc":1629,"id":3567,"name":"dodge","nodeType":"Attribute","startLoc":1629,"text":"self.dodge"},{"col":4,"comment":"null","endLoc":115,"header":"def test_y(self, df)","id":3568,"name":"test_y","nodeType":"Function","startLoc":108,"text":"def test_y(self, df):\n\n        val = .2\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res = Jitter(y=val)(df, groupby, orient, {})\n        self.check_same(res, df, \"x\", \"grp2\", \"width\")\n        self.check_pos(res, df, \"y\", val)"},{"attributeType":"null","col":8,"comment":"null","endLoc":1632,"id":3569,"name":"errwidth","nodeType":"Attribute","startLoc":1632,"text":"self.errwidth"},{"attributeType":"Pattern","col":4,"comment":"null","endLoc":40,"id":3570,"name":"pat","nodeType":"Attribute","startLoc":40,"text":"pat"},{"fileName":"test_scales.py","filePath":"tests/_core","id":3571,"nodeType":"File","text":"import re\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\n\nimport pytest\nfrom numpy.testing import assert_array_equal\nfrom pandas.testing import assert_series_equal\n\nfrom seaborn._core.scales import (\n    Nominal,\n    Continuous,\n    Temporal,\n    PseudoAxis,\n)\nfrom seaborn._core.properties import (\n    IntervalProperty,\n    ObjectProperty,\n    Coordinate,\n    Alpha,\n    Color,\n    Fill,\n)\nfrom seaborn.palettes import color_palette\nfrom seaborn.external.version import Version\n\n\nclass TestContinuous:\n\n    @pytest.fixture\n    def x(self):\n        return pd.Series([1, 3, 9], name=\"x\", dtype=float)\n\n    def setup_ticks(self, x, *args, **kwargs):\n\n        s = Continuous().tick(*args, **kwargs)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(0, 1)\n        return a\n\n    def setup_labels(self, x, *args, **kwargs):\n\n        s = Continuous().label(*args, **kwargs)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(0, 1)\n        locs = a.major.locator()\n        return a, locs\n\n    def test_coordinate_defaults(self, x):\n\n        s = Continuous()._setup(x, Coordinate())\n        assert_series_equal(s(x), x)\n\n    def test_coordinate_transform(self, x):\n\n        s = Continuous(trans=\"log\")._setup(x, Coordinate())\n        assert_series_equal(s(x), np.log10(x))\n\n    def test_coordinate_transform_with_parameter(self, x):\n\n        s = Continuous(trans=\"pow3\")._setup(x, Coordinate())\n        assert_series_equal(s(x), np.power(x, 3))\n\n    def test_coordinate_transform_error(self, x):\n\n        s = Continuous(trans=\"bad\")\n        with pytest.raises(ValueError, match=\"Unknown value provided\"):\n            s._setup(x, Coordinate())\n\n    def test_interval_defaults(self, x):\n\n        s = Continuous()._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [0, .25, 1])\n\n    def test_interval_with_range(self, x):\n\n        s = Continuous((1, 3))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [1, 1.5, 3])\n\n    def test_interval_with_norm(self, x):\n\n        s = Continuous(norm=(3, 7))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [-.5, 0, 1.5])\n\n    def test_interval_with_range_norm_and_transform(self, x):\n\n        x = pd.Series([1, 10, 100])\n        # TODO param order?\n        s = Continuous((2, 3), (10, 100), \"log\")._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [1, 2, 3])\n\n    def test_color_defaults(self, x):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous()._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_named_values(self, x):\n\n        cmap = color_palette(\"viridis\", as_cmap=True)\n        s = Continuous(\"viridis\")._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_tuple_values(self, x):\n\n        cmap = color_palette(\"blend:b,g\", as_cmap=True)\n        s = Continuous((\"b\", \"g\"))._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_callable_values(self, x):\n\n        cmap = color_palette(\"light:r\", as_cmap=True)\n        s = Continuous(cmap)._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_with_norm(self, x):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous(norm=(3, 7))._setup(x, Color())\n        assert_array_equal(s(x), cmap([-.5, 0, 1.5])[:, :3])  # FIXME RGBA\n\n    def test_color_with_transform(self, x):\n\n        x = pd.Series([1, 10, 100], name=\"x\", dtype=float)\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous(trans=\"log\")._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .5, 1])[:, :3])  # FIXME RGBA\n\n    def test_tick_locator(self, x):\n\n        locs = [.2, .5, .8]\n        locator = mpl.ticker.FixedLocator(locs)\n        a = self.setup_ticks(x, locator)\n        assert_array_equal(a.major.locator(), locs)\n\n    def test_tick_locator_input_check(self, x):\n\n        err = \"Tick locator must be an instance of .*?, not .\"\n        with pytest.raises(TypeError, match=err):\n            Continuous().tick((1, 2))\n\n    def test_tick_upto(self, x):\n\n        for n in [2, 5, 10]:\n            a = self.setup_ticks(x, upto=n)\n            assert len(a.major.locator()) <= (n + 1)\n\n    def test_tick_every(self, x):\n\n        for d in [.05, .2, .5]:\n            a = self.setup_ticks(x, every=d)\n            assert np.allclose(np.diff(a.major.locator()), d)\n\n    def test_tick_every_between(self, x):\n\n        lo, hi = .2, .8\n        for d in [.05, .2, .5]:\n            a = self.setup_ticks(x, every=d, between=(lo, hi))\n            expected = np.arange(lo, hi + d, d)\n            assert_array_equal(a.major.locator(), expected)\n\n    def test_tick_at(self, x):\n\n        locs = [.2, .5, .9]\n        a = self.setup_ticks(x, at=locs)\n        assert_array_equal(a.major.locator(), locs)\n\n    def test_tick_count(self, x):\n\n        n = 8\n        a = self.setup_ticks(x, count=n)\n        assert_array_equal(a.major.locator(), np.linspace(0, 1, n))\n\n    def test_tick_count_between(self, x):\n\n        n = 5\n        lo, hi = .2, .7\n        a = self.setup_ticks(x, count=n, between=(lo, hi))\n        assert_array_equal(a.major.locator(), np.linspace(lo, hi, n))\n\n    def test_tick_minor(self, x):\n\n        n = 3\n        a = self.setup_ticks(x, count=2, minor=n)\n        # I am not sure why matplotlib's minor ticks include the\n        # largest major location but exclude the smalllest one ...\n        expected = np.linspace(0, 1, n + 2)[1:]\n        assert_array_equal(a.minor.locator(), expected)\n\n    def test_log_tick_default(self, x):\n\n        s = Continuous(trans=\"log\")._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(.5, 1050)\n        ticks = a.major.locator()\n        assert np.allclose(np.diff(np.log10(ticks)), 1)\n\n    def test_log_tick_upto(self, x):\n\n        n = 3\n        s = Continuous(trans=\"log\").tick(upto=n)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        assert a.major.locator.numticks == n\n\n    def test_log_tick_count(self, x):\n\n        with pytest.raises(RuntimeError, match=\"`count` requires\"):\n            Continuous(trans=\"log\").tick(count=4)\n\n        s = Continuous(trans=\"log\").tick(count=4, between=(1, 1000))\n        a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)\n        a.set_view_interval(.5, 1050)\n        assert_array_equal(a.major.locator(), [1, 10, 100, 1000])\n\n    def test_log_tick_every(self, x):\n\n        with pytest.raises(RuntimeError, match=\"`every` not supported\"):\n            Continuous(trans=\"log\").tick(every=2)\n\n    def test_symlog_tick_default(self, x):\n\n        s = Continuous(trans=\"symlog\")._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(-1050, 1050)\n        ticks = a.major.locator()\n        assert ticks[0] == -ticks[-1]\n        pos_ticks = np.sort(np.unique(np.abs(ticks)))\n        assert np.allclose(np.diff(np.log10(pos_ticks[1:])), 1)\n        assert pos_ticks[0] == 0\n\n    def test_label_formatter(self, x):\n\n        fmt = mpl.ticker.FormatStrFormatter(\"%.3f\")\n        a, locs = self.setup_labels(x, fmt)\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^\\d\\.\\d{3}$\", text)\n\n    def test_label_like_pattern(self, x):\n\n        a, locs = self.setup_labels(x, like=\".4f\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^\\d\\.\\d{4}$\", text)\n\n    def test_label_like_string(self, x):\n\n        a, locs = self.setup_labels(x, like=\"x = {x:.1f}\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^x = \\d\\.\\d$\", text)\n\n    def test_label_like_function(self, x):\n\n        a, locs = self.setup_labels(x, like=\"{:^5.1f}\".format)\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^ \\d\\.\\d $\", text)\n\n    def test_label_base(self, x):\n\n        a, locs = self.setup_labels(100 * x, base=2)\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:]:\n            assert not text or \"2^\" in text\n\n    def test_label_unit(self, x):\n\n        a, locs = self.setup_labels(1000 * x, unit=\"g\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:-1]:\n            assert re.match(r\"^\\d+ mg$\", text)\n\n    def test_label_unit_with_sep(self, x):\n\n        a, locs = self.setup_labels(1000 * x, unit=(\"\", \"g\"))\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:-1]:\n            assert re.match(r\"^\\d+mg$\", text)\n\n    def test_label_empty_unit(self, x):\n\n        a, locs = self.setup_labels(1000 * x, unit=\"\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:-1]:\n            assert re.match(r\"^\\d+m$\", text)\n\n    def test_label_base_from_transform(self, x):\n\n        s = Continuous(trans=\"log\")\n        a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)\n        a.set_view_interval(10, 1000)\n        label, = a.major.formatter.format_ticks([100])\n        assert r\"10^{2}\" in label\n\n    def test_label_type_checks(self):\n\n        s = Continuous()\n        with pytest.raises(TypeError, match=\"Label formatter must be\"):\n            s.label(\"{x}\")\n\n        with pytest.raises(TypeError, match=\"`like` must be\"):\n            s.label(like=2)\n\n\nclass TestNominal:\n\n    @pytest.fixture\n    def x(self):\n        return pd.Series([\"a\", \"c\", \"b\", \"c\"], name=\"x\")\n\n    @pytest.fixture\n    def y(self):\n        return pd.Series([1, -1.5, 3, -1.5], name=\"y\")\n\n    def test_coordinate_defaults(self, x):\n\n        s = Nominal()._setup(x, Coordinate())\n        assert_array_equal(s(x), np.array([0, 1, 2, 1], float))\n\n    def test_coordinate_with_order(self, x):\n\n        s = Nominal(order=[\"a\", \"b\", \"c\"])._setup(x, Coordinate())\n        assert_array_equal(s(x), np.array([0, 2, 1, 2], float))\n\n    def test_coordinate_with_subset_order(self, x):\n\n        s = Nominal(order=[\"c\", \"a\"])._setup(x, Coordinate())\n        assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))\n\n    def test_coordinate_axis(self, x):\n\n        ax = mpl.figure.Figure().subplots()\n        s = Nominal()._setup(x, Coordinate(), ax.xaxis)\n        assert_array_equal(s(x), np.array([0, 1, 2, 1], float))\n        f = ax.xaxis.get_major_formatter()\n        assert f.format_ticks([0, 1, 2]) == [\"a\", \"c\", \"b\"]\n\n    def test_coordinate_axis_with_order(self, x):\n\n        order = [\"a\", \"b\", \"c\"]\n        ax = mpl.figure.Figure().subplots()\n        s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)\n        assert_array_equal(s(x), np.array([0, 2, 1, 2], float))\n        f = ax.xaxis.get_major_formatter()\n        assert f.format_ticks([0, 1, 2]) == order\n\n    def test_coordinate_axis_with_subset_order(self, x):\n\n        order = [\"c\", \"a\"]\n        ax = mpl.figure.Figure().subplots()\n        s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)\n        assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))\n        f = ax.xaxis.get_major_formatter()\n        assert f.format_ticks([0, 1, 2]) == [*order, \"\"]\n\n    def test_coordinate_axis_with_category_dtype(self, x):\n\n        order = [\"b\", \"a\", \"d\", \"c\"]\n        x = x.astype(pd.CategoricalDtype(order))\n        ax = mpl.figure.Figure().subplots()\n        s = Nominal()._setup(x, Coordinate(), ax.xaxis)\n        assert_array_equal(s(x), np.array([1, 3, 0, 3], float))\n        f = ax.xaxis.get_major_formatter()\n        assert f.format_ticks([0, 1, 2, 3]) == order\n\n    def test_coordinate_numeric_data(self, y):\n\n        ax = mpl.figure.Figure().subplots()\n        s = Nominal()._setup(y, Coordinate(), ax.yaxis)\n        assert_array_equal(s(y), np.array([1, 0, 2, 0], float))\n        f = ax.yaxis.get_major_formatter()\n        assert f.format_ticks([0, 1, 2]) == [\"-1.5\", \"1.0\", \"3.0\"]\n\n    def test_coordinate_numeric_data_with_order(self, y):\n\n        order = [1, 4, -1.5]\n        ax = mpl.figure.Figure().subplots()\n        s = Nominal(order=order)._setup(y, Coordinate(), ax.yaxis)\n        assert_array_equal(s(y), np.array([0, 2, np.nan, 2], float))\n        f = ax.yaxis.get_major_formatter()\n        assert f.format_ticks([0, 1, 2]) == [\"1.0\", \"4.0\", \"-1.5\"]\n\n    def test_color_defaults(self, x):\n\n        s = Nominal()._setup(x, Color())\n        cs = color_palette()\n        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n    def test_color_named_palette(self, x):\n\n        pal = \"flare\"\n        s = Nominal(pal)._setup(x, Color())\n        cs = color_palette(pal, 3)\n        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n    def test_color_list_palette(self, x):\n\n        cs = color_palette(\"crest\", 3)\n        s = Nominal(cs)._setup(x, Color())\n        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n    def test_color_dict_palette(self, x):\n\n        cs = color_palette(\"crest\", 3)\n        pal = dict(zip(\"bac\", cs))\n        s = Nominal(pal)._setup(x, Color())\n        assert_array_equal(s(x), [cs[1], cs[2], cs[0], cs[2]])\n\n    def test_color_numeric_data(self, y):\n\n        s = Nominal()._setup(y, Color())\n        cs = color_palette()\n        assert_array_equal(s(y), [cs[1], cs[0], cs[2], cs[0]])\n\n    def test_color_numeric_with_order_subset(self, y):\n\n        s = Nominal(order=[-1.5, 1])._setup(y, Color())\n        c1, c2 = color_palette(n_colors=2)\n        null = (np.nan, np.nan, np.nan)\n        assert_array_equal(s(y), [c2, c1, null, c1])\n\n    @pytest.mark.xfail(reason=\"Need to sort out float/int order\")\n    def test_color_numeric_int_float_mix(self):\n\n        z = pd.Series([1, 2], name=\"z\")\n        s = Nominal(order=[1.0, 2])._setup(z, Color())\n        c1, c2 = color_palette(n_colors=2)\n        null = (np.nan, np.nan, np.nan)\n        assert_array_equal(s(z), [c1, null, c2])\n\n    def test_color_alpha_in_palette(self, x):\n\n        cs = [(.2, .2, .3, .5), (.1, .2, .3, 1), (.5, .6, .2, 0)]\n        s = Nominal(cs)._setup(x, Color())\n        assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n    def test_color_unknown_palette(self, x):\n\n        pal = \"not_a_palette\"\n        err = f\"{pal} is not a valid palette name\"\n        with pytest.raises(ValueError, match=err):\n            Nominal(pal)._setup(x, Color())\n\n    def test_object_defaults(self, x):\n\n        class MockProperty(ObjectProperty):\n            def _default_values(self, n):\n                return list(\"xyz\"[:n])\n\n        s = Nominal()._setup(x, MockProperty())\n        assert s(x) == [\"x\", \"y\", \"z\", \"y\"]\n\n    def test_object_list(self, x):\n\n        vs = [\"x\", \"y\", \"z\"]\n        s = Nominal(vs)._setup(x, ObjectProperty())\n        assert s(x) == [\"x\", \"y\", \"z\", \"y\"]\n\n    def test_object_dict(self, x):\n\n        vs = {\"a\": \"x\", \"b\": \"y\", \"c\": \"z\"}\n        s = Nominal(vs)._setup(x, ObjectProperty())\n        assert s(x) == [\"x\", \"z\", \"y\", \"z\"]\n\n    def test_object_order(self, x):\n\n        vs = [\"x\", \"y\", \"z\"]\n        s = Nominal(vs, order=[\"c\", \"a\", \"b\"])._setup(x, ObjectProperty())\n        assert s(x) == [\"y\", \"x\", \"z\", \"x\"]\n\n    def test_object_order_subset(self, x):\n\n        vs = [\"x\", \"y\"]\n        s = Nominal(vs, order=[\"a\", \"c\"])._setup(x, ObjectProperty())\n        assert s(x) == [\"x\", \"y\", None, \"y\"]\n\n    def test_objects_that_are_weird(self, x):\n\n        vs = [(\"x\", 1), (None, None, 0), {}]\n        s = Nominal(vs)._setup(x, ObjectProperty())\n        assert s(x) == [vs[0], vs[1], vs[2], vs[1]]\n\n    def test_alpha_default(self, x):\n\n        s = Nominal()._setup(x, Alpha())\n        assert_array_equal(s(x), [.95, .625, .3, .625])\n\n    def test_fill(self):\n\n        x = pd.Series([\"a\", \"a\", \"b\", \"a\"], name=\"x\")\n        s = Nominal()._setup(x, Fill())\n        assert_array_equal(s(x), [True, True, False, True])\n\n    def test_fill_dict(self):\n\n        x = pd.Series([\"a\", \"a\", \"b\", \"a\"], name=\"x\")\n        vs = {\"a\": False, \"b\": True}\n        s = Nominal(vs)._setup(x, Fill())\n        assert_array_equal(s(x), [False, False, True, False])\n\n    def test_fill_nunique_warning(self):\n\n        x = pd.Series([\"a\", \"b\", \"c\", \"a\", \"b\"], name=\"x\")\n        with pytest.warns(UserWarning, match=\"The variable assigned to fill\"):\n            s = Nominal()._setup(x, Fill())\n        assert_array_equal(s(x), [True, False, True, True, False])\n\n    def test_interval_defaults(self, x):\n\n        class MockProperty(IntervalProperty):\n            _default_range = (1, 2)\n\n        s = Nominal()._setup(x, MockProperty())\n        assert_array_equal(s(x), [2, 1.5, 1, 1.5])\n\n    def test_interval_tuple(self, x):\n\n        s = Nominal((1, 2))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [2, 1.5, 1, 1.5])\n\n    def test_interval_tuple_numeric(self, y):\n\n        s = Nominal((1, 2))._setup(y, IntervalProperty())\n        assert_array_equal(s(y), [1.5, 2, 1, 2])\n\n    def test_interval_list(self, x):\n\n        vs = [2, 5, 4]\n        s = Nominal(vs)._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [2, 5, 4, 5])\n\n    def test_interval_dict(self, x):\n\n        vs = {\"a\": 3, \"b\": 4, \"c\": 6}\n        s = Nominal(vs)._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [3, 6, 4, 6])\n\n    def test_interval_with_transform(self, x):\n\n        class MockProperty(IntervalProperty):\n            _forward = np.square\n            _inverse = np.sqrt\n\n        s = Nominal((2, 4))._setup(x, MockProperty())\n        assert_array_equal(s(x), [4, np.sqrt(10), 2, np.sqrt(10)])\n\n\nclass TestTemporal:\n\n    @pytest.fixture\n    def t(self):\n        dates = pd.to_datetime([\"1972-09-27\", \"1975-06-24\", \"1980-12-14\"])\n        return pd.Series(dates, name=\"x\")\n\n    @pytest.fixture\n    def x(self, t):\n        return pd.Series(mpl.dates.date2num(t), name=t.name)\n\n    def test_coordinate_defaults(self, t, x):\n\n        s = Temporal()._setup(t, Coordinate())\n        assert_array_equal(s(t), x)\n\n    def test_interval_defaults(self, t, x):\n\n        s = Temporal()._setup(t, IntervalProperty())\n        normed = (x - x.min()) / (x.max() - x.min())\n        assert_array_equal(s(t), normed)\n\n    def test_interval_with_range(self, t, x):\n\n        values = (1, 3)\n        s = Temporal((1, 3))._setup(t, IntervalProperty())\n        normed = (x - x.min()) / (x.max() - x.min())\n        expected = normed * (values[1] - values[0]) + values[0]\n        assert_array_equal(s(t), expected)\n\n    def test_interval_with_norm(self, t, x):\n\n        norm = t[1], t[2]\n        s = Temporal(norm=norm)._setup(t, IntervalProperty())\n        n = mpl.dates.date2num(norm)\n        normed = (x - n[0]) / (n[1] - n[0])\n        assert_array_equal(s(t), normed)\n\n    def test_color_defaults(self, t, x):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Temporal()._setup(t, Color())\n        normed = (x - x.min()) / (x.max() - x.min())\n        assert_array_equal(s(t), cmap(normed)[:, :3])  # FIXME RGBA\n\n    def test_color_named_values(self, t, x):\n\n        name = \"viridis\"\n        cmap = color_palette(name, as_cmap=True)\n        s = Temporal(name)._setup(t, Color())\n        normed = (x - x.min()) / (x.max() - x.min())\n        assert_array_equal(s(t), cmap(normed)[:, :3])  # FIXME RGBA\n\n    def test_coordinate_axis(self, t, x):\n\n        ax = mpl.figure.Figure().subplots()\n        s = Temporal()._setup(t, Coordinate(), ax.xaxis)\n        assert_array_equal(s(t), x)\n        locator = ax.xaxis.get_major_locator()\n        formatter = ax.xaxis.get_major_formatter()\n        assert isinstance(locator, mpl.dates.AutoDateLocator)\n        assert isinstance(formatter, mpl.dates.AutoDateFormatter)\n\n    @pytest.mark.skipif(\n        Version(mpl.__version__) < Version(\"3.3.0\"),\n        reason=\"Test requires new matplotlib date epoch.\"\n    )\n    def test_tick_locator(self, t):\n\n        locator = mpl.dates.YearLocator(month=3, day=15)\n        s = Temporal().tick(locator)\n        a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)\n        a.set_view_interval(0, 365)\n        assert 73 in a.major.locator()\n\n    def test_tick_upto(self, t, x):\n\n        n = 8\n        ax = mpl.figure.Figure().subplots()\n        Temporal().tick(upto=n)._setup(t, Coordinate(), ax.xaxis)\n        locator = ax.xaxis.get_major_locator()\n        assert set(locator.maxticks.values()) == {n}\n\n    @pytest.mark.skipif(\n        Version(mpl.__version__) < Version(\"3.3.0\"),\n        reason=\"Test requires new matplotlib date epoch.\"\n    )\n    def test_label_formatter(self, t):\n\n        formatter = mpl.dates.DateFormatter(\"%Y\")\n        s = Temporal().label(formatter)\n        a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)\n        a.set_view_interval(10, 1000)\n        label, = a.major.formatter.format_ticks([100])\n        assert label == \"1970\"\n\n    def test_label_concise(self, t, x):\n\n        ax = mpl.figure.Figure().subplots()\n        Temporal().label(concise=True)._setup(t, Coordinate(), ax.xaxis)\n        formatter = ax.xaxis.get_major_formatter()\n        assert isinstance(formatter, mpl.dates.ConciseDateFormatter)\n"},{"col":4,"comment":"null","endLoc":125,"header":"def test_seed(self, df)","id":3572,"name":"test_seed","nodeType":"Function","startLoc":117,"text":"def test_seed(self, df):\n\n        kws = dict(width=.2, y=.1, seed=0)\n        orient = \"x\"\n        groupby = self.get_groupby(df, orient)\n        res1 = Jitter(**kws)(df, groupby, orient, {})\n        res2 = Jitter(**kws)(df, groupby, orient, {})\n        for var in \"xy\":\n            assert_series_equal(res1[var], res2[var])"},{"className":"TestContinuous","col":0,"comment":"null","endLoc":304,"id":3573,"nodeType":"Class","startLoc":29,"text":"class TestContinuous:\n\n    @pytest.fixture\n    def x(self):\n        return pd.Series([1, 3, 9], name=\"x\", dtype=float)\n\n    def setup_ticks(self, x, *args, **kwargs):\n\n        s = Continuous().tick(*args, **kwargs)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(0, 1)\n        return a\n\n    def setup_labels(self, x, *args, **kwargs):\n\n        s = Continuous().label(*args, **kwargs)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(0, 1)\n        locs = a.major.locator()\n        return a, locs\n\n    def test_coordinate_defaults(self, x):\n\n        s = Continuous()._setup(x, Coordinate())\n        assert_series_equal(s(x), x)\n\n    def test_coordinate_transform(self, x):\n\n        s = Continuous(trans=\"log\")._setup(x, Coordinate())\n        assert_series_equal(s(x), np.log10(x))\n\n    def test_coordinate_transform_with_parameter(self, x):\n\n        s = Continuous(trans=\"pow3\")._setup(x, Coordinate())\n        assert_series_equal(s(x), np.power(x, 3))\n\n    def test_coordinate_transform_error(self, x):\n\n        s = Continuous(trans=\"bad\")\n        with pytest.raises(ValueError, match=\"Unknown value provided\"):\n            s._setup(x, Coordinate())\n\n    def test_interval_defaults(self, x):\n\n        s = Continuous()._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [0, .25, 1])\n\n    def test_interval_with_range(self, x):\n\n        s = Continuous((1, 3))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [1, 1.5, 3])\n\n    def test_interval_with_norm(self, x):\n\n        s = Continuous(norm=(3, 7))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [-.5, 0, 1.5])\n\n    def test_interval_with_range_norm_and_transform(self, x):\n\n        x = pd.Series([1, 10, 100])\n        # TODO param order?\n        s = Continuous((2, 3), (10, 100), \"log\")._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [1, 2, 3])\n\n    def test_color_defaults(self, x):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous()._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_named_values(self, x):\n\n        cmap = color_palette(\"viridis\", as_cmap=True)\n        s = Continuous(\"viridis\")._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_tuple_values(self, x):\n\n        cmap = color_palette(\"blend:b,g\", as_cmap=True)\n        s = Continuous((\"b\", \"g\"))._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_callable_values(self, x):\n\n        cmap = color_palette(\"light:r\", as_cmap=True)\n        s = Continuous(cmap)._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA\n\n    def test_color_with_norm(self, x):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous(norm=(3, 7))._setup(x, Color())\n        assert_array_equal(s(x), cmap([-.5, 0, 1.5])[:, :3])  # FIXME RGBA\n\n    def test_color_with_transform(self, x):\n\n        x = pd.Series([1, 10, 100], name=\"x\", dtype=float)\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous(trans=\"log\")._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .5, 1])[:, :3])  # FIXME RGBA\n\n    def test_tick_locator(self, x):\n\n        locs = [.2, .5, .8]\n        locator = mpl.ticker.FixedLocator(locs)\n        a = self.setup_ticks(x, locator)\n        assert_array_equal(a.major.locator(), locs)\n\n    def test_tick_locator_input_check(self, x):\n\n        err = \"Tick locator must be an instance of .*?, not .\"\n        with pytest.raises(TypeError, match=err):\n            Continuous().tick((1, 2))\n\n    def test_tick_upto(self, x):\n\n        for n in [2, 5, 10]:\n            a = self.setup_ticks(x, upto=n)\n            assert len(a.major.locator()) <= (n + 1)\n\n    def test_tick_every(self, x):\n\n        for d in [.05, .2, .5]:\n            a = self.setup_ticks(x, every=d)\n            assert np.allclose(np.diff(a.major.locator()), d)\n\n    def test_tick_every_between(self, x):\n\n        lo, hi = .2, .8\n        for d in [.05, .2, .5]:\n            a = self.setup_ticks(x, every=d, between=(lo, hi))\n            expected = np.arange(lo, hi + d, d)\n            assert_array_equal(a.major.locator(), expected)\n\n    def test_tick_at(self, x):\n\n        locs = [.2, .5, .9]\n        a = self.setup_ticks(x, at=locs)\n        assert_array_equal(a.major.locator(), locs)\n\n    def test_tick_count(self, x):\n\n        n = 8\n        a = self.setup_ticks(x, count=n)\n        assert_array_equal(a.major.locator(), np.linspace(0, 1, n))\n\n    def test_tick_count_between(self, x):\n\n        n = 5\n        lo, hi = .2, .7\n        a = self.setup_ticks(x, count=n, between=(lo, hi))\n        assert_array_equal(a.major.locator(), np.linspace(lo, hi, n))\n\n    def test_tick_minor(self, x):\n\n        n = 3\n        a = self.setup_ticks(x, count=2, minor=n)\n        # I am not sure why matplotlib's minor ticks include the\n        # largest major location but exclude the smalllest one ...\n        expected = np.linspace(0, 1, n + 2)[1:]\n        assert_array_equal(a.minor.locator(), expected)\n\n    def test_log_tick_default(self, x):\n\n        s = Continuous(trans=\"log\")._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(.5, 1050)\n        ticks = a.major.locator()\n        assert np.allclose(np.diff(np.log10(ticks)), 1)\n\n    def test_log_tick_upto(self, x):\n\n        n = 3\n        s = Continuous(trans=\"log\").tick(upto=n)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        assert a.major.locator.numticks == n\n\n    def test_log_tick_count(self, x):\n\n        with pytest.raises(RuntimeError, match=\"`count` requires\"):\n            Continuous(trans=\"log\").tick(count=4)\n\n        s = Continuous(trans=\"log\").tick(count=4, between=(1, 1000))\n        a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)\n        a.set_view_interval(.5, 1050)\n        assert_array_equal(a.major.locator(), [1, 10, 100, 1000])\n\n    def test_log_tick_every(self, x):\n\n        with pytest.raises(RuntimeError, match=\"`every` not supported\"):\n            Continuous(trans=\"log\").tick(every=2)\n\n    def test_symlog_tick_default(self, x):\n\n        s = Continuous(trans=\"symlog\")._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(-1050, 1050)\n        ticks = a.major.locator()\n        assert ticks[0] == -ticks[-1]\n        pos_ticks = np.sort(np.unique(np.abs(ticks)))\n        assert np.allclose(np.diff(np.log10(pos_ticks[1:])), 1)\n        assert pos_ticks[0] == 0\n\n    def test_label_formatter(self, x):\n\n        fmt = mpl.ticker.FormatStrFormatter(\"%.3f\")\n        a, locs = self.setup_labels(x, fmt)\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^\\d\\.\\d{3}$\", text)\n\n    def test_label_like_pattern(self, x):\n\n        a, locs = self.setup_labels(x, like=\".4f\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^\\d\\.\\d{4}$\", text)\n\n    def test_label_like_string(self, x):\n\n        a, locs = self.setup_labels(x, like=\"x = {x:.1f}\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^x = \\d\\.\\d$\", text)\n\n    def test_label_like_function(self, x):\n\n        a, locs = self.setup_labels(x, like=\"{:^5.1f}\".format)\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels:\n            assert re.match(r\"^ \\d\\.\\d $\", text)\n\n    def test_label_base(self, x):\n\n        a, locs = self.setup_labels(100 * x, base=2)\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:]:\n            assert not text or \"2^\" in text\n\n    def test_label_unit(self, x):\n\n        a, locs = self.setup_labels(1000 * x, unit=\"g\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:-1]:\n            assert re.match(r\"^\\d+ mg$\", text)\n\n    def test_label_unit_with_sep(self, x):\n\n        a, locs = self.setup_labels(1000 * x, unit=(\"\", \"g\"))\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:-1]:\n            assert re.match(r\"^\\d+mg$\", text)\n\n    def test_label_empty_unit(self, x):\n\n        a, locs = self.setup_labels(1000 * x, unit=\"\")\n        labels = a.major.formatter.format_ticks(locs)\n        for text in labels[1:-1]:\n            assert re.match(r\"^\\d+m$\", text)\n\n    def test_label_base_from_transform(self, x):\n\n        s = Continuous(trans=\"log\")\n        a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)\n        a.set_view_interval(10, 1000)\n        label, = a.major.formatter.format_ticks([100])\n        assert r\"10^{2}\" in label\n\n    def test_label_type_checks(self):\n\n        s = Continuous()\n        with pytest.raises(TypeError, match=\"Label formatter must be\"):\n            s.label(\"{x}\")\n\n        with pytest.raises(TypeError, match=\"`like` must be\"):\n            s.label(like=2)"},{"attributeType":"str","col":8,"comment":"null","endLoc":61,"id":3574,"name":"system","nodeType":"Attribute","startLoc":61,"text":"system"},{"attributeType":"str","col":8,"comment":"null","endLoc":63,"id":3575,"name":"system","nodeType":"Attribute","startLoc":63,"text":"system"},{"attributeType":"str","col":8,"comment":"null","endLoc":68,"id":3576,"name":"system","nodeType":"Attribute","startLoc":68,"text":"system"},{"attributeType":"str","col":4,"comment":"null","endLoc":70,"id":3577,"name":"system","nodeType":"Attribute","startLoc":70,"text":"system"},{"col":4,"comment":"null","endLoc":33,"header":"@pytest.fixture\n    def x(self)","id":3578,"name":"x","nodeType":"Function","startLoc":31,"text":"@pytest.fixture\n    def x(self):\n        return pd.Series([1, 3, 9], name=\"x\", dtype=float)"},{"attributeType":"function","col":8,"comment":"null","endLoc":235,"id":3579,"name":"_get_win_folder","nodeType":"Attribute","startLoc":235,"text":"_get_win_folder"},{"col":4,"comment":"null","endLoc":40,"header":"def setup_ticks(self, x, *args, **kwargs)","id":3580,"name":"setup_ticks","nodeType":"Function","startLoc":35,"text":"def setup_ticks(self, x, *args, **kwargs):\n\n        s = Continuous().tick(*args, **kwargs)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(0, 1)\n        return a"},{"col":0,"comment":"","endLoc":36,"header":"appdirs.py#","id":3581,"name":"","nodeType":"Function","startLoc":7,"text":"\"\"\"\nThis file is directly from\nhttps://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py\n\nThe license of https://github.com/ActiveState/appdirs copied below:\n\n\n# This is the MIT license\n\nCopyright (c) 2010 ActiveState Software Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\"\"\"Utilities for determining application-specific dirs.\n\nSee  for details and usage.\n\"\"\"\n\n__version__ = \"1.4.4\"\n\n__version_info__ = tuple(int(segment) for segment in __version__.split(\".\"))\n\nunicode = str\n\nif sys.platform.startswith('java'):\n    import platform\n    os_name = platform.java_ver()[3][0]\n    if os_name.startswith('Windows'): # \"Windows XP\", \"Windows 7\", etc.\n        system = 'win32'\n    elif os_name.startswith('Mac'): # \"Mac OS X\", etc.\n        system = 'darwin'\n    else: # \"Linux\", \"SunOS\", \"FreeBSD\", etc.\n        # Setting this to \"linux2\" is not ideal, but only Windows or Mac\n        # are actually checked for and the rest of the module expects\n        # *sys.platform* style strings.\n        system = 'linux2'\nelse:\n    system = sys.platform\n\nif system == \"win32\":\n    try:\n        import win32com.shell\n        _get_win_folder = _get_win_folder_with_pywin32\n    except ImportError:\n        try:\n            from ctypes import windll\n            _get_win_folder = _get_win_folder_with_ctypes\n        except ImportError:\n            try:\n                import com.sun.jna\n                _get_win_folder = _get_win_folder_with_jna\n            except ImportError:\n                _get_win_folder = _get_win_folder_from_registry"},{"col":4,"comment":"null","endLoc":178,"header":"def test_filled_unfilled_mix(self)","id":3583,"name":"test_filled_unfilled_mix","nodeType":"Function","startLoc":163,"text":"def test_filled_unfilled_mix(self):\n\n        x = [1, 2]\n        y = [4, 5]\n        marker = [\"a\", \"b\"]\n        shapes = [\"o\", \"x\"]\n\n        mark = Dots(stroke=2)\n        p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot()\n        ax = p._figure.axes[0]\n        points, = ax.collections\n        C0, C1, *_ = p._theme[\"axes.prop_cycle\"].by_key()[\"color\"]\n        self.check_offsets(points, x, y)\n        self.check_colors(\"face\", points, [to_rgba(C0, .2), to_rgba(C0, 0)], None)\n        self.check_colors(\"edge\", points, [C0, C0], 1)\n        assert_array_equal(points.get_linewidths(), [mark.stroke] * 2)"},{"attributeType":"null","col":4,"comment":"null","endLoc":42,"id":3584,"name":"nb","nodeType":"Attribute","startLoc":42,"text":"nb"},{"attributeType":"str","col":4,"comment":"null","endLoc":45,"id":3585,"name":"cell_type","nodeType":"Attribute","startLoc":45,"text":"cell_type"},{"attributeType":"list","col":4,"comment":"null","endLoc":46,"id":3586,"name":"cell","nodeType":"Attribute","startLoc":46,"text":"cell"},{"attributeType":"null","col":8,"comment":"null","endLoc":1631,"id":3587,"name":"scale","nodeType":"Attribute","startLoc":1631,"text":"self.scale"},{"attributeType":"null","col":4,"comment":"null","endLoc":1463,"id":3588,"name":"rs","nodeType":"Attribute","startLoc":1463,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":1464,"id":3589,"name":"x","nodeType":"Attribute","startLoc":1464,"text":"x"},{"attributeType":"null","col":4,"comment":"null","endLoc":1465,"id":3590,"name":"y","nodeType":"Attribute","startLoc":1465,"text":"y"},{"attributeType":"null","col":4,"comment":"null","endLoc":1466,"id":3591,"name":"x_na","nodeType":"Attribute","startLoc":1466,"text":"x_na"},{"attributeType":"null","col":4,"comment":"null","endLoc":1469,"id":3592,"name":"data","nodeType":"Attribute","startLoc":1469,"text":"data"},{"attributeType":"list","col":8,"comment":"null","endLoc":1626,"id":3593,"name":"linestyles","nodeType":"Attribute","startLoc":1626,"text":"self.linestyles"},{"className":"TestJointPlot","col":0,"comment":"null","endLoc":1847,"id":3594,"nodeType":"Class","startLoc":1672,"text":"class TestJointPlot:\n\n    rs = np.random.RandomState(sum(map(ord, \"jointplot\")))\n    x = rs.randn(100)\n    y = rs.randn(100)\n    data = pd.DataFrame(dict(x=x, y=y))\n\n    def test_scatter(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data)\n        assert len(g.ax_joint.collections) == 1\n\n        x, y = g.ax_joint.collections[0].get_offsets().T\n        assert_array_equal(self.x, x)\n        assert_array_equal(self.y, y)\n\n        assert_array_almost_equal(\n            [b.get_x() for b in g.ax_marg_x.patches],\n            np.histogram_bin_edges(self.x, \"auto\")[:-1],\n        )\n\n        assert_array_almost_equal(\n            [b.get_y() for b in g.ax_marg_y.patches],\n            np.histogram_bin_edges(self.y, \"auto\")[:-1],\n        )\n\n    def test_scatter_hue(self, long_df):\n\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\")\n\n        g2 = ag.JointGrid()\n        scatterplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", ax=g2.ax_joint)\n        kdeplot(data=long_df, x=\"x\", hue=\"a\", ax=g2.ax_marg_x, fill=True)\n        kdeplot(data=long_df, y=\"y\", hue=\"a\", ax=g2.ax_marg_y, fill=True)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n    def test_reg(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"reg\")\n        assert len(g.ax_joint.collections) == 2\n\n        x, y = g.ax_joint.collections[0].get_offsets().T\n        assert_array_equal(self.x, x)\n        assert_array_equal(self.y, y)\n\n        assert g.ax_marg_x.patches\n        assert g.ax_marg_y.patches\n\n        assert g.ax_marg_x.lines\n        assert g.ax_marg_y.lines\n\n    def test_resid(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"resid\")\n        assert g.ax_joint.collections\n        assert g.ax_joint.lines\n        assert not g.ax_marg_x.lines\n        assert not g.ax_marg_y.lines\n\n    def test_hist(self, long_df):\n\n        bins = 3, 6\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", kind=\"hist\", bins=bins)\n\n        g2 = ag.JointGrid()\n        histplot(data=long_df, x=\"x\", y=\"y\", ax=g2.ax_joint, bins=bins)\n        histplot(data=long_df, x=\"x\", ax=g2.ax_marg_x, bins=bins[0])\n        histplot(data=long_df, y=\"y\", ax=g2.ax_marg_y, bins=bins[1])\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n    def test_hex(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"hex\")\n        assert g.ax_joint.collections\n        assert g.ax_marg_x.patches\n        assert g.ax_marg_y.patches\n\n    def test_kde(self, long_df):\n\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", kind=\"kde\")\n\n        g2 = ag.JointGrid()\n        kdeplot(data=long_df, x=\"x\", y=\"y\", ax=g2.ax_joint)\n        kdeplot(data=long_df, x=\"x\", ax=g2.ax_marg_x)\n        kdeplot(data=long_df, y=\"y\", ax=g2.ax_marg_y)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n    def test_kde_hue(self, long_df):\n\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", kind=\"kde\")\n\n        g2 = ag.JointGrid()\n        kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", ax=g2.ax_joint)\n        kdeplot(data=long_df, x=\"x\", hue=\"a\", ax=g2.ax_marg_x)\n        kdeplot(data=long_df, y=\"y\", hue=\"a\", ax=g2.ax_marg_y)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n    def test_color(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, color=\"purple\")\n\n        scatter_color = g.ax_joint.collections[0].get_facecolor()\n        assert_colors_equal(scatter_color, \"purple\")\n\n        hist_color = g.ax_marg_x.patches[0].get_facecolor()[:3]\n        assert_colors_equal(hist_color, \"purple\")\n\n    def test_palette(self, long_df):\n\n        kws = dict(data=long_df, hue=\"a\", palette=\"Set2\")\n\n        g1 = ag.jointplot(x=\"x\", y=\"y\", **kws)\n\n        g2 = ag.JointGrid()\n        scatterplot(x=\"x\", y=\"y\", ax=g2.ax_joint, **kws)\n        kdeplot(x=\"x\", ax=g2.ax_marg_x, fill=True, **kws)\n        kdeplot(y=\"y\", ax=g2.ax_marg_y, fill=True, **kws)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)\n\n    def test_hex_customise(self):\n\n        # test that default gridsize can be overridden\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"hex\",\n                         joint_kws=dict(gridsize=5))\n        assert len(g.ax_joint.collections) == 1\n        a = g.ax_joint.collections[0].get_array()\n        assert a.shape[0] == 28  # 28 hexagons expected for gridsize 5\n\n    def test_bad_kind(self):\n\n        with pytest.raises(ValueError):\n            ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"not_a_kind\")\n\n    def test_unsupported_hue_kind(self):\n\n        for kind in [\"reg\", \"resid\", \"hex\"]:\n            with pytest.raises(ValueError):\n                ag.jointplot(x=\"x\", y=\"y\", hue=\"a\", data=self.data, kind=kind)\n\n    def test_leaky_dict(self):\n        # Validate input dicts are unchanged by jointplot plotting function\n\n        for kwarg in (\"joint_kws\", \"marginal_kws\"):\n            for kind in (\"hex\", \"kde\", \"resid\", \"reg\", \"scatter\"):\n                empty_dict = {}\n                ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=kind,\n                             **{kwarg: empty_dict})\n                assert empty_dict == {}\n\n    def test_distplot_kwarg_warning(self, long_df):\n\n        with pytest.warns(UserWarning):\n            g = ag.jointplot(data=long_df, x=\"x\", y=\"y\", marginal_kws=dict(rug=True))\n        assert g.ax_marg_x.patches\n\n    def test_ax_warning(self, long_df):\n\n        ax = plt.gca()\n        with pytest.warns(UserWarning):\n            g = ag.jointplot(data=long_df, x=\"x\", y=\"y\", ax=ax)\n        assert g.ax_joint.collections"},{"col":4,"comment":"null","endLoc":1696,"header":"def test_scatter(self)","id":3595,"name":"test_scatter","nodeType":"Function","startLoc":1679,"text":"def test_scatter(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data)\n        assert len(g.ax_joint.collections) == 1\n\n        x, y = g.ax_joint.collections[0].get_offsets().T\n        assert_array_equal(self.x, x)\n        assert_array_equal(self.y, y)\n\n        assert_array_almost_equal(\n            [b.get_x() for b in g.ax_marg_x.patches],\n            np.histogram_bin_edges(self.x, \"auto\")[:-1],\n        )\n\n        assert_array_almost_equal(\n            [b.get_y() for b in g.ax_marg_y.patches],\n            np.histogram_bin_edges(self.y, \"auto\")[:-1],\n        )"},{"className":"TestDodge","col":0,"comment":"null","endLoc":270,"id":3596,"nodeType":"Class","startLoc":128,"text":"class TestDodge(MoveFixtures):\n\n    # First some very simple toy examples\n\n    def test_default(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge()(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3]),\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1.2])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])\n\n    def test_fill(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"fill\")(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3]),\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .8])\n\n    def test_drop(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(\"drop\")(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])\n\n    def test_gap(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(gap=.25)(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1.2])\n        assert_array_almost_equal(res[\"width\"], [.3, .3, .3])\n\n    def test_widths_default(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge()(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1.1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .2])\n\n    def test_widths_fill(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"fill\")(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .4])\n\n    def test_widths_drop(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"drop\")(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .2])\n\n    def test_faceted_default(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge()(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, .8, .2, .8, 2.2])\n        assert_array_almost_equal(res[\"width\"], [.4] * 6)\n\n    def test_faceted_fill(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge(empty=\"fill\")(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1, 0, 1, 2])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .8, .8, .8, .8])\n\n    def test_faceted_drop(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge(empty=\"drop\")(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1, 0, 1, 2])\n        assert_array_almost_equal(res[\"width\"], [.4] * 6)\n\n    def test_orient(self, toy_df):\n\n        df = toy_df.assign(x=toy_df[\"y\"], y=toy_df[\"x\"])\n\n        groupby = GroupBy([\"y\", \"grp\"])\n        res = Dodge(\"drop\")(df, groupby, \"y\", {})\n\n        assert_array_equal(res[\"x\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"y\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])\n\n    # Now tests with slightly more complicated data\n\n    @pytest.mark.parametrize(\"grp\", [\"grp2\", \"grp3\"])\n    def test_single_semantic(self, df, grp):\n\n        groupby = GroupBy([\"x\", grp])\n        res = Dodge()(df, groupby, \"x\", {})\n\n        levels = categorical_order(df[grp])\n        w, n = 0.8, len(levels)\n\n        shifts = np.linspace(0, w - w / n, n)\n        shifts -= shifts.mean()\n\n        assert_series_equal(res[\"y\"], df[\"y\"])\n        assert_series_equal(res[\"width\"], df[\"width\"] / n)\n\n        for val, shift in zip(levels, shifts):\n            rows = df[grp] == val\n            assert_series_equal(res.loc[rows, \"x\"], df.loc[rows, \"x\"] + shift)\n\n    def test_two_semantics(self, df):\n\n        groupby = GroupBy([\"x\", \"grp2\", \"grp3\"])\n        res = Dodge()(df, groupby, \"x\", {})\n\n        levels = categorical_order(df[\"grp2\"]), categorical_order(df[\"grp3\"])\n        w, n = 0.8, len(levels[0]) * len(levels[1])\n\n        shifts = np.linspace(0, w - w / n, n)\n        shifts -= shifts.mean()\n\n        assert_series_equal(res[\"y\"], df[\"y\"])\n        assert_series_equal(res[\"width\"], df[\"width\"] / n)\n\n        for (v2, v3), shift in zip(product(*levels), shifts):\n            rows = (df[\"grp2\"] == v2) & (df[\"grp3\"] == v3)\n            assert_series_equal(res.loc[rows, \"x\"], df.loc[rows, \"x\"] + shift)"},{"col":4,"comment":"null","endLoc":139,"header":"def test_default(self, toy_df)","id":3597,"name":"test_default","nodeType":"Function","startLoc":132,"text":"def test_default(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge()(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3]),\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1.2])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])"},{"fileName":"test_base.py","filePath":"tests/_marks","id":3598,"nodeType":"File","text":"from dataclasses import dataclass\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._marks.base import Mark, Mappable, resolve_color\n\n\nclass TestMappable:\n\n    def mark(self, **features):\n\n        @dataclass\n        class MockMark(Mark):\n            linewidth: float = Mappable(rc=\"lines.linewidth\")\n            pointsize: float = Mappable(4)\n            color: str = Mappable(\"C0\")\n            fillcolor: str = Mappable(depend=\"color\")\n            alpha: float = Mappable(1)\n            fillalpha: float = Mappable(depend=\"alpha\")\n\n        m = MockMark(**features)\n        return m\n\n    def test_repr(self):\n\n        assert str(Mappable(.5)) == \"<0.5>\"\n        assert str(Mappable(\"CO\")) == \"<'CO'>\"\n        assert str(Mappable(rc=\"lines.linewidth\")) == \"\"\n        assert str(Mappable(depend=\"color\")) == \"\"\n        assert str(Mappable(auto=True)) == \"\"\n\n    def test_input_checks(self):\n\n        with pytest.raises(AssertionError):\n            Mappable(rc=\"bogus.parameter\")\n        with pytest.raises(AssertionError):\n            Mappable(depend=\"nonexistent_feature\")\n\n    def test_value(self):\n\n        val = 3\n        m = self.mark(linewidth=val)\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n    def test_default(self):\n\n        val = 3\n        m = self.mark(linewidth=Mappable(val))\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n    def test_rcparam(self):\n\n        param = \"lines.linewidth\"\n        val = mpl.rcParams[param]\n\n        m = self.mark(linewidth=Mappable(rc=param))\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n    def test_depends(self):\n\n        val = 2\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n\n        m = self.mark(pointsize=Mappable(val), linewidth=Mappable(depend=\"pointsize\"))\n        assert m._resolve({}, \"linewidth\") == val\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n        m = self.mark(pointsize=val * 2, linewidth=Mappable(depend=\"pointsize\"))\n        assert m._resolve({}, \"linewidth\") == val * 2\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val * 2))\n\n    def test_mapped(self):\n\n        values = {\"a\": 1, \"b\": 2, \"c\": 3}\n\n        def f(x):\n            return np.array([values[x_i] for x_i in x])\n\n        m = self.mark(linewidth=Mappable(2))\n        scales = {\"linewidth\": f}\n\n        assert m._resolve({\"linewidth\": \"c\"}, \"linewidth\", scales) == 3\n\n        df = pd.DataFrame({\"linewidth\": [\"a\", \"b\", \"c\"]})\n        expected = np.array([1, 2, 3], float)\n        assert_array_equal(m._resolve(df, \"linewidth\", scales), expected)\n\n    def test_color(self):\n\n        c, a = \"C1\", .5\n        m = self.mark(color=c, alpha=a)\n\n        assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        cs = [c] * len(df)\n        assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))\n\n    def test_color_mapped_alpha(self):\n\n        c = \"r\"\n        values = {\"a\": .2, \"b\": .5, \"c\": .8}\n\n        m = self.mark(color=c, alpha=Mappable(1))\n        scales = {\"alpha\": lambda s: np.array([values[s_i] for s_i in s])}\n\n        assert resolve_color(m, {\"alpha\": \"b\"}, \"\", scales) == mpl.colors.to_rgba(c, .5)\n\n        df = pd.DataFrame({\"alpha\": list(values.keys())})\n\n        # Do this in two steps for mpl 3.2 compat\n        expected = mpl.colors.to_rgba_array([c] * len(df))\n        expected[:, 3] = list(values.values())\n\n        assert_array_equal(resolve_color(m, df, \"\", scales), expected)\n\n    def test_color_scaled_as_strings(self):\n\n        colors = [\"C1\", \"dodgerblue\", \"#445566\"]\n        m = self.mark()\n        scales = {\"color\": lambda s: colors}\n\n        actual = resolve_color(m, {\"color\": pd.Series([\"a\", \"b\", \"c\"])}, \"\", scales)\n        expected = mpl.colors.to_rgba_array(colors)\n        assert_array_equal(actual, expected)\n\n    def test_fillcolor(self):\n\n        c, a = \"green\", .8\n        fa = .2\n        m = self.mark(\n            color=c, alpha=a,\n            fillcolor=Mappable(depend=\"color\"), fillalpha=Mappable(fa),\n        )\n\n        assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)\n        assert resolve_color(m, {}, \"fill\") == mpl.colors.to_rgba(c, fa)\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        cs = [c] * len(df)\n        assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))\n        assert_array_equal(\n            resolve_color(m, df, \"fill\"), mpl.colors.to_rgba_array(cs, fa)\n        )\n"},{"className":"TestMappable","col":0,"comment":"null","endLoc":158,"id":3599,"nodeType":"Class","startLoc":13,"text":"class TestMappable:\n\n    def mark(self, **features):\n\n        @dataclass\n        class MockMark(Mark):\n            linewidth: float = Mappable(rc=\"lines.linewidth\")\n            pointsize: float = Mappable(4)\n            color: str = Mappable(\"C0\")\n            fillcolor: str = Mappable(depend=\"color\")\n            alpha: float = Mappable(1)\n            fillalpha: float = Mappable(depend=\"alpha\")\n\n        m = MockMark(**features)\n        return m\n\n    def test_repr(self):\n\n        assert str(Mappable(.5)) == \"<0.5>\"\n        assert str(Mappable(\"CO\")) == \"<'CO'>\"\n        assert str(Mappable(rc=\"lines.linewidth\")) == \"\"\n        assert str(Mappable(depend=\"color\")) == \"\"\n        assert str(Mappable(auto=True)) == \"\"\n\n    def test_input_checks(self):\n\n        with pytest.raises(AssertionError):\n            Mappable(rc=\"bogus.parameter\")\n        with pytest.raises(AssertionError):\n            Mappable(depend=\"nonexistent_feature\")\n\n    def test_value(self):\n\n        val = 3\n        m = self.mark(linewidth=val)\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n    def test_default(self):\n\n        val = 3\n        m = self.mark(linewidth=Mappable(val))\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n    def test_rcparam(self):\n\n        param = \"lines.linewidth\"\n        val = mpl.rcParams[param]\n\n        m = self.mark(linewidth=Mappable(rc=param))\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n    def test_depends(self):\n\n        val = 2\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n\n        m = self.mark(pointsize=Mappable(val), linewidth=Mappable(depend=\"pointsize\"))\n        assert m._resolve({}, \"linewidth\") == val\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n        m = self.mark(pointsize=val * 2, linewidth=Mappable(depend=\"pointsize\"))\n        assert m._resolve({}, \"linewidth\") == val * 2\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val * 2))\n\n    def test_mapped(self):\n\n        values = {\"a\": 1, \"b\": 2, \"c\": 3}\n\n        def f(x):\n            return np.array([values[x_i] for x_i in x])\n\n        m = self.mark(linewidth=Mappable(2))\n        scales = {\"linewidth\": f}\n\n        assert m._resolve({\"linewidth\": \"c\"}, \"linewidth\", scales) == 3\n\n        df = pd.DataFrame({\"linewidth\": [\"a\", \"b\", \"c\"]})\n        expected = np.array([1, 2, 3], float)\n        assert_array_equal(m._resolve(df, \"linewidth\", scales), expected)\n\n    def test_color(self):\n\n        c, a = \"C1\", .5\n        m = self.mark(color=c, alpha=a)\n\n        assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        cs = [c] * len(df)\n        assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))\n\n    def test_color_mapped_alpha(self):\n\n        c = \"r\"\n        values = {\"a\": .2, \"b\": .5, \"c\": .8}\n\n        m = self.mark(color=c, alpha=Mappable(1))\n        scales = {\"alpha\": lambda s: np.array([values[s_i] for s_i in s])}\n\n        assert resolve_color(m, {\"alpha\": \"b\"}, \"\", scales) == mpl.colors.to_rgba(c, .5)\n\n        df = pd.DataFrame({\"alpha\": list(values.keys())})\n\n        # Do this in two steps for mpl 3.2 compat\n        expected = mpl.colors.to_rgba_array([c] * len(df))\n        expected[:, 3] = list(values.values())\n\n        assert_array_equal(resolve_color(m, df, \"\", scales), expected)\n\n    def test_color_scaled_as_strings(self):\n\n        colors = [\"C1\", \"dodgerblue\", \"#445566\"]\n        m = self.mark()\n        scales = {\"color\": lambda s: colors}\n\n        actual = resolve_color(m, {\"color\": pd.Series([\"a\", \"b\", \"c\"])}, \"\", scales)\n        expected = mpl.colors.to_rgba_array(colors)\n        assert_array_equal(actual, expected)\n\n    def test_fillcolor(self):\n\n        c, a = \"green\", .8\n        fa = .2\n        m = self.mark(\n            color=c, alpha=a,\n            fillcolor=Mappable(depend=\"color\"), fillalpha=Mappable(fa),\n        )\n\n        assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)\n        assert resolve_color(m, {}, \"fill\") == mpl.colors.to_rgba(c, fa)\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        cs = [c] * len(df)\n        assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))\n        assert_array_equal(\n            resolve_color(m, df, \"fill\"), mpl.colors.to_rgba_array(cs, fa)\n        )"},{"col":4,"comment":"null","endLoc":27,"header":"def mark(self, **features)","id":3600,"name":"mark","nodeType":"Function","startLoc":15,"text":"def mark(self, **features):\n\n        @dataclass\n        class MockMark(Mark):\n            linewidth: float = Mappable(rc=\"lines.linewidth\")\n            pointsize: float = Mappable(4)\n            color: str = Mappable(\"C0\")\n            fillcolor: str = Mappable(depend=\"color\")\n            alpha: float = Mappable(1)\n            fillalpha: float = Mappable(depend=\"alpha\")\n\n        m = MockMark(**features)\n        return m"},{"col":4,"comment":"null","endLoc":148,"header":"def test_fill(self, toy_df)","id":3601,"name":"test_fill","nodeType":"Function","startLoc":141,"text":"def test_fill(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"fill\")(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3]),\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .8])"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1630,"id":3602,"name":"join","nodeType":"Attribute","startLoc":1630,"text":"self.join"},{"col":4,"comment":"null","endLoc":1709,"header":"def test_scatter_hue(self, long_df)","id":3603,"name":"test_scatter_hue","nodeType":"Function","startLoc":1698,"text":"def test_scatter_hue(self, long_df):\n\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\")\n\n        g2 = ag.JointGrid()\n        scatterplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", ax=g2.ax_joint)\n        kdeplot(data=long_df, x=\"x\", hue=\"a\", ax=g2.ax_marg_x, fill=True)\n        kdeplot(data=long_df, y=\"y\", hue=\"a\", ax=g2.ax_marg_y, fill=True)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)"},{"attributeType":"list","col":8,"comment":"null","endLoc":1621,"id":3604,"name":"markers","nodeType":"Attribute","startLoc":1621,"text":"self.markers"},{"col":4,"comment":"null","endLoc":157,"header":"def test_drop(self, toy_df)","id":3605,"name":"test_drop","nodeType":"Function","startLoc":150,"text":"def test_drop(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(\"drop\")(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])"},{"col":0,"comment":"null","endLoc":14,"header":"@pytest.fixture(autouse=True)\ndef default_palette()","id":3606,"name":"default_palette","nodeType":"Function","startLoc":11,"text":"@pytest.fixture(autouse=True)\ndef default_palette():\n    with color_palette(\"deep\"):\n        yield"},{"col":4,"comment":"null","endLoc":1724,"header":"def test_reg(self)","id":3607,"name":"test_reg","nodeType":"Function","startLoc":1711,"text":"def test_reg(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"reg\")\n        assert len(g.ax_joint.collections) == 2\n\n        x, y = g.ax_joint.collections[0].get_offsets().T\n        assert_array_equal(self.x, x)\n        assert_array_equal(self.y, y)\n\n        assert g.ax_marg_x.patches\n        assert g.ax_marg_y.patches\n\n        assert g.ax_marg_x.lines\n        assert g.ax_marg_y.lines"},{"attributeType":"null","col":8,"comment":"null","endLoc":1633,"id":3608,"name":"capsize","nodeType":"Attribute","startLoc":1633,"text":"self.capsize"},{"id":3609,"name":"plot.rst","nodeType":"TextFile","path":"doc/_templates/autosummary","text":"{{ fullname | escape | underline}}\n\n.. currentmodule:: {{ module }}\n\n.. autoclass:: {{ objname }}\n\n   {% block methods %}\n\n   .. rubric:: Specification methods\n\n   .. autosummary::\n      :toctree: ./\n      :nosignatures:\n\n      ~Plot.add\n      ~Plot.scale\n\n   .. rubric:: Subplot methods\n\n   .. autosummary::\n      :toctree: ./\n      :nosignatures:\n\n      ~Plot.facet\n      ~Plot.pair\n\n   .. rubric:: Customization methods\n\n   .. autosummary::\n      :toctree: ./\n      :nosignatures:\n\n      ~Plot.layout\n      ~Plot.label\n      ~Plot.limit\n      ~Plot.share\n      ~Plot.theme\n\n   .. rubric:: Integration methods\n\n   .. autosummary::\n      :toctree: ./\n      :nosignatures:\n\n      ~Plot.on\n\n   .. rubric:: Output methods\n\n   .. autosummary::\n      :toctree: ./\n      :nosignatures:\n\n      ~Plot.plot\n      ~Plot.save\n      ~Plot.show\n\n   {% endblock %}\n"},{"id":3610,"name":"pointplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"43f842ee-44c9-476b-ab08-112d23e2effb\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme(style=\\\"whitegrid\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"9aa5bc8a-03cd-4792-906d-7e7318c2cecc\",\n   \"metadata\": {},\n   \"source\": [\n    \"Group by a categorical varaible and plot aggregated values, with confidence intervals:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9a865fec-c034-4000-938d-b7cd89157495\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df = sns.load_dataset(\\\"penguins\\\")\\n\",\n    \"sns.pointplot(data=df, x=\\\"island\\\", y=\\\"body_mass_g\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"a0002e29-0ad6-41c7-b66d-c80bb1844924\",\n   \"metadata\": {},\n   \"source\": [\n    \"Add a second layer of grouping:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f27011f1-0e3c-4dc4-818e-4a77930977b9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pointplot(data=df, x=\\\"island\\\", y=\\\"body_mass_g\\\", hue=\\\"sex\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"a63681f6-e692-400f-b9fe-0d9fd0521398\",\n   \"metadata\": {},\n   \"source\": [\n    \"Adjust the artists along the categorical axis to reduce overplotting:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8f94d069-c5f4-4579-a4bf-6d755962d48d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pointplot(data=df, x=\\\"sex\\\", y=\\\"bill_depth_mm\\\", hue=\\\"island\\\", dodge=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"51523904-3b42-4818-9de6-52dc30090e56\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the error bars to show the standard deviation rather than a confidence interval:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"386b25eb-7ab7-4a1d-9498-cef3e4fd3e6b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pointplot(data=df, x=\\\"island\\\", y=\\\"body_mass_g\\\", errorbar=\\\"sd\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"41253d65-b3be-4aab-87a2-be34e66a2d7c\",\n   \"metadata\": {},\n   \"source\": [\n    \"Customize the appearance of the plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"50b14810-2299-479c-b6c5-0fd10c4ed3de\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pointplot(\\n\",\n    \"    data=df, x=\\\"body_mass_g\\\", y=\\\"island\\\",\\n\",\n    \"    errorbar=(\\\"pi\\\", 100), capsize=.4, join=False, color=\\\".5\\\",\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"94d6718d-2cfe-44f4-88e5-f47461d7d51f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":1732,"header":"def test_resid(self)","id":3611,"name":"test_resid","nodeType":"Function","startLoc":1726,"text":"def test_resid(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"resid\")\n        assert g.ax_joint.collections\n        assert g.ax_joint.lines\n        assert not g.ax_marg_x.lines\n        assert not g.ax_marg_y.lines"},{"id":3612,"name":"objects.Bars.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn.objects as so\\n\",\n    \"from seaborn import load_dataset\\n\",\n    \"diamonds = load_dataset(\\\"diamonds\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"5cf83822-ceb1-4ce5-8364-069466f7aa40\",\n   \"metadata\": {},\n   \"source\": [\n    \"This mark draws bars between a baseline and a value. In contrast to :class:`Bar`, the bars have a full width and thin edges by default; this makes this mark a better choice for a continuous histogram:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e9b99eaf-695f-41ae-9bd1-bfe406dedb63\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = so.Plot(diamonds, \\\"price\\\").scale(x=\\\"log\\\")\\n\",\n    \"p.add(so.Bars(), so.Hist())\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"bc4c0f25-3f7a-4a2c-a032-151da47f5ea3\",\n   \"metadata\": {},\n   \"source\": [\n    \"When mapping the color or other properties, bars will overlap by default; this is usually confusing:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"7989211b-7a29-4763-bb97-4ea19cdef081\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Bars(), so.Hist(), color=\\\"cut\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"f16a3b5d-1ac1-4d9d-9bc6-d4cea7f83a17\",\n   \"metadata\": {},\n   \"source\": [\n    \"Using a move transform, such as :class:`Stack` or :class:`Dodge`, will resolve the overlap (although faceting might often be a better approach):\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8933f5f7-1423-4741-b7be-6239ea8b2fee\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Bars(), so.Hist(), so.Stack(), color=\\\"cut\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"74075e80-0361-4388-a459-cbfa6418df6c\",\n   \"metadata\": {},\n   \"source\": [\n    \"A number of different properties can be set or mapped:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"04fada68-a61b-451c-b3bd-9aaab16b5f29\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Bars(edgewidth=0), so.Hist(), so.Stack(), alpha=\\\"clarity\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"a14d7d36-9d8b-4024-8653-002e9da946d7\",\n   \"metadata\": {},\n   \"source\": [\n    \"It is possible to draw unfilled bars, but you must override the default edge color:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"21642f8c-99c7-4f61-b3f5-bc1dacc638c3\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Bars(fill=False, edgecolor=\\\"C0\\\", edgewidth=1.5), so.Hist())\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"dce5b6cc-0808-48ec-b4d6-0c0c2e5178d2\",\n   \"metadata\": {},\n   \"source\": [\n    \"It is also possible to narrow the bars, which may be useful for dealing with overlap in some cases:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"166693bf-420c-4ec3-8da2-abc22724952b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"hist = so.Hist(binwidth=.075, binrange=(2, 5))\\n\",\n    \"(\\n\",\n    \"    p.add(so.Bars(), hist)\\n\",\n    \"    .add(\\n\",\n    \"        so.Bars(color=\\\".9\\\", width=.5), hist,\\n\",\n    \"        data=diamonds.query(\\\"cut == 'Ideal'\\\")\\n\",\n    \"    )\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b40b02c4-fb2c-4300-93e4-24ea28bc6ef8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":1746,"header":"def test_hist(self, long_df)","id":3613,"name":"test_hist","nodeType":"Function","startLoc":1734,"text":"def test_hist(self, long_df):\n\n        bins = 3, 6\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", kind=\"hist\", bins=bins)\n\n        g2 = ag.JointGrid()\n        histplot(data=long_df, x=\"x\", y=\"y\", ax=g2.ax_joint, bins=bins)\n        histplot(data=long_df, x=\"x\", ax=g2.ax_marg_x, bins=bins[0])\n        histplot(data=long_df, y=\"y\", ax=g2.ax_marg_y, bins=bins[1])\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)"},{"id":3614,"name":"axes_style.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"dated-mother\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"prospective-sellers\",\n   \"metadata\": {},\n   \"source\": [\n    \"Calling with no arguments will return the current defaults for the style parameters:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"recognized-rehabilitation\",\n   \"metadata\": {\n    \"tags\": [\n     \"show-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"sns.axes_style()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"furnished-irrigation\",\n   \"metadata\": {},\n   \"source\": [\n    \"Calling with the name of a predefined style will show those parameter values:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"coordinate-reward\",\n   \"metadata\": {\n    \"tags\": [\n     \"show-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"sns.axes_style(\\\"darkgrid\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"mediterranean-picking\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the function as a context manager to temporarily change the style of your plots:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"missing-essence\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"with sns.axes_style(\\\"whitegrid\\\"):\\n\",\n    \"    sns.barplot(x=[1, 2, 3], y=[2, 5, 3])\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"attributeType":"list","col":12,"comment":"null","endLoc":1608,"id":3615,"name":"colors","nodeType":"Attribute","startLoc":1608,"text":"self.colors"},{"id":3616,"name":"objects.Plot.facet.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"fb8e120d-5dcf-483b-a0d1-74857d09ce7d\",\n   \"metadata\": {},\n   \"source\": [\n    \".. currentmodule:: seaborn.objects\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn.objects as so\\n\",\n    \"from seaborn import load_dataset\\n\",\n    \"penguins = load_dataset(\\\"penguins\\\")\\n\",\n    \"diamonds = load_dataset(\\\"diamonds\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ae85e302-354c-46ca-a17f-aaec7ed1cbd6\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assigning a faceting variable will create multiple subplots and plot subsets of the data on each of them:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d65405fd-cf28-4248-8e51-1aa1999354a2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = so.Plot(penguins, \\\"bill_length_mm\\\", \\\"bill_depth_mm\\\").add(so.Dots())\\n\",\n    \"p.facet(\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2b9630aa-3b46-4e72-82ef-5717c2d8c686\",\n   \"metadata\": {},\n   \"source\": [\n    \"Multiple faceting variables can be defined to create a two-dimensional grid:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1857144f-1373-4704-9332-d3fc649ceb9d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(\\\"species\\\", \\\"sex\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"7664e2d2-c254-44b4-9973-88e1d013fb3d\",\n   \"metadata\": {},\n   \"source\": [\n    \"Facet variables can be provided as references to the global plot data or as vectors:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6569616d-480b-4b8c-a761-f5bd2bde60e3\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(penguins[\\\"island\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"198f63a0-bb0f-40c4-b790-bd15f8656acb\",\n   \"metadata\": {},\n   \"source\": [\n    \"With a single faceting variable, arrange the facets or limit to a subset by passing a list of levels to `order`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b1344f7f-50d0-4592-b4fb-ab81d97a4798\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(\\\"species\\\", order=[\\\"Gentoo\\\", \\\"Adelie\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2090297c-414f-4448-a930-5b6f0de18deb\",\n   \"metadata\": {},\n   \"source\": [\n    \"With multiple variables, pass `order` as a dictionary:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"58ed1b13-71a7-462a-af99-78be566268a6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(\\\"species\\\", \\\"sex\\\", order={\\\"col\\\": [\\\"Gentoo\\\", \\\"Adelie\\\"], \\\"row\\\": [\\\"Female\\\", \\\"Male\\\"]})\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"e440f14d-24b2-4f83-a247-0bb917f9f4c3\",\n   \"metadata\": {},\n   \"source\": [\n    \"When the faceting variable has multiple levels, you can `wrap` it to distribute subplots across both dimensions:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"92baf66c-6dd9-4f50-adf2-386c4daab094\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\").add(so.Dots())\\n\",\n    \"p.facet(\\\"color\\\", wrap=4)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8d0872cb-e261-4796-b81e-a416fea85201\",\n   \"metadata\": {},\n   \"source\": [\n    \"Wrapping works only when there is a single variable, but you can wrap in either direction:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c5a66a64-bfba-437c-80be-1311e85cf5a5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(row=\\\"color\\\", wrap=2)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"e1bdaad7-5883-45ad-af39-c10183569bdc\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use :meth:`Plot.share` to specify whether facets should be scaled the same way:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"14c1f977-79d4-4f9c-a846-1fd70ad3569e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(\\\"clarity\\\", wrap=3).share(x=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"a4fc64d9-b7ba-4061-8160-63d8fd89e47a\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use :meth:`Plot.label` to tweak the titles:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4206b12c-d7a3-419f-b278-6edfe487c5de\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.facet(\\\"color\\\").label(title=\\\"{} grade\\\".format)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"28b4fb9d-2bb0-40ff-a541-5f300aca6200\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":3617,"name":"class.rst","nodeType":"TextFile","path":"doc/_templates/autosummary","text":"{{ fullname | escape | underline}}\n\n.. currentmodule:: {{ module }}\n\n.. autoclass:: {{ objname }}\n\n   {% block methods %}\n   .. automethod:: __init__\n\n   {% if methods %}\n   .. rubric:: Methods\n\n   .. autosummary::\n      :toctree: ./\n   {% for item in methods %}\n      ~{{ name }}.{{ item }}\n   {%- endfor %}\n   {% endif %}\n   {% endblock %}\n\n   {% block attributes %}\n   {% if attributes %}\n   .. rubric:: Attributes\n\n   .. autosummary::\n   {% for item in attributes %}\n      ~{{ name }}.{{ item }}\n   {%- endfor %}\n   {% endif %}\n   {% endblock %}\n"},{"col":4,"comment":"null","endLoc":166,"header":"def test_gap(self, toy_df)","id":3618,"name":"test_gap","nodeType":"Function","startLoc":159,"text":"def test_gap(self, toy_df):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(gap=.25)(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1.2])\n        assert_array_almost_equal(res[\"width\"], [.3, .3, .3])"},{"col":4,"comment":"null","endLoc":1753,"header":"def test_hex(self)","id":3619,"name":"test_hex","nodeType":"Function","startLoc":1748,"text":"def test_hex(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"hex\")\n        assert g.ax_joint.collections\n        assert g.ax_marg_x.patches\n        assert g.ax_marg_y.patches"},{"col":4,"comment":"null","endLoc":1766,"header":"def test_kde(self, long_df)","id":3620,"name":"test_kde","nodeType":"Function","startLoc":1755,"text":"def test_kde(self, long_df):\n\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", kind=\"kde\")\n\n        g2 = ag.JointGrid()\n        kdeplot(data=long_df, x=\"x\", y=\"y\", ax=g2.ax_joint)\n        kdeplot(data=long_df, x=\"x\", ax=g2.ax_marg_x)\n        kdeplot(data=long_df, y=\"y\", ax=g2.ax_marg_y)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)"},{"className":"_CountPlotter","col":0,"comment":"null","endLoc":1741,"id":3621,"nodeType":"Class","startLoc":1740,"text":"class _CountPlotter(_BarPlotter):\n    require_numeric = False"},{"attributeType":"bool","col":4,"comment":"null","endLoc":1741,"id":3622,"name":"require_numeric","nodeType":"Attribute","startLoc":1741,"text":"require_numeric"},{"className":"_LVPlotter","col":0,"comment":"null","endLoc":2047,"id":3623,"nodeType":"Class","startLoc":1744,"text":"class _LVPlotter(_CategoricalPlotter):\n\n    def __init__(self, x, y, hue, data, order, hue_order,\n                 orient, color, palette, saturation,\n                 width, dodge, k_depth, linewidth, scale, outlier_prop,\n                 trust_alpha, showfliers=True):\n\n        self.width = width\n        self.dodge = dodge\n        self.saturation = saturation\n\n        k_depth_methods = ['proportion', 'tukey', 'trustworthy', 'full']\n        if not (k_depth in k_depth_methods or isinstance(k_depth, Number)):\n            msg = (f'k_depth must be one of {k_depth_methods} or a number, '\n                   f'but {k_depth} was passed.')\n            raise ValueError(msg)\n        self.k_depth = k_depth\n\n        if linewidth is None:\n            linewidth = mpl.rcParams[\"lines.linewidth\"]\n        self.linewidth = linewidth\n\n        scales = ['linear', 'exponential', 'area']\n        if scale not in scales:\n            msg = f'scale must be one of {scales}, but {scale} was passed.'\n            raise ValueError(msg)\n        self.scale = scale\n\n        if ((outlier_prop > 1) or (outlier_prop <= 0)):\n            msg = f'outlier_prop {outlier_prop} not in range (0, 1]'\n            raise ValueError(msg)\n        self.outlier_prop = outlier_prop\n\n        if not 0 < trust_alpha < 1:\n            msg = f'trust_alpha {trust_alpha} not in range (0, 1)'\n            raise ValueError(msg)\n        self.trust_alpha = trust_alpha\n\n        self.showfliers = showfliers\n\n        self.establish_variables(x, y, hue, data, orient, order, hue_order)\n        self.establish_colors(color, palette, saturation)\n\n    def _lv_box_ends(self, vals):\n        \"\"\"Get the number of data points and calculate `depth` of\n        letter-value plot.\"\"\"\n        vals = np.asarray(vals)\n        # Remove infinite values while handling a 'object' dtype\n        # that can come from pd.Float64Dtype() input\n        with pd.option_context('mode.use_inf_as_null', True):\n            vals = vals[~pd.isnull(vals)]\n        n = len(vals)\n        p = self.outlier_prop\n\n        # Select the depth, i.e. number of boxes to draw, based on the method\n        if self.k_depth == 'full':\n            # extend boxes to 100% of the data\n            k = int(np.log2(n)) + 1\n        elif self.k_depth == 'tukey':\n            # This results with 5-8 points in each tail\n            k = int(np.log2(n)) - 3\n        elif self.k_depth == 'proportion':\n            k = int(np.log2(n)) - int(np.log2(n * p)) + 1\n        elif self.k_depth == 'trustworthy':\n            point_conf = 2 * _normal_quantile_func(1 - self.trust_alpha / 2) ** 2\n            k = int(np.log2(n / point_conf)) + 1\n        else:\n            k = int(self.k_depth)  # allow having k as input\n        # If the number happens to be less than 1, set k to 1\n        if k < 1:\n            k = 1\n\n        # Calculate the upper end for each of the k boxes\n        upper = [100 * (1 - 0.5 ** (i + 1)) for i in range(k, 0, -1)]\n        # Calculate the lower end for each of the k boxes\n        lower = [100 * (0.5 ** (i + 1)) for i in range(k, 0, -1)]\n        # Stitch the box ends together\n        percentile_ends = [(i, j) for i, j in zip(lower, upper)]\n        box_ends = [np.percentile(vals, q) for q in percentile_ends]\n        return box_ends, k\n\n    def _lv_outliers(self, vals, k):\n        \"\"\"Find the outliers based on the letter value depth.\"\"\"\n        box_edge = 0.5 ** (k + 1)\n        perc_ends = (100 * box_edge, 100 * (1 - box_edge))\n        edges = np.percentile(vals, perc_ends)\n        lower_out = vals[np.where(vals < edges[0])[0]]\n        upper_out = vals[np.where(vals > edges[1])[0]]\n        return np.concatenate((lower_out, upper_out))\n\n    def _width_functions(self, width_func):\n        # Dictionary of functions for computing the width of the boxes\n        width_functions = {'linear': lambda h, i, k: (i + 1.) / k,\n                           'exponential': lambda h, i, k: 2**(-k + i - 1),\n                           'area': lambda h, i, k: (1 - 2**(-k + i - 2)) / h}\n        return width_functions[width_func]\n\n    def _lvplot(self, box_data, positions,\n                color=[255. / 256., 185. / 256., 0.],\n                widths=1, ax=None, box_kws=None,\n                flier_kws=None,\n                line_kws=None):\n\n        # -- Default keyword dicts - based on\n        # distributions.plot_univariate_histogram\n        box_kws = {} if box_kws is None else box_kws.copy()\n        flier_kws = {} if flier_kws is None else flier_kws.copy()\n        line_kws = {} if line_kws is None else line_kws.copy()\n\n        # Set the default kwargs for the boxes\n        box_default_kws = dict(edgecolor=self.gray,\n                               linewidth=self.linewidth)\n        for k, v in box_default_kws.items():\n            box_kws.setdefault(k, v)\n\n        # Set the default kwargs for the lines denoting medians\n        line_default_kws = dict(\n            color=\".15\", alpha=0.45, solid_capstyle=\"butt\", linewidth=self.linewidth\n        )\n        for k, v in line_default_kws.items():\n            line_kws.setdefault(k, v)\n\n        # Set the default kwargs for the outliers scatterplot\n        flier_default_kws = dict(marker='d', color=self.gray)\n        for k, v in flier_default_kws.items():\n            flier_kws.setdefault(k, v)\n\n        vert = self.orient == \"v\"\n        x = positions[0]\n        box_data = np.asarray(box_data)\n\n        # If we only have one data point, plot a line\n        if len(box_data) == 1:\n            line_kws.update({\n                'color': box_kws['edgecolor'],\n                'linestyle': box_kws.get('linestyle', '-'),\n                'linewidth': max(box_kws[\"linewidth\"], line_kws[\"linewidth\"])\n            })\n            ys = [box_data[0], box_data[0]]\n            xs = [x - widths / 2, x + widths / 2]\n            if vert:\n                xx, yy = xs, ys\n            else:\n                xx, yy = ys, xs\n            ax.plot(xx, yy, **line_kws)\n        else:\n            # Get the number of data points and calculate \"depth\" of\n            # letter-value plot\n            box_ends, k = self._lv_box_ends(box_data)\n\n            # Anonymous functions for calculating the width and height\n            # of the letter value boxes\n            width = self._width_functions(self.scale)\n\n            # Function to find height of boxes\n            def height(b):\n                return b[1] - b[0]\n\n            # Functions to construct the letter value boxes\n            def vert_perc_box(x, b, i, k, w):\n                rect = Patches.Rectangle((x - widths * w / 2, b[0]),\n                                         widths * w,\n                                         height(b), fill=True)\n                return rect\n\n            def horz_perc_box(x, b, i, k, w):\n                rect = Patches.Rectangle((b[0], x - widths * w / 2),\n                                         height(b), widths * w,\n                                         fill=True)\n                return rect\n\n            # Scale the width of the boxes so the biggest starts at 1\n            w_area = np.array([width(height(b), i, k)\n                               for i, b in enumerate(box_ends)])\n            w_area = w_area / np.max(w_area)\n\n            # Calculate the medians\n            y = np.median(box_data)\n\n            # Calculate the outliers and plot (only if showfliers == True)\n            outliers = []\n            if self.showfliers:\n                outliers = self._lv_outliers(box_data, k)\n            hex_color = mpl.colors.rgb2hex(color)\n\n            if vert:\n                box_func = vert_perc_box\n                xs_median = [x - widths / 2, x + widths / 2]\n                ys_median = [y, y]\n                xs_outliers = np.full(len(outliers), x)\n                ys_outliers = outliers\n\n            else:\n                box_func = horz_perc_box\n                xs_median = [y, y]\n                ys_median = [x - widths / 2, x + widths / 2]\n                xs_outliers = outliers\n                ys_outliers = np.full(len(outliers), x)\n\n            # Plot the medians\n            ax.plot(\n                xs_median,\n                ys_median,\n                **line_kws\n            )\n\n            # Plot outliers (if any)\n            if len(outliers) > 0:\n                ax.scatter(xs_outliers, ys_outliers,\n                           **flier_kws\n                           )\n\n            # Construct a color map from the input color\n            rgb = [hex_color, (1, 1, 1)]\n            cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n            # Make sure that the last boxes contain hue and are not pure white\n            rgb = [hex_color, cmap(.85)]\n            cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n\n            # Update box_kws with `cmap` if not defined in dict until now\n            box_kws.setdefault('cmap', cmap)\n\n            boxes = [box_func(x, b[0], i, k, b[1])\n                     for i, b in enumerate(zip(box_ends, w_area))]\n\n            collection = PatchCollection(boxes, **box_kws)\n\n            # Set the color gradation, first box will have color=hex_color\n            collection.set_array(np.array(np.linspace(1, 0, len(boxes))))\n\n            # Plot the boxes\n            ax.add_collection(collection)\n\n    def draw_letter_value_plot(self, ax, box_kws=None, flier_kws=None,\n                               line_kws=None):\n        \"\"\"Use matplotlib to draw a letter value plot on an Axes.\"\"\"\n\n        for i, group_data in enumerate(self.plot_data):\n\n            if self.plot_hues is None:\n\n                # Handle case where there is data at this level\n                if group_data.size == 0:\n                    continue\n\n                # Draw a single box or a set of boxes\n                # with a single level of grouping\n                box_data = remove_na(group_data)\n\n                # Handle case where there is no non-null data\n                if box_data.size == 0:\n                    continue\n\n                color = self.colors[i]\n\n                self._lvplot(box_data,\n                             positions=[i],\n                             color=color,\n                             widths=self.width,\n                             ax=ax,\n                             box_kws=box_kws,\n                             flier_kws=flier_kws,\n                             line_kws=line_kws)\n\n            else:\n                # Draw nested groups of boxes\n                offsets = self.hue_offsets\n                for j, hue_level in enumerate(self.hue_names):\n\n                    # Add a legend for this hue level\n                    if not i:\n                        self.add_legend_data(ax, self.colors[j], hue_level)\n\n                    # Handle case where there is data at this level\n                    if group_data.size == 0:\n                        continue\n\n                    hue_mask = self.plot_hues[i] == hue_level\n                    box_data = remove_na(group_data[hue_mask])\n\n                    # Handle case where there is no non-null data\n                    if box_data.size == 0:\n                        continue\n\n                    color = self.colors[j]\n                    center = i + offsets[j]\n                    self._lvplot(box_data,\n                                 positions=[center],\n                                 color=color,\n                                 widths=self.nested_width,\n                                 ax=ax,\n                                 box_kws=box_kws,\n                                 flier_kws=flier_kws,\n                                 line_kws=line_kws)\n\n        # Autoscale the values axis to make sure all patches are visible\n        ax.autoscale_view(scalex=self.orient == \"h\", scaley=self.orient == \"v\")\n\n    def plot(self, ax, box_kws, flier_kws, line_kws):\n        \"\"\"Make the plot.\"\"\"\n        self.draw_letter_value_plot(ax, box_kws, flier_kws, line_kws)\n        self.annotate_axes(ax)\n        if self.orient == \"h\":\n            ax.invert_yaxis()"},{"col":4,"comment":"Get the number of data points and calculate `depth` of\n        letter-value plot.","endLoc":1823,"header":"def _lv_box_ends(self, vals)","id":3624,"name":"_lv_box_ends","nodeType":"Function","startLoc":1787,"text":"def _lv_box_ends(self, vals):\n        \"\"\"Get the number of data points and calculate `depth` of\n        letter-value plot.\"\"\"\n        vals = np.asarray(vals)\n        # Remove infinite values while handling a 'object' dtype\n        # that can come from pd.Float64Dtype() input\n        with pd.option_context('mode.use_inf_as_null', True):\n            vals = vals[~pd.isnull(vals)]\n        n = len(vals)\n        p = self.outlier_prop\n\n        # Select the depth, i.e. number of boxes to draw, based on the method\n        if self.k_depth == 'full':\n            # extend boxes to 100% of the data\n            k = int(np.log2(n)) + 1\n        elif self.k_depth == 'tukey':\n            # This results with 5-8 points in each tail\n            k = int(np.log2(n)) - 3\n        elif self.k_depth == 'proportion':\n            k = int(np.log2(n)) - int(np.log2(n * p)) + 1\n        elif self.k_depth == 'trustworthy':\n            point_conf = 2 * _normal_quantile_func(1 - self.trust_alpha / 2) ** 2\n            k = int(np.log2(n / point_conf)) + 1\n        else:\n            k = int(self.k_depth)  # allow having k as input\n        # If the number happens to be less than 1, set k to 1\n        if k < 1:\n            k = 1\n\n        # Calculate the upper end for each of the k boxes\n        upper = [100 * (1 - 0.5 ** (i + 1)) for i in range(k, 0, -1)]\n        # Calculate the lower end for each of the k boxes\n        lower = [100 * (0.5 ** (i + 1)) for i in range(k, 0, -1)]\n        # Stitch the box ends together\n        percentile_ends = [(i, j) for i, j in zip(lower, upper)]\n        box_ends = [np.percentile(vals, q) for q in percentile_ends]\n        return box_ends, k"},{"col":4,"comment":"null","endLoc":1779,"header":"def test_kde_hue(self, long_df)","id":3625,"name":"test_kde_hue","nodeType":"Function","startLoc":1768,"text":"def test_kde_hue(self, long_df):\n\n        g1 = ag.jointplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", kind=\"kde\")\n\n        g2 = ag.JointGrid()\n        kdeplot(data=long_df, x=\"x\", y=\"y\", hue=\"a\", ax=g2.ax_joint)\n        kdeplot(data=long_df, x=\"x\", hue=\"a\", ax=g2.ax_marg_x)\n        kdeplot(data=long_df, y=\"y\", hue=\"a\", ax=g2.ax_marg_y)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)"},{"col":4,"comment":"null","endLoc":1789,"header":"def test_color(self)","id":3626,"name":"test_color","nodeType":"Function","startLoc":1781,"text":"def test_color(self):\n\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, color=\"purple\")\n\n        scatter_color = g.ax_joint.collections[0].get_facecolor()\n        assert_colors_equal(scatter_color, \"purple\")\n\n        hist_color = g.ax_marg_x.patches[0].get_facecolor()[:3]\n        assert_colors_equal(hist_color, \"purple\")"},{"col":4,"comment":"null","endLoc":175,"header":"def test_widths_default(self, toy_df_widths)","id":3627,"name":"test_widths_default","nodeType":"Function","startLoc":168,"text":"def test_widths_default(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge()(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1.1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .2])"},{"col":4,"comment":"null","endLoc":1804,"header":"def test_palette(self, long_df)","id":3628,"name":"test_palette","nodeType":"Function","startLoc":1791,"text":"def test_palette(self, long_df):\n\n        kws = dict(data=long_df, hue=\"a\", palette=\"Set2\")\n\n        g1 = ag.jointplot(x=\"x\", y=\"y\", **kws)\n\n        g2 = ag.JointGrid()\n        scatterplot(x=\"x\", y=\"y\", ax=g2.ax_joint, **kws)\n        kdeplot(x=\"x\", ax=g2.ax_marg_x, fill=True, **kws)\n        kdeplot(y=\"y\", ax=g2.ax_marg_y, fill=True, **kws)\n\n        assert_plots_equal(g1.ax_joint, g2.ax_joint)\n        assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)\n        assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)"},{"col":4,"comment":"null","endLoc":184,"header":"def test_widths_fill(self, toy_df_widths)","id":3629,"name":"test_widths_fill","nodeType":"Function","startLoc":177,"text":"def test_widths_fill(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"fill\")(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .4])"},{"col":4,"comment":"null","endLoc":193,"header":"def test_widths_drop(self, toy_df_widths)","id":3630,"name":"test_widths_drop","nodeType":"Function","startLoc":186,"text":"def test_widths_drop(self, toy_df_widths):\n\n        groupby = GroupBy([\"x\", \"grp\"])\n        res = Dodge(empty=\"drop\")(toy_df_widths, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.08, .32, 1])\n        assert_array_almost_equal(res[\"width\"], [.64, .16, .2])"},{"attributeType":"null","col":8,"comment":"null","endLoc":48,"id":3631,"name":"line","nodeType":"Attribute","startLoc":48,"text":"line"},{"attributeType":"str","col":12,"comment":"null","endLoc":62,"id":3632,"name":"cell_type","nodeType":"Attribute","startLoc":62,"text":"cell_type"},{"attributeType":"list","col":12,"comment":"null","endLoc":63,"id":3633,"name":"cell","nodeType":"Attribute","startLoc":63,"text":"cell"},{"attributeType":"str","col":12,"comment":"null","endLoc":66,"id":3634,"name":"line","nodeType":"Attribute","startLoc":66,"text":"line"},{"col":0,"comment":"","endLoc":1,"header":"extract_examples.py#","id":3635,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Turn the examples section of a function docstring into a notebook.\"\"\"\n\nif __name__ == \"__main__\":\n\n    _, name = sys.argv\n\n    # Parse the docstring and get the examples section\n    obj = getattr(seaborn, name)\n    if obj.__class__.__name__ != \"function\":\n        obj = obj.__init__\n    lines = NumpyDocString(pydoc.getdoc(obj))[\"Examples\"]\n\n    # Remove code indentation, the prompt, and mpl return variable\n    pat = re.compile(r\"\\s{4}[>\\.]{3} (ax = ){0,1}(g = ){0,1}\")\n\n    nb = nbformat.v4.new_notebook()\n\n    # We always start with at least one line of text\n    cell_type = \"markdown\"\n    cell = []\n\n    for line in lines:\n\n        # Ignore matplotlib plot directive\n        if \".. plot\" in line or \":context:\" in line:\n            continue\n\n        # Ignore blank lines\n        if not line:\n            continue\n\n        if line_type(line) != cell_type:\n            # We are on the first line of the next cell,\n            # so package up the last cell\n            add_cell(nb, cell, cell_type)\n            cell_type = line_type(line)\n            cell = []\n\n        if line_type(line) == \"code\":\n            line = re.sub(pat, \"\", line)\n\n        cell.append(line)\n\n    # Package the final cell\n    add_cell(nb, cell, cell_type)\n\n    nbformat.write(nb, f\"docstrings/{name}.ipynb\")"},{"col":4,"comment":"null","endLoc":202,"header":"def test_faceted_default(self, toy_df_facets)","id":3638,"name":"test_faceted_default","nodeType":"Function","startLoc":195,"text":"def test_faceted_default(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge()(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, .8, .2, .8, 2.2])\n        assert_array_almost_equal(res[\"width\"], [.4] * 6)"},{"col":4,"comment":"null","endLoc":1813,"header":"def test_hex_customise(self)","id":3639,"name":"test_hex_customise","nodeType":"Function","startLoc":1806,"text":"def test_hex_customise(self):\n\n        # test that default gridsize can be overridden\n        g = ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"hex\",\n                         joint_kws=dict(gridsize=5))\n        assert len(g.ax_joint.collections) == 1\n        a = g.ax_joint.collections[0].get_array()\n        assert a.shape[0] == 28  # 28 hexagons expected for gridsize 5"},{"col":4,"comment":"null","endLoc":211,"header":"def test_faceted_fill(self, toy_df_facets)","id":3640,"name":"test_faceted_fill","nodeType":"Function","startLoc":204,"text":"def test_faceted_fill(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge(empty=\"fill\")(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1, 0, 1, 2])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .8, .8, .8, .8])"},{"col":4,"comment":"null","endLoc":220,"header":"def test_faceted_drop(self, toy_df_facets)","id":3641,"name":"test_faceted_drop","nodeType":"Function","startLoc":213,"text":"def test_faceted_drop(self, toy_df_facets):\n\n        groupby = GroupBy([\"x\", \"grp\", \"col\"])\n        res = Dodge(empty=\"drop\")(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"y\"], [1, 2, 3, 1, 2, 3])\n        assert_array_almost_equal(res[\"x\"], [-.2, .2, 1, 0, 1, 2])\n        assert_array_almost_equal(res[\"width\"], [.4] * 6)"},{"fileName":"wide_data_lineplot.py","filePath":"examples","id":3642,"nodeType":"File","text":"\"\"\"\nLineplot from a wide-form dataset\n=================================\n\n_thumb: .52, .5\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\nrs = np.random.RandomState(365)\nvalues = rs.randn(365, 4).cumsum(axis=0)\ndates = pd.date_range(\"1 1 2016\", periods=365, freq=\"D\")\ndata = pd.DataFrame(values, dates, columns=[\"A\", \"B\", \"C\", \"D\"])\ndata = data.rolling(7).mean()\n\nsns.lineplot(data=data, palette=\"tab10\", linewidth=2.5)\n"},{"fileName":"test_properties.py","filePath":"tests/_core","id":3643,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nfrom matplotlib.colors import same_color, to_rgb, to_rgba\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn.external.version import Version\nfrom seaborn._core.rules import categorical_order\nfrom seaborn._core.scales import Nominal, Continuous\nfrom seaborn._core.properties import (\n    Alpha,\n    Color,\n    Coordinate,\n    EdgeWidth,\n    Fill,\n    LineStyle,\n    LineWidth,\n    Marker,\n    PointSize,\n)\nfrom seaborn._compat import MarkerStyle, get_colormap\nfrom seaborn.palettes import color_palette\n\n\nclass DataFixtures:\n\n    @pytest.fixture\n    def num_vector(self, long_df):\n        return long_df[\"s\"]\n\n    @pytest.fixture\n    def num_order(self, num_vector):\n        return categorical_order(num_vector)\n\n    @pytest.fixture\n    def cat_vector(self, long_df):\n        return long_df[\"a\"]\n\n    @pytest.fixture\n    def cat_order(self, cat_vector):\n        return categorical_order(cat_vector)\n\n    @pytest.fixture\n    def dt_num_vector(self, long_df):\n        return long_df[\"t\"]\n\n    @pytest.fixture\n    def dt_cat_vector(self, long_df):\n        return long_df[\"d\"]\n\n    @pytest.fixture\n    def vectors(self, num_vector, cat_vector):\n        return {\"num\": num_vector, \"cat\": cat_vector}\n\n\nclass TestCoordinate(DataFixtures):\n\n    def test_bad_scale_arg_str(self, num_vector):\n\n        err = \"Unknown magic arg for x scale: 'xxx'.\"\n        with pytest.raises(ValueError, match=err):\n            Coordinate(\"x\").infer_scale(\"xxx\", num_vector)\n\n    def test_bad_scale_arg_type(self, cat_vector):\n\n        err = \"Magic arg for x scale must be str, not list.\"\n        with pytest.raises(TypeError, match=err):\n            Coordinate(\"x\").infer_scale([1, 2, 3], cat_vector)\n\n\nclass TestColor(DataFixtures):\n\n    def assert_same_rgb(self, a, b):\n        assert_array_equal(a[:, :3], b[:, :3])\n\n    def test_nominal_default_palette(self, cat_vector, cat_order):\n\n        m = Color().get_mapping(Nominal(), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = color_palette(None, n)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_default_palette_large(self):\n\n        vector = pd.Series(list(\"abcdefghijklmnopqrstuvwxyz\"))\n        m = Color().get_mapping(Nominal(), vector)\n        actual = m(np.arange(26))\n        expected = color_palette(\"husl\", 26)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_named_palette(self, cat_vector, cat_order):\n\n        palette = \"Blues\"\n        m = Color().get_mapping(Nominal(palette), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = color_palette(palette, n)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_list_palette(self, cat_vector, cat_order):\n\n        palette = color_palette(\"Reds\", len(cat_order))\n        m = Color().get_mapping(Nominal(palette), cat_vector)\n        actual = m(np.arange(len(palette)))\n        expected = palette\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_dict_palette(self, cat_vector, cat_order):\n\n        colors = color_palette(\"Greens\")\n        palette = dict(zip(cat_order, colors))\n        m = Color().get_mapping(Nominal(palette), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = colors\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_dict_with_missing_keys(self, cat_vector, cat_order):\n\n        palette = dict(zip(cat_order[1:], color_palette(\"Purples\")))\n        with pytest.raises(ValueError, match=\"No entry in color dict\"):\n            Color(\"color\").get_mapping(Nominal(palette), cat_vector)\n\n    def test_nominal_list_too_short(self, cat_vector, cat_order):\n\n        n = len(cat_order) - 1\n        palette = color_palette(\"Oranges\", n)\n        msg = rf\"The edgecolor list has fewer values \\({n}\\) than needed \\({n + 1}\\)\"\n        with pytest.warns(UserWarning, match=msg):\n            Color(\"edgecolor\").get_mapping(Nominal(palette), cat_vector)\n\n    def test_nominal_list_too_long(self, cat_vector, cat_order):\n\n        n = len(cat_order) + 1\n        palette = color_palette(\"Oranges\", n)\n        msg = rf\"The edgecolor list has more values \\({n}\\) than needed \\({n - 1}\\)\"\n        with pytest.warns(UserWarning, match=msg):\n            Color(\"edgecolor\").get_mapping(Nominal(palette), cat_vector)\n\n    def test_continuous_default_palette(self, num_vector):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        m = Color().get_mapping(Continuous(), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_named_palette(self, num_vector):\n\n        pal = \"flare\"\n        cmap = color_palette(pal, as_cmap=True)\n        m = Color().get_mapping(Continuous(pal), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_tuple_palette(self, num_vector):\n\n        vals = (\"blue\", \"red\")\n        cmap = color_palette(\"blend:\" + \",\".join(vals), as_cmap=True)\n        m = Color().get_mapping(Continuous(vals), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_callable_palette(self, num_vector):\n\n        cmap = get_colormap(\"viridis\")\n        m = Color().get_mapping(Continuous(cmap), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_missing(self):\n\n        x = pd.Series([1, 2, np.nan, 4])\n        m = Color().get_mapping(Continuous(), x)\n        assert np.isnan(m(x)[2]).all()\n\n    def test_bad_scale_values_continuous(self, num_vector):\n\n        with pytest.raises(TypeError, match=\"Scale values for color with a Continuous\"):\n            Color().get_mapping(Continuous([\"r\", \"g\", \"b\"]), num_vector)\n\n    def test_bad_scale_values_nominal(self, cat_vector):\n\n        with pytest.raises(TypeError, match=\"Scale values for color with a Nominal\"):\n            Color().get_mapping(Nominal(get_colormap(\"viridis\")), cat_vector)\n\n    def test_bad_inference_arg(self, cat_vector):\n\n        with pytest.raises(TypeError, match=\"A single scale argument for color\"):\n            Color().infer_scale(123, cat_vector)\n\n    @pytest.mark.parametrize(\n        \"data_type,scale_class\",\n        [(\"cat\", Nominal), (\"num\", Continuous)]\n    )\n    def test_default(self, data_type, scale_class, vectors):\n\n        scale = Color().default_scale(vectors[data_type])\n        assert isinstance(scale, scale_class)\n\n    def test_default_numeric_data_category_dtype(self, num_vector):\n\n        scale = Color().default_scale(num_vector.astype(\"category\"))\n        assert isinstance(scale, Nominal)\n\n    def test_default_binary_data(self):\n\n        x = pd.Series([0, 0, 1, 0, 1], dtype=int)\n        scale = Color().default_scale(x)\n        assert isinstance(scale, Continuous)\n\n    # TODO default scales for other types\n\n    @pytest.mark.parametrize(\n        \"values,data_type,scale_class\",\n        [\n            (\"viridis\", \"cat\", Nominal),  # Based on variable type\n            (\"viridis\", \"num\", Continuous),  # Based on variable type\n            (\"muted\", \"num\", Nominal),  # Based on qualitative palette\n            ([\"r\", \"g\", \"b\"], \"num\", Nominal),  # Based on list palette\n            ({2: \"r\", 4: \"g\", 8: \"b\"}, \"num\", Nominal),  # Based on dict palette\n            ((\"r\", \"b\"), \"num\", Continuous),  # Based on tuple / variable type\n            ((\"g\", \"m\"), \"cat\", Nominal),  # Based on tuple / variable type\n            (get_colormap(\"inferno\"), \"num\", Continuous),  # Based on callable\n        ]\n    )\n    def test_inference(self, values, data_type, scale_class, vectors):\n\n        scale = Color().infer_scale(values, vectors[data_type])\n        assert isinstance(scale, scale_class)\n        assert scale.values == values\n\n    def test_inference_binary_data(self):\n\n        x = pd.Series([0, 0, 1, 0, 1], dtype=int)\n        scale = Color().infer_scale(\"viridis\", x)\n        assert isinstance(scale, Nominal)\n\n    def test_standardization(self):\n\n        f = Color().standardize\n        assert f(\"C3\") == to_rgb(\"C3\")\n        assert f(\"dodgerblue\") == to_rgb(\"dodgerblue\")\n\n        assert f((.1, .2, .3)) == (.1, .2, .3)\n        assert f((.1, .2, .3, .4)) == (.1, .2, .3, .4)\n\n        assert f(\"#123456\") == to_rgb(\"#123456\")\n        assert f(\"#12345678\") == to_rgba(\"#12345678\")\n\n        if Version(mpl.__version__) >= Version(\"3.4.0\"):\n            assert f(\"#123\") == to_rgb(\"#123\")\n            assert f(\"#1234\") == to_rgba(\"#1234\")\n\n\nclass ObjectPropertyBase(DataFixtures):\n\n    def assert_equal(self, a, b):\n\n        assert self.unpack(a) == self.unpack(b)\n\n    def unpack(self, x):\n        return x\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n    def test_default(self, data_type, vectors):\n\n        scale = self.prop().default_scale(vectors[data_type])\n        assert isinstance(scale, Nominal)\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n    def test_inference_list(self, data_type, vectors):\n\n        scale = self.prop().infer_scale(self.values, vectors[data_type])\n        assert isinstance(scale, Nominal)\n        assert scale.values == self.values\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n    def test_inference_dict(self, data_type, vectors):\n\n        x = vectors[data_type]\n        values = dict(zip(categorical_order(x), self.values))\n        scale = self.prop().infer_scale(values, x)\n        assert isinstance(scale, Nominal)\n        assert scale.values == values\n\n    def test_dict_missing(self, cat_vector):\n\n        levels = categorical_order(cat_vector)\n        values = dict(zip(levels, self.values[:-1]))\n        scale = Nominal(values)\n        name = self.prop.__name__.lower()\n        msg = f\"No entry in {name} dictionary for {repr(levels[-1])}\"\n        with pytest.raises(ValueError, match=msg):\n            self.prop().get_mapping(scale, cat_vector)\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n    def test_mapping_default(self, data_type, vectors):\n\n        x = vectors[data_type]\n        mapping = self.prop().get_mapping(Nominal(), x)\n        n = x.nunique()\n        for i, expected in enumerate(self.prop()._default_values(n)):\n            actual, = mapping([i])\n            self.assert_equal(actual, expected)\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n    def test_mapping_from_list(self, data_type, vectors):\n\n        x = vectors[data_type]\n        scale = Nominal(self.values)\n        mapping = self.prop().get_mapping(scale, x)\n        for i, expected in enumerate(self.standardized_values):\n            actual, = mapping([i])\n            self.assert_equal(actual, expected)\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n    def test_mapping_from_dict(self, data_type, vectors):\n\n        x = vectors[data_type]\n        levels = categorical_order(x)\n        values = dict(zip(levels, self.values[::-1]))\n        standardized_values = dict(zip(levels, self.standardized_values[::-1]))\n\n        scale = Nominal(values)\n        mapping = self.prop().get_mapping(scale, x)\n        for i, level in enumerate(levels):\n            actual, = mapping([i])\n            expected = standardized_values[level]\n            self.assert_equal(actual, expected)\n\n    def test_mapping_with_null_value(self, cat_vector):\n\n        mapping = self.prop().get_mapping(Nominal(self.values), cat_vector)\n        actual = mapping(np.array([0, np.nan, 2]))\n        v0, _, v2 = self.standardized_values\n        expected = [v0, self.prop.null_value, v2]\n        for a, b in zip(actual, expected):\n            self.assert_equal(a, b)\n\n    def test_unique_default_large_n(self):\n\n        n = 24\n        x = pd.Series(np.arange(n))\n        mapping = self.prop().get_mapping(Nominal(), x)\n        assert len({self.unpack(x_i) for x_i in mapping(x)}) == n\n\n    def test_bad_scale_values(self, cat_vector):\n\n        var_name = self.prop.__name__.lower()\n        with pytest.raises(TypeError, match=f\"Scale values for a {var_name} variable\"):\n            self.prop().get_mapping(Nominal((\"o\", \"s\")), cat_vector)\n\n\nclass TestMarker(ObjectPropertyBase):\n\n    prop = Marker\n    values = [\"o\", (5, 2, 0), MarkerStyle(\"^\")]\n    standardized_values = [MarkerStyle(x) for x in values]\n\n    def unpack(self, x):\n        return (\n            x.get_path(),\n            x.get_joinstyle(),\n            x.get_transform().to_values(),\n            x.get_fillstyle(),\n        )\n\n\nclass TestLineStyle(ObjectPropertyBase):\n\n    prop = LineStyle\n    values = [\"solid\", \"--\", (1, .5)]\n    standardized_values = [LineStyle._get_dash_pattern(x) for x in values]\n\n    def test_bad_type(self):\n\n        p = LineStyle()\n        with pytest.raises(TypeError, match=\"^Linestyle must be .+, not list.$\"):\n            p.standardize([1, 2])\n\n    def test_bad_style(self):\n\n        p = LineStyle()\n        with pytest.raises(ValueError, match=\"^Linestyle string must be .+, not 'o'.$\"):\n            p.standardize(\"o\")\n\n    def test_bad_dashes(self):\n\n        p = LineStyle()\n        with pytest.raises(TypeError, match=\"^Invalid dash pattern\"):\n            p.standardize((1, 2, \"x\"))\n\n\nclass TestFill(DataFixtures):\n\n    @pytest.fixture\n    def vectors(self):\n\n        return {\n            \"cat\": pd.Series([\"a\", \"a\", \"b\"]),\n            \"num\": pd.Series([1, 1, 2]),\n            \"bool\": pd.Series([True, True, False])\n        }\n\n    @pytest.fixture\n    def cat_vector(self, vectors):\n        return vectors[\"cat\"]\n\n    @pytest.fixture\n    def num_vector(self, vectors):\n        return vectors[\"num\"]\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n    def test_default(self, data_type, vectors):\n\n        x = vectors[data_type]\n        scale = Fill().default_scale(x)\n        assert isinstance(scale, Nominal)\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n    def test_inference_list(self, data_type, vectors):\n\n        x = vectors[data_type]\n        scale = Fill().infer_scale([True, False], x)\n        assert isinstance(scale, Nominal)\n        assert scale.values == [True, False]\n\n    @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n    def test_inference_dict(self, data_type, vectors):\n\n        x = vectors[data_type]\n        values = dict(zip(x.unique(), [True, False]))\n        scale = Fill().infer_scale(values, x)\n        assert isinstance(scale, Nominal)\n        assert scale.values == values\n\n    def test_mapping_categorical_data(self, cat_vector):\n\n        mapping = Fill().get_mapping(Nominal(), cat_vector)\n        assert_array_equal(mapping([0, 1, 0]), [True, False, True])\n\n    def test_mapping_numeric_data(self, num_vector):\n\n        mapping = Fill().get_mapping(Nominal(), num_vector)\n        assert_array_equal(mapping([0, 1, 0]), [True, False, True])\n\n    def test_mapping_list(self, cat_vector):\n\n        mapping = Fill().get_mapping(Nominal([False, True]), cat_vector)\n        assert_array_equal(mapping([0, 1, 0]), [False, True, False])\n\n    def test_mapping_truthy_list(self, cat_vector):\n\n        mapping = Fill().get_mapping(Nominal([0, 1]), cat_vector)\n        assert_array_equal(mapping([0, 1, 0]), [False, True, False])\n\n    def test_mapping_dict(self, cat_vector):\n\n        values = dict(zip(cat_vector.unique(), [False, True]))\n        mapping = Fill().get_mapping(Nominal(values), cat_vector)\n        assert_array_equal(mapping([0, 1, 0]), [False, True, False])\n\n    def test_cycle_warning(self):\n\n        x = pd.Series([\"a\", \"b\", \"c\"])\n        with pytest.warns(UserWarning, match=\"The variable assigned to fill\"):\n            Fill().get_mapping(Nominal(), x)\n\n    def test_values_error(self):\n\n        x = pd.Series([\"a\", \"b\"])\n        with pytest.raises(TypeError, match=\"Scale values for fill must be\"):\n            Fill().get_mapping(Nominal(\"bad_values\"), x)\n\n\nclass IntervalBase(DataFixtures):\n\n    def norm(self, x):\n        return (x - x.min()) / (x.max() - x.min())\n\n    @pytest.mark.parametrize(\"data_type,scale_class\", [\n        (\"cat\", Nominal),\n        (\"num\", Continuous),\n    ])\n    def test_default(self, data_type, scale_class, vectors):\n\n        x = vectors[data_type]\n        scale = self.prop().default_scale(x)\n        assert isinstance(scale, scale_class)\n\n    @pytest.mark.parametrize(\"arg,data_type,scale_class\", [\n        ((1, 3), \"cat\", Nominal),\n        ((1, 3), \"num\", Continuous),\n        ([1, 2, 3], \"cat\", Nominal),\n        ([1, 2, 3], \"num\", Nominal),\n        ({\"a\": 1, \"b\": 3, \"c\": 2}, \"cat\", Nominal),\n        ({2: 1, 4: 3, 8: 2}, \"num\", Nominal),\n    ])\n    def test_inference(self, arg, data_type, scale_class, vectors):\n\n        x = vectors[data_type]\n        scale = self.prop().infer_scale(arg, x)\n        assert isinstance(scale, scale_class)\n        assert scale.values == arg\n\n    def test_mapped_interval_numeric(self, num_vector):\n\n        mapping = self.prop().get_mapping(Continuous(), num_vector)\n        assert_array_equal(mapping([0, 1]), self.prop().default_range)\n\n    def test_mapped_interval_categorical(self, cat_vector):\n\n        mapping = self.prop().get_mapping(Nominal(), cat_vector)\n        n = cat_vector.nunique()\n        assert_array_equal(mapping([n - 1, 0]), self.prop().default_range)\n\n    def test_bad_scale_values_numeric_data(self, num_vector):\n\n        prop_name = self.prop.__name__.lower()\n        err_stem = (\n            f\"Values for {prop_name} variables with Continuous scale must be 2-tuple\"\n        )\n\n        with pytest.raises(TypeError, match=f\"{err_stem}; not .\"):\n            self.prop().get_mapping(Continuous(\"abc\"), num_vector)\n\n        with pytest.raises(TypeError, match=f\"{err_stem}; not 3-tuple.\"):\n            self.prop().get_mapping(Continuous((1, 2, 3)), num_vector)\n\n    def test_bad_scale_values_categorical_data(self, cat_vector):\n\n        prop_name = self.prop.__name__.lower()\n        err_text = f\"Values for {prop_name} variables with Nominal scale\"\n        with pytest.raises(TypeError, match=err_text):\n            self.prop().get_mapping(Nominal(\"abc\"), cat_vector)\n\n\nclass TestAlpha(IntervalBase):\n    prop = Alpha\n\n\nclass TestLineWidth(IntervalBase):\n    prop = LineWidth\n\n    def test_rcparam_default(self):\n\n        with mpl.rc_context({\"lines.linewidth\": 2}):\n            assert self.prop().default_range == (1, 4)\n\n\nclass TestEdgeWidth(IntervalBase):\n    prop = EdgeWidth\n\n    def test_rcparam_default(self):\n\n        with mpl.rc_context({\"patch.linewidth\": 2}):\n            assert self.prop().default_range == (1, 4)\n\n\nclass TestPointSize(IntervalBase):\n    prop = PointSize\n\n    def test_areal_scaling_numeric(self, num_vector):\n\n        limits = 5, 10\n        scale = Continuous(limits)\n        mapping = self.prop().get_mapping(scale, num_vector)\n        x = np.linspace(0, 1, 6)\n        expected = np.sqrt(np.linspace(*np.square(limits), num=len(x)))\n        assert_array_equal(mapping(x), expected)\n\n    def test_areal_scaling_categorical(self, cat_vector):\n\n        limits = (2, 4)\n        scale = Nominal(limits)\n        mapping = self.prop().get_mapping(scale, cat_vector)\n        assert_array_equal(mapping(np.arange(3)), [4, np.sqrt(10), 2])\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":8,"id":3644,"name":"np","nodeType":"Attribute","startLoc":8,"text":"np"},{"col":4,"comment":"null","endLoc":231,"header":"def test_orient(self, toy_df)","id":3645,"name":"test_orient","nodeType":"Function","startLoc":222,"text":"def test_orient(self, toy_df):\n\n        df = toy_df.assign(x=toy_df[\"y\"], y=toy_df[\"x\"])\n\n        groupby = GroupBy([\"y\", \"grp\"])\n        res = Dodge(\"drop\")(df, groupby, \"y\", {})\n\n        assert_array_equal(res[\"x\"], [1, 2, 3])\n        assert_array_almost_equal(res[\"y\"], [-.2, .2, 1])\n        assert_array_almost_equal(res[\"width\"], [.4, .4, .4])"},{"attributeType":"null","col":17,"comment":"null","endLoc":9,"id":3646,"name":"pd","nodeType":"Attribute","startLoc":9,"text":"pd"},{"attributeType":"null","col":18,"comment":"null","endLoc":10,"id":3647,"name":"sns","nodeType":"Attribute","startLoc":10,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":3648,"name":"rs","nodeType":"Attribute","startLoc":13,"text":"rs"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":3649,"name":"values","nodeType":"Attribute","startLoc":14,"text":"values"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":3650,"name":"dates","nodeType":"Attribute","startLoc":15,"text":"dates"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":3651,"name":"data","nodeType":"Attribute","startLoc":16,"text":"data"},{"className":"DataFixtures","col":0,"comment":"null","endLoc":56,"id":3652,"nodeType":"Class","startLoc":28,"text":"class DataFixtures:\n\n    @pytest.fixture\n    def num_vector(self, long_df):\n        return long_df[\"s\"]\n\n    @pytest.fixture\n    def num_order(self, num_vector):\n        return categorical_order(num_vector)\n\n    @pytest.fixture\n    def cat_vector(self, long_df):\n        return long_df[\"a\"]\n\n    @pytest.fixture\n    def cat_order(self, cat_vector):\n        return categorical_order(cat_vector)\n\n    @pytest.fixture\n    def dt_num_vector(self, long_df):\n        return long_df[\"t\"]\n\n    @pytest.fixture\n    def dt_cat_vector(self, long_df):\n        return long_df[\"d\"]\n\n    @pytest.fixture\n    def vectors(self, num_vector, cat_vector):\n        return {\"num\": num_vector, \"cat\": cat_vector}"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":3653,"name":"data","nodeType":"Attribute","startLoc":17,"text":"data"},{"col":4,"comment":"null","endLoc":32,"header":"@pytest.fixture\n    def num_vector(self, long_df)","id":3654,"name":"num_vector","nodeType":"Function","startLoc":30,"text":"@pytest.fixture\n    def num_vector(self, long_df):\n        return long_df[\"s\"]"},{"col":4,"comment":"null","endLoc":36,"header":"@pytest.fixture\n    def num_order(self, num_vector)","id":3655,"name":"num_order","nodeType":"Function","startLoc":34,"text":"@pytest.fixture\n    def num_order(self, num_vector):\n        return categorical_order(num_vector)"},{"col":0,"comment":"","endLoc":7,"header":"wide_data_lineplot.py#","id":3656,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nLineplot from a wide-form dataset\n=================================\n\n_thumb: .52, .5\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\nrs = np.random.RandomState(365)\n\nvalues = rs.randn(365, 4).cumsum(axis=0)\n\ndates = pd.date_range(\"1 1 2016\", periods=365, freq=\"D\")\n\ndata = pd.DataFrame(values, dates, columns=[\"A\", \"B\", \"C\", \"D\"])\n\ndata = data.rolling(7).mean()\n\nsns.lineplot(data=data, palette=\"tab10\", linewidth=2.5)"},{"col":4,"comment":"null","endLoc":35,"header":"def test_repr(self)","id":3657,"name":"test_repr","nodeType":"Function","startLoc":29,"text":"def test_repr(self):\n\n        assert str(Mappable(.5)) == \"<0.5>\"\n        assert str(Mappable(\"CO\")) == \"<'CO'>\"\n        assert str(Mappable(rc=\"lines.linewidth\")) == \"\"\n        assert str(Mappable(depend=\"color\")) == \"\"\n        assert str(Mappable(auto=True)) == \"\""},{"col":4,"comment":"null","endLoc":252,"header":"@pytest.mark.parametrize(\"grp\", [\"grp2\", \"grp3\"])\n    def test_single_semantic(self, df, grp)","id":3658,"name":"test_single_semantic","nodeType":"Function","startLoc":235,"text":"@pytest.mark.parametrize(\"grp\", [\"grp2\", \"grp3\"])\n    def test_single_semantic(self, df, grp):\n\n        groupby = GroupBy([\"x\", grp])\n        res = Dodge()(df, groupby, \"x\", {})\n\n        levels = categorical_order(df[grp])\n        w, n = 0.8, len(levels)\n\n        shifts = np.linspace(0, w - w / n, n)\n        shifts -= shifts.mean()\n\n        assert_series_equal(res[\"y\"], df[\"y\"])\n        assert_series_equal(res[\"width\"], df[\"width\"] / n)\n\n        for val, shift in zip(levels, shifts):\n            rows = df[grp] == val\n            assert_series_equal(res.loc[rows, \"x\"], df.loc[rows, \"x\"] + shift)"},{"col":4,"comment":"null","endLoc":40,"header":"@pytest.fixture\n    def cat_vector(self, long_df)","id":3659,"name":"cat_vector","nodeType":"Function","startLoc":38,"text":"@pytest.fixture\n    def cat_vector(self, long_df):\n        return long_df[\"a\"]"},{"col":4,"comment":"null","endLoc":44,"header":"@pytest.fixture\n    def cat_order(self, cat_vector)","id":3660,"name":"cat_order","nodeType":"Function","startLoc":42,"text":"@pytest.fixture\n    def cat_order(self, cat_vector):\n        return categorical_order(cat_vector)"},{"col":4,"comment":"null","endLoc":270,"header":"def test_two_semantics(self, df)","id":3661,"name":"test_two_semantics","nodeType":"Function","startLoc":254,"text":"def test_two_semantics(self, df):\n\n        groupby = GroupBy([\"x\", \"grp2\", \"grp3\"])\n        res = Dodge()(df, groupby, \"x\", {})\n\n        levels = categorical_order(df[\"grp2\"]), categorical_order(df[\"grp3\"])\n        w, n = 0.8, len(levels[0]) * len(levels[1])\n\n        shifts = np.linspace(0, w - w / n, n)\n        shifts -= shifts.mean()\n\n        assert_series_equal(res[\"y\"], df[\"y\"])\n        assert_series_equal(res[\"width\"], df[\"width\"] / n)\n\n        for (v2, v3), shift in zip(product(*levels), shifts):\n            rows = (df[\"grp2\"] == v2) & (df[\"grp3\"] == v3)\n            assert_series_equal(res.loc[rows, \"x\"], df.loc[rows, \"x\"] + shift)"},{"id":3662,"name":"barplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6a6d582b-08c2-4fed-be56-afa1b986943a\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme(style=\\\"whitegrid\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"a7ef20b6-3bd8-4992-a270-4c3ecc86a0fa\",\n   \"metadata\": {},\n   \"source\": [\n    \"Group by a categorical varaible and plot aggregated values, with confidence intervals:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"0f5c3ece-6295-4933-8a87-e80cd604c089\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"df = sns.load_dataset(\\\"penguins\\\")\\n\",\n    \"sns.barplot(data=df, x=\\\"island\\\", y=\\\"body_mass_g\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"38f7c39e-485d-4b50-ac21-f1b402f26aa4\",\n   \"metadata\": {},\n   \"source\": [\n    \"Add a second layer of grouping:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ac1a28d1-b3bd-4158-86d0-3defc12f8566\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.barplot(data=df, x=\\\"island\\\", y=\\\"body_mass_g\\\", hue=\\\"sex\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"7f8fa070-a8f4-41fb-be74-c489acbdbcbe\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the error bars to show the standard deviation rather than a confidence interval:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"10445b78-a74a-4f14-a28b-a9164e592ae4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.barplot(data=df, x=\\\"island\\\", y=\\\"body_mass_g\\\", errorbar=\\\"sd\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"7f579f70-39a2-4d0c-baa2-9adae11ce2ce\",\n   \"metadata\": {},\n   \"source\": [\n    \"Customize the appearance of the plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d6f9ac1c-a77d-4ee3-bc5e-fec2071b33df\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.barplot(\\n\",\n    \"    data=df, x=\\\"body_mass_g\\\", y=\\\"island\\\",\\n\",\n    \"    errorbar=(\\\"pi\\\", 50), capsize=.4, errcolor=\\\".5\\\",\\n\",\n    \"    linewidth=3, edgecolor=\\\".5\\\", facecolor=(0, 0, 0, 0),\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"faedd6f9-a123-4927-9eff-a2046edf5c72\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"className":"TestStack","col":0,"comment":"null","endLoc":311,"id":3663,"nodeType":"Class","startLoc":273,"text":"class TestStack(MoveFixtures):\n\n    def test_basic(self, toy_df):\n\n        groupby = GroupBy([\"color\", \"group\"])\n        res = Stack()(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"x\"], [0, 0, 1])\n        assert_array_equal(res[\"y\"], [1, 3, 3])\n        assert_array_equal(res[\"baseline\"], [0, 1, 0])\n\n    def test_faceted(self, toy_df_facets):\n\n        groupby = GroupBy([\"color\", \"group\"])\n        res = Stack()(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"x\"], [0, 0, 1, 0, 1, 2])\n        assert_array_equal(res[\"y\"], [1, 3, 3, 1, 2, 3])\n        assert_array_equal(res[\"baseline\"], [0, 1, 0, 0, 0, 0])\n\n    def test_misssing_data(self, toy_df):\n\n        df = pd.DataFrame({\n            \"x\": [0, 0, 0],\n            \"y\": [2, np.nan, 1],\n            \"baseline\": [0, 0, 0],\n        })\n        res = Stack()(df, None, \"x\", {})\n        assert_array_equal(res[\"y\"], [2, np.nan, 3])\n        assert_array_equal(res[\"baseline\"], [0, np.nan, 2])\n\n    def test_baseline_homogeneity_check(self, toy_df):\n\n        toy_df[\"baseline\"] = [0, 1, 2]\n        groupby = GroupBy([\"color\", \"group\"])\n        move = Stack()\n        err = \"Stack move cannot be used when baselines\"\n        with pytest.raises(RuntimeError, match=err):\n            move(toy_df, groupby, \"x\", {})"},{"col":4,"comment":"null","endLoc":282,"header":"def test_basic(self, toy_df)","id":3664,"name":"test_basic","nodeType":"Function","startLoc":275,"text":"def test_basic(self, toy_df):\n\n        groupby = GroupBy([\"color\", \"group\"])\n        res = Stack()(toy_df, groupby, \"x\", {})\n\n        assert_array_equal(res[\"x\"], [0, 0, 1])\n        assert_array_equal(res[\"y\"], [1, 3, 3])\n        assert_array_equal(res[\"baseline\"], [0, 1, 0])"},{"col":4,"comment":"null","endLoc":48,"header":"@pytest.fixture\n    def dt_num_vector(self, long_df)","id":3665,"name":"dt_num_vector","nodeType":"Function","startLoc":46,"text":"@pytest.fixture\n    def dt_num_vector(self, long_df):\n        return long_df[\"t\"]"},{"id":3666,"name":"objects.Area.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn.objects as so\\n\",\n    \"from seaborn import load_dataset\\n\",\n    \"healthexp = (\\n\",\n    \"    load_dataset(\\\"healthexp\\\")\\n\",\n    \"    .pivot(\\\"Year\\\", \\\"Country\\\", \\\"Spending_USD\\\")\\n\",\n    \"    .interpolate()\\n\",\n    \"    .stack()\\n\",\n    \"    .rename(\\\"Spending_USD\\\")\\n\",\n    \"    .reset_index()\\n\",\n    \"    .sort_values(\\\"Country\\\")\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6d3bc7fe-0b0b-49eb-8f8b-ddd8c7441044\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p = so.Plot(healthexp, \\\"Year\\\", \\\"Spending_USD\\\").facet(\\\"Country\\\", wrap=3)\\n\",\n    \"p.add(so.Area())\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"3a47b7f1-31ef-4218-a1ea-c289f3c64ab5\",\n   \"metadata\": {},\n   \"source\": [\n    \"The `color` property sets both the edge and fill color:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1697359a-bf26-49d0-891b-49c207cab82d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Area(), color=\\\"Country\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"9bfaed37-7153-45d9-89e5-b348c7c14401\",\n   \"metadata\": {},\n   \"source\": [\n    \"It's also possible to map only the `edgecolor`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"39e5c9e5-793e-450c-a5d2-e09d5ad1f854\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Area(color=\\\".5\\\", edgewidth=2), edgecolor=\\\"Country\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"0b1a5297-9e96-472d-b284-919048e41358\",\n   \"metadata\": {},\n   \"source\": [\n    \"The mark is drawn as a polygon, but it can be combined with :class:`Line` to draw a shaded region by setting `edgewidth=0`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"42b65535-acf6-4634-84bd-6e35305e3018\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Area(edgewidth=0)).add(so.Line())\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"59761f97-eadb-4047-9e6b-09339545fe57\",\n   \"metadata\": {},\n   \"source\": [\n    \"The layer's orientation defines the axis that the mark fills from:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a1c30f88-6287-486d-ae4b-fc272bc8e6ab\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p.add(so.Area(), x=\\\"Spending_USD\\\", y=\\\"Year\\\", orient=\\\"y\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"f1b893c5-6847-4e5b-9fc2-4190ddd75099\",\n   \"metadata\": {},\n   \"source\": [\n    \"This mark can be stacked to show part-whole relationships:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"66a79e6e-3e7f-4f54-9394-f8b003a0e228\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"(\\n\",\n    \"    so.Plot(healthexp, \\\"Year\\\", \\\"Spending_USD\\\", color=\\\"Country\\\")\\n\",\n    \"    .add(so.Area(alpha=.7), so.Stack())\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"69f4e423-94f4-4003-b337-12162d1040c2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":52,"header":"@pytest.fixture\n    def dt_cat_vector(self, long_df)","id":3667,"name":"dt_cat_vector","nodeType":"Function","startLoc":50,"text":"@pytest.fixture\n    def dt_cat_vector(self, long_df):\n        return long_df[\"d\"]"},{"col":4,"comment":"null","endLoc":56,"header":"@pytest.fixture\n    def vectors(self, num_vector, cat_vector)","id":3668,"name":"vectors","nodeType":"Function","startLoc":54,"text":"@pytest.fixture\n    def vectors(self, num_vector, cat_vector):\n        return {\"num\": num_vector, \"cat\": cat_vector}"},{"className":"TestCoordinate","col":0,"comment":"null","endLoc":71,"id":3669,"nodeType":"Class","startLoc":59,"text":"class TestCoordinate(DataFixtures):\n\n    def test_bad_scale_arg_str(self, num_vector):\n\n        err = \"Unknown magic arg for x scale: 'xxx'.\"\n        with pytest.raises(ValueError, match=err):\n            Coordinate(\"x\").infer_scale(\"xxx\", num_vector)\n\n    def test_bad_scale_arg_type(self, cat_vector):\n\n        err = \"Magic arg for x scale must be str, not list.\"\n        with pytest.raises(TypeError, match=err):\n            Coordinate(\"x\").infer_scale([1, 2, 3], cat_vector)"},{"id":3670,"name":"objects.Dots.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn.objects as so\\n\",\n    \"from seaborn import load_dataset\\n\",\n    \"mpg = load_dataset(\\\"mpg\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"f8e7b343-0301-49b3-8d42-862266d322bb\",\n   \"metadata\": {},\n   \"source\": [\n    \"This mark draws relatively small, partially-transparent dots:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d668d7f6-555b-4b5d-876e-35e259076d2a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p1 = so.Plot(mpg, \\\"horsepower\\\", \\\"mpg\\\")\\n\",\n    \"p1.add(so.Dots())\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"a2cf4669-9c91-4adc-9e3a-3b0660e7898e\",\n   \"metadata\": {},\n   \"source\": [\n    \"Fixing or mapping the `color` property changes both the stroke (edge) and fill:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"bba2b1c5-22fd-4f44-af8d-defb31dfbe9d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p1.add(so.Dots(), color=\\\"origin\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"bf967d57-22cf-4bce-b718-aae6936719e6\",\n   \"metadata\": {},\n   \"source\": [\n    \"These properties can be independently parametrized (although the resulting plot may not always be clear):\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c45261a9-fb88-4eb5-b633-060debda261b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"(\\n\",\n    \"    p1.add(so.Dots(fillalpha=.5), color=\\\"origin\\\", fillcolor=\\\"weight\\\")\\n\",\n    \"    .scale(fillcolor=\\\"binary\\\")\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"b20dcaee-8e09-4a76-8eff-5289ef43ea8c\",\n   \"metadata\": {},\n   \"source\": [\n    \"Filled and unfilled markers will happily mix:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a1a9bdda-abb7-4850-a936-ceed518b9b17\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"p1.add(so.Dots(stroke=1), marker=\\\"origin\\\").scale(marker=[\\\"o\\\", \\\"x\\\", (6, 2, 1)])\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"1d932f10-e8f8-4114-9362-3da82c7b5ac0\",\n   \"metadata\": {},\n   \"source\": [\n    \"The partial opacity also helps to see local density when using jitter:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"692e1611-4804-4979-b616-041e9fa9cdd9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"(\\n\",\n    \"    so.Plot(mpg, \\\"horsepower\\\", \\\"origin\\\")\\n\",\n    \"    .add(so.Dots(), so.Jitter(.25))\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"acd5788f-e62b-497c-a109-f0bc02b8cae9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":65,"header":"def test_bad_scale_arg_str(self, num_vector)","id":3671,"name":"test_bad_scale_arg_str","nodeType":"Function","startLoc":61,"text":"def test_bad_scale_arg_str(self, num_vector):\n\n        err = \"Unknown magic arg for x scale: 'xxx'.\"\n        with pytest.raises(ValueError, match=err):\n            Coordinate(\"x\").infer_scale(\"xxx\", num_vector)"},{"fileName":"pair_grid_with_kde.py","filePath":"examples","id":3672,"nodeType":"File","text":"\"\"\"\nPaired density and scatterplot matrix\n=====================================\n\n_thumb: .5, .5\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"white\")\n\ndf = sns.load_dataset(\"penguins\")\n\ng = sns.PairGrid(df, diag_sharey=False)\ng.map_upper(sns.scatterplot, s=15)\ng.map_lower(sns.kdeplot)\ng.map_diag(sns.kdeplot, lw=2)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3673,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"col":4,"comment":"null","endLoc":291,"header":"def test_faceted(self, toy_df_facets)","id":3674,"name":"test_faceted","nodeType":"Function","startLoc":284,"text":"def test_faceted(self, toy_df_facets):\n\n        groupby = GroupBy([\"color\", \"group\"])\n        res = Stack()(toy_df_facets, groupby, \"x\", {})\n\n        assert_array_equal(res[\"x\"], [0, 0, 1, 0, 1, 2])\n        assert_array_equal(res[\"y\"], [1, 3, 3, 1, 2, 3])\n        assert_array_equal(res[\"baseline\"], [0, 1, 0, 0, 0, 0])"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":3675,"name":"df","nodeType":"Attribute","startLoc":10,"text":"df"},{"col":4,"comment":"null","endLoc":302,"header":"def test_misssing_data(self, toy_df)","id":3676,"name":"test_misssing_data","nodeType":"Function","startLoc":293,"text":"def test_misssing_data(self, toy_df):\n\n        df = pd.DataFrame({\n            \"x\": [0, 0, 0],\n            \"y\": [2, np.nan, 1],\n            \"baseline\": [0, 0, 0],\n        })\n        res = Stack()(df, None, \"x\", {})\n        assert_array_equal(res[\"y\"], [2, np.nan, 3])\n        assert_array_equal(res[\"baseline\"], [0, np.nan, 2])"},{"col":4,"comment":"null","endLoc":311,"header":"def test_baseline_homogeneity_check(self, toy_df)","id":3677,"name":"test_baseline_homogeneity_check","nodeType":"Function","startLoc":304,"text":"def test_baseline_homogeneity_check(self, toy_df):\n\n        toy_df[\"baseline\"] = [0, 1, 2]\n        groupby = GroupBy([\"color\", \"group\"])\n        move = Stack()\n        err = \"Stack move cannot be used when baselines\"\n        with pytest.raises(RuntimeError, match=err):\n            move(toy_df, groupby, \"x\", {})"},{"attributeType":"PairGrid","col":0,"comment":"null","endLoc":12,"id":3678,"name":"g","nodeType":"Attribute","startLoc":12,"text":"g"},{"className":"TestShift","col":0,"comment":"null","endLoc":329,"id":3679,"nodeType":"Class","startLoc":314,"text":"class TestShift(MoveFixtures):\n\n    def test_default(self, toy_df):\n\n        gb = GroupBy([\"color\", \"group\"])\n        res = Shift()(toy_df, gb, \"x\", {})\n        for col in toy_df:\n            assert_series_equal(toy_df[col], res[col])\n\n    @pytest.mark.parametrize(\"x,y\", [(.3, 0), (0, .2), (.1, .3)])\n    def test_moves(self, toy_df, x, y):\n\n        gb = GroupBy([\"color\", \"group\"])\n        res = Shift(x=x, y=y)(toy_df, gb, \"x\", {})\n        assert_array_equal(res[\"x\"], toy_df[\"x\"] + x)\n        assert_array_equal(res[\"y\"], toy_df[\"y\"] + y)"},{"col":4,"comment":"null","endLoc":321,"header":"def test_default(self, toy_df)","id":3680,"name":"test_default","nodeType":"Function","startLoc":316,"text":"def test_default(self, toy_df):\n\n        gb = GroupBy([\"color\", \"group\"])\n        res = Shift()(toy_df, gb, \"x\", {})\n        for col in toy_df:\n            assert_series_equal(toy_df[col], res[col])"},{"col":0,"comment":"","endLoc":6,"header":"pair_grid_with_kde.py#","id":3681,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nPaired density and scatterplot matrix\n=====================================\n\n_thumb: .5, .5\n\"\"\"\n\nsns.set_theme(style=\"white\")\n\ndf = sns.load_dataset(\"penguins\")\n\ng = sns.PairGrid(df, diag_sharey=False)\n\ng.map_upper(sns.scatterplot, s=15)\n\ng.map_lower(sns.kdeplot)\n\ng.map_diag(sns.kdeplot, lw=2)"},{"id":3682,"name":"introduction.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _introduction:\\n\",\n    \"\\n\",\n    \".. currentmodule:: seaborn\\n\",\n    \"\\n\",\n    \"An introduction to seaborn\\n\",\n    \"==========================\\n\",\n    \"\\n\",\n    \"Seaborn is a library for making statistical graphics in Python. It builds on top of `matplotlib `_ and integrates closely with `pandas `_ data structures.\\n\",\n    \"\\n\",\n    \"Seaborn helps you explore and understand your data. Its plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.\\n\",\n    \"\\n\",\n    \"Here's an example of what seaborn can do:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Import seaborn\\n\",\n    \"import seaborn as sns\\n\",\n    \"\\n\",\n    \"# Apply the default theme\\n\",\n    \"sns.set_theme()\\n\",\n    \"\\n\",\n    \"# Load an example dataset\\n\",\n    \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n    \"\\n\",\n    \"# Create a visualization\\n\",\n    \"sns.relplot(\\n\",\n    \"    data=tips,\\n\",\n    \"    x=\\\"total_bill\\\", y=\\\"tip\\\", col=\\\"time\\\",\\n\",\n    \"    hue=\\\"smoker\\\", style=\\\"smoker\\\", size=\\\"size\\\",\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"A few things have happened here. Let's go through them one by one:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# Import seaborn\\n\",\n    \"import seaborn as sns\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Seaborn is the only library we need to import for this simple example. By convention, it is imported with the shorthand ``sns``.\\n\",\n    \"\\n\",\n    \"Behind the scenes, seaborn uses matplotlib to draw its plots. For interactive work, it's recommended to use a Jupyter/IPython interface in `matplotlib mode `_, or else you'll have to call :func:`matplotlib.pyplot.show` when you want to see the plot.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# Apply the default theme\\n\",\n    \"sns.set_theme()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"This uses the matplotlib rcParam system and will affect how all matplotlib plots look, even if you don't make them with seaborn. Beyond the default theme, there are :doc:`several other options `, and you can independently control the style and scaling of the plot to quickly translate your work between presentation contexts (e.g., making a version of your figure that will have readable fonts when projected during a talk). If you like the matplotlib defaults or prefer a different theme, you can skip this step and still use the seaborn plotting functions.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# Load an example dataset\\n\",\n    \"tips = sns.load_dataset(\\\"tips\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Most code in the docs will use the :func:`load_dataset` function to get quick access to an example dataset. There's nothing special about these datasets: they are just pandas dataframes, and we could have loaded them with :func:`pandas.read_csv` or built them by hand. Most of the examples in the documentation will specify data using pandas dataframes, but seaborn is very flexible about the :doc:`data structures ` that it accepts.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide-output\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# Create a visualization\\n\",\n    \"sns.relplot(\\n\",\n    \"    data=tips,\\n\",\n    \"    x=\\\"total_bill\\\", y=\\\"tip\\\", col=\\\"time\\\",\\n\",\n    \"    hue=\\\"smoker\\\", style=\\\"smoker\\\", size=\\\"size\\\",\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"This plot shows the relationship between five variables in the tips dataset using a single call to the seaborn function :func:`relplot`. Notice how we provided only the names of the variables and their roles in the plot. Unlike when using matplotlib directly, it wasn't necessary to specify attributes of the plot elements in terms of the color values or marker codes. Behind the scenes, seaborn handled the translation from values in the dataframe to arguments that matplotlib understands. This declarative approach lets you stay focused on the questions that you want to answer, rather than on the details of how to control matplotlib.\\n\",\n    \"\\n\",\n    \".. _intro_api_abstraction:\\n\",\n    \"\\n\",\n    \"A high-level API for statistical graphics\\n\",\n    \"-----------------------------------------\\n\",\n    \"\\n\",\n    \"There is no universally best way to visualize data. Different questions are best answered by different plots. Seaborn makes it easy to switch between different visual representations by using a consistent dataset-oriented API.\\n\",\n    \"\\n\",\n    \"The function :func:`relplot` is named that way because it is designed to visualize many different statistical *relationships*. While scatter plots are often effective, relationships where one variable represents a measure of time are better represented by a line. The :func:`relplot` function has a convenient ``kind`` parameter that lets you easily switch to this alternate representation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"dots = sns.load_dataset(\\\"dots\\\")\\n\",\n    \"sns.relplot(\\n\",\n    \"    data=dots, kind=\\\"line\\\",\\n\",\n    \"    x=\\\"time\\\", y=\\\"firing_rate\\\", col=\\\"align\\\",\\n\",\n    \"    hue=\\\"choice\\\", size=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n    \"    facet_kws=dict(sharex=False),\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Notice how the ``size`` and ``style`` parameters are used in both the scatter and line plots, but they affect the two visualizations differently: changing the marker area and symbol in the scatter plot vs the line width and dashing in the line plot. We did not need to keep those details in mind, letting us focus on the overall structure of the plot and the information we want it to convey.\\n\",\n    \"\\n\",\n    \".. _intro_stat_estimation:\\n\",\n    \"\\n\",\n    \"Statistical estimation\\n\",\n    \"~~~~~~~~~~~~~~~~~~~~~~\\n\",\n    \"\\n\",\n    \"Often, we are interested in the *average* value of one variable as a function of other variables. Many seaborn functions will automatically perform the statistical estimation that is necessary to answer these questions:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"fmri = sns.load_dataset(\\\"fmri\\\")\\n\",\n    \"sns.relplot(\\n\",\n    \"    data=fmri, kind=\\\"line\\\",\\n\",\n    \"    x=\\\"timepoint\\\", y=\\\"signal\\\", col=\\\"region\\\",\\n\",\n    \"    hue=\\\"event\\\", style=\\\"event\\\",\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"When statistical values are estimated, seaborn will use bootstrapping to compute confidence intervals and draw error bars representing the uncertainty of the estimate.\\n\",\n    \"\\n\",\n    \"Statistical estimation in seaborn goes beyond descriptive statistics. For example, it is possible to enhance a scatterplot by including a linear regression model (and its uncertainty) using :func:`lmplot`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lmplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", col=\\\"time\\\", hue=\\\"smoker\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_distributions:\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"Distributional representations\\n\",\n    \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n    \"\\n\",\n    \"Statistical analyses require knowledge about the distribution of variables in your dataset. The seaborn function :func:`displot` supports several approaches to visualizing distributions. These include classic techniques like histograms and computationally-intensive approaches like kernel density estimation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=tips, x=\\\"total_bill\\\", col=\\\"time\\\", kde=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Seaborn also tries to promote techniques that are powerful but less familiar, such as calculating and plotting the empirical cumulative distribution function of the data:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=tips, kind=\\\"ecdf\\\", x=\\\"total_bill\\\", col=\\\"time\\\", hue=\\\"smoker\\\", rug=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_categorical:\\n\",\n    \"\\n\",\n    \"Plots for categorical data\\n\",\n    \"~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n    \"\\n\",\n    \"Several specialized plot types in seaborn are oriented towards visualizing categorical data. They can be accessed through :func:`catplot`. These plots offer different levels of granularity. At the finest level, you may wish to see every observation by drawing a \\\"swarm\\\" plot: a scatter plot that adjusts the positions of the points along the categorical axis so that they don't overlap:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.catplot(data=tips, kind=\\\"swarm\\\", x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"smoker\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Alternately, you could use kernel density estimation to represent the underlying distribution that the points are sampled from:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.catplot(data=tips, kind=\\\"violin\\\", x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"smoker\\\", split=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Or you could show only the mean value and its confidence interval within each nested category:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.catplot(data=tips, kind=\\\"bar\\\", x=\\\"day\\\", y=\\\"total_bill\\\", hue=\\\"smoker\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_dataset_funcs:\\n\",\n    \"\\n\",\n    \"Multivariate views on complex datasets\\n\",\n    \"--------------------------------------\\n\",\n    \"\\n\",\n    \"Some seaborn functions combine multiple kinds of plots to quickly give informative summaries of a dataset. One, :func:`jointplot`, focuses on a single relationship. It plots the joint distribution between two variables along with each variable's marginal distribution:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n    \"sns.jointplot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", hue=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The other, :func:`pairplot`, takes a broader view: it shows joint and marginal distributions for all pairwise relationships and for each variable, respectively:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(data=penguins, hue=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_figure_classes:\\n\",\n    \"\\n\",\n    \"Lower-level tools for building figures\\n\",\n    \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n    \"\\n\",\n    \"These tools work by combining :doc:`axes-level ` plotting functions with objects that manage the layout of the figure, linking the structure of a dataset to a :doc:`grid of axes `. Both elements are part of the public API, and you can use them directly to create complex figures with only a few more lines of code:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.PairGrid(penguins, hue=\\\"species\\\", corner=True)\\n\",\n    \"g.map_lower(sns.kdeplot, hue=None, levels=5, color=\\\".2\\\")\\n\",\n    \"g.map_lower(sns.scatterplot, marker=\\\"+\\\")\\n\",\n    \"g.map_diag(sns.histplot, element=\\\"step\\\", linewidth=0, kde=True)\\n\",\n    \"g.add_legend(frameon=True)\\n\",\n    \"g.legend.set_bbox_to_anchor((.61, .6))\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_defaults:\\n\",\n    \"\\n\",\n    \"Opinionated defaults and flexible customization\\n\",\n    \"-----------------------------------------------\\n\",\n    \"\\n\",\n    \"Seaborn creates complete graphics with a single function call: when possible, its functions will automatically add informative axis labels and legends that explain the semantic mappings in the plot.\\n\",\n    \"\\n\",\n    \"In many cases, seaborn will also choose default values for its parameters based on characteristics of the data. For example, the :doc:`color mappings ` that we have seen so far used distinct hues (blue, orange, and sometimes green) to represent different levels of the categorical variables assigned to ``hue``. When mapping a numeric variable, some functions will switch to a continuous gradient:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.relplot(\\n\",\n    \"    data=penguins,\\n\",\n    \"    x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"body_mass_g\\\"\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"When you're ready to share or publish your work, you'll probably want to polish the figure beyond what the defaults achieve. Seaborn allows for several levels of customization. It defines multiple built-in :doc:`themes ` that apply to all figures, its functions have standardized parameters that can modify the semantic mappings for each plot, and additional keyword arguments are passed down to the underlying matplotlib artists, allowing even more control. Once you've created a plot, its properties can be modified through both the seaborn API and by dropping down to the matplotlib layer for fine-grained tweaking:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.set_theme(style=\\\"ticks\\\", font_scale=1.25)\\n\",\n    \"g = sns.relplot(\\n\",\n    \"    data=penguins,\\n\",\n    \"    x=\\\"bill_length_mm\\\", y=\\\"bill_depth_mm\\\", hue=\\\"body_mass_g\\\",\\n\",\n    \"    palette=\\\"crest\\\", marker=\\\"x\\\", s=100,\\n\",\n    \")\\n\",\n    \"g.set_axis_labels(\\\"Bill length (mm)\\\", \\\"Bill depth (mm)\\\", labelpad=10)\\n\",\n    \"g.legend.set_title(\\\"Body mass (g)\\\")\\n\",\n    \"g.figure.set_size_inches(6.5, 4.5)\\n\",\n    \"g.ax.margins(.15)\\n\",\n    \"g.despine(trim=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_matplotlib:\\n\",\n    \"\\n\",\n    \"Relationship to matplotlib\\n\",\n    \"~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n    \"\\n\",\n    \"Seaborn's integration with matplotlib allows you to use it across the many environments that matplotlib supports, including exploratory analysis in notebooks, real-time interaction in GUI applications, and archival output in a number of raster and vector formats.\\n\",\n    \"\\n\",\n    \"While you can be productive using only seaborn functions, full customization of your graphics will require some knowledge of matplotlib's concepts and API. One aspect of the learning curve for new users of seaborn will be knowing when dropping down to the matplotlib layer is necessary to achieve a particular customization. On the other hand, users coming from matplotlib will find that much of their knowledge transfers.\\n\",\n    \"\\n\",\n    \"Matplotlib has a comprehensive and powerful API; just about any attribute of the figure can be changed to your liking. A combination of seaborn's high-level interface and matplotlib's deep customizability will allow you both to quickly explore your data and to create graphics that can be tailored into a `publication quality `_ final product.\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _intro_next_steps:\\n\",\n    \"\\n\",\n    \"Next steps\\n\",\n    \"~~~~~~~~~~\\n\",\n    \"\\n\",\n    \"You have a few options for where to go next. You might first want to learn how to :doc:`install seaborn `. Once that's done, you can browse the :doc:`example gallery ` to get a broader sense for what kind of graphics seaborn can produce. Or you can read through the rest of the :doc:`user guide and tutorial ` for a deeper discussion of the different tools and what they are designed to accomplish. If you have a specific plot in mind and want to know how to make it, you could check out the :doc:`API reference `, which documents each function's parameters and shows many examples to illustrate usage.\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"celltoolbar\": \"Tags\",\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":3683,"name":"PACKAGING_LICENSE","nodeType":"TextFile","path":"licences","text":"Copyright (c) Donald Stufft and individual contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright\n       notice, this list of conditions and the following disclaimer in the\n       documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"col":4,"comment":"null","endLoc":1818,"header":"def test_bad_kind(self)","id":3684,"name":"test_bad_kind","nodeType":"Function","startLoc":1815,"text":"def test_bad_kind(self):\n\n        with pytest.raises(ValueError):\n            ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=\"not_a_kind\")"},{"fileName":"regression.py","filePath":"seaborn/_stats","id":3685,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass\n\nimport numpy as np\nimport pandas as pd\n\nfrom seaborn._stats.base import Stat\n\n\n@dataclass\nclass PolyFit(Stat):\n    \"\"\"\n    Fit a polynomial of the given order and resample data onto predicted curve.\n    \"\"\"\n    # This is a provisional class that is useful for building out functionality.\n    # It may or may not change substantially in form or dissappear as we think\n    # through the organization of the stats subpackage.\n\n    order: int = 2\n    gridsize: int = 100\n\n    def _fit_predict(self, data):\n\n        x = data[\"x\"]\n        y = data[\"y\"]\n        if x.nunique() <= self.order:\n            # TODO warn?\n            xx = yy = []\n        else:\n            p = np.polyfit(x, y, self.order)\n            xx = np.linspace(x.min(), x.max(), self.gridsize)\n            yy = np.polyval(p, xx)\n\n        return pd.DataFrame(dict(x=xx, y=yy))\n\n    # TODO we should have a way of identifying the method that will be applied\n    # and then only define __call__ on a base-class of stats with this pattern\n\n    def __call__(self, data, groupby, orient, scales):\n\n        return (\n            groupby\n            .apply(data.dropna(subset=[\"x\", \"y\"]), self._fit_predict)\n        )\n\n\n@dataclass\nclass OLSFit(Stat):\n\n    ...\n"},{"col":4,"comment":"null","endLoc":1824,"header":"def test_unsupported_hue_kind(self)","id":3686,"name":"test_unsupported_hue_kind","nodeType":"Function","startLoc":1820,"text":"def test_unsupported_hue_kind(self):\n\n        for kind in [\"reg\", \"resid\", \"hex\"]:\n            with pytest.raises(ValueError):\n                ag.jointplot(x=\"x\", y=\"y\", hue=\"a\", data=self.data, kind=kind)"},{"className":"OLSFit","col":0,"comment":"null","endLoc":50,"id":3687,"nodeType":"Class","startLoc":47,"text":"@dataclass\nclass OLSFit(Stat):\n\n    ..."},{"col":4,"comment":"null","endLoc":1834,"header":"def test_leaky_dict(self)","id":3688,"name":"test_leaky_dict","nodeType":"Function","startLoc":1826,"text":"def test_leaky_dict(self):\n        # Validate input dicts are unchanged by jointplot plotting function\n\n        for kwarg in (\"joint_kws\", \"marginal_kws\"):\n            for kind in (\"hex\", \"kde\", \"resid\", \"reg\", \"scatter\"):\n                empty_dict = {}\n                ag.jointplot(x=\"x\", y=\"y\", data=self.data, kind=kind,\n                             **{kwarg: empty_dict})\n                assert empty_dict == {}"},{"id":3689,"name":"lineplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import pandas as pd\\n\",\n    \"import seaborn as sns\\n\",\n    \"import matplotlib as mpl\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"sns.set_theme()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The ``flights`` dataset has 10 years of monthly airline passenger data:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"flights = sns.load_dataset(\\\"flights\\\")\\n\",\n    \"flights.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"To draw a line plot using long-form data, assign the ``x`` and ``y`` variables:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"may_flights = flights.query(\\\"month == 'May'\\\")\\n\",\n    \"sns.lineplot(data=may_flights, x=\\\"year\\\", y=\\\"passengers\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Pivot the dataframe to a wide-form representation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"flights_wide = flights.pivot(\\\"year\\\", \\\"month\\\", \\\"passengers\\\")\\n\",\n    \"flights_wide.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"To plot a single vector, pass it to ``data``. If the vector is a :class:`pandas.Series`, it will be plotted against its index:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=flights_wide[\\\"May\\\"])\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Passing the entire wide-form dataset to ``data`` plots a separate line for each column:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=flights_wide)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Passing the entire dataset in long-form mode will aggregate over repeated values (each year) to show the mean and 95% confidence interval:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=flights, x=\\\"year\\\", y=\\\"passengers\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assign a grouping semantic (``hue``, ``size``, or ``style``) to plot separate lines\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=flights, x=\\\"year\\\", y=\\\"passengers\\\", hue=\\\"month\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The same column can be assigned to multiple semantic variables, which can increase the accessibility of the plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=flights, x=\\\"year\\\", y=\\\"passengers\\\", hue=\\\"month\\\", style=\\\"month\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the `orient` parameter to aggregate and sort along the vertical dimension of the plot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=flights, x=\\\"passengers\\\", y=\\\"year\\\", orient=\\\"y\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Each semantic variable can also represent a different column. For that, we'll need a more complex dataset:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"fmri = sns.load_dataset(\\\"fmri\\\")\\n\",\n    \"fmri.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Repeated observations are aggregated even when semantic grouping is used:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assign both ``hue`` and ``style`` to represent two different grouping variables:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(data=fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"region\\\", style=\\\"event\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"When assigning a ``style`` variable, markers can be used instead of (or along with) dashes to distinguish the groups:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=fmri,\\n\",\n    \"    x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\", style=\\\"event\\\",\\n\",\n    \"    markers=True, dashes=False\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Show error bars instead of error bands and extend them to two standard error widths:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\", err_style=\\\"bars\\\", errorbar=(\\\"se\\\", 2),\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assigning the ``units`` variable will plot multiple lines without applying a semantic mapping:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=fmri.query(\\\"region == 'frontal'\\\"),\\n\",\n    \"    x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\", units=\\\"subject\\\",\\n\",\n    \"    estimator=None, lw=1,\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Load another dataset with a numeric grouping variable:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"dots = sns.load_dataset(\\\"dots\\\").query(\\\"align == 'dots'\\\")\\n\",\n    \"dots.head()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assigning a numeric variable to ``hue`` maps it differently, using a different default palette and a quantitative color mapping:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=dots, x=\\\"time\\\", y=\\\"firing_rate\\\", hue=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Control the color mapping by setting the ``palette`` and passing a :class:`matplotlib.colors.Normalize` object:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=dots.query(\\\"coherence > 0\\\"),\\n\",\n    \"    x=\\\"time\\\", y=\\\"firing_rate\\\", hue=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n    \"     palette=\\\"flare\\\", hue_norm=mpl.colors.LogNorm(),\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Or pass specific colors, either as a Python list or dictionary:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"palette = sns.color_palette(\\\"mako_r\\\", 6)\\n\",\n    \"sns.lineplot(\\n\",\n    \"    data=dots, x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n    \"    hue=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n    \"    palette=palette\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Assign the ``size`` semantic to map the width of the lines with a numeric variable:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=dots, x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n    \"    size=\\\"coherence\\\", hue=\\\"choice\\\",\\n\",\n    \"    legend=\\\"full\\\"\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Pass a a tuple, ``sizes=(smallest, largest)``, to control the range of linewidths used to map the ``size`` semantic:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.lineplot(\\n\",\n    \"    data=dots, x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n    \"    size=\\\"coherence\\\", hue=\\\"choice\\\",\\n\",\n    \"    sizes=(.25, 2.5)\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"By default, the observations are sorted by ``x``. Disable this to plot a line with the order that observations appear in the dataset:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"x, y = np.random.normal(size=(2, 5000)).cumsum(axis=1)\\n\",\n    \"sns.lineplot(x=x, y=y, sort=False, lw=1)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use :func:`relplot` to combine :func:`lineplot` and :class:`FacetGrid`. This allows grouping within additional categorical variables. Using :func:`relplot` is safer than using :class:`FacetGrid` directly, as it ensures synchronization of the semantic mappings across facets:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.relplot(\\n\",\n    \"    data=fmri, x=\\\"timepoint\\\", y=\\\"signal\\\",\\n\",\n    \"    col=\\\"region\\\", hue=\\\"event\\\", style=\\\"event\\\",\\n\",\n    \"    kind=\\\"line\\\"\\n\",\n    \")\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"interpreter\": {\n   \"hash\": \"8bdfc9d9da1e36addfcfc8a3409187c45d33387af0f87d0d91e99e8d6403f1c3\"\n  },\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"col":4,"comment":"null","endLoc":329,"header":"@pytest.mark.parametrize(\"x,y\", [(.3, 0), (0, .2), (.1, .3)])\n    def test_moves(self, toy_df, x, y)","id":3690,"name":"test_moves","nodeType":"Function","startLoc":323,"text":"@pytest.mark.parametrize(\"x,y\", [(.3, 0), (0, .2), (.1, .3)])\n    def test_moves(self, toy_df, x, y):\n\n        gb = GroupBy([\"color\", \"group\"])\n        res = Shift(x=x, y=y)(toy_df, gb, \"x\", {})\n        assert_array_equal(res[\"x\"], toy_df[\"x\"] + x)\n        assert_array_equal(res[\"y\"], toy_df[\"y\"] + y)"},{"col":4,"comment":"null","endLoc":1840,"header":"def test_distplot_kwarg_warning(self, long_df)","id":3691,"name":"test_distplot_kwarg_warning","nodeType":"Function","startLoc":1836,"text":"def test_distplot_kwarg_warning(self, long_df):\n\n        with pytest.warns(UserWarning):\n            g = ag.jointplot(data=long_df, x=\"x\", y=\"y\", marginal_kws=dict(rug=True))\n        assert g.ax_marg_x.patches"},{"col":4,"comment":"null","endLoc":48,"header":"def setup_labels(self, x, *args, **kwargs)","id":3692,"name":"setup_labels","nodeType":"Function","startLoc":42,"text":"def setup_labels(self, x, *args, **kwargs):\n\n        s = Continuous().label(*args, **kwargs)._setup(x, Coordinate())\n        a = PseudoAxis(s._matplotlib_scale)\n        a.set_view_interval(0, 1)\n        locs = a.major.locator()\n        return a, locs"},{"id":3693,"name":"layout.html","nodeType":"TextFile","path":"doc/_templates","text":"{% extends \"!layout.html\" %}\n\n{%- block footer %}\n\n{%- endblock %}\n"},{"id":3694,"name":"SCIPY_LICENSE","nodeType":"TextFile","path":"licences","text":"Copyright (c) 2001-2002 Enthought, Inc.  2003-2019, SciPy Developers.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following\n   disclaimer in the documentation and/or other materials provided\n   with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"col":4,"comment":"null","endLoc":71,"header":"def test_bad_scale_arg_type(self, cat_vector)","id":3695,"name":"test_bad_scale_arg_type","nodeType":"Function","startLoc":67,"text":"def test_bad_scale_arg_type(self, cat_vector):\n\n        err = \"Magic arg for x scale must be str, not list.\"\n        with pytest.raises(TypeError, match=err):\n            Coordinate(\"x\").infer_scale([1, 2, 3], cat_vector)"},{"className":"TestNorm","col":0,"comment":"null","endLoc":367,"id":3696,"nodeType":"Class","startLoc":332,"text":"class TestNorm(MoveFixtures):\n\n    @pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_no_groups(self, df, orient):\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        gb = GroupBy([\"null\"])\n        res = Norm()(df, gb, orient, {})\n        assert res[other].max() == pytest.approx(1)\n\n    @pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_groups(self, df, orient):\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        gb = GroupBy([\"grp2\"])\n        res = Norm()(df, gb, orient, {})\n        for _, grp in res.groupby(\"grp2\"):\n            assert grp[other].max() == pytest.approx(1)\n\n    def test_sum(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(\"sum\")(df, gb, \"x\", {})\n        assert res[\"y\"].sum() == pytest.approx(1)\n\n    def test_where(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(where=\"x == 2\")(df, gb, \"x\", {})\n        assert res.loc[res[\"x\"] == 2, \"y\"].max() == pytest.approx(1)\n\n    def test_percent(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(percent=True)(df, gb, \"x\", {})\n        assert res[\"y\"].max() == pytest.approx(100)"},{"col":4,"comment":"null","endLoc":340,"header":"@pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_no_groups(self, df, orient)","id":3697,"name":"test_default_no_groups","nodeType":"Function","startLoc":334,"text":"@pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_no_groups(self, df, orient):\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        gb = GroupBy([\"null\"])\n        res = Norm()(df, gb, orient, {})\n        assert res[other].max() == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":349,"header":"@pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_groups(self, df, orient)","id":3698,"name":"test_default_groups","nodeType":"Function","startLoc":342,"text":"@pytest.mark.parametrize(\"orient\", [\"x\", \"y\"])\n    def test_default_groups(self, df, orient):\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        gb = GroupBy([\"grp2\"])\n        res = Norm()(df, gb, orient, {})\n        for _, grp in res.groupby(\"grp2\"):\n            assert grp[other].max() == pytest.approx(1)"},{"className":"TestColor","col":0,"comment":"null","endLoc":257,"id":3699,"nodeType":"Class","startLoc":74,"text":"class TestColor(DataFixtures):\n\n    def assert_same_rgb(self, a, b):\n        assert_array_equal(a[:, :3], b[:, :3])\n\n    def test_nominal_default_palette(self, cat_vector, cat_order):\n\n        m = Color().get_mapping(Nominal(), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = color_palette(None, n)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_default_palette_large(self):\n\n        vector = pd.Series(list(\"abcdefghijklmnopqrstuvwxyz\"))\n        m = Color().get_mapping(Nominal(), vector)\n        actual = m(np.arange(26))\n        expected = color_palette(\"husl\", 26)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_named_palette(self, cat_vector, cat_order):\n\n        palette = \"Blues\"\n        m = Color().get_mapping(Nominal(palette), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = color_palette(palette, n)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_list_palette(self, cat_vector, cat_order):\n\n        palette = color_palette(\"Reds\", len(cat_order))\n        m = Color().get_mapping(Nominal(palette), cat_vector)\n        actual = m(np.arange(len(palette)))\n        expected = palette\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_dict_palette(self, cat_vector, cat_order):\n\n        colors = color_palette(\"Greens\")\n        palette = dict(zip(cat_order, colors))\n        m = Color().get_mapping(Nominal(palette), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = colors\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)\n\n    def test_nominal_dict_with_missing_keys(self, cat_vector, cat_order):\n\n        palette = dict(zip(cat_order[1:], color_palette(\"Purples\")))\n        with pytest.raises(ValueError, match=\"No entry in color dict\"):\n            Color(\"color\").get_mapping(Nominal(palette), cat_vector)\n\n    def test_nominal_list_too_short(self, cat_vector, cat_order):\n\n        n = len(cat_order) - 1\n        palette = color_palette(\"Oranges\", n)\n        msg = rf\"The edgecolor list has fewer values \\({n}\\) than needed \\({n + 1}\\)\"\n        with pytest.warns(UserWarning, match=msg):\n            Color(\"edgecolor\").get_mapping(Nominal(palette), cat_vector)\n\n    def test_nominal_list_too_long(self, cat_vector, cat_order):\n\n        n = len(cat_order) + 1\n        palette = color_palette(\"Oranges\", n)\n        msg = rf\"The edgecolor list has more values \\({n}\\) than needed \\({n - 1}\\)\"\n        with pytest.warns(UserWarning, match=msg):\n            Color(\"edgecolor\").get_mapping(Nominal(palette), cat_vector)\n\n    def test_continuous_default_palette(self, num_vector):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        m = Color().get_mapping(Continuous(), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_named_palette(self, num_vector):\n\n        pal = \"flare\"\n        cmap = color_palette(pal, as_cmap=True)\n        m = Color().get_mapping(Continuous(pal), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_tuple_palette(self, num_vector):\n\n        vals = (\"blue\", \"red\")\n        cmap = color_palette(\"blend:\" + \",\".join(vals), as_cmap=True)\n        m = Color().get_mapping(Continuous(vals), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_callable_palette(self, num_vector):\n\n        cmap = get_colormap(\"viridis\")\n        m = Color().get_mapping(Continuous(cmap), num_vector)\n        self.assert_same_rgb(m(num_vector), cmap(num_vector))\n\n    def test_continuous_missing(self):\n\n        x = pd.Series([1, 2, np.nan, 4])\n        m = Color().get_mapping(Continuous(), x)\n        assert np.isnan(m(x)[2]).all()\n\n    def test_bad_scale_values_continuous(self, num_vector):\n\n        with pytest.raises(TypeError, match=\"Scale values for color with a Continuous\"):\n            Color().get_mapping(Continuous([\"r\", \"g\", \"b\"]), num_vector)\n\n    def test_bad_scale_values_nominal(self, cat_vector):\n\n        with pytest.raises(TypeError, match=\"Scale values for color with a Nominal\"):\n            Color().get_mapping(Nominal(get_colormap(\"viridis\")), cat_vector)\n\n    def test_bad_inference_arg(self, cat_vector):\n\n        with pytest.raises(TypeError, match=\"A single scale argument for color\"):\n            Color().infer_scale(123, cat_vector)\n\n    @pytest.mark.parametrize(\n        \"data_type,scale_class\",\n        [(\"cat\", Nominal), (\"num\", Continuous)]\n    )\n    def test_default(self, data_type, scale_class, vectors):\n\n        scale = Color().default_scale(vectors[data_type])\n        assert isinstance(scale, scale_class)\n\n    def test_default_numeric_data_category_dtype(self, num_vector):\n\n        scale = Color().default_scale(num_vector.astype(\"category\"))\n        assert isinstance(scale, Nominal)\n\n    def test_default_binary_data(self):\n\n        x = pd.Series([0, 0, 1, 0, 1], dtype=int)\n        scale = Color().default_scale(x)\n        assert isinstance(scale, Continuous)\n\n    # TODO default scales for other types\n\n    @pytest.mark.parametrize(\n        \"values,data_type,scale_class\",\n        [\n            (\"viridis\", \"cat\", Nominal),  # Based on variable type\n            (\"viridis\", \"num\", Continuous),  # Based on variable type\n            (\"muted\", \"num\", Nominal),  # Based on qualitative palette\n            ([\"r\", \"g\", \"b\"], \"num\", Nominal),  # Based on list palette\n            ({2: \"r\", 4: \"g\", 8: \"b\"}, \"num\", Nominal),  # Based on dict palette\n            ((\"r\", \"b\"), \"num\", Continuous),  # Based on tuple / variable type\n            ((\"g\", \"m\"), \"cat\", Nominal),  # Based on tuple / variable type\n            (get_colormap(\"inferno\"), \"num\", Continuous),  # Based on callable\n        ]\n    )\n    def test_inference(self, values, data_type, scale_class, vectors):\n\n        scale = Color().infer_scale(values, vectors[data_type])\n        assert isinstance(scale, scale_class)\n        assert scale.values == values\n\n    def test_inference_binary_data(self):\n\n        x = pd.Series([0, 0, 1, 0, 1], dtype=int)\n        scale = Color().infer_scale(\"viridis\", x)\n        assert isinstance(scale, Nominal)\n\n    def test_standardization(self):\n\n        f = Color().standardize\n        assert f(\"C3\") == to_rgb(\"C3\")\n        assert f(\"dodgerblue\") == to_rgb(\"dodgerblue\")\n\n        assert f((.1, .2, .3)) == (.1, .2, .3)\n        assert f((.1, .2, .3, .4)) == (.1, .2, .3, .4)\n\n        assert f(\"#123456\") == to_rgb(\"#123456\")\n        assert f(\"#12345678\") == to_rgba(\"#12345678\")\n\n        if Version(mpl.__version__) >= Version(\"3.4.0\"):\n            assert f(\"#123\") == to_rgb(\"#123\")\n            assert f(\"#1234\") == to_rgba(\"#1234\")"},{"col":4,"comment":"null","endLoc":77,"header":"def assert_same_rgb(self, a, b)","id":3700,"name":"assert_same_rgb","nodeType":"Function","startLoc":76,"text":"def assert_same_rgb(self, a, b):\n        assert_array_equal(a[:, :3], b[:, :3])"},{"fileName":"moves.py","filePath":"seaborn/_core","id":3701,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Callable, Optional, Union, cast\n\nimport numpy as np\nfrom pandas import DataFrame\n\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._core.scales import Scale\nfrom seaborn._core.typing import Default\n\ndefault = Default()\n\n\n@dataclass\nclass Move:\n    \"\"\"Base class for objects that apply simple positional transforms.\"\"\"\n\n    group_by_orient: ClassVar[bool] = True\n\n    def __call__(\n        self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n    ) -> DataFrame:\n        raise NotImplementedError\n\n\n@dataclass\nclass Jitter(Move):\n    \"\"\"\n    Random displacement along one or both axes to reduce overplotting.\n\n    Parameters\n    ----------\n    width : float\n        Magnitude of jitter, relative to mark width, along the orientation axis.\n        If not provided, the default value will be 0 when `x` or `y` are set, otherwise\n        there will be a small amount of jitter applied by default.\n    x : float\n        Magnitude of jitter, in data units, along the x axis.\n    y : float\n        Magnitude of jitter, in data units, along the y axis.\n\n    Examples\n    --------\n    .. include:: ../docstrings/objects.Jitter.rst\n\n    \"\"\"\n    width: float | Default = default\n    x: float = 0\n    y: float = 0\n    seed: int | None = None\n\n    def __call__(\n        self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n    ) -> DataFrame:\n\n        data = data.copy()\n        rng = np.random.default_rng(self.seed)\n\n        def jitter(data, col, scale):\n            noise = rng.uniform(-.5, +.5, len(data))\n            offsets = noise * scale\n            return data[col] + offsets\n\n        if self.width is default:\n            width = 0.0 if self.x or self.y else 0.2\n        else:\n            width = cast(float, self.width)\n\n        if self.width:\n            data[orient] = jitter(data, orient, width * data[\"width\"])\n        if self.x:\n            data[\"x\"] = jitter(data, \"x\", self.x)\n        if self.y:\n            data[\"y\"] = jitter(data, \"y\", self.y)\n\n        return data\n\n\n@dataclass\nclass Dodge(Move):\n    \"\"\"\n    Displacement and narrowing of overlapping marks along orientation axis.\n    \"\"\"\n    empty: str = \"keep\"  # Options: keep, drop, fill\n    gap: float = 0\n\n    # TODO accept just a str here?\n    # TODO should this always be present?\n    # TODO should the default be an \"all\" singleton?\n    by: Optional[list[str]] = None\n\n    def __call__(\n        self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n    ) -> DataFrame:\n\n        grouping_vars = [v for v in groupby.order if v in data]\n        groups = groupby.agg(data, {\"width\": \"max\"})\n        if self.empty == \"fill\":\n            groups = groups.dropna()\n\n        def groupby_pos(s):\n            grouper = [groups[v] for v in [orient, \"col\", \"row\"] if v in data]\n            return s.groupby(grouper, sort=False, observed=True)\n\n        def scale_widths(w):\n            # TODO what value to fill missing widths??? Hard problem...\n            # TODO short circuit this if outer widths has no variance?\n            empty = 0 if self.empty == \"fill\" else w.mean()\n            filled = w.fillna(empty)\n            scale = filled.max()\n            norm = filled.sum()\n            if self.empty == \"keep\":\n                w = filled\n            return w / norm * scale\n\n        def widths_to_offsets(w):\n            return w.shift(1).fillna(0).cumsum() + (w - w.sum()) / 2\n\n        new_widths = groupby_pos(groups[\"width\"]).transform(scale_widths)\n        offsets = groupby_pos(new_widths).transform(widths_to_offsets)\n\n        if self.gap:\n            new_widths *= 1 - self.gap\n\n        groups[\"_dodged\"] = groups[orient] + offsets\n        groups[\"width\"] = new_widths\n\n        out = (\n            data\n            .drop(\"width\", axis=1)\n            .merge(groups, on=grouping_vars, how=\"left\")\n            .drop(orient, axis=1)\n            .rename(columns={\"_dodged\": orient})\n        )\n\n        return out\n\n\n@dataclass\nclass Stack(Move):\n    \"\"\"\n    Displacement of overlapping bar or area marks along the value axis.\n    \"\"\"\n    # TODO center? (or should this be a different move, eg. Stream())\n\n    def _stack(self, df, orient):\n\n        # TODO should stack do something with ymin/ymax style marks?\n        # Should there be an upstream conversion to baseline/height parameterization?\n\n        if df[\"baseline\"].nunique() > 1:\n            err = \"Stack move cannot be used when baselines are already heterogeneous\"\n            raise RuntimeError(err)\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        stacked_lengths = (df[other] - df[\"baseline\"]).dropna().cumsum()\n        offsets = stacked_lengths.shift(1).fillna(0)\n\n        df[other] = stacked_lengths\n        df[\"baseline\"] = df[\"baseline\"] + offsets\n\n        return df\n\n    def __call__(\n        self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n    ) -> DataFrame:\n\n        # TODO where to ensure that other semantic variables are sorted properly?\n        # TODO why are we not using the passed in groupby here?\n        groupers = [\"col\", \"row\", orient]\n        return GroupBy(groupers).apply(data, self._stack, orient)\n\n\n@dataclass\nclass Shift(Move):\n    \"\"\"\n    Displacement of all marks with the same magnitude / direction.\n    \"\"\"\n    x: float = 0\n    y: float = 0\n\n    def __call__(\n        self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n    ) -> DataFrame:\n\n        data = data.copy(deep=False)\n        data[\"x\"] = data[\"x\"] + self.x\n        data[\"y\"] = data[\"y\"] + self.y\n        return data\n\n\n@dataclass\nclass Norm(Move):\n    \"\"\"\n    Divisive scaling on the value axis after aggregating within groups.\n    \"\"\"\n\n    func: Union[Callable, str] = \"max\"\n    where: Optional[str] = None\n    by: Optional[list[str]] = None\n    percent: bool = False\n\n    group_by_orient: ClassVar[bool] = False\n\n    def _norm(self, df, var):\n\n        if self.where is None:\n            denom_data = df[var]\n        else:\n            denom_data = df.query(self.where)[var]\n        df[var] = df[var] / denom_data.agg(self.func)\n\n        if self.percent:\n            df[var] = df[var] * 100\n\n        return df\n\n    def __call__(\n        self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],\n    ) -> DataFrame:\n\n        other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n        return groupby.apply(data, self._norm, other)\n\n\n# TODO\n# @dataclass\n# class Ridge(Move):\n#     ...\n"},{"col":4,"comment":"null","endLoc":86,"header":"def test_nominal_default_palette(self, cat_vector, cat_order)","id":3702,"name":"test_nominal_default_palette","nodeType":"Function","startLoc":79,"text":"def test_nominal_default_palette(self, cat_vector, cat_order):\n\n        m = Color().get_mapping(Nominal(), cat_vector)\n        n = len(cat_order)\n        actual = m(np.arange(n))\n        expected = color_palette(None, n)\n        for have, want in zip(actual, expected):\n            assert same_color(have, want)"},{"attributeType":"Default","col":0,"comment":"null","endLoc":12,"id":3703,"name":"default","nodeType":"Attribute","startLoc":12,"text":"default"},{"col":0,"comment":"","endLoc":1,"header":"moves.py#","id":3704,"name":"","nodeType":"Function","startLoc":1,"text":"default = Default()"},{"col":4,"comment":"null","endLoc":1847,"header":"def test_ax_warning(self, long_df)","id":3705,"name":"test_ax_warning","nodeType":"Function","startLoc":1842,"text":"def test_ax_warning(self, long_df):\n\n        ax = plt.gca()\n        with pytest.warns(UserWarning):\n            g = ag.jointplot(data=long_df, x=\"x\", y=\"y\", ax=ax)\n        assert g.ax_joint.collections"},{"attributeType":"null","col":4,"comment":"null","endLoc":1674,"id":3706,"name":"rs","nodeType":"Attribute","startLoc":1674,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":1675,"id":3707,"name":"x","nodeType":"Attribute","startLoc":1675,"text":"x"},{"col":4,"comment":"null","endLoc":355,"header":"def test_sum(self, df)","id":3708,"name":"test_sum","nodeType":"Function","startLoc":351,"text":"def test_sum(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(\"sum\")(df, gb, \"x\", {})\n        assert res[\"y\"].sum() == pytest.approx(1)"},{"col":4,"comment":"null","endLoc":53,"header":"def test_coordinate_defaults(self, x)","id":3709,"name":"test_coordinate_defaults","nodeType":"Function","startLoc":50,"text":"def test_coordinate_defaults(self, x):\n\n        s = Continuous()._setup(x, Coordinate())\n        assert_series_equal(s(x), x)"},{"fileName":"test_utils.py","filePath":"tests","id":3710,"nodeType":"File","text":"\"\"\"Tests for seaborn utility functions.\"\"\"\nimport re\nimport tempfile\nfrom urllib.request import urlopen\nfrom http.client import HTTPException\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom cycler import cycler\n\nimport pytest\nfrom numpy.testing import (\n    assert_array_equal,\n)\nfrom pandas.testing import (\n    assert_series_equal,\n    assert_frame_equal,\n)\n\nfrom seaborn import utils, rcmod\nfrom seaborn.external.version import Version\nfrom seaborn.utils import (\n    get_dataset_names,\n    get_color_cycle,\n    remove_na,\n    load_dataset,\n    _assign_default_kwargs,\n    _draw_figure,\n    _deprecate_ci,\n)\n\n\na_norm = np.random.randn(100)\n\n\ndef _network(t=None, url=\"https://github.com\"):\n    \"\"\"\n    Decorator that will skip a test if `url` is unreachable.\n\n    Parameters\n    ----------\n    t : function, optional\n    url : str, optional\n\n    \"\"\"\n    if t is None:\n        return lambda x: _network(x, url=url)\n\n    def wrapper(*args, **kwargs):\n        # attempt to connect\n        try:\n            f = urlopen(url)\n        except (OSError, HTTPException):\n            pytest.skip(\"No internet connection\")\n        else:\n            f.close()\n            return t(*args, **kwargs)\n    return wrapper\n\n\ndef test_ci_to_errsize():\n    \"\"\"Test behavior of ci_to_errsize.\"\"\"\n    cis = [[.5, .5],\n           [1.25, 1.5]]\n\n    heights = [1, 1.5]\n\n    actual_errsize = np.array([[.5, 1],\n                               [.25, 0]])\n\n    test_errsize = utils.ci_to_errsize(cis, heights)\n    assert_array_equal(actual_errsize, test_errsize)\n\n\ndef test_desaturate():\n    \"\"\"Test color desaturation.\"\"\"\n    out1 = utils.desaturate(\"red\", .5)\n    assert out1 == (.75, .25, .25)\n\n    out2 = utils.desaturate(\"#00FF00\", .5)\n    assert out2 == (.25, .75, .25)\n\n    out3 = utils.desaturate((0, 0, 1), .5)\n    assert out3 == (.25, .25, .75)\n\n    out4 = utils.desaturate(\"red\", .5)\n    assert out4 == (.75, .25, .25)\n\n\ndef test_desaturation_prop():\n    \"\"\"Test that pct outside of [0, 1] raises exception.\"\"\"\n    with pytest.raises(ValueError):\n        utils.desaturate(\"blue\", 50)\n\n\ndef test_saturate():\n    \"\"\"Test performance of saturation function.\"\"\"\n    out = utils.saturate((.75, .25, .25))\n    assert out == (1, 0, 0)\n\n\n@pytest.mark.parametrize(\n    \"s,exp\",\n    [\n        (\"a\", \"a\"),\n        (\"abc\", \"abc\"),\n        (b\"a\", \"a\"),\n        (b\"abc\", \"abc\"),\n        (bytearray(\"abc\", \"utf-8\"), \"abc\"),\n        (bytearray(), \"\"),\n        (1, \"1\"),\n        (0, \"0\"),\n        ([], str([])),\n    ],\n)\ndef test_to_utf8(s, exp):\n    \"\"\"Test the to_utf8 function: object to string\"\"\"\n    u = utils.to_utf8(s)\n    assert type(u) == str\n    assert u == exp\n\n\nclass TestSpineUtils:\n\n    sides = [\"left\", \"right\", \"bottom\", \"top\"]\n    outer_sides = [\"top\", \"right\"]\n    inner_sides = [\"left\", \"bottom\"]\n\n    offset = 10\n    original_position = (\"outward\", 0)\n    offset_position = (\"outward\", offset)\n\n    def test_despine(self):\n        f, ax = plt.subplots()\n        for side in self.sides:\n            assert ax.spines[side].get_visible()\n\n        utils.despine()\n        for side in self.outer_sides:\n            assert ~ax.spines[side].get_visible()\n        for side in self.inner_sides:\n            assert ax.spines[side].get_visible()\n\n        utils.despine(**dict(zip(self.sides, [True] * 4)))\n        for side in self.sides:\n            assert ~ax.spines[side].get_visible()\n\n    def test_despine_specific_axes(self):\n        f, (ax1, ax2) = plt.subplots(2, 1)\n\n        utils.despine(ax=ax2)\n\n        for side in self.sides:\n            assert ax1.spines[side].get_visible()\n\n        for side in self.outer_sides:\n            assert ~ax2.spines[side].get_visible()\n        for side in self.inner_sides:\n            assert ax2.spines[side].get_visible()\n\n    def test_despine_with_offset(self):\n        f, ax = plt.subplots()\n\n        for side in self.sides:\n            pos = ax.spines[side].get_position()\n            assert pos == self.original_position\n\n        utils.despine(ax=ax, offset=self.offset)\n\n        for side in self.sides:\n            is_visible = ax.spines[side].get_visible()\n            new_position = ax.spines[side].get_position()\n            if is_visible:\n                assert new_position == self.offset_position\n            else:\n                assert new_position == self.original_position\n\n    def test_despine_side_specific_offset(self):\n\n        f, ax = plt.subplots()\n        utils.despine(ax=ax, offset=dict(left=self.offset))\n\n        for side in self.sides:\n            is_visible = ax.spines[side].get_visible()\n            new_position = ax.spines[side].get_position()\n            if is_visible and side == \"left\":\n                assert new_position == self.offset_position\n            else:\n                assert new_position == self.original_position\n\n    def test_despine_with_offset_specific_axes(self):\n        f, (ax1, ax2) = plt.subplots(2, 1)\n\n        utils.despine(offset=self.offset, ax=ax2)\n\n        for side in self.sides:\n            pos1 = ax1.spines[side].get_position()\n            pos2 = ax2.spines[side].get_position()\n            assert pos1 == self.original_position\n            if ax2.spines[side].get_visible():\n                assert pos2 == self.offset_position\n            else:\n                assert pos2 == self.original_position\n\n    def test_despine_trim_spines(self):\n\n        f, ax = plt.subplots()\n        ax.plot([1, 2, 3], [1, 2, 3])\n        ax.set_xlim(.75, 3.25)\n\n        utils.despine(trim=True)\n        for side in self.inner_sides:\n            bounds = ax.spines[side].get_bounds()\n            assert bounds == (1, 3)\n\n    def test_despine_trim_inverted(self):\n\n        f, ax = plt.subplots()\n        ax.plot([1, 2, 3], [1, 2, 3])\n        ax.set_ylim(.85, 3.15)\n        ax.invert_yaxis()\n\n        utils.despine(trim=True)\n        for side in self.inner_sides:\n            bounds = ax.spines[side].get_bounds()\n            assert bounds == (1, 3)\n\n    def test_despine_trim_noticks(self):\n\n        f, ax = plt.subplots()\n        ax.plot([1, 2, 3], [1, 2, 3])\n        ax.set_yticks([])\n        utils.despine(trim=True)\n        assert ax.get_yticks().size == 0\n\n    def test_despine_trim_categorical(self):\n\n        f, ax = plt.subplots()\n        ax.plot([\"a\", \"b\", \"c\"], [1, 2, 3])\n\n        utils.despine(trim=True)\n\n        bounds = ax.spines[\"left\"].get_bounds()\n        assert bounds == (1, 3)\n\n        bounds = ax.spines[\"bottom\"].get_bounds()\n        assert bounds == (0, 2)\n\n    def test_despine_moved_ticks(self):\n\n        f, ax = plt.subplots()\n        for t in ax.yaxis.majorTicks:\n            t.tick1line.set_visible(True)\n        utils.despine(ax=ax, left=True, right=False)\n        for t in ax.yaxis.majorTicks:\n            assert t.tick2line.get_visible()\n        plt.close(f)\n\n        f, ax = plt.subplots()\n        for t in ax.yaxis.majorTicks:\n            t.tick1line.set_visible(False)\n        utils.despine(ax=ax, left=True, right=False)\n        for t in ax.yaxis.majorTicks:\n            assert not t.tick2line.get_visible()\n        plt.close(f)\n\n        f, ax = plt.subplots()\n        for t in ax.xaxis.majorTicks:\n            t.tick1line.set_visible(True)\n        utils.despine(ax=ax, bottom=True, top=False)\n        for t in ax.xaxis.majorTicks:\n            assert t.tick2line.get_visible()\n        plt.close(f)\n\n        f, ax = plt.subplots()\n        for t in ax.xaxis.majorTicks:\n            t.tick1line.set_visible(False)\n        utils.despine(ax=ax, bottom=True, top=False)\n        for t in ax.xaxis.majorTicks:\n            assert not t.tick2line.get_visible()\n        plt.close(f)\n\n\ndef test_ticklabels_overlap():\n\n    rcmod.set()\n    f, ax = plt.subplots(figsize=(2, 2))\n    f.tight_layout()  # This gets the Agg renderer working\n\n    assert not utils.axis_ticklabels_overlap(ax.get_xticklabels())\n\n    big_strings = \"abcdefgh\", \"ijklmnop\"\n    ax.set_xlim(-.5, 1.5)\n    ax.set_xticks([0, 1])\n    ax.set_xticklabels(big_strings)\n\n    assert utils.axis_ticklabels_overlap(ax.get_xticklabels())\n\n    x, y = utils.axes_ticklabels_overlap(ax)\n    assert x\n    assert not y\n\n\ndef test_locator_to_legend_entries():\n\n    locator = mpl.ticker.MaxNLocator(nbins=3)\n    limits = (0.09, 0.4)\n    levels, str_levels = utils.locator_to_legend_entries(\n        locator, limits, float\n    )\n    assert str_levels == [\"0.15\", \"0.30\"]\n\n    limits = (0.8, 0.9)\n    levels, str_levels = utils.locator_to_legend_entries(\n        locator, limits, float\n    )\n    assert str_levels == [\"0.80\", \"0.84\", \"0.88\"]\n\n    limits = (1, 6)\n    levels, str_levels = utils.locator_to_legend_entries(locator, limits, int)\n    assert str_levels == [\"2\", \"4\", \"6\"]\n\n    locator = mpl.ticker.LogLocator(numticks=5)\n    limits = (5, 1425)\n    levels, str_levels = utils.locator_to_legend_entries(locator, limits, int)\n    if Version(mpl.__version__) >= Version(\"3.1\"):\n        assert str_levels == ['10', '100', '1000']\n\n    limits = (0.00003, 0.02)\n    _, str_levels = utils.locator_to_legend_entries(locator, limits, float)\n    for i, exp in enumerate([4, 3, 2]):\n        # Use regex as mpl switched to minus sign, not hyphen, in 3.6\n        assert re.match(f\"1e.0{exp}\", str_levels[i])\n\n\ndef test_move_legend_matplotlib_objects():\n\n    fig, ax = plt.subplots()\n\n    colors = \"C2\", \"C5\"\n    labels = \"first label\", \"second label\"\n    title = \"the legend\"\n\n    for color, label in zip(colors, labels):\n        ax.plot([0, 1], color=color, label=label)\n    ax.legend(loc=\"upper right\", title=title)\n    utils._draw_figure(fig)\n    xfm = ax.transAxes.inverted().transform\n\n    # --- Test axes legend\n\n    old_pos = xfm(ax.legend_.legendPatch.get_extents())\n\n    new_fontsize = 14\n    utils.move_legend(ax, \"lower left\", title_fontsize=new_fontsize)\n    utils._draw_figure(fig)\n    new_pos = xfm(ax.legend_.legendPatch.get_extents())\n\n    assert (new_pos < old_pos).all()\n    assert ax.legend_.get_title().get_text() == title\n    assert ax.legend_.get_title().get_size() == new_fontsize\n\n    # --- Test title replacement\n\n    new_title = \"new title\"\n    utils.move_legend(ax, \"lower left\", title=new_title)\n    utils._draw_figure(fig)\n    assert ax.legend_.get_title().get_text() == new_title\n\n    # --- Test figure legend\n\n    fig.legend(loc=\"upper right\", title=title)\n    _draw_figure(fig)\n    xfm = fig.transFigure.inverted().transform\n    old_pos = xfm(fig.legends[0].legendPatch.get_extents())\n\n    utils.move_legend(fig, \"lower left\", title=new_title)\n    _draw_figure(fig)\n\n    new_pos = xfm(fig.legends[0].legendPatch.get_extents())\n    assert (new_pos < old_pos).all()\n    assert fig.legends[0].get_title().get_text() == new_title\n\n\ndef test_move_legend_grid_object(long_df):\n\n    from seaborn.axisgrid import FacetGrid\n\n    hue_var = \"a\"\n    g = FacetGrid(long_df, hue=hue_var)\n    g.map(plt.plot, \"x\", \"y\")\n\n    g.add_legend()\n    _draw_figure(g.figure)\n\n    xfm = g.figure.transFigure.inverted().transform\n    old_pos = xfm(g.legend.legendPatch.get_extents())\n\n    fontsize = 20\n    utils.move_legend(g, \"lower left\", title_fontsize=fontsize)\n    _draw_figure(g.figure)\n\n    new_pos = xfm(g.legend.legendPatch.get_extents())\n    assert (new_pos < old_pos).all()\n    assert g.legend.get_title().get_text() == hue_var\n    assert g.legend.get_title().get_size() == fontsize\n\n    assert g.legend.legendHandles\n    for i, h in enumerate(g.legend.legendHandles):\n        assert mpl.colors.to_rgb(h.get_color()) == mpl.colors.to_rgb(f\"C{i}\")\n\n\ndef test_move_legend_input_checks():\n\n    ax = plt.figure().subplots()\n    with pytest.raises(TypeError):\n        utils.move_legend(ax.xaxis, \"best\")\n\n    with pytest.raises(ValueError):\n        utils.move_legend(ax, \"best\")\n\n    with pytest.raises(ValueError):\n        utils.move_legend(ax.figure, \"best\")\n\n\ndef check_load_dataset(name):\n    ds = load_dataset(name, cache=False)\n    assert isinstance(ds, pd.DataFrame)\n\n\ndef check_load_cached_dataset(name):\n    # Test the caching using a temporary file.\n    with tempfile.TemporaryDirectory() as tmpdir:\n        # download and cache\n        ds = load_dataset(name, cache=True, data_home=tmpdir)\n\n        # use cached version\n        ds2 = load_dataset(name, cache=True, data_home=tmpdir)\n        assert_frame_equal(ds, ds2)\n\n\n@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_get_dataset_names():\n    names = get_dataset_names()\n    assert names\n    assert \"tips\" in names\n\n\n@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_datasets():\n\n    # Heavy test to verify that we can load all available datasets\n    for name in get_dataset_names():\n        # unfortunately @network somehow obscures this generator so it\n        # does not get in effect, so we need to call explicitly\n        # yield check_load_dataset, name\n        check_load_dataset(name)\n\n\n@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_dataset_string_error():\n\n    name = \"bad_name\"\n    err = f\"'{name}' is not one of the example datasets.\"\n    with pytest.raises(ValueError, match=err):\n        load_dataset(name)\n\n\ndef test_load_dataset_passed_data_error():\n\n    df = pd.DataFrame()\n    err = \"This function accepts only strings\"\n    with pytest.raises(TypeError, match=err):\n        load_dataset(df)\n\n\n@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_cached_datasets():\n\n    # Heavy test to verify that we can load all available datasets\n    for name in get_dataset_names():\n        # unfortunately @network somehow obscures this generator so it\n        # does not get in effect, so we need to call explicitly\n        # yield check_load_dataset, name\n        check_load_cached_dataset(name)\n\n\ndef test_relative_luminance():\n    \"\"\"Test relative luminance.\"\"\"\n    out1 = utils.relative_luminance(\"white\")\n    assert out1 == 1\n\n    out2 = utils.relative_luminance(\"#000000\")\n    assert out2 == 0\n\n    out3 = utils.relative_luminance((.25, .5, .75))\n    assert out3 == pytest.approx(0.201624536)\n\n    rgbs = mpl.cm.RdBu(np.linspace(0, 1, 10))\n    lums1 = [utils.relative_luminance(rgb) for rgb in rgbs]\n    lums2 = utils.relative_luminance(rgbs)\n\n    for lum1, lum2 in zip(lums1, lums2):\n        assert lum1 == pytest.approx(lum2)\n\n\n@pytest.mark.parametrize(\n    \"cycler,result\",\n    [\n        (cycler(color=[\"y\"]), [\"y\"]),\n        (cycler(color=[\"k\"]), [\"k\"]),\n        (cycler(color=[\"k\", \"y\"]), [\"k\", \"y\"]),\n        (cycler(color=[\"y\", \"k\"]), [\"y\", \"k\"]),\n        (cycler(color=[\"b\", \"r\"]), [\"b\", \"r\"]),\n        (cycler(color=[\"r\", \"b\"]), [\"r\", \"b\"]),\n        (cycler(lw=[1, 2]), [\".15\"]),  # no color in cycle\n    ],\n)\ndef test_get_color_cycle(cycler, result):\n    with mpl.rc_context(rc={\"axes.prop_cycle\": cycler}):\n        assert get_color_cycle() == result\n\n\ndef test_remove_na():\n\n    a_array = np.array([1, 2, np.nan, 3])\n    a_array_rm = remove_na(a_array)\n    assert_array_equal(a_array_rm, np.array([1, 2, 3]))\n\n    a_series = pd.Series([1, 2, np.nan, 3])\n    a_series_rm = remove_na(a_series)\n    assert_series_equal(a_series_rm, pd.Series([1., 2, 3], [0, 1, 3]))\n\n\ndef test_assign_default_kwargs():\n\n    def f(a, b, c, d):\n        pass\n\n    def g(c=1, d=2):\n        pass\n\n    kws = {\"c\": 3}\n\n    kws = _assign_default_kwargs(kws, f, g)\n    assert kws == {\"c\": 3, \"d\": 2}\n\n\ndef test_draw_figure():\n\n    f, ax = plt.subplots()\n    ax.plot([\"a\", \"b\", \"c\"], [1, 2, 3])\n    _draw_figure(f)\n    assert not f.stale\n    # ticklabels are not populated until a draw, but this may change\n    assert ax.get_xticklabels()[0].get_text() == \"a\"\n\n\ndef test_deprecate_ci():\n\n    msg = \"\\n\\nThe `ci` parameter is deprecated. Use `errorbar=\"\n\n    with pytest.warns(FutureWarning, match=msg + \"None\"):\n        out = _deprecate_ci(None, None)\n    assert out is None\n\n    with pytest.warns(FutureWarning, match=msg + \"'sd'\"):\n        out = _deprecate_ci(None, \"sd\")\n    assert out == \"sd\"\n\n    with pytest.warns(FutureWarning, match=msg + r\"\\('ci', 68\\)\"):\n        out = _deprecate_ci(None, 68)\n    assert out == (\"ci\", 68)\n"},{"col":4,"comment":"null","endLoc":58,"header":"def test_coordinate_transform(self, x)","id":3711,"name":"test_coordinate_transform","nodeType":"Function","startLoc":55,"text":"def test_coordinate_transform(self, x):\n\n        s = Continuous(trans=\"log\")._setup(x, Coordinate())\n        assert_series_equal(s(x), np.log10(x))"},{"attributeType":"null","col":4,"comment":"null","endLoc":1676,"id":3712,"name":"y","nodeType":"Attribute","startLoc":1676,"text":"y"},{"attributeType":"null","col":4,"comment":"null","endLoc":1677,"id":3713,"name":"data","nodeType":"Attribute","startLoc":1677,"text":"data"},{"className":"HTTPException","col":0,"comment":"null","endLoc":216,"id":3714,"nodeType":"Class","startLoc":216,"text":"class HTTPException(Exception): ..."},{"col":4,"comment":"null","endLoc":361,"header":"def test_where(self, df)","id":3715,"name":"test_where","nodeType":"Function","startLoc":357,"text":"def test_where(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(where=\"x == 2\")(df, gb, \"x\", {})\n        assert res.loc[res[\"x\"] == 2, \"y\"].max() == pytest.approx(1)"},{"attributeType":"null","col":16,"comment":"null","endLoc":1,"id":3716,"name":"np","nodeType":"Attribute","startLoc":1,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":2,"id":3717,"name":"pd","nodeType":"Attribute","startLoc":2,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":3,"id":3718,"name":"mpl","nodeType":"Attribute","startLoc":3,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":4,"id":3719,"name":"plt","nodeType":"Attribute","startLoc":4,"text":"plt"},{"attributeType":"null","col":24,"comment":"null","endLoc":7,"id":3720,"name":"npt","nodeType":"Attribute","startLoc":7,"text":"npt"},{"attributeType":"null","col":29,"comment":"null","endLoc":10,"id":3721,"name":"tm","nodeType":"Attribute","startLoc":10,"text":"tm"},{"attributeType":"null","col":34,"comment":"null","endLoc":12,"id":3722,"name":"tm","nodeType":"Attribute","startLoc":12,"text":"tm"},{"attributeType":"null","col":32,"comment":"null","endLoc":20,"id":3723,"name":"ag","nodeType":"Attribute","startLoc":20,"text":"ag"},{"attributeType":"null","col":0,"comment":"null","endLoc":26,"id":3724,"name":"rs","nodeType":"Attribute","startLoc":26,"text":"rs"},{"col":0,"comment":"","endLoc":1,"header":"test_axisgrid.py#","id":3725,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n    import pandas.testing as tm\nexcept ImportError:\n    import pandas.util.testing as tm\n\nrs = np.random.RandomState(0)"},{"col":4,"comment":"null","endLoc":367,"header":"def test_percent(self, df)","id":3726,"name":"test_percent","nodeType":"Function","startLoc":363,"text":"def test_percent(self, df):\n\n        gb = GroupBy([\"null\"])\n        res = Norm(percent=True)(df, gb, \"x\", {})\n        assert res[\"y\"].max() == pytest.approx(100)"},{"className":"TestSpineUtils","col":0,"comment":"null","endLoc":283,"id":3727,"nodeType":"Class","startLoc":125,"text":"class TestSpineUtils:\n\n    sides = [\"left\", \"right\", \"bottom\", \"top\"]\n    outer_sides = [\"top\", \"right\"]\n    inner_sides = [\"left\", \"bottom\"]\n\n    offset = 10\n    original_position = (\"outward\", 0)\n    offset_position = (\"outward\", offset)\n\n    def test_despine(self):\n        f, ax = plt.subplots()\n        for side in self.sides:\n            assert ax.spines[side].get_visible()\n\n        utils.despine()\n        for side in self.outer_sides:\n            assert ~ax.spines[side].get_visible()\n        for side in self.inner_sides:\n            assert ax.spines[side].get_visible()\n\n        utils.despine(**dict(zip(self.sides, [True] * 4)))\n        for side in self.sides:\n            assert ~ax.spines[side].get_visible()\n\n    def test_despine_specific_axes(self):\n        f, (ax1, ax2) = plt.subplots(2, 1)\n\n        utils.despine(ax=ax2)\n\n        for side in self.sides:\n            assert ax1.spines[side].get_visible()\n\n        for side in self.outer_sides:\n            assert ~ax2.spines[side].get_visible()\n        for side in self.inner_sides:\n            assert ax2.spines[side].get_visible()\n\n    def test_despine_with_offset(self):\n        f, ax = plt.subplots()\n\n        for side in self.sides:\n            pos = ax.spines[side].get_position()\n            assert pos == self.original_position\n\n        utils.despine(ax=ax, offset=self.offset)\n\n        for side in self.sides:\n            is_visible = ax.spines[side].get_visible()\n            new_position = ax.spines[side].get_position()\n            if is_visible:\n                assert new_position == self.offset_position\n            else:\n                assert new_position == self.original_position\n\n    def test_despine_side_specific_offset(self):\n\n        f, ax = plt.subplots()\n        utils.despine(ax=ax, offset=dict(left=self.offset))\n\n        for side in self.sides:\n            is_visible = ax.spines[side].get_visible()\n            new_position = ax.spines[side].get_position()\n            if is_visible and side == \"left\":\n                assert new_position == self.offset_position\n            else:\n                assert new_position == self.original_position\n\n    def test_despine_with_offset_specific_axes(self):\n        f, (ax1, ax2) = plt.subplots(2, 1)\n\n        utils.despine(offset=self.offset, ax=ax2)\n\n        for side in self.sides:\n            pos1 = ax1.spines[side].get_position()\n            pos2 = ax2.spines[side].get_position()\n            assert pos1 == self.original_position\n            if ax2.spines[side].get_visible():\n                assert pos2 == self.offset_position\n            else:\n                assert pos2 == self.original_position\n\n    def test_despine_trim_spines(self):\n\n        f, ax = plt.subplots()\n        ax.plot([1, 2, 3], [1, 2, 3])\n        ax.set_xlim(.75, 3.25)\n\n        utils.despine(trim=True)\n        for side in self.inner_sides:\n            bounds = ax.spines[side].get_bounds()\n            assert bounds == (1, 3)\n\n    def test_despine_trim_inverted(self):\n\n        f, ax = plt.subplots()\n        ax.plot([1, 2, 3], [1, 2, 3])\n        ax.set_ylim(.85, 3.15)\n        ax.invert_yaxis()\n\n        utils.despine(trim=True)\n        for side in self.inner_sides:\n            bounds = ax.spines[side].get_bounds()\n            assert bounds == (1, 3)\n\n    def test_despine_trim_noticks(self):\n\n        f, ax = plt.subplots()\n        ax.plot([1, 2, 3], [1, 2, 3])\n        ax.set_yticks([])\n        utils.despine(trim=True)\n        assert ax.get_yticks().size == 0\n\n    def test_despine_trim_categorical(self):\n\n        f, ax = plt.subplots()\n        ax.plot([\"a\", \"b\", \"c\"], [1, 2, 3])\n\n        utils.despine(trim=True)\n\n        bounds = ax.spines[\"left\"].get_bounds()\n        assert bounds == (1, 3)\n\n        bounds = ax.spines[\"bottom\"].get_bounds()\n        assert bounds == (0, 2)\n\n    def test_despine_moved_ticks(self):\n\n        f, ax = plt.subplots()\n        for t in ax.yaxis.majorTicks:\n            t.tick1line.set_visible(True)\n        utils.despine(ax=ax, left=True, right=False)\n        for t in ax.yaxis.majorTicks:\n            assert t.tick2line.get_visible()\n        plt.close(f)\n\n        f, ax = plt.subplots()\n        for t in ax.yaxis.majorTicks:\n            t.tick1line.set_visible(False)\n        utils.despine(ax=ax, left=True, right=False)\n        for t in ax.yaxis.majorTicks:\n            assert not t.tick2line.get_visible()\n        plt.close(f)\n\n        f, ax = plt.subplots()\n        for t in ax.xaxis.majorTicks:\n            t.tick1line.set_visible(True)\n        utils.despine(ax=ax, bottom=True, top=False)\n        for t in ax.xaxis.majorTicks:\n            assert t.tick2line.get_visible()\n        plt.close(f)\n\n        f, ax = plt.subplots()\n        for t in ax.xaxis.majorTicks:\n            t.tick1line.set_visible(False)\n        utils.despine(ax=ax, bottom=True, top=False)\n        for t in ax.xaxis.majorTicks:\n            assert not t.tick2line.get_visible()\n        plt.close(f)"},{"id":3728,"name":"setup.cfg","nodeType":"TextFile","path":"","text":"[flake8]\nmax-line-length = 88\nexclude = seaborn/cm.py,seaborn/external\nignore = E741,F522,W503\n\n[mypy]\n# Currently this ignores pandas and matplotlib\n# We may want to make custom stub files for the parts we use\n# I have found the available third party stubs to be less\n# complete than they would need to be useful\nignore_missing_imports = True\n\n[coverage:run]\nomit =\n    seaborn/widgets.py\n    seaborn/external/*\n    seaborn/colors/*\n    seaborn/cm.py\n    seaborn/conftest.py\n\n[coverage:report]\nexclude_lines =\n    pragma: no cover\n    if TYPE_CHECKING:\n    raise NotImplementedError\n"},{"col":4,"comment":"null","endLoc":148,"header":"def test_despine(self)","id":3729,"name":"test_despine","nodeType":"Function","startLoc":135,"text":"def test_despine(self):\n        f, ax = plt.subplots()\n        for side in self.sides:\n            assert ax.spines[side].get_visible()\n\n        utils.despine()\n        for side in self.outer_sides:\n            assert ~ax.spines[side].get_visible()\n        for side in self.inner_sides:\n            assert ax.spines[side].get_visible()\n\n        utils.despine(**dict(zip(self.sides, [True] * 4)))\n        for side in self.sides:\n            assert ~ax.spines[side].get_visible()"},{"id":3730,"name":"hls_palette.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"158cd1cf-6b30-4054-b32f-a166fcb883be\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme()\\n\",\n    \"sns.palettes._patch_colormap_display()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"c81b86cb-fb4e-418b-8d2f-6cd10601ac5a\",\n   \"metadata\": {},\n   \"source\": [\n    \"By default, return 6 colors with identical lightness and saturation and evenly-sampled hues:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6c3eaeaf-88eb-4012-96ea-41b328fa98b9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.hls_palette()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"f7624b0b-2311-45de-b6a5-fc07132ce455\",\n   \"metadata\": {},\n   \"source\": [\n    \"Increase the number of colors:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"555c29d1-6972-4a19-ad32-957fb7545634\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.hls_palette(8)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"24713fa6-e485-4358-9ffc-d40bd9543caa\",\n   \"metadata\": {},\n   \"source\": [\n    \"Decrease the lightness:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b6f80b4c-f7b4-4deb-a119-cdf6cfe1f7b5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.hls_palette(l=.3)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"e521b514-5572-43e8-95ae-a20cc30169b8\",\n   \"metadata\": {},\n   \"source\": [\n    \"Decrease the saturation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f88bd038-0c9c-48b1-92b0-d272a9c199f4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.hls_palette(s=.3)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"92a2212c-2177-4c82-8a5e-9dd788e9f87c\",\n   \"metadata\": {},\n   \"source\": [\n    \"Change the start-point for hue sampling:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f8da8fbc-551c-4896-b1b8-04203e740d78\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.hls_palette(h=.5)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"87780608-1f5a-409f-b31f-6a31a599f122\",\n   \"metadata\": {},\n   \"source\": [\n    \"Return a continuous colormap. Notice the perceptual discontinuities, especially around yellow, cyan, and magenta: \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4c622b3b-70d7-4139-8389-f3d0d4addd66\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.hls_palette(as_cmap=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3a83c1de-88c5-4327-abd2-19e8f3642052\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":63,"header":"def test_coordinate_transform_with_parameter(self, x)","id":3731,"name":"test_coordinate_transform_with_parameter","nodeType":"Function","startLoc":60,"text":"def test_coordinate_transform_with_parameter(self, x):\n\n        s = Continuous(trans=\"pow3\")._setup(x, Coordinate())\n        assert_series_equal(s(x), np.power(x, 3))"},{"id":3732,"name":"function_overview.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _function_tutorial:\\n\",\n    \"\\n\",\n    \".. currentmodule:: seaborn\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Overview of seaborn plotting functions\\n\",\n    \"======================================\\n\",\n    \"\\n\",\n    \"Most of your interactions with seaborn will happen through a set of plotting functions. Later chapters in the tutorial will explore the specific features offered by each function. This chapter will introduce, at a high-level, the different kinds of functions that you will encounter.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import pandas as pd\\n\",\n    \"import seaborn as sns\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"from IPython.display import HTML\\n\",\n    \"sns.set_theme()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Similar functions for similar tasks\\n\",\n    \"-----------------------------------\\n\",\n    \"\\n\",\n    \"The seaborn namespace is flat; all of the functionality is accessible at the top level. But the code itself is hierarchically structured, with modules of functions that achieve similar visualization goals through different means. Most of the docs are structured around these modules: you'll encounter names like \\\"relational\\\", \\\"distributional\\\", and \\\"categorical\\\".\\n\",\n    \"\\n\",\n    \"For example, the :ref:`distributions module ` defines functions that specialize in representing the distribution of datapoints. This includes familiar methods like the histogram:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"penguins = sns.load_dataset(\\\"penguins\\\")\\n\",\n    \"sns.histplot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Along with similar, but perhaps less familiar, options such as kernel density estimation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.kdeplot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Functions within a module share a lot of underlying code and offer similar features that may not be present in other components of the library (such as ``multiple=\\\"stack\\\"`` in the examples above). They are designed to facilitate switching between different visual representations as you explore a dataset, because different representations often have complementary strengths and weaknesses.\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Figure-level vs. axes-level functions\\n\",\n    \"-------------------------------------\\n\",\n    \"\\n\",\n    \"In addition to the different modules, there is a cross-cutting classification of seaborn functions as \\\"axes-level\\\" or \\\"figure-level\\\". The examples above are axes-level functions. They plot data onto a single :class:`matplotlib.pyplot.Axes` object, which is the return value of the function.\\n\",\n    \"\\n\",\n    \"In contrast, figure-level functions interface with matplotlib through a seaborn object, usually a :class:`FacetGrid`, that manages the figure. Each module has a single figure-level function, which offers a unitary interface to its various axes-level functions. The organization looks a bit like this:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"tags\": [\n     \"hide-input\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"from matplotlib.patches import FancyBboxPatch\\n\",\n    \"\\n\",\n    \"f, ax = plt.subplots(figsize=(7, 5))\\n\",\n    \"f.subplots_adjust(0, 0, 1, 1)\\n\",\n    \"ax.set_axis_off()\\n\",\n    \"ax.set(xlim=(0, 1), ylim=(0, 1))\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"modules = \\\"relational\\\", \\\"distributions\\\", \\\"categorical\\\"\\n\",\n    \"\\n\",\n    \"pal = sns.color_palette(\\\"deep\\\")\\n\",\n    \"colors = dict(relational=pal[0], distributions=pal[1], categorical=pal[2])\\n\",\n    \"\\n\",\n    \"pal = sns.color_palette(\\\"dark\\\")\\n\",\n    \"text_colors = dict(relational=pal[0], distributions=pal[1], categorical=pal[2])\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"functions = dict(\\n\",\n    \"    relational=[\\\"scatterplot\\\", \\\"lineplot\\\"],\\n\",\n    \"    distributions=[\\\"histplot\\\", \\\"kdeplot\\\", \\\"ecdfplot\\\", \\\"rugplot\\\"],\\n\",\n    \"    categorical=[\\\"stripplot\\\", \\\"swarmplot\\\", \\\"boxplot\\\", \\\"violinplot\\\", \\\"pointplot\\\", \\\"barplot\\\"],\\n\",\n    \")\\n\",\n    \"\\n\",\n    \"pad = .06\\n\",\n    \"\\n\",\n    \"w = .2\\n\",\n    \"h = .15\\n\",\n    \"\\n\",\n    \"xs = np.arange(0, 1,  1 / 3) + pad * 1.05\\n\",\n    \"y = .7\\n\",\n    \"\\n\",\n    \"for x, mod in zip(xs, modules):\\n\",\n    \"    color = colors[mod] + (.2,)\\n\",\n    \"    text_color = text_colors[mod]\\n\",\n    \"    box = FancyBboxPatch((x, y), w, h, f\\\"round,pad={pad}\\\", color=\\\"white\\\")\\n\",\n    \"    ax.add_artist(box)\\n\",\n    \"    box = FancyBboxPatch((x, y), w, h, f\\\"round,pad={pad}\\\", linewidth=1, edgecolor=text_color, facecolor=color)\\n\",\n    \"    ax.add_artist(box)\\n\",\n    \"    ax.text(x + w / 2, y + h / 2, f\\\"{mod[:3]}plot\\\\n({mod})\\\", ha=\\\"center\\\", va=\\\"center\\\", size=22, color=text_color)\\n\",\n    \"\\n\",\n    \"    for i, func in enumerate(functions[mod]):\\n\",\n    \"        x_i = x + w / 2\\n\",\n    \"        y_i =  y - i * .1 - h / 2 - pad\\n\",\n    \"        box = FancyBboxPatch((x_i - w / 2, y_i - pad / 3), w, h / 4, f\\\"round,pad={pad / 3}\\\",\\n\",\n    \"                              color=\\\"white\\\")\\n\",\n    \"        ax.add_artist(box)\\n\",\n    \"        box = FancyBboxPatch((x_i - w / 2, y_i - pad / 3), w, h / 4, f\\\"round,pad={pad / 3}\\\",\\n\",\n    \"                             linewidth=1, edgecolor=text_color, facecolor=color)\\n\",\n    \"        ax.add_artist(box)\\n\",\n    \"        ax.text(x_i, y_i, func, ha=\\\"center\\\", va=\\\"center\\\", size=18, color=text_color)\\n\",\n    \"\\n\",\n    \"    ax.plot([x_i, x_i], [y, y_i], zorder=-100, color=text_color, lw=1)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"For example, :func:`displot` is the figure-level function for the distributions module. Its default behavior is to draw a histogram, using the same code as :func:`histplot` behind the scenes:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"To draw a kernel density plot instead, using the same code as :func:`kdeplot`, select it using the ``kind`` parameter:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", multiple=\\\"stack\\\", kind=\\\"kde\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"You'll notice that the figure-level plots look mostly like their axes-level counterparts, but there are a few differences. Notably, the legend is placed outside the plot. They also have a slightly different shape (more on that shortly).\\n\",\n    \"\\n\",\n    \"The most useful feature offered by the figure-level functions is that they can easily create figures with multiple subplots. For example, instead of stacking the three distributions for each species of penguins in the same axes, we can \\\"facet\\\" them by plotting each distribution across the columns of the figure:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.displot(data=penguins, x=\\\"flipper_length_mm\\\", hue=\\\"species\\\", col=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The figure-level functions wrap their axes-level counterparts and pass the kind-specific keyword arguments (such as the bin size for a histogram) down to the underlying function. That means they are no less flexible, but there is a downside: the kind-specific parameters don't appear in the function signature or docstrings. Some of their features might be less discoverable, and you may need to look at two different pages of the documentation before understanding how to achieve a specific goal.\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Axes-level functions make self-contained plots\\n\",\n    \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n    \"\\n\",\n    \"The axes-level functions are written to act like drop-in replacements for matplotlib functions. While they add axis labels and legends automatically, they don't modify anything beyond the axes that they are drawn into. That means they can be composed into arbitrarily-complex matplotlib figures with predictable results.\\n\",\n    \"\\n\",\n    \"The axes-level functions call :func:`matplotlib.pyplot.gca` internally, which hooks into the matplotlib state-machine interface so that they draw their plots on the \\\"currently-active\\\" axes. But they additionally accept an ``ax=`` argument, which integrates with the object-oriented interface and lets you specify exactly where each plot should go:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"f, axs = plt.subplots(1, 2, figsize=(8, 4), gridspec_kw=dict(width_ratios=[4, 3]))\\n\",\n    \"sns.scatterplot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", hue=\\\"species\\\", ax=axs[0])\\n\",\n    \"sns.histplot(data=penguins, x=\\\"species\\\", hue=\\\"species\\\", shrink=.8, alpha=.8, legend=False, ax=axs[1])\\n\",\n    \"f.tight_layout()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Figure-level functions own their figure\\n\",\n    \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n    \"\\n\",\n    \"In contrast, figure-level functions cannot (easily) be composed with other plots. By design, they \\\"own\\\" their own figure, including its initialization, so there's no notion of using a figure-level function to draw a plot onto an existing axes. This constraint allows the figure-level functions to implement features such as putting the legend outside of the plot.\\n\",\n    \"\\n\",\n    \"Nevertheless, it is possible to go beyond what the figure-level functions offer by accessing the matplotlib axes on the object that they return and adding other elements to the plot that way:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n    \"g = sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\\n\",\n    \"g.ax.axline(xy1=(10, 2), slope=.2, color=\\\"b\\\", dashes=(5, 2))\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Customizing plots from a figure-level function\\n\",\n    \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n    \"\\n\",\n    \"The figure-level functions return a :class:`FacetGrid` instance, which has a few methods for customizing attributes of the plot in a way that is \\\"smart\\\" about the subplot organization. For example, you can change the labels on the external axes using a single line of code:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.relplot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", col=\\\"sex\\\")\\n\",\n    \"g.set_axis_labels(\\\"Flipper length (mm)\\\", \\\"Bill length (mm)\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"While convenient, this does add a bit of extra complexity, as you need to remember that this method is not part of the matplotlib API and exists only when using a figure-level function.\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \".. _figure_size_tutorial:\\n\",\n    \"\\n\",\n    \"Specifying figure sizes\\n\",\n    \"^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n    \"\\n\",\n    \"To increase or decrease the size of a matplotlib plot, you set the width and height of the entire figure, either in the `global rcParams `_, while setting up the plot (e.g. with the ``figsize`` parameter of :func:`matplotlib.pyplot.subplots`), or by calling a method on the figure object (e.g. :meth:`matplotlib.Figure.set_size_inches`). When using an axes-level function in seaborn, the same rules apply: the size of the plot is determined by the size of the figure it is part of and the axes layout in that figure.\\n\",\n    \"\\n\",\n    \"When using a figure-level function, there are several key differences. First, the functions themselves have parameters to control the figure size (although these are actually parameters of the underlying :class:`FacetGrid` that manages the figure). Second, these parameters, ``height`` and ``aspect``, parameterize the size slightly differently than the ``width``, ``height`` parameterization in matplotlib (using the seaborn parameters, ``width = height * aspect``). Most importantly, the parameters correspond to the size of each *subplot*, rather than the size of the overall figure.\\n\",\n    \"\\n\",\n    \"To illustrate the difference between these approaches, here is the default output of :func:`matplotlib.pyplot.subplots` with one subplot:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"f, ax = plt.subplots()\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"A figure with multiple columns will have the same overall size, but the axes will be squeezed horizontally to fit in the space:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"f, ax = plt.subplots(1, 2, sharey=True)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"In contrast, a plot created by a figure-level function will be square. To demonstrate that, let's set up an empty plot by using :class:`FacetGrid` directly. This happens behind the scenes in functions like :func:`relplot`, :func:`displot`, or :func:`catplot`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.FacetGrid(penguins)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"When additional columns are added, the figure itself will become wider, so that its subplots have the same size and shape:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.FacetGrid(penguins, col=\\\"sex\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"And you can adjust the size and shape of each subplot without accounting for the total number of rows and columns in the figure:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.FacetGrid(penguins, col=\\\"sex\\\", height=3.5, aspect=.75)\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"The upshot is that you can assign faceting variables without stopping to think about how you'll need to adjust the total figure size. A downside is that, when you do want to change the figure size, you'll need to remember that things work a bit differently than they do in matplotlib.\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Relative merits of figure-level functions\\n\",\n    \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n    \"\\n\",\n    \"Here is a summary of the pros and cons that we have discussed above:\\n\",\n    \"\\n\",\n    \".. list-table::\\n\",\n    \"   :header-rows: 1\\n\",\n    \"\\n\",\n    \"   * - Advantages\\n\",\n    \"     - Drawbacks\\n\",\n    \"   * - Easy faceting by data variables\\n\",\n    \"     - Many parameters not in function signature\\n\",\n    \"   * - Legend outside of plot by default\\n\",\n    \"     - Cannot be part of a larger matplotlib figure\\n\",\n    \"   * - Easy figure-level customization\\n\",\n    \"     - Different API from matplotlib\\n\",\n    \"   * - Different figure size parameterization\\n\",\n    \"     - Different figure size parameterization\\n\",\n    \"\\n\",\n    \"On balance, the figure-level functions add some additional complexity that can make things more confusing for beginners, but their distinct features give them additional power. The tutorial documentation mostly uses the figure-level functions, because they produce slightly cleaner plots, and we generally recommend their use for most applications. The one situation where they are not a good choice is when you need to make a complex, standalone figure that composes multiple different plot kinds. At this point, it's recommended to set up the figure using matplotlib directly and to fill in the individual components using axes-level functions.\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Combining multiple views on the data\\n\",\n    \"------------------------------------\\n\",\n    \"\\n\",\n    \"Two important plotting functions in seaborn don't fit cleanly into the classification scheme discussed above. These functions, :func:`jointplot` and :func:`pairplot`, employ multiple kinds of plots from different modules to represent multiple aspects of a dataset in a single figure. Both plots are figure-level functions and create figures with multiple subplots by default. But they use different objects to manage the figure: :class:`JointGrid` and :class:`PairGrid`, respectively.\\n\",\n    \"\\n\",\n    \":func:`jointplot` plots the relationship or joint distribution of two variables while adding marginal axes that show the univariate distribution of each one separately:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.jointplot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", hue=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \":func:`pairplot` is similar — it combines joint and marginal views — but rather than focusing on a single relationship, it visualizes every pairwise combination of variables simultaneously:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.pairplot(data=penguins, hue=\\\"species\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"metadata\": {},\n   \"source\": [\n    \"Behind the scenes, these functions are using axes-level functions that you have already met (:func:`scatterplot` and :func:`kdeplot`), and they also have a ``kind`` parameter that lets you quickly swap in a different representation:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"sns.jointplot(data=penguins, x=\\\"flipper_length_mm\\\", y=\\\"bill_length_mm\\\", hue=\\\"species\\\", kind=\\\"hist\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":3733,"name":"move_legend.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8ec46ad8-bc4c-4ee0-9626-271088c702f9\",\n   \"metadata\": {\n    \"tags\": [\n     \"hide\"\n    ]\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import seaborn as sns\\n\",\n    \"sns.set_theme()\\n\",\n    \"penguins = sns.load_dataset(\\\"penguins\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"008bdd98-88cb-4a81-9f50-9b0e5a357305\",\n   \"metadata\": {},\n   \"source\": [\n    \"For axes-level functions, pass the :class:`matplotlib.axes.Axes` object and provide a new location.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b82e58f9-b15d-4554-bee5-de6a689344a6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"ax = sns.histplot(penguins, x=\\\"bill_length_mm\\\", hue=\\\"species\\\")\\n\",\n    \"sns.move_legend(ax, \\\"center right\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"4f2a7f5d-ab39-46c7-87f4-532e607adf0b\",\n   \"metadata\": {},\n   \"source\": [\n    \"Use the `bbox_to_anchor` parameter for more fine-grained control, including moving the legend outside of the axes:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ed610a98-447a-4459-8342-48abc80330f0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"ax = sns.histplot(penguins, x=\\\"bill_length_mm\\\", hue=\\\"species\\\")\\n\",\n    \"sns.move_legend(ax, \\\"upper left\\\", bbox_to_anchor=(1, 1))\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"9d2fd766-a806-45d9-949d-1572991cf512\",\n   \"metadata\": {},\n   \"source\": [\n    \"Pass additional :meth:`matplotlib.axes.Axes.legend` parameters to update other properties:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"5ad4342c-c46e-49e9-98a2-6c88c6fb4c54\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"ax = sns.histplot(penguins, x=\\\"bill_length_mm\\\", hue=\\\"species\\\")\\n\",\n    \"sns.move_legend(\\n\",\n    \"    ax, \\\"lower center\\\",\\n\",\n    \"    bbox_to_anchor=(.5, 1), ncol=3, title=None, frameon=False,\\n\",\n    \")\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"0d573092-46fd-4a95-b7ed-7e6833823adc\",\n   \"metadata\": {},\n   \"source\": [\n    \"It's also possible to move the legend created by a figure-level function. But when fine-tuning the position, you must bear in mind that the figure will have extra blank space on the right:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b258a9b8-69e5-4d4a-94cb-5b6baddc402b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.displot(\\n\",\n    \"    penguins,\\n\",\n    \"    x=\\\"bill_length_mm\\\", hue=\\\"species\\\",\\n\",\n    \"    col=\\\"island\\\", col_wrap=2, height=3,\\n\",\n    \")\\n\",\n    \"sns.move_legend(g, \\\"upper left\\\", bbox_to_anchor=(.55, .45))\"\n   ]\n  },\n  {\n   \"cell_type\": \"raw\",\n   \"id\": \"c9dc54e2-2c66-412f-ab2a-4f2bc2cb5782\",\n   \"metadata\": {},\n   \"source\": [\n    \"One way to avoid this would be to set `legend_out=False` on the :class:`FacetGrid`:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"06cff408-4cdf-47af-8def-176f3e70ec5a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"g = sns.displot(\\n\",\n    \"    penguins,\\n\",\n    \"    x=\\\"bill_length_mm\\\", hue=\\\"species\\\",\\n\",\n    \"    col=\\\"island\\\", col_wrap=2, height=3,\\n\",\n    \"    facet_kws=dict(legend_out=False),\\n\",\n    \")\\n\",\n    \"sns.move_legend(g, \\\"upper left\\\", bbox_to_anchor=(.55, .45), frameon=False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b170f20d-22a9-4f7d-917a-d09e10b1f08c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"py310\",\n   \"language\": \"python\",\n   \"name\": \"py310\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.0\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":69,"header":"def test_coordinate_transform_error(self, x)","id":3734,"name":"test_coordinate_transform_error","nodeType":"Function","startLoc":65,"text":"def test_coordinate_transform_error(self, x):\n\n        s = Continuous(trans=\"bad\")\n        with pytest.raises(ValueError, match=\"Unknown value provided\"):\n            s._setup(x, Coordinate())"},{"col":4,"comment":"null","endLoc":42,"header":"def test_input_checks(self)","id":3735,"name":"test_input_checks","nodeType":"Function","startLoc":37,"text":"def test_input_checks(self):\n\n        with pytest.raises(AssertionError):\n            Mappable(rc=\"bogus.parameter\")\n        with pytest.raises(AssertionError):\n            Mappable(depend=\"nonexistent_feature\")"},{"col":4,"comment":"null","endLoc":51,"header":"def test_value(self)","id":3736,"name":"test_value","nodeType":"Function","startLoc":44,"text":"def test_value(self):\n\n        val = 3\n        m = self.mark(linewidth=val)\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))"},{"col":4,"comment":"null","endLoc":74,"header":"def test_interval_defaults(self, x)","id":3737,"name":"test_interval_defaults","nodeType":"Function","startLoc":71,"text":"def test_interval_defaults(self, x):\n\n        s = Continuous()._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [0, .25, 1])"},{"fileName":"heat_scatter.py","filePath":"examples","id":3738,"nodeType":"File","text":"\"\"\"\nScatterplot heatmap\n-------------------\n\n_thumb: .5, .5\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the brain networks dataset, select subset, and collapse the multi-index\ndf = sns.load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n\nused_networks = [1, 5, 6, 7, 8, 12, 13, 17]\nused_columns = (df.columns\n                  .get_level_values(\"network\")\n                  .astype(int)\n                  .isin(used_networks))\ndf = df.loc[:, used_columns]\n\ndf.columns = df.columns.map(\"-\".join)\n\n# Compute a correlation matrix and convert to long-form\ncorr_mat = df.corr().stack().reset_index(name=\"correlation\")\n\n# Draw each cell as a scatter point with varying size and color\ng = sns.relplot(\n    data=corr_mat,\n    x=\"level_0\", y=\"level_1\", hue=\"correlation\", size=\"correlation\",\n    palette=\"vlag\", hue_norm=(-1, 1), edgecolor=\".7\",\n    height=10, sizes=(50, 250), size_norm=(-.2, .8),\n)\n\n# Tweak the figure to finalize\ng.set(xlabel=\"\", ylabel=\"\", aspect=\"equal\")\ng.despine(left=True, bottom=True)\ng.ax.margins(.02)\nfor label in g.ax.get_xticklabels():\n    label.set_rotation(90)\nfor artist in g.legend.legendHandles:\n    artist.set_edgecolor(\".7\")\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":3739,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"col":4,"comment":"null","endLoc":79,"header":"def test_interval_with_range(self, x)","id":3740,"name":"test_interval_with_range","nodeType":"Function","startLoc":76,"text":"def test_interval_with_range(self, x):\n\n        s = Continuous((1, 3))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [1, 1.5, 3])"},{"col":4,"comment":"null","endLoc":84,"header":"def test_interval_with_norm(self, x)","id":3741,"name":"test_interval_with_norm","nodeType":"Function","startLoc":81,"text":"def test_interval_with_norm(self, x):\n\n        s = Continuous(norm=(3, 7))._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [-.5, 0, 1.5])"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":3742,"name":"df","nodeType":"Attribute","startLoc":12,"text":"df"},{"col":4,"comment":"null","endLoc":60,"header":"def test_default(self)","id":3743,"name":"test_default","nodeType":"Function","startLoc":53,"text":"def test_default(self):\n\n        val = 3\n        m = self.mark(linewidth=Mappable(val))\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))"},{"col":4,"comment":"null","endLoc":71,"header":"def test_rcparam(self)","id":3744,"name":"test_rcparam","nodeType":"Function","startLoc":62,"text":"def test_rcparam(self):\n\n        param = \"lines.linewidth\"\n        val = mpl.rcParams[param]\n\n        m = self.mark(linewidth=Mappable(rc=param))\n        assert m._resolve({}, \"linewidth\") == val\n\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))"},{"attributeType":"list","col":0,"comment":"null","endLoc":14,"id":3745,"name":"used_networks","nodeType":"Attribute","startLoc":14,"text":"used_networks"},{"col":4,"comment":"null","endLoc":91,"header":"def test_interval_with_range_norm_and_transform(self, x)","id":3746,"name":"test_interval_with_range_norm_and_transform","nodeType":"Function","startLoc":86,"text":"def test_interval_with_range_norm_and_transform(self, x):\n\n        x = pd.Series([1, 10, 100])\n        # TODO param order?\n        s = Continuous((2, 3), (10, 100), \"log\")._setup(x, IntervalProperty())\n        assert_array_equal(s(x), [1, 2, 3])"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":3747,"name":"used_columns","nodeType":"Attribute","startLoc":15,"text":"used_columns"},{"col":4,"comment":"null","endLoc":84,"header":"def test_depends(self)","id":3748,"name":"test_depends","nodeType":"Function","startLoc":73,"text":"def test_depends(self):\n\n        val = 2\n        df = pd.DataFrame(index=pd.RangeIndex(10))\n\n        m = self.mark(pointsize=Mappable(val), linewidth=Mappable(depend=\"pointsize\"))\n        assert m._resolve({}, \"linewidth\") == val\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val))\n\n        m = self.mark(pointsize=val * 2, linewidth=Mappable(depend=\"pointsize\"))\n        assert m._resolve({}, \"linewidth\") == val * 2\n        assert_array_equal(m._resolve(df, \"linewidth\"), np.full(len(df), val * 2))"},{"fileName":"scatterplot_sizes.py","filePath":"examples","id":3749,"nodeType":"File","text":"\"\"\"\nScatterplot with continuous hues and sizes\n==========================================\n\n_thumb: .51, .44\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the example planets dataset\nplanets = sns.load_dataset(\"planets\")\n\ncmap = sns.cubehelix_palette(rot=-.2, as_cmap=True)\ng = sns.relplot(\n    data=planets,\n    x=\"distance\", y=\"orbital_period\",\n    hue=\"year\", size=\"mass\",\n    palette=cmap, sizes=(10, 200),\n)\ng.set(xscale=\"log\", yscale=\"log\")\ng.ax.xaxis.grid(True, \"minor\", linewidth=.25)\ng.ax.yaxis.grid(True, \"minor\", linewidth=.25)\ng.despine(left=True, bottom=True)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":3750,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"col":4,"comment":"null","endLoc":100,"header":"def test_mapped(self)","id":3751,"name":"test_mapped","nodeType":"Function","startLoc":86,"text":"def test_mapped(self):\n\n        values = {\"a\": 1, \"b\": 2, \"c\": 3}\n\n        def f(x):\n            return np.array([values[x_i] for x_i in x])\n\n        m = self.mark(linewidth=Mappable(2))\n        scales = {\"linewidth\": f}\n\n        assert m._resolve({\"linewidth\": \"c\"}, \"linewidth\", scales) == 3\n\n        df = pd.DataFrame({\"linewidth\": [\"a\", \"b\", \"c\"]})\n        expected = np.array([1, 2, 3], float)\n        assert_array_equal(m._resolve(df, \"linewidth\", scales), expected)"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":3752,"name":"planets","nodeType":"Attribute","startLoc":12,"text":"planets"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":3753,"name":"df","nodeType":"Attribute","startLoc":19,"text":"df"},{"attributeType":"null","col":0,"comment":"null","endLoc":21,"id":3754,"name":"columns","nodeType":"Attribute","startLoc":21,"text":"df.columns"},{"attributeType":"null","col":0,"comment":"null","endLoc":24,"id":3755,"name":"corr_mat","nodeType":"Attribute","startLoc":24,"text":"corr_mat"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":3756,"name":"g","nodeType":"Attribute","startLoc":27,"text":"g"},{"attributeType":"null","col":4,"comment":"null","endLoc":38,"id":3757,"name":"label","nodeType":"Attribute","startLoc":38,"text":"label"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":3758,"name":"cmap","nodeType":"Attribute","startLoc":14,"text":"cmap"},{"attributeType":"null","col":4,"comment":"null","endLoc":40,"id":3759,"name":"artist","nodeType":"Attribute","startLoc":40,"text":"artist"},{"col":0,"comment":"","endLoc":7,"header":"heat_scatter.py#","id":3760,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot heatmap\n-------------------\n\n_thumb: .5, .5\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ndf = sns.load_dataset(\"brain_networks\", header=[0, 1, 2], index_col=0)\n\nused_networks = [1, 5, 6, 7, 8, 12, 13, 17]\n\nused_columns = (df.columns\n                  .get_level_values(\"network\")\n                  .astype(int)\n                  .isin(used_networks))\n\ndf = df.loc[:, used_columns]\n\ndf.columns = df.columns.map(\"-\".join)\n\ncorr_mat = df.corr().stack().reset_index(name=\"correlation\")\n\ng = sns.relplot(\n    data=corr_mat,\n    x=\"level_0\", y=\"level_1\", hue=\"correlation\", size=\"correlation\",\n    palette=\"vlag\", hue_norm=(-1, 1), edgecolor=\".7\",\n    height=10, sizes=(50, 250), size_norm=(-.2, .8),\n)\n\ng.set(xlabel=\"\", ylabel=\"\", aspect=\"equal\")\n\ng.despine(left=True, bottom=True)\n\ng.ax.margins(.02)\n\nfor label in g.ax.get_xticklabels():\n    label.set_rotation(90)\n\nfor artist in g.legend.legendHandles:\n    artist.set_edgecolor(\".7\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":3761,"name":"g","nodeType":"Attribute","startLoc":15,"text":"g"},{"col":0,"comment":"","endLoc":7,"header":"scatterplot_sizes.py#","id":3762,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot with continuous hues and sizes\n==========================================\n\n_thumb: .51, .44\n\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\nplanets = sns.load_dataset(\"planets\")\n\ncmap = sns.cubehelix_palette(rot=-.2, as_cmap=True)\n\ng = sns.relplot(\n    data=planets,\n    x=\"distance\", y=\"orbital_period\",\n    hue=\"year\", size=\"mass\",\n    palette=cmap, sizes=(10, 200),\n)\n\ng.set(xscale=\"log\", yscale=\"log\")\n\ng.ax.xaxis.grid(True, \"minor\", linewidth=.25)\n\ng.ax.yaxis.grid(True, \"minor\", linewidth=.25)\n\ng.despine(left=True, bottom=True)"},{"fileName":"__init__.py","filePath":"seaborn/_core","id":3763,"nodeType":"File","text":""},{"id":3764,"name":".github","nodeType":"Package"},{"id":3765,"name":"CONTRIBUTING.md","nodeType":"TextFile","path":".github","text":"Contributing to seaborn\n=======================\n\nGeneral support\n---------------\n\nGeneral support questions (\"how do I do X?\") are most at home on [StackOverflow](https://stackoverflow.com/), which has a larger audience of people who will see your post and may be able to offer assistance. Your chance of getting a quick answer will be higher if you include runnable code, a precise statement of what you are hoping to achieve, and a clear explanation of the problems that you have encountered.\n\nReporting bugs\n--------------\n\nIf you think you've encountered a bug in seaborn, please report it on the [Github issue tracker](https://github.com/mwaskom/seaborn/issues/new). To be useful, bug reports *must* include the following information:\n\n- A reproducible code example that demonstrates the problem\n- The output that you are seeing (an image of a plot, or the error message)\n- A clear explanation of why you think something is wrong\n- The specific versions of seaborn and matplotlib that you are working with\n\nBug reports are easiest to address if they can be demonstrated using one of the example datasets from the seaborn docs (i.e. with `seaborn.load_dataset`). Otherwise, it is preferable that your example generate synthetic data to reproduce the problem. If you can only demonstrate the issue with your actual dataset, you will need to share it, ideally as a csv. Note that you can upload a csv directly to a github issue thread, but it must have a `.txt` suffix.\n\nIf you've encountered an error, searching the specific text of the message before opening a new issue can often help you solve the problem quickly and avoid making a duplicate report.\n\nBecause matplotlib handles the actual rendering, errors or incorrect outputs may be due to a problem in matplotlib rather than one in seaborn. It can save time if you try to reproduce the issue in an example that uses only matplotlib, so that you can report it in the right place. But it is alright to skip this step if it's not obvious how to do it.\n\n\nNew features\n------------\n\nIf you think there is a new feature that should be added to seaborn, you can open an issue to discuss it. But please be aware that current development efforts are mostly focused on standardizing the API and internals, and there may be relatively low enthusiasm for novel features that do not fit well into short- and medium-term development plans.\n"},{"col":4,"comment":"null","endLoc":97,"header":"def test_color_defaults(self, x)","id":3766,"name":"test_color_defaults","nodeType":"Function","startLoc":93,"text":"def test_color_defaults(self, x):\n\n        cmap = color_palette(\"ch:\", as_cmap=True)\n        s = Continuous()._setup(x, Color())\n        assert_array_equal(s(x), cmap([0, .25, 1])[:, :3])  # FIXME RGBA"},{"id":3767,"name":"README.md","nodeType":"TextFile","path":"","text":"
\n\n--------------------------------------\n\nseaborn: statistical data visualization\n=======================================\n\n[![PyPI Version](https://img.shields.io/pypi/v/seaborn.svg)](https://pypi.org/project/seaborn/)\n[![License](https://img.shields.io/pypi/l/seaborn.svg)](https://github.com/mwaskom/seaborn/blob/master/LICENSE)\n[![DOI](https://joss.theoj.org/papers/10.21105/joss.03021/status.svg)](https://doi.org/10.21105/joss.03021)\n[![Tests](https://github.com/mwaskom/seaborn/workflows/CI/badge.svg)](https://github.com/mwaskom/seaborn/actions)\n[![Code Coverage](https://codecov.io/gh/mwaskom/seaborn/branch/master/graph/badge.svg)](https://codecov.io/gh/mwaskom/seaborn)\n\nSeaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics.\n\n\nDocumentation\n-------------\n\nOnline documentation is available at [seaborn.pydata.org](https://seaborn.pydata.org).\n\nThe docs include a [tutorial](https://seaborn.pydata.org/tutorial.html), [example gallery](https://seaborn.pydata.org/examples/index.html), [API reference](https://seaborn.pydata.org/api.html), and other useful information.\n\nTo build the documentation locally, please refer to [`doc/README.md`](doc/README.md).\n\nThere is also a [FAQ](https://github.com/mwaskom/seaborn/wiki/Frequently-Asked-Questions-(FAQs)) page, currently hosted on GitHub.\n\nDependencies\n------------\n\nSeaborn supports Python 3.7+ and no longer supports Python 2.\n\nInstallation requires [numpy](https://numpy.org/), [pandas](https://pandas.pydata.org/), and [matplotlib](https://matplotlib.org/). Some advanced statistical functionality requires [scipy](https://www.scipy.org/) and/or [statsmodels](https://www.statsmodels.org/).\n\n\nInstallation\n------------\n\nThe latest stable release (and required dependencies) can be installed from PyPI:\n\n pip install seaborn\n\nIt is also possible to include optional statistical dependencies (only relevant for v0.12+):\n\n pip install seaborn[stats]\n\nSeaborn can also be installed with conda:\n\n conda install seaborn\n\nNote that the main anaconda repository lags PyPI in adding new releases, but conda-forge (`-c conda-forge`) typically updates quickly.\n\nCiting\n------\n\nA paper describing seaborn has been published in the [Journal of Open Source Software](https://joss.theoj.org/papers/10.21105/joss.03021). The paper provides an introduction to the key features of the library, and it can be used as a citation if seaborn proves integral to a scientific publication.\n\nTesting\n-------\n\nTesting seaborn requires installing additional dependencies; they can be installed with the `dev` extra (e.g., `pip install .[dev]`).\n\nTo test the code, run `make test` in the source directory. This will exercise the unit tests (using [pytest](https://docs.pytest.org/)) and generate a coverage report.\n\nCode style is enforced with `flake8` using the settings in the [`setup.cfg`](./setup.cfg) file. Run `make lint` to check. Alternately, you can use `pre-commit` to automatically run lint checks on any files you are committing: just run `pre-commit install` to set it up, and then commit as usual going forward.\n\nDevelopment\n-----------\n\nSeaborn development takes place on Github: https://github.com/mwaskom/seaborn\n\nPlease submit bugs that you encounter to the [issue tracker](https://github.com/mwaskom/seaborn/issues) with a reproducible example demonstrating the problem. Questions about usage are more at home on StackOverflow, where there is a [seaborn tag](https://stackoverflow.com/questions/tagged/seaborn).\n"},{"fileName":"groupby.py","filePath":"seaborn/_core","id":3768,"nodeType":"File","text":"\"\"\"Simplified split-apply-combine paradigm on dataframes for internal use.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import cast, Iterable\n\nimport pandas as pd\n\nfrom seaborn._core.rules import categorical_order\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Callable\n from pandas import DataFrame, MultiIndex, Index\n\n\nclass GroupBy:\n \"\"\"\n Interface for Pandas GroupBy operations allowing specified group order.\n\n Writing our own class to do this has a few advantages:\n - It constrains the interface between Plot and Stat/Move objects\n - It allows control over the row order of the GroupBy result, which is\n important when using in the context of some Move operations (dodge, stack, ...)\n - It simplifies some complexities regarding the return type and Index contents\n one encounters with Pandas, especially for DataFrame -> DataFrame applies\n - It increases future flexibility regarding alternate DataFrame libraries\n\n \"\"\"\n def __init__(self, order: list[str] | dict[str, list | None]):\n \"\"\"\n Initialize the GroupBy from grouping variables and optional level orders.\n\n Parameters\n ----------\n order\n List of variable names or dict mapping names to desired level orders.\n Level order values can be None to use default ordering rules. The\n variables can include names that are not expected to appear in the\n data; these will be dropped before the groups are defined.\n\n \"\"\"\n if not order:\n raise ValueError(\"GroupBy requires at least one grouping variable\")\n\n if isinstance(order, list):\n order = {k: None for k in order}\n self.order = order\n\n def _get_groups(\n self, data: DataFrame\n ) -> tuple[str | list[str], Index | MultiIndex]:\n \"\"\"Return index with Cartesian product of ordered grouping variable levels.\"\"\"\n levels = {}\n for var, order in self.order.items():\n if var in data:\n if order is None:\n order = categorical_order(data[var])\n levels[var] = order\n\n grouper: str | list[str]\n groups: Index | MultiIndex\n if not levels:\n grouper = []\n groups = pd.Index([])\n elif len(levels) > 1:\n grouper = list(levels)\n groups = pd.MultiIndex.from_product(levels.values(), names=grouper)\n else:\n grouper, = list(levels)\n groups = pd.Index(levels[grouper], name=grouper)\n return grouper, groups\n\n def _reorder_columns(self, res, data):\n \"\"\"Reorder result columns to match original order with new columns appended.\"\"\"\n cols = [c for c in data if c in res]\n cols += [c for c in res if c not in data]\n return res.reindex(columns=pd.Index(cols))\n\n def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame:\n \"\"\"\n Reduce each group to a single row in the output.\n\n The output will have a row for each unique combination of the grouping\n variable levels with null values for the aggregated variable(s) where\n those combinations do not appear in the dataset.\n\n \"\"\"\n grouper, groups = self._get_groups(data)\n\n if not grouper:\n # We will need to see whether there are valid usecases that end up here\n raise ValueError(\"No grouping variables are present in dataframe\")\n\n res = (\n data\n .groupby(grouper, sort=False, observed=True)\n .agg(*args, **kwargs)\n .reindex(groups)\n .reset_index()\n .pipe(self._reorder_columns, data)\n )\n\n return res\n\n def apply(\n self, data: DataFrame, func: Callable[..., DataFrame],\n *args, **kwargs,\n ) -> DataFrame:\n \"\"\"Apply a DataFrame -> DataFrame mapping to each group.\"\"\"\n grouper, groups = self._get_groups(data)\n\n if not grouper:\n return self._reorder_columns(func(data, *args, **kwargs), data)\n\n parts = {}\n for key, part_df in data.groupby(grouper, sort=False):\n parts[key] = func(part_df, *args, **kwargs)\n stack = []\n for key in groups:\n if key in parts:\n if isinstance(grouper, list):\n # Implies that we had a MultiIndex so key is iterable\n group_ids = dict(zip(grouper, cast(Iterable, key)))\n else:\n group_ids = {grouper: key}\n stack.append(parts[key].assign(**group_ids))\n\n res = pd.concat(stack, ignore_index=True)\n return self._reorder_columns(res, data)\n"},{"col":4,"comment":"null","endLoc":111,"header":"def test_color(self)","id":3769,"name":"test_color","nodeType":"Function","startLoc":102,"text":"def test_color(self):\n\n c, a = \"C1\", .5\n m = self.mark(color=c, alpha=a)\n\n assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)\n\n df = pd.DataFrame(index=pd.RangeIndex(10))\n cs = [c] * len(df)\n assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))"},{"col":0,"comment":"","endLoc":1,"header":"groupby.py#","id":3770,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Simplified split-apply-combine paradigm on dataframes for internal use.\"\"\"\n\nif TYPE_CHECKING:\n from typing import Callable\n from pandas import DataFrame, MultiIndex, Index"},{"id":3771,"name":"v0.5.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.5.0 (November 2014)\n--------------------------\n\nThis is a major release from 0.4. Highlights include new functions for plotting heatmaps, possibly while applying clustering algorithms to discover structured relationships. These functions are complemented by new custom colormap functions and a full set of IPython widgets that allow interactive selection of colormap parameters. The palette tutorial has been rewritten to cover these new tools and more generally provide guidance on how to use color in visualizations. There are also a number of smaller changes and bugfixes.\n\nPlotting functions\n~~~~~~~~~~~~~~~~~~\n\n- Added the :func:`heatmap` function for visualizing a matrix of data by color-encoding the values. See the docs for more information.\n\n- Added the :func:`clustermap` function for clustering and visualizing a matrix of data, with options to label individual rows and columns by colors. See the docs for more information. This work was lead by Olga Botvinnik.\n\n- :func:`lmplot` and :func:`pairplot` get a new keyword argument, ``markers``. This can be a single kind of marker or a list of different markers for each level of the ``hue`` variable. Using different markers for different hues should let plots be more comprehensible when reproduced to black-and-white (i.e. when printed). See the `github pull request (#323) `_ for examples.\n\n- More generally, there is a new keyword argument in :class:`FacetGrid` and :class:`PairGrid`, ``hue_kws``. This similarly lets plot aesthetics vary across the levels of the hue variable, but more flexibly. ``hue_kws`` should be a dictionary that maps the name of keyword arguments to lists of values that are as long as the number of levels of the hue variable.\n\n- The argument ``subplot_kws`` has been added to ``FacetGrid``. This allows for faceted plots with custom projections, including `maps with Cartopy `_.\n\nColor palettes\n~~~~~~~~~~~~~~\n\n- Added two new functions to create custom color palettes. For sequential palettes, you can use the :func:`light_palette` function, which takes a seed color and creates a ramp from a very light, desaturated variant of it. For diverging palettes, you can use the :func:`diverging_palette` function to create a balanced ramp between two endpoints to a light or dark midpoint. See the :ref:`palette tutorial ` for more information.\n\n- Added the ability to specify the seed color for :func:`light_palette` and :func:`dark_palette` as a tuple of ``husl`` or ``hls`` space values or as a named ``xkcd`` color. The interpretation of the seed color is now provided by the new ``input`` parameter to these functions.\n\n- Added several new interactive palette widgets: :func:`choose_colorbrewer_palette`, :func:`choose_light_palette`, :func:`choose_dark_palette`, and :func:`choose_diverging_palette`. For consistency, renamed the cubehelix widget to :func:`choose_cubehelix_palette` (and fixed a bug where the cubehelix palette was reversed). These functions also now return either a color palette list or a matplotlib colormap when called, and that object will be live-updated as you play with the widget. This should make it easy to iterate over a plot until you find a good representation for the data. See the `Github pull request `_ or `this notebook (download it to use the widgets) `_ for more information.\n\n- Overhauled the color :ref:`palette tutorial ` to organize the discussion by class of color palette and provide more motivation behind the various choices one might make when choosing colors for their data.\n\nBug fixes\n~~~~~~~~~\n- Fixed a bug in :class:`PairGrid` that gave incorrect results (or a crash) when the input DataFrame has a non-default index.\n\n- Fixed a bug in :class:`PairGrid` where passing columns with a date-like datatype raised an exception.\n\n- Fixed a bug where :func:`lmplot` would show a legend when the hue variable was also used on either the rows or columns (making the legend redundant).\n\n- Worked around a matplotlib bug that was forcing outliers in :func:`boxplot` to appear as blue.\n\n- :func:`kdeplot` now accepts pandas Series for the ``data`` and ``data2`` arguments.\n\n- Using a non-default correlation method in :func:`corrplot` now implies ``sig_stars=False`` as the permutation test used to significance values for the correlations uses a pearson metric.\n\n- Removed ``pdf.fonttype`` from the style definitions, as the value used in version 0.4 resulted in very large PDF files.\n"},{"id":3772,"name":"objects.Band.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"fmri = load_dataset(\\\"fmri\\\").query(\\\"region == 'parietal'\\\")\\n\",\n \"seaice = (\\n\",\n \" load_dataset(\\\"seaice\\\")\\n\",\n \" .assign(\\n\",\n \" Day=lambda x: x[\\\"Date\\\"].dt.day_of_year,\\n\",\n \" Year=lambda x: x[\\\"Date\\\"].dt.year,\\n\",\n \" )\\n\",\n \" .query(\\\"Year >= 1980\\\")\\n\",\n \" .astype({\\\"Year\\\": str})\\n\",\n \" .pivot(index=\\\"Day\\\", columns=\\\"Year\\\", values=\\\"Extent\\\")\\n\",\n \" .filter([\\\"1980\\\", \\\"2019\\\"])\\n\",\n \" .dropna()\\n\",\n \" .reset_index()\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e840e876-fbd6-4bfd-868c-a9d7af7913fa\",\n \"metadata\": {},\n \"source\": [\n \"The mark fills between pairs of data points to show an interval on the value axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"518cf20d-bb0b-433a-9b25-f1ed8d432149\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(seaice, x=\\\"Day\\\", ymin=\\\"1980\\\", ymax=\\\"2019\\\")\\n\",\n \"p.add(so.Band())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fa50b778-13f9-4368-a967-68365fd51117\",\n \"metadata\": {},\n \"source\": [\n \"By default it draws a faint ribbon with no edges, but edges can be added:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a05176c4-0615-49ca-a2df-48ced8b5a8a8\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Band(alpha=.5, edgewidth=2))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"776d192a-f35f-4253-be7f-01e4b2466dad\",\n \"metadata\": {},\n \"source\": [\n \"The defaults are optimized for the main expected usecase, where the mark is combined with a line to show an errorbar interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"69f4e423-94f4-4003-b337-12162d1040c2\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", color=\\\"event\\\")\\n\",\n \" .add(so.Band(), so.Est())\\n\",\n \" .add(so.Line(), so.Agg())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"9f0c82bf-3457-4ac5-ba48-8930bac03d75\",\n \"metadata\": {},\n \"source\": [\n \"When min/max values are not explicitly assigned or added in a transform, the band will cover the full extent of the data:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"309f578e-da3d-4dc5-b6ac-a354321334c8\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", color=\\\"event\\\")\\n\",\n \" .add(so.Line(linewidth=.5), group=\\\"subject\\\")\\n\",\n \" .add(so.Band())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4330a3cd-63fe-470a-8e83-09e9606643b5\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":129,"header":"def test_color_mapped_alpha(self)","id":3773,"name":"test_color_mapped_alpha","nodeType":"Function","startLoc":113,"text":"def test_color_mapped_alpha(self):\n\n c = \"r\"\n values = {\"a\": .2, \"b\": .5, \"c\": .8}\n\n m = self.mark(color=c, alpha=Mappable(1))\n scales = {\"alpha\": lambda s: np.array([values[s_i] for s_i in s])}\n\n assert resolve_color(m, {\"alpha\": \"b\"}, \"\", scales) == mpl.colors.to_rgba(c, .5)\n\n df = pd.DataFrame({\"alpha\": list(values.keys())})\n\n # Do this in two steps for mpl 3.2 compat\n expected = mpl.colors.to_rgba_array([c] * len(df))\n expected[:, 3] = list(values.values())\n\n assert_array_equal(resolve_color(m, df, \"\", scales), expected)"},{"col":27,"endLoc":119,"id":3774,"nodeType":"Lambda","startLoc":119,"text":"lambda s: np.array([values[s_i] for s_i in s])"},{"fileName":"algorithms.py","filePath":"seaborn","id":3775,"nodeType":"File","text":"\"\"\"Algorithms to support fitting routines in seaborn plotting functions.\"\"\"\nimport numbers\nimport numpy as np\nimport warnings\n\n\ndef bootstrap(*args, **kwargs):\n \"\"\"Resample one or more arrays with replacement and store aggregate values.\n\n Positional arguments are a sequence of arrays to bootstrap along the first\n axis and pass to a summary function.\n\n Keyword arguments:\n n_boot : int, default=10000\n Number of iterations\n axis : int, default=None\n Will pass axis to ``func`` as a keyword argument.\n units : array, default=None\n Array of sampling unit IDs. When used the bootstrap resamples units\n and then observations within units instead of individual\n datapoints.\n func : string or callable, default=\"mean\"\n Function to call on the args that are passed in. If string, uses as\n name of function in the numpy namespace. If nans are present in the\n data, will try to use nan-aware version of named function.\n seed : Generator | SeedSequence | RandomState | int | None\n Seed for the random number generator; useful if you want\n reproducible resamples.\n\n Returns\n -------\n boot_dist: array\n array of bootstrapped statistic values\n\n \"\"\"\n # Ensure list of arrays are same length\n if len(np.unique(list(map(len, args)))) > 1:\n raise ValueError(\"All input arrays must have the same length\")\n n = len(args[0])\n\n # Default keyword arguments\n n_boot = kwargs.get(\"n_boot\", 10000)\n func = kwargs.get(\"func\", \"mean\")\n axis = kwargs.get(\"axis\", None)\n units = kwargs.get(\"units\", None)\n random_seed = kwargs.get(\"random_seed\", None)\n if random_seed is not None:\n msg = \"`random_seed` has been renamed to `seed` and will be removed\"\n warnings.warn(msg)\n seed = kwargs.get(\"seed\", random_seed)\n if axis is None:\n func_kwargs = dict()\n else:\n func_kwargs = dict(axis=axis)\n\n # Initialize the resampler\n rng = _handle_random_seed(seed)\n\n # Coerce to arrays\n args = list(map(np.asarray, args))\n if units is not None:\n units = np.asarray(units)\n\n if isinstance(func, str):\n\n # Allow named numpy functions\n f = getattr(np, func)\n\n # Try to use nan-aware version of function if necessary\n missing_data = np.isnan(np.sum(np.column_stack(args)))\n\n if missing_data and not func.startswith(\"nan\"):\n nanf = getattr(np, f\"nan{func}\", None)\n if nanf is None:\n msg = f\"Data contain nans but no nan-aware version of `{func}` found\"\n warnings.warn(msg, UserWarning)\n else:\n f = nanf\n\n else:\n f = func\n\n # Handle numpy changes\n try:\n integers = rng.integers\n except AttributeError:\n integers = rng.randint\n\n # Do the bootstrap\n if units is not None:\n return _structured_bootstrap(args, n_boot, units, f,\n func_kwargs, integers)\n\n boot_dist = []\n for i in range(int(n_boot)):\n resampler = integers(0, n, n, dtype=np.intp) # intp is indexing dtype\n sample = [a.take(resampler, axis=0) for a in args]\n boot_dist.append(f(*sample, **func_kwargs))\n return np.array(boot_dist)\n\n\ndef _structured_bootstrap(args, n_boot, units, func, func_kwargs, integers):\n \"\"\"Resample units instead of datapoints.\"\"\"\n unique_units = np.unique(units)\n n_units = len(unique_units)\n\n args = [[a[units == unit] for unit in unique_units] for a in args]\n\n boot_dist = []\n for i in range(int(n_boot)):\n resampler = integers(0, n_units, n_units, dtype=np.intp)\n sample = [[a[i] for i in resampler] for a in args]\n lengths = map(len, sample[0])\n resampler = [integers(0, n, n, dtype=np.intp) for n in lengths]\n sample = [[c.take(r, axis=0) for c, r in zip(a, resampler)] for a in sample]\n sample = list(map(np.concatenate, sample))\n boot_dist.append(func(*sample, **func_kwargs))\n return np.array(boot_dist)\n\n\ndef _handle_random_seed(seed=None):\n \"\"\"Given a seed in one of many formats, return a random number generator.\n\n Generalizes across the numpy 1.17 changes, preferring newer functionality.\n\n \"\"\"\n if isinstance(seed, np.random.RandomState):\n rng = seed\n else:\n try:\n # General interface for seeding on numpy >= 1.17\n rng = np.random.default_rng(seed)\n except AttributeError:\n # We are on numpy < 1.17, handle options ourselves\n if isinstance(seed, (numbers.Integral, np.integer)):\n rng = np.random.RandomState(seed)\n elif seed is None:\n rng = np.random.RandomState()\n else:\n err = \"{} cannot be used to seed the random number generator\"\n raise ValueError(err.format(seed))\n return rng\n"},{"col":0,"comment":"","endLoc":1,"header":"algorithms.py#","id":3776,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Algorithms to support fitting routines in seaborn plotting functions.\"\"\""},{"fileName":"multiple_conditional_kde.py","filePath":"examples","id":3777,"nodeType":"File","text":"\"\"\"\nConditional kernel density estimate\n===================================\n\n_thumb: .4, .5\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the diamonds dataset\ndiamonds = sns.load_dataset(\"diamonds\")\n\n# Plot the distribution of clarity ratings, conditional on carat\nsns.displot(\n data=diamonds,\n x=\"carat\", hue=\"cut\",\n kind=\"kde\", height=6,\n multiple=\"fill\", clip=(0, None),\n palette=\"ch:rot=-.25,hue=1,light=.75\",\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3778,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3779,"name":"diamonds","nodeType":"Attribute","startLoc":11,"text":"diamonds"},{"col":4,"comment":"null","endLoc":103,"header":"def test_color_named_values(self, x)","id":3780,"name":"test_color_named_values","nodeType":"Function","startLoc":99,"text":"def test_color_named_values(self, x):\n\n cmap = color_palette(\"viridis\", as_cmap=True)\n s = Continuous(\"viridis\")._setup(x, Color())\n assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA"},{"col":0,"comment":"","endLoc":6,"header":"multiple_conditional_kde.py#","id":3781,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nConditional kernel density estimate\n===================================\n\n_thumb: .4, .5\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ndiamonds = sns.load_dataset(\"diamonds\")\n\nsns.displot(\n data=diamonds,\n x=\"carat\", hue=\"cut\",\n kind=\"kde\", height=6,\n multiple=\"fill\", clip=(0, None),\n palette=\"ch:rot=-.25,hue=1,light=.75\",\n)"},{"fileName":"hexbin_marginals.py","filePath":"examples","id":3782,"nodeType":"File","text":"\"\"\"\nHexbin plot with marginal distributions\n=======================================\n\n_thumb: .45, .4\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\n\nrs = np.random.RandomState(11)\nx = rs.gamma(2, size=1000)\ny = -.5 * x + rs.normal(size=1000)\n\nsns.jointplot(x=x, y=y, kind=\"hex\", color=\"#4CB391\")\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":7,"id":3783,"name":"np","nodeType":"Attribute","startLoc":7,"text":"np"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":3784,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3785,"name":"rs","nodeType":"Attribute","startLoc":11,"text":"rs"},{"col":4,"comment":"null","endLoc":109,"header":"def test_color_tuple_values(self, x)","id":3786,"name":"test_color_tuple_values","nodeType":"Function","startLoc":105,"text":"def test_color_tuple_values(self, x):\n\n cmap = color_palette(\"blend:b,g\", as_cmap=True)\n s = Continuous((\"b\", \"g\"))._setup(x, Color())\n assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":3787,"name":"x","nodeType":"Attribute","startLoc":12,"text":"x"},{"attributeType":"float","col":0,"comment":"null","endLoc":13,"id":3788,"name":"y","nodeType":"Attribute","startLoc":13,"text":"y"},{"col":4,"comment":"null","endLoc":115,"header":"def test_color_callable_values(self, x)","id":3789,"name":"test_color_callable_values","nodeType":"Function","startLoc":111,"text":"def test_color_callable_values(self, x):\n\n cmap = color_palette(\"light:r\", as_cmap=True)\n s = Continuous(cmap)._setup(x, Color())\n assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA"},{"col":0,"comment":"","endLoc":6,"header":"hexbin_marginals.py#","id":3790,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nHexbin plot with marginal distributions\n=======================================\n\n_thumb: .45, .4\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\nrs = np.random.RandomState(11)\n\nx = rs.gamma(2, size=1000)\n\ny = -.5 * x + rs.normal(size=1000)\n\nsns.jointplot(x=x, y=y, kind=\"hex\", color=\"#4CB391\")"},{"id":3791,"name":"v0.11.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.11.1 (December 2020)\n-----------------------\n\nThis a bug fix release and is a recommended upgrade for all users on v0.11.0.\n\n- |Enhancement| Reduced the use of matplotlib global state in the :ref:`multi-grid classes ` (:pr:`2388`).\n\n- |Fix| Restored support for using tuples or numeric keys to reference fields in a long-form `data` object (:pr:`2386`).\n\n- |Fix| Fixed a bug in :func:`lineplot` where NAs were propagating into the confidence interval, sometimes erasing it from the plot (:pr:`2273`).\n\n- |Fix| Fixed a bug in :class:`PairGrid`/:func:`pairplot` where diagonal axes would be empty when the grid was not square and the diagonal axes did not contain the marginal plots (:pr:`2270`).\n\n- |Fix| Fixed a bug in :class:`PairGrid`/:func:`pairplot` where off-diagonal plots would not appear when column names in `data` had non-string type (:pr:`2368`).\n\n- |Fix| Fixed a bug where categorical dtype information was ignored when data consisted of boolean or boolean-like values (:pr:`2379`).\n\n- |Fix| Fixed a bug in :class:`FacetGrid` where interior tick labels would be hidden when only the orthogonal axis was shared (:pr:`2347`).\n\n- |Fix| Fixed a bug in :class:`FacetGrid` that caused an error when `legend_out=False` was set (:pr:`2304`).\n\n- |Fix| Fixed a bug in :func:`kdeplot` where ``common_norm=True`` was ignored if ``hue`` was not assigned (:pr:`2378`).\n\n- |Fix| Fixed a bug in :func:`displot` where the ``row_order`` and ``col_order`` parameters were not used (:pr:`2262`).\n\n- |Fix| Fixed a bug in :class:`PairGrid`/:func:`pairplot` that caused an exception when using `corner=True` and `diag_kind=None` (:pr:`2382`).\n\n- |Fix| Fixed a bug in :func:`clustermap` where `annot=False` was ignored (:pr:`2323`).\n\n- |Fix| Fixed a bug in :func:`clustermap` where row/col color annotations could not have a categorical dtype (:pr:`2389`).\n\n- |Fix| Fixed a bug in :func:`boxenplot` where the `linewidth` parameter was ignored (:pr:`2287`).\n\n- |Fix| Raise a more informative error in :class:`PairGrid`/:func:`pairplot` when no variables can be found to define the rows/columns of the grid (:pr:`2382`).\n\n- |Fix| Raise a more informative error from :func:`clustermap` if row/col color objects have semantic index but data object does not (:pr:`2313`).\n"},{"col":4,"comment":"null","endLoc":121,"header":"def test_color_with_norm(self, x)","id":3792,"name":"test_color_with_norm","nodeType":"Function","startLoc":117,"text":"def test_color_with_norm(self, x):\n\n cmap = color_palette(\"ch:\", as_cmap=True)\n s = Continuous(norm=(3, 7))._setup(x, Color())\n assert_array_equal(s(x), cmap([-.5, 0, 1.5])[:, :3]) # FIXME RGBA"},{"id":3793,"name":"violinplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"cc19031c-bc2f-4294-95ce-3a2d9b86f44d\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"863c03b1-63e2-4d60-a3a4-4693afab4b5b\",\n \"metadata\": {},\n \"source\": [\n \"Draw a single horizontal boxplot, assigning the data directly to the coordinate variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"27d578fb-1c20-4d31-b93d-b1b4a053992b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"df = sns.load_dataset(\\\"titanic\\\")\\n\",\n \"sns.violinplot(x=df[\\\"age\\\"])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"aeea380b-405e-4762-8ede-db57f5549ca5\",\n \"metadata\": {},\n \"source\": [\n \"Group by a categorical variable, referencing columns in a dataframe:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2b851b2c-0011-4cff-8719-11f6138c44e7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"age\\\", y=\\\"class\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"c9a99aa4-2da0-42fa-879a-0c3b264803f4\",\n \"metadata\": {},\n \"source\": [\n \"Draw vertical violins, grouped by two variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4810c8e7-0864-496f-8e86-a6527369b9e1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"class\\\", y=\\\"age\\\", hue=\\\"alive\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"973e6617-5720-428d-a0ac-447e76aa9fde\",\n \"metadata\": {},\n \"source\": [\n \"Draw split violins to take up less space:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2ae35376-5272-496c-afec-c60a3426f1bf\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"deck\\\", y=\\\"age\\\", hue=\\\"alive\\\", split=True)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"f291d4a2-41bc-4eb0-813d-7a1ceacc0cb0\",\n \"metadata\": {},\n \"source\": [\n \"Prevent the density from smoothing beyond the limits of the data:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"82556de0-3756-426c-a591-9af6ed6c45d4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"age\\\", y=\\\"alive\\\", cut=0)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"6f351f71-1db3-4c5a-948c-9e1dbc550234\",\n \"metadata\": {},\n \"source\": [\n \"Use a narrower bandwidth to reduce the amount of smoothing:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"8d17e1e3-e0f4-4d2c-ac6e-aec42ed75390\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"age\\\", y=\\\"alive\\\", bw=.15)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"c4aaeb60-6c1b-4337-91ce-d6b744a3dd90\",\n \"metadata\": {},\n \"source\": [\n \"Represent every observation inside the distribution\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"00b5f00e-a515-4e53-9d73-d13b045cd4c8\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"age\\\", y=\\\"embark_town\\\", inner=\\\"stick\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"01622556-9df8-4af1-b36c-9bc5f6b6099e\",\n \"metadata\": {},\n \"source\": [\n \"Use a different scaling rule for normalizing the density:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"be59f17e-824e-4a8c-a0e1-a27874a05df6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.violinplot(data=df, x=\\\"age\\\", y=\\\"embark_town\\\", scale=\\\"count\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"fdda9a33-37f3-43fd-b02d-1ff414657a37\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"id":3794,"name":"objects.Line.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"dowjones = load_dataset(\\\"dowjones\\\")\\n\",\n \"fmri = load_dataset(\\\"fmri\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"05468ecf-d2f5-46f0-ba43-ea13aba0ebd2\",\n \"metadata\": {},\n \"source\": [\n \"The mark draws a connecting line between sorted observations:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"acd5788f-e62b-497c-a109-f0bc02b8cae9\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(dowjones, \\\"Date\\\", \\\"Price\\\").add(so.Line())\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"94efb077-49a5-4214-891a-c68f89c79926\",\n \"metadata\": {},\n \"source\": [\n \"Change the orientation to connect observations along the opposite axis (`orient=\\\"y\\\"` is redundant here; the plot would detect that the date variable has a lower orientation priority than the price variable):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4c5db48f-1c88-4905-a5f5-2ae96ceb0f95\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(dowjones, x=\\\"Price\\\", y=\\\"Date\\\").add(so.Line(), orient=\\\"y\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"77bd0b1e-d9d1-4741-9821-83cec708e877\",\n \"metadata\": {},\n \"source\": [\n \"To replicate the same line multiple times, assign a `group` variable (but consider using :class:`Lines` here instead):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2c1b699c-4e42-4461-a7fb-0d664ef8fe1b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" fmri\\n\",\n \" .query(\\\"region == 'parietal' and event == 'stim'\\\")\\n\",\n \" .pipe(so.Plot, \\\"timepoint\\\", \\\"signal\\\")\\n\",\n \" .add(so.Line(color=\\\".2\\\", linewidth=1), group=\\\"subject\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"c09cc6a1-a86b-48b7-b276-e0e9125d279e\",\n \"metadata\": {},\n \"source\": [\n \"When mapping variables to properties like `color` or `linestyle`, stat transforms are computed within each grouping:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"83b8c68d-a1ae-4bfb-b3dc-4a11bbe85cbc\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(fmri, \\\"timepoint\\\", \\\"signal\\\", color=\\\"region\\\", linestyle=\\\"event\\\")\\n\",\n \"p.add(so.Line(), so.Agg())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"c9390f58-0fb1-47ba-8b86-bde4c41e6d1d\",\n \"metadata\": {},\n \"source\": [\n \"Combine with :class:`Band` to show an error bar:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"b6ab0006-0f28-4992-b687-41889a424684\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" p\\n\",\n \" .add(so.Line(), so.Agg())\\n\",\n \" .add(so.Band(), so.Est(), group=\\\"event\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e567df5c-6675-423f-bcd8-94cb3a400251\",\n \"metadata\": {},\n \"source\": [\n \"Add markers to indicate values where the data were sampled:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2541701c-1a2c-44dd-b300-6551861c8b98\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Line(marker=\\\"o\\\", edgecolor=\\\"w\\\"), so.Agg(), linestyle=None)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a25d0379-b374-4539-82a4-00ce37245e1b\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"test_histogram.py","filePath":"tests/_stats","id":3795,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.histogram import Hist\n\n\nclass TestHist:\n\n @pytest.fixture\n def single_args(self):\n\n groupby = GroupBy([\"group\"])\n\n class Scale:\n scale_type = \"continuous\"\n\n return groupby, \"x\", {\"x\": Scale()}\n\n @pytest.fixture\n def triple_args(self):\n\n groupby = GroupBy([\"group\", \"a\", \"s\"])\n\n class Scale:\n scale_type = \"continuous\"\n\n return groupby, \"x\", {\"x\": Scale()}\n\n def test_string_bins(self, long_df):\n\n h = Hist(bins=\"sqrt\")\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (long_df[\"x\"].min(), long_df[\"x\"].max())\n assert bin_kws[\"bins\"] == int(np.sqrt(len(long_df)))\n\n def test_int_bins(self, long_df):\n\n n = 24\n h = Hist(bins=n)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (long_df[\"x\"].min(), long_df[\"x\"].max())\n assert bin_kws[\"bins\"] == n\n\n def test_array_bins(self, long_df):\n\n bins = [-3, -2, 1, 2, 3]\n h = Hist(bins=bins)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert_array_equal(bin_kws[\"bins\"], bins)\n\n def test_binwidth(self, long_df):\n\n binwidth = .5\n h = Hist(binwidth=binwidth)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n n_bins = bin_kws[\"bins\"]\n left, right = bin_kws[\"range\"]\n assert (right - left) / n_bins == pytest.approx(binwidth)\n\n def test_binrange(self, long_df):\n\n binrange = (-4, 4)\n h = Hist(binrange=binrange)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == binrange\n\n def test_discrete_bins(self, long_df):\n\n h = Hist(discrete=True)\n x = long_df[\"x\"].astype(int)\n bin_kws = h._define_bin_params(long_df.assign(x=x), \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)\n\n def test_discrete_bins_from_nominal_scale(self, rng):\n\n h = Hist()\n x = rng.randint(0, 5, 10)\n df = pd.DataFrame({\"x\": x})\n bin_kws = h._define_bin_params(df, \"x\", \"nominal\")\n assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)\n\n def test_count_stat(self, long_df, single_args):\n\n h = Hist(stat=\"count\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == len(long_df)\n\n def test_probability_stat(self, long_df, single_args):\n\n h = Hist(stat=\"probability\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 1\n\n def test_proportion_stat(self, long_df, single_args):\n\n h = Hist(stat=\"proportion\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 1\n\n def test_percent_stat(self, long_df, single_args):\n\n h = Hist(stat=\"percent\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 100\n\n def test_density_stat(self, long_df, single_args):\n\n h = Hist(stat=\"density\")\n out = h(long_df, *single_args)\n assert (out[\"y\"] * out[\"space\"]).sum() == 1\n\n def test_frequency_stat(self, long_df, single_args):\n\n h = Hist(stat=\"frequency\")\n out = h(long_df, *single_args)\n assert (out[\"y\"] * out[\"space\"]).sum() == len(long_df)\n\n def test_invalid_stat(self):\n\n with pytest.raises(ValueError, match=\"The `stat` parameter for `Hist`\"):\n Hist(stat=\"invalid\")\n\n def test_cumulative_count(self, long_df, single_args):\n\n h = Hist(stat=\"count\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == len(long_df)\n\n def test_cumulative_proportion(self, long_df, single_args):\n\n h = Hist(stat=\"proportion\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == 1\n\n def test_cumulative_density(self, long_df, single_args):\n\n h = Hist(stat=\"density\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == 1\n\n def test_common_norm_default(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\")\n out = h(long_df, *triple_args)\n assert out[\"y\"].sum() == pytest.approx(100)\n\n def test_common_norm_false(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\", common_norm=False)\n out = h(long_df, *triple_args)\n for _, out_part in out.groupby([\"a\", \"s\"]):\n assert out_part[\"y\"].sum() == pytest.approx(100)\n\n def test_common_norm_subset(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\", common_norm=[\"a\"])\n out = h(long_df, *triple_args)\n for _, out_part in out.groupby(\"a\"):\n assert out_part[\"y\"].sum() == pytest.approx(100)\n\n def test_common_norm_warning(self, long_df, triple_args):\n\n h = Hist(common_norm=[\"b\"])\n with pytest.warns(UserWarning, match=\"Undefined variable(s)\"):\n h(long_df, *triple_args)\n\n def test_common_bins_default(self, long_df, triple_args):\n\n h = Hist()\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby([\"a\", \"s\"]):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == 1\n\n def test_common_bins_false(self, long_df, triple_args):\n\n h = Hist(common_bins=False)\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby([\"a\", \"s\"]):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == len(out.groupby([\"a\", \"s\"]))\n\n def test_common_bins_subset(self, long_df, triple_args):\n\n h = Hist(common_bins=False)\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby(\"a\"):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == out[\"a\"].nunique()\n\n def test_common_bins_warning(self, long_df, triple_args):\n\n h = Hist(common_bins=[\"b\"])\n with pytest.warns(UserWarning, match=\"Undefined variable(s)\"):\n h(long_df, *triple_args)\n\n def test_histogram_single(self, long_df, single_args):\n\n h = Hist()\n out = h(long_df, *single_args)\n hist, edges = np.histogram(long_df[\"x\"], bins=\"auto\")\n assert_array_equal(out[\"y\"], hist)\n assert_array_equal(out[\"space\"], np.diff(edges))\n\n def test_histogram_multiple(self, long_df, triple_args):\n\n h = Hist()\n out = h(long_df, *triple_args)\n bins = np.histogram_bin_edges(long_df[\"x\"], \"auto\")\n for (a, s), out_part in out.groupby([\"a\", \"s\"]):\n x = long_df.loc[(long_df[\"a\"] == a) & (long_df[\"s\"] == s), \"x\"]\n hist, edges = np.histogram(x, bins=bins)\n assert_array_equal(out_part[\"y\"], hist)\n assert_array_equal(out_part[\"space\"], np.diff(edges))\n"},{"id":3796,"name":"stripplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"whitegrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a single numeric variable shows its univariate distribution with points randomly \\\"jittered\\\" on the other axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a second variable splits the strips of points to compare categorical levels of that variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Show vertically-oriented strips by swapping the assignment of the categorical and numerical variables:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"day\\\", y=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Prior to version 0.12, the levels of the categorical variable had different colors by default. To get the same effect, assign the `hue` variable explicitly:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"day\\\", legend=False)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Or you can assign a distinct variable to `hue` to show a multidimensional relationship:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"If the `hue` variable is numeric, it will be mapped with a quantitative palette by default (note that this was not the case prior to version 0.12):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Use `palette` to control the color mapping, including forcing a categorical mapping by passing the name of a qualitative palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"size\\\", palette=\\\"deep\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, the different levels of the `hue` variable are intermingled in each strip, but setting `dodge=True` will split them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\", dodge=True)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The random jitter can be disabled by setting `jitter=False`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"sex\\\", dodge=True, jitter=False)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"If plotting in wide-form mode, each numeric column of the dataframe will be mapped to both `x` and `hue`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To change the orientation while in wide-form mode, pass `orient` explicitly:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, orient=\\\"h\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The `orient` parameter is also useful when both axis variables are numeric, as it will resolve ambiguity about which dimension to group (and jitter) along:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(data=tips, x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"By default, the categorical variable will be mapped to discrete indices with a fixed scale (0, 1, ...), even when it is numeric:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(\\n\",\n \" data=tips.query(\\\"size in [2, 3, 5]\\\"),\\n\",\n \" x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To disable this behavior and use the original scale of the variable, set `native_scale=True`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(\\n\",\n \" data=tips.query(\\\"size in [2, 3, 5]\\\"),\\n\",\n \" x=\\\"total_bill\\\", y=\\\"size\\\", orient=\\\"h\\\",\\n\",\n \" native_scale=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Further visual customization can be achieved by passing keyword arguments for :func:`matplotlib.axes.Axes.scatter`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.stripplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"day\\\", hue=\\\"time\\\",\\n\",\n \" jitter=False, s=20, marker=\\\"D\\\", linewidth=1, alpha=.1,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To make a plot with multiple facets, it is safer to use :func:`catplot` than to work with :class:`FacetGrid` directly, because :func:`catplot` will ensure that the categorical and hue variables are properly synchronized in each facet:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.catplot(data=tips, x=\\\"time\\\", y=\\\"total_bill\\\", hue=\\\"sex\\\", col=\\\"day\\\", aspect=.5)\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"className":"TestHist","col":0,"comment":"null","endLoc":224,"id":3797,"nodeType":"Class","startLoc":12,"text":"class TestHist:\n\n @pytest.fixture\n def single_args(self):\n\n groupby = GroupBy([\"group\"])\n\n class Scale:\n scale_type = \"continuous\"\n\n return groupby, \"x\", {\"x\": Scale()}\n\n @pytest.fixture\n def triple_args(self):\n\n groupby = GroupBy([\"group\", \"a\", \"s\"])\n\n class Scale:\n scale_type = \"continuous\"\n\n return groupby, \"x\", {\"x\": Scale()}\n\n def test_string_bins(self, long_df):\n\n h = Hist(bins=\"sqrt\")\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (long_df[\"x\"].min(), long_df[\"x\"].max())\n assert bin_kws[\"bins\"] == int(np.sqrt(len(long_df)))\n\n def test_int_bins(self, long_df):\n\n n = 24\n h = Hist(bins=n)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (long_df[\"x\"].min(), long_df[\"x\"].max())\n assert bin_kws[\"bins\"] == n\n\n def test_array_bins(self, long_df):\n\n bins = [-3, -2, 1, 2, 3]\n h = Hist(bins=bins)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert_array_equal(bin_kws[\"bins\"], bins)\n\n def test_binwidth(self, long_df):\n\n binwidth = .5\n h = Hist(binwidth=binwidth)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n n_bins = bin_kws[\"bins\"]\n left, right = bin_kws[\"range\"]\n assert (right - left) / n_bins == pytest.approx(binwidth)\n\n def test_binrange(self, long_df):\n\n binrange = (-4, 4)\n h = Hist(binrange=binrange)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == binrange\n\n def test_discrete_bins(self, long_df):\n\n h = Hist(discrete=True)\n x = long_df[\"x\"].astype(int)\n bin_kws = h._define_bin_params(long_df.assign(x=x), \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)\n\n def test_discrete_bins_from_nominal_scale(self, rng):\n\n h = Hist()\n x = rng.randint(0, 5, 10)\n df = pd.DataFrame({\"x\": x})\n bin_kws = h._define_bin_params(df, \"x\", \"nominal\")\n assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)\n\n def test_count_stat(self, long_df, single_args):\n\n h = Hist(stat=\"count\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == len(long_df)\n\n def test_probability_stat(self, long_df, single_args):\n\n h = Hist(stat=\"probability\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 1\n\n def test_proportion_stat(self, long_df, single_args):\n\n h = Hist(stat=\"proportion\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 1\n\n def test_percent_stat(self, long_df, single_args):\n\n h = Hist(stat=\"percent\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 100\n\n def test_density_stat(self, long_df, single_args):\n\n h = Hist(stat=\"density\")\n out = h(long_df, *single_args)\n assert (out[\"y\"] * out[\"space\"]).sum() == 1\n\n def test_frequency_stat(self, long_df, single_args):\n\n h = Hist(stat=\"frequency\")\n out = h(long_df, *single_args)\n assert (out[\"y\"] * out[\"space\"]).sum() == len(long_df)\n\n def test_invalid_stat(self):\n\n with pytest.raises(ValueError, match=\"The `stat` parameter for `Hist`\"):\n Hist(stat=\"invalid\")\n\n def test_cumulative_count(self, long_df, single_args):\n\n h = Hist(stat=\"count\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == len(long_df)\n\n def test_cumulative_proportion(self, long_df, single_args):\n\n h = Hist(stat=\"proportion\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == 1\n\n def test_cumulative_density(self, long_df, single_args):\n\n h = Hist(stat=\"density\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == 1\n\n def test_common_norm_default(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\")\n out = h(long_df, *triple_args)\n assert out[\"y\"].sum() == pytest.approx(100)\n\n def test_common_norm_false(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\", common_norm=False)\n out = h(long_df, *triple_args)\n for _, out_part in out.groupby([\"a\", \"s\"]):\n assert out_part[\"y\"].sum() == pytest.approx(100)\n\n def test_common_norm_subset(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\", common_norm=[\"a\"])\n out = h(long_df, *triple_args)\n for _, out_part in out.groupby(\"a\"):\n assert out_part[\"y\"].sum() == pytest.approx(100)\n\n def test_common_norm_warning(self, long_df, triple_args):\n\n h = Hist(common_norm=[\"b\"])\n with pytest.warns(UserWarning, match=\"Undefined variable(s)\"):\n h(long_df, *triple_args)\n\n def test_common_bins_default(self, long_df, triple_args):\n\n h = Hist()\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby([\"a\", \"s\"]):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == 1\n\n def test_common_bins_false(self, long_df, triple_args):\n\n h = Hist(common_bins=False)\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby([\"a\", \"s\"]):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == len(out.groupby([\"a\", \"s\"]))\n\n def test_common_bins_subset(self, long_df, triple_args):\n\n h = Hist(common_bins=False)\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby(\"a\"):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == out[\"a\"].nunique()\n\n def test_common_bins_warning(self, long_df, triple_args):\n\n h = Hist(common_bins=[\"b\"])\n with pytest.warns(UserWarning, match=\"Undefined variable(s)\"):\n h(long_df, *triple_args)\n\n def test_histogram_single(self, long_df, single_args):\n\n h = Hist()\n out = h(long_df, *single_args)\n hist, edges = np.histogram(long_df[\"x\"], bins=\"auto\")\n assert_array_equal(out[\"y\"], hist)\n assert_array_equal(out[\"space\"], np.diff(edges))\n\n def test_histogram_multiple(self, long_df, triple_args):\n\n h = Hist()\n out = h(long_df, *triple_args)\n bins = np.histogram_bin_edges(long_df[\"x\"], \"auto\")\n for (a, s), out_part in out.groupby([\"a\", \"s\"]):\n x = long_df.loc[(long_df[\"a\"] == a) & (long_df[\"s\"] == s), \"x\"]\n hist, edges = np.histogram(x, bins=bins)\n assert_array_equal(out_part[\"y\"], hist)\n assert_array_equal(out_part[\"space\"], np.diff(edges))"},{"col":4,"comment":"null","endLoc":22,"header":"@pytest.fixture\n def single_args(self)","id":3798,"name":"single_args","nodeType":"Function","startLoc":14,"text":"@pytest.fixture\n def single_args(self):\n\n groupby = GroupBy([\"group\"])\n\n class Scale:\n scale_type = \"continuous\"\n\n return groupby, \"x\", {\"x\": Scale()}"},{"fileName":"joint_kde.py","filePath":"examples","id":3799,"nodeType":"File","text":"\"\"\"\nJoint kernel density estimate\n=============================\n\n_thumb: .6, .4\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\n\n# Load the penguins dataset\npenguins = sns.load_dataset(\"penguins\")\n\n# Show the joint distribution using kernel density estimation\ng = sns.jointplot(\n data=penguins,\n x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\",\n kind=\"kde\",\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3800,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"col":4,"comment":"null","endLoc":128,"header":"def test_color_with_transform(self, x)","id":3801,"name":"test_color_with_transform","nodeType":"Function","startLoc":123,"text":"def test_color_with_transform(self, x):\n\n x = pd.Series([1, 10, 100], name=\"x\", dtype=float)\n cmap = color_palette(\"ch:\", as_cmap=True)\n s = Continuous(trans=\"log\")._setup(x, Color())\n assert_array_equal(s(x), cmap([0, .5, 1])[:, :3]) # FIXME RGBA"},{"col":4,"comment":"null","endLoc":135,"header":"def test_tick_locator(self, x)","id":3802,"name":"test_tick_locator","nodeType":"Function","startLoc":130,"text":"def test_tick_locator(self, x):\n\n locs = [.2, .5, .8]\n locator = mpl.ticker.FixedLocator(locs)\n a = self.setup_ticks(x, locator)\n assert_array_equal(a.major.locator(), locs)"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3803,"name":"penguins","nodeType":"Attribute","startLoc":11,"text":"penguins"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":3804,"name":"g","nodeType":"Attribute","startLoc":14,"text":"g"},{"col":0,"comment":"","endLoc":6,"header":"joint_kde.py#","id":3805,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nJoint kernel density estimate\n=============================\n\n_thumb: .6, .4\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\npenguins = sns.load_dataset(\"penguins\")\n\ng = sns.jointplot(\n data=penguins,\n x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\",\n kind=\"kde\",\n)"},{"col":4,"comment":"null","endLoc":141,"header":"def test_tick_locator_input_check(self, x)","id":3806,"name":"test_tick_locator_input_check","nodeType":"Function","startLoc":137,"text":"def test_tick_locator_input_check(self, x):\n\n err = \"Tick locator must be an instance of .*?, not .\"\n with pytest.raises(TypeError, match=err):\n Continuous().tick((1, 2))"},{"col":4,"comment":"null","endLoc":147,"header":"def test_tick_upto(self, x)","id":3807,"name":"test_tick_upto","nodeType":"Function","startLoc":143,"text":"def test_tick_upto(self, x):\n\n for n in [2, 5, 10]:\n a = self.setup_ticks(x, upto=n)\n assert len(a.major.locator()) <= (n + 1)"},{"col":4,"comment":"null","endLoc":32,"header":"@pytest.fixture\n def triple_args(self)","id":3808,"name":"triple_args","nodeType":"Function","startLoc":24,"text":"@pytest.fixture\n def triple_args(self):\n\n groupby = GroupBy([\"group\", \"a\", \"s\"])\n\n class Scale:\n scale_type = \"continuous\"\n\n return groupby, \"x\", {\"x\": Scale()}"},{"col":4,"comment":"null","endLoc":153,"header":"def test_tick_every(self, x)","id":3809,"name":"test_tick_every","nodeType":"Function","startLoc":149,"text":"def test_tick_every(self, x):\n\n for d in [.05, .2, .5]:\n a = self.setup_ticks(x, every=d)\n assert np.allclose(np.diff(a.major.locator()), d)"},{"col":4,"comment":"null","endLoc":39,"header":"def test_string_bins(self, long_df)","id":3810,"name":"test_string_bins","nodeType":"Function","startLoc":34,"text":"def test_string_bins(self, long_df):\n\n h = Hist(bins=\"sqrt\")\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (long_df[\"x\"].min(), long_df[\"x\"].max())\n assert bin_kws[\"bins\"] == int(np.sqrt(len(long_df)))"},{"fileName":"widgets.py","filePath":"seaborn","id":3811,"nodeType":"File","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\n\ntry:\n from ipywidgets import interact, FloatSlider, IntSlider\nexcept ImportError:\n def interact(f):\n msg = \"Interactive palettes require `ipywidgets`, which is not installed.\"\n raise ImportError(msg)\n\nfrom .miscplot import palplot\nfrom .palettes import (color_palette, dark_palette, light_palette,\n diverging_palette, cubehelix_palette)\n\n\n__all__ = [\"choose_colorbrewer_palette\", \"choose_cubehelix_palette\",\n \"choose_dark_palette\", \"choose_light_palette\",\n \"choose_diverging_palette\"]\n\n\ndef _init_mutable_colormap():\n \"\"\"Create a matplotlib colormap that will be updated by the widgets.\"\"\"\n greys = color_palette(\"Greys\", 256)\n cmap = LinearSegmentedColormap.from_list(\"interactive\", greys)\n cmap._init()\n cmap._set_extremes()\n return cmap\n\n\ndef _update_lut(cmap, colors):\n \"\"\"Change the LUT values in a matplotlib colormap in-place.\"\"\"\n cmap._lut[:256] = colors\n cmap._set_extremes()\n\n\ndef _show_cmap(cmap):\n \"\"\"Show a continuous matplotlib colormap.\"\"\"\n from .rcmod import axes_style # Avoid circular import\n with axes_style(\"white\"):\n f, ax = plt.subplots(figsize=(8.25, .75))\n ax.set(xticks=[], yticks=[])\n x = np.linspace(0, 1, 256)[np.newaxis, :]\n ax.pcolormesh(x, cmap=cmap)\n\n\ndef choose_colorbrewer_palette(data_type, as_cmap=False):\n \"\"\"Select a palette from the ColorBrewer set.\n\n These palettes are built into matplotlib and can be used by name in\n many seaborn functions, or by passing the object returned by this function.\n\n Parameters\n ----------\n data_type : {'sequential', 'diverging', 'qualitative'}\n This describes the kind of data you want to visualize. See the seaborn\n color palette docs for more information about how to choose this value.\n Note that you can pass substrings (e.g. 'q' for 'qualitative.\n\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n diverging_palette : Create a diverging palette from selected colors.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n\n \"\"\"\n if data_type.startswith(\"q\") and as_cmap:\n raise ValueError(\"Qualitative palettes cannot be colormaps.\")\n\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n if data_type.startswith(\"s\"):\n opts = [\"Greys\", \"Reds\", \"Greens\", \"Blues\", \"Oranges\", \"Purples\",\n \"BuGn\", \"BuPu\", \"GnBu\", \"OrRd\", \"PuBu\", \"PuRd\", \"RdPu\", \"YlGn\",\n \"PuBuGn\", \"YlGnBu\", \"YlOrBr\", \"YlOrRd\"]\n variants = [\"regular\", \"reverse\", \"dark\"]\n\n @interact\n def choose_sequential(name=opts, n=(2, 18),\n desat=FloatSlider(min=0, max=1, value=1),\n variant=variants):\n if variant == \"reverse\":\n name += \"_r\"\n elif variant == \"dark\":\n name += \"_d\"\n\n if as_cmap:\n colors = color_palette(name, 256, desat)\n _update_lut(cmap, np.c_[colors, np.ones(256)])\n _show_cmap(cmap)\n else:\n pal[:] = color_palette(name, n, desat)\n palplot(pal)\n\n elif data_type.startswith(\"d\"):\n opts = [\"RdBu\", \"RdGy\", \"PRGn\", \"PiYG\", \"BrBG\",\n \"RdYlBu\", \"RdYlGn\", \"Spectral\"]\n variants = [\"regular\", \"reverse\"]\n\n @interact\n def choose_diverging(name=opts, n=(2, 16),\n desat=FloatSlider(min=0, max=1, value=1),\n variant=variants):\n if variant == \"reverse\":\n name += \"_r\"\n if as_cmap:\n colors = color_palette(name, 256, desat)\n _update_lut(cmap, np.c_[colors, np.ones(256)])\n _show_cmap(cmap)\n else:\n pal[:] = color_palette(name, n, desat)\n palplot(pal)\n\n elif data_type.startswith(\"q\"):\n opts = [\"Set1\", \"Set2\", \"Set3\", \"Paired\", \"Accent\",\n \"Pastel1\", \"Pastel2\", \"Dark2\"]\n\n @interact\n def choose_qualitative(name=opts, n=(2, 16),\n desat=FloatSlider(min=0, max=1, value=1)):\n pal[:] = color_palette(name, n, desat)\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal\n\n\ndef choose_dark_palette(input=\"husl\", as_cmap=False):\n \"\"\"Launch an interactive widget to create a dark sequential palette.\n\n This corresponds with the :func:`dark_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n input : {'husl', 'hls', 'rgb'}\n Color space for defining the seed value. Note that the default is\n different than the default input for :func:`dark_palette`.\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n if input == \"rgb\":\n @interact\n def choose_dark_palette_rgb(r=(0., 1.),\n g=(0., 1.),\n b=(0., 1.),\n n=(3, 17)):\n color = r, g, b\n if as_cmap:\n colors = dark_palette(color, 256, input=\"rgb\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = dark_palette(color, n, input=\"rgb\")\n palplot(pal)\n\n elif input == \"hls\":\n @interact\n def choose_dark_palette_hls(h=(0., 1.),\n l=(0., 1.), # noqa: E741\n s=(0., 1.),\n n=(3, 17)):\n color = h, l, s\n if as_cmap:\n colors = dark_palette(color, 256, input=\"hls\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = dark_palette(color, n, input=\"hls\")\n palplot(pal)\n\n elif input == \"husl\":\n @interact\n def choose_dark_palette_husl(h=(0, 359),\n s=(0, 99),\n l=(0, 99), # noqa: E741\n n=(3, 17)):\n color = h, s, l\n if as_cmap:\n colors = dark_palette(color, 256, input=\"husl\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = dark_palette(color, n, input=\"husl\")\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal\n\n\ndef choose_light_palette(input=\"husl\", as_cmap=False):\n \"\"\"Launch an interactive widget to create a light sequential palette.\n\n This corresponds with the :func:`light_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n input : {'husl', 'hls', 'rgb'}\n Color space for defining the seed value. Note that the default is\n different than the default input for :func:`light_palette`.\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n light_palette : Create a sequential palette with bright low values.\n dark_palette : Create a sequential palette with dark low values.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n if input == \"rgb\":\n @interact\n def choose_light_palette_rgb(r=(0., 1.),\n g=(0., 1.),\n b=(0., 1.),\n n=(3, 17)):\n color = r, g, b\n if as_cmap:\n colors = light_palette(color, 256, input=\"rgb\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = light_palette(color, n, input=\"rgb\")\n palplot(pal)\n\n elif input == \"hls\":\n @interact\n def choose_light_palette_hls(h=(0., 1.),\n l=(0., 1.), # noqa: E741\n s=(0., 1.),\n n=(3, 17)):\n color = h, l, s\n if as_cmap:\n colors = light_palette(color, 256, input=\"hls\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = light_palette(color, n, input=\"hls\")\n palplot(pal)\n\n elif input == \"husl\":\n @interact\n def choose_light_palette_husl(h=(0, 359),\n s=(0, 99),\n l=(0, 99), # noqa: E741\n n=(3, 17)):\n color = h, s, l\n if as_cmap:\n colors = light_palette(color, 256, input=\"husl\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = light_palette(color, n, input=\"husl\")\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal\n\n\ndef choose_diverging_palette(as_cmap=False):\n \"\"\"Launch an interactive widget to choose a diverging color palette.\n\n This corresponds with the :func:`diverging_palette` function. This kind\n of palette is good for data that range between interesting low values\n and interesting high values with a meaningful midpoint. (For example,\n change scores relative to some baseline value).\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n diverging_palette : Create a diverging color palette or colormap.\n choose_colorbrewer_palette : Interactively choose palettes from the\n colorbrewer set, including diverging palettes.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n @interact\n def choose_diverging_palette(\n h_neg=IntSlider(min=0,\n max=359,\n value=220),\n h_pos=IntSlider(min=0,\n max=359,\n value=10),\n s=IntSlider(min=0, max=99, value=74),\n l=IntSlider(min=0, max=99, value=50), # noqa: E741\n sep=IntSlider(min=1, max=50, value=10),\n n=(2, 16),\n center=[\"light\", \"dark\"]\n ):\n if as_cmap:\n colors = diverging_palette(h_neg, h_pos, s, l, sep, 256, center)\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = diverging_palette(h_neg, h_pos, s, l, sep, n, center)\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal\n\n\ndef choose_cubehelix_palette(as_cmap=False):\n \"\"\"Launch an interactive widget to create a sequential cubehelix palette.\n\n This corresponds with the :func:`cubehelix_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values. The cubehelix system allows the\n palette to have more hue variance across the range, which can be helpful\n for distinguishing a wider range of values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n @interact\n def choose_cubehelix(n_colors=IntSlider(min=2, max=16, value=9),\n start=FloatSlider(min=0, max=3, value=0),\n rot=FloatSlider(min=-1, max=1, value=.4),\n gamma=FloatSlider(min=0, max=5, value=1),\n hue=FloatSlider(min=0, max=1, value=.8),\n light=FloatSlider(min=0, max=1, value=.85),\n dark=FloatSlider(min=0, max=1, value=.15),\n reverse=False):\n\n if as_cmap:\n colors = cubehelix_palette(256, start, rot, gamma,\n hue, light, dark, reverse)\n _update_lut(cmap, np.c_[colors, np.ones(256)])\n _show_cmap(cmap)\n else:\n pal[:] = cubehelix_palette(n_colors, start, rot, gamma,\n hue, light, dark, reverse)\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal\n"},{"col":0,"comment":"Create a matplotlib colormap that will be updated by the widgets.","endLoc":28,"header":"def _init_mutable_colormap()","id":3812,"name":"_init_mutable_colormap","nodeType":"Function","startLoc":22,"text":"def _init_mutable_colormap():\n \"\"\"Create a matplotlib colormap that will be updated by the widgets.\"\"\"\n greys = color_palette(\"Greys\", 256)\n cmap = LinearSegmentedColormap.from_list(\"interactive\", greys)\n cmap._init()\n cmap._set_extremes()\n return cmap"},{"col":4,"comment":"null","endLoc":161,"header":"def test_tick_every_between(self, x)","id":3813,"name":"test_tick_every_between","nodeType":"Function","startLoc":155,"text":"def test_tick_every_between(self, x):\n\n lo, hi = .2, .8\n for d in [.05, .2, .5]:\n a = self.setup_ticks(x, every=d, between=(lo, hi))\n expected = np.arange(lo, hi + d, d)\n assert_array_equal(a.major.locator(), expected)"},{"col":0,"comment":"Change the LUT values in a matplotlib colormap in-place.","endLoc":34,"header":"def _update_lut(cmap, colors)","id":3814,"name":"_update_lut","nodeType":"Function","startLoc":31,"text":"def _update_lut(cmap, colors):\n \"\"\"Change the LUT values in a matplotlib colormap in-place.\"\"\"\n cmap._lut[:256] = colors\n cmap._set_extremes()"},{"col":0,"comment":"Show a continuous matplotlib colormap.","endLoc":44,"header":"def _show_cmap(cmap)","id":3815,"name":"_show_cmap","nodeType":"Function","startLoc":37,"text":"def _show_cmap(cmap):\n \"\"\"Show a continuous matplotlib colormap.\"\"\"\n from .rcmod import axes_style # Avoid circular import\n with axes_style(\"white\"):\n f, ax = plt.subplots(figsize=(8.25, .75))\n ax.set(xticks=[], yticks=[])\n x = np.linspace(0, 1, 256)[np.newaxis, :]\n ax.pcolormesh(x, cmap=cmap)"},{"col":4,"comment":"null","endLoc":167,"header":"def test_tick_at(self, x)","id":3816,"name":"test_tick_at","nodeType":"Function","startLoc":163,"text":"def test_tick_at(self, x):\n\n locs = [.2, .5, .9]\n a = self.setup_ticks(x, at=locs)\n assert_array_equal(a.major.locator(), locs)"},{"col":0,"comment":"Select a palette from the ColorBrewer set.\n\n These palettes are built into matplotlib and can be used by name in\n many seaborn functions, or by passing the object returned by this function.\n\n Parameters\n ----------\n data_type : {'sequential', 'diverging', 'qualitative'}\n This describes the kind of data you want to visualize. See the seaborn\n color palette docs for more information about how to choose this value.\n Note that you can pass substrings (e.g. 'q' for 'qualitative.\n\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n diverging_palette : Create a diverging palette from selected colors.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n\n ","endLoc":140,"header":"def choose_colorbrewer_palette(data_type, as_cmap=False)","id":3817,"name":"choose_colorbrewer_palette","nodeType":"Function","startLoc":47,"text":"def choose_colorbrewer_palette(data_type, as_cmap=False):\n \"\"\"Select a palette from the ColorBrewer set.\n\n These palettes are built into matplotlib and can be used by name in\n many seaborn functions, or by passing the object returned by this function.\n\n Parameters\n ----------\n data_type : {'sequential', 'diverging', 'qualitative'}\n This describes the kind of data you want to visualize. See the seaborn\n color palette docs for more information about how to choose this value.\n Note that you can pass substrings (e.g. 'q' for 'qualitative.\n\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n diverging_palette : Create a diverging palette from selected colors.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n\n \"\"\"\n if data_type.startswith(\"q\") and as_cmap:\n raise ValueError(\"Qualitative palettes cannot be colormaps.\")\n\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n if data_type.startswith(\"s\"):\n opts = [\"Greys\", \"Reds\", \"Greens\", \"Blues\", \"Oranges\", \"Purples\",\n \"BuGn\", \"BuPu\", \"GnBu\", \"OrRd\", \"PuBu\", \"PuRd\", \"RdPu\", \"YlGn\",\n \"PuBuGn\", \"YlGnBu\", \"YlOrBr\", \"YlOrRd\"]\n variants = [\"regular\", \"reverse\", \"dark\"]\n\n @interact\n def choose_sequential(name=opts, n=(2, 18),\n desat=FloatSlider(min=0, max=1, value=1),\n variant=variants):\n if variant == \"reverse\":\n name += \"_r\"\n elif variant == \"dark\":\n name += \"_d\"\n\n if as_cmap:\n colors = color_palette(name, 256, desat)\n _update_lut(cmap, np.c_[colors, np.ones(256)])\n _show_cmap(cmap)\n else:\n pal[:] = color_palette(name, n, desat)\n palplot(pal)\n\n elif data_type.startswith(\"d\"):\n opts = [\"RdBu\", \"RdGy\", \"PRGn\", \"PiYG\", \"BrBG\",\n \"RdYlBu\", \"RdYlGn\", \"Spectral\"]\n variants = [\"regular\", \"reverse\"]\n\n @interact\n def choose_diverging(name=opts, n=(2, 16),\n desat=FloatSlider(min=0, max=1, value=1),\n variant=variants):\n if variant == \"reverse\":\n name += \"_r\"\n if as_cmap:\n colors = color_palette(name, 256, desat)\n _update_lut(cmap, np.c_[colors, np.ones(256)])\n _show_cmap(cmap)\n else:\n pal[:] = color_palette(name, n, desat)\n palplot(pal)\n\n elif data_type.startswith(\"q\"):\n opts = [\"Set1\", \"Set2\", \"Set3\", \"Paired\", \"Accent\",\n \"Pastel1\", \"Pastel2\", \"Dark2\"]\n\n @interact\n def choose_qualitative(name=opts, n=(2, 16),\n desat=FloatSlider(min=0, max=1, value=1)):\n pal[:] = color_palette(name, n, desat)\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal"},{"col":0,"comment":"null","endLoc":166,"header":"def savefig(fig, shape, variant)","id":3818,"name":"savefig","nodeType":"Function","startLoc":159,"text":"def savefig(fig, shape, variant):\n\n fig.subplots_adjust(0, 0, 1, 1, 0, 0)\n\n facecolor = (1, 1, 1, 1) if bg == \"white\" else (1, 1, 1, 0)\n\n for ext in [\"png\", \"svg\"]:\n fig.savefig(f\"{STATIC_DIR}/logo-{shape}-{variant}bg.{ext}\", facecolor=facecolor)"},{"col":4,"comment":"null","endLoc":173,"header":"def test_tick_count(self, x)","id":3819,"name":"test_tick_count","nodeType":"Function","startLoc":169,"text":"def test_tick_count(self, x):\n\n n = 8\n a = self.setup_ticks(x, count=n)\n assert_array_equal(a.major.locator(), np.linspace(0, 1, n))"},{"attributeType":"null","col":16,"comment":"null","endLoc":1,"id":3820,"name":"np","nodeType":"Attribute","startLoc":1,"text":"np"},{"attributeType":"null","col":18,"comment":"null","endLoc":2,"id":3821,"name":"sns","nodeType":"Attribute","startLoc":2,"text":"sns"},{"attributeType":"null","col":28,"comment":"null","endLoc":4,"id":3822,"name":"plt","nodeType":"Attribute","startLoc":4,"text":"plt"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":9,"id":3823,"name":"XY_CACHE","nodeType":"Attribute","startLoc":9,"text":"XY_CACHE"},{"attributeType":"str","col":0,"comment":"null","endLoc":11,"id":3824,"name":"STATIC_DIR","nodeType":"Attribute","startLoc":11,"text":"STATIC_DIR"},{"attributeType":"str","col":8,"comment":"null","endLoc":171,"id":3825,"name":"bg","nodeType":"Attribute","startLoc":171,"text":"bg"},{"col":4,"comment":"null","endLoc":180,"header":"def test_tick_count_between(self, x)","id":3826,"name":"test_tick_count_between","nodeType":"Function","startLoc":175,"text":"def test_tick_count_between(self, x):\n\n n = 5\n lo, hi = .2, .7\n a = self.setup_ticks(x, count=n, between=(lo, hi))\n assert_array_equal(a.major.locator(), np.linspace(lo, hi, n))"},{"col":4,"comment":"null","endLoc":189,"header":"def test_tick_minor(self, x)","id":3827,"name":"test_tick_minor","nodeType":"Function","startLoc":182,"text":"def test_tick_minor(self, x):\n\n n = 3\n a = self.setup_ticks(x, count=2, minor=n)\n # I am not sure why matplotlib's minor ticks include the\n # largest major location but exclude the smalllest one ...\n expected = np.linspace(0, 1, n + 2)[1:]\n assert_array_equal(a.minor.locator(), expected)"},{"col":4,"comment":"null","endLoc":197,"header":"def test_log_tick_default(self, x)","id":3828,"name":"test_log_tick_default","nodeType":"Function","startLoc":191,"text":"def test_log_tick_default(self, x):\n\n s = Continuous(trans=\"log\")._setup(x, Coordinate())\n a = PseudoAxis(s._matplotlib_scale)\n a.set_view_interval(.5, 1050)\n ticks = a.major.locator()\n assert np.allclose(np.diff(np.log10(ticks)), 1)"},{"col":4,"comment":"null","endLoc":204,"header":"def test_log_tick_upto(self, x)","id":3829,"name":"test_log_tick_upto","nodeType":"Function","startLoc":199,"text":"def test_log_tick_upto(self, x):\n\n n = 3\n s = Continuous(trans=\"log\").tick(upto=n)._setup(x, Coordinate())\n a = PseudoAxis(s._matplotlib_scale)\n assert a.major.locator.numticks == n"},{"col":4,"comment":"null","endLoc":214,"header":"def test_log_tick_count(self, x)","id":3830,"name":"test_log_tick_count","nodeType":"Function","startLoc":206,"text":"def test_log_tick_count(self, x):\n\n with pytest.raises(RuntimeError, match=\"`count` requires\"):\n Continuous(trans=\"log\").tick(count=4)\n\n s = Continuous(trans=\"log\").tick(count=4, between=(1, 1000))\n a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)\n a.set_view_interval(.5, 1050)\n assert_array_equal(a.major.locator(), [1, 10, 100, 1000])"},{"col":4,"comment":"Find the outliers based on the letter value depth.","endLoc":1832,"header":"def _lv_outliers(self, vals, k)","id":3831,"name":"_lv_outliers","nodeType":"Function","startLoc":1825,"text":"def _lv_outliers(self, vals, k):\n \"\"\"Find the outliers based on the letter value depth.\"\"\"\n box_edge = 0.5 ** (k + 1)\n perc_ends = (100 * box_edge, 100 * (1 - box_edge))\n edges = np.percentile(vals, perc_ends)\n lower_out = vals[np.where(vals < edges[0])[0]]\n upper_out = vals[np.where(vals > edges[1])[0]]\n return np.concatenate((lower_out, upper_out))"},{"attributeType":"int","col":8,"comment":"null","endLoc":173,"id":3832,"name":"color_idx","nodeType":"Attribute","startLoc":173,"text":"color_idx"},{"col":4,"comment":"null","endLoc":1839,"header":"def _width_functions(self, width_func)","id":3833,"name":"_width_functions","nodeType":"Function","startLoc":1834,"text":"def _width_functions(self, width_func):\n # Dictionary of functions for computing the width of the boxes\n width_functions = {'linear': lambda h, i, k: (i + 1.) / k,\n 'exponential': lambda h, i, k: 2**(-k + i - 1),\n 'area': lambda h, i, k: (1 - 2**(-k + i - 2)) / h}\n return width_functions[width_func]"},{"col":37,"endLoc":1836,"id":3834,"nodeType":"Lambda","startLoc":1836,"text":"lambda h, i, k: (i + 1.) / k"},{"col":42,"endLoc":1837,"id":3835,"nodeType":"Lambda","startLoc":1837,"text":"lambda h, i, k: 2**(-k + i - 1)"},{"col":35,"endLoc":1838,"id":3836,"nodeType":"Lambda","startLoc":1838,"text":"lambda h, i, k: (1 - 2**(-k + i - 2)) / h"},{"col":4,"comment":"null","endLoc":1975,"header":"def _lvplot(self, box_data, positions,\n color=[255. / 256., 185. / 256., 0.],\n widths=1, ax=None, box_kws=None,\n flier_kws=None,\n line_kws=None)","id":3837,"name":"_lvplot","nodeType":"Function","startLoc":1841,"text":"def _lvplot(self, box_data, positions,\n color=[255. / 256., 185. / 256., 0.],\n widths=1, ax=None, box_kws=None,\n flier_kws=None,\n line_kws=None):\n\n # -- Default keyword dicts - based on\n # distributions.plot_univariate_histogram\n box_kws = {} if box_kws is None else box_kws.copy()\n flier_kws = {} if flier_kws is None else flier_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n\n # Set the default kwargs for the boxes\n box_default_kws = dict(edgecolor=self.gray,\n linewidth=self.linewidth)\n for k, v in box_default_kws.items():\n box_kws.setdefault(k, v)\n\n # Set the default kwargs for the lines denoting medians\n line_default_kws = dict(\n color=\".15\", alpha=0.45, solid_capstyle=\"butt\", linewidth=self.linewidth\n )\n for k, v in line_default_kws.items():\n line_kws.setdefault(k, v)\n\n # Set the default kwargs for the outliers scatterplot\n flier_default_kws = dict(marker='d', color=self.gray)\n for k, v in flier_default_kws.items():\n flier_kws.setdefault(k, v)\n\n vert = self.orient == \"v\"\n x = positions[0]\n box_data = np.asarray(box_data)\n\n # If we only have one data point, plot a line\n if len(box_data) == 1:\n line_kws.update({\n 'color': box_kws['edgecolor'],\n 'linestyle': box_kws.get('linestyle', '-'),\n 'linewidth': max(box_kws[\"linewidth\"], line_kws[\"linewidth\"])\n })\n ys = [box_data[0], box_data[0]]\n xs = [x - widths / 2, x + widths / 2]\n if vert:\n xx, yy = xs, ys\n else:\n xx, yy = ys, xs\n ax.plot(xx, yy, **line_kws)\n else:\n # Get the number of data points and calculate \"depth\" of\n # letter-value plot\n box_ends, k = self._lv_box_ends(box_data)\n\n # Anonymous functions for calculating the width and height\n # of the letter value boxes\n width = self._width_functions(self.scale)\n\n # Function to find height of boxes\n def height(b):\n return b[1] - b[0]\n\n # Functions to construct the letter value boxes\n def vert_perc_box(x, b, i, k, w):\n rect = Patches.Rectangle((x - widths * w / 2, b[0]),\n widths * w,\n height(b), fill=True)\n return rect\n\n def horz_perc_box(x, b, i, k, w):\n rect = Patches.Rectangle((b[0], x - widths * w / 2),\n height(b), widths * w,\n fill=True)\n return rect\n\n # Scale the width of the boxes so the biggest starts at 1\n w_area = np.array([width(height(b), i, k)\n for i, b in enumerate(box_ends)])\n w_area = w_area / np.max(w_area)\n\n # Calculate the medians\n y = np.median(box_data)\n\n # Calculate the outliers and plot (only if showfliers == True)\n outliers = []\n if self.showfliers:\n outliers = self._lv_outliers(box_data, k)\n hex_color = mpl.colors.rgb2hex(color)\n\n if vert:\n box_func = vert_perc_box\n xs_median = [x - widths / 2, x + widths / 2]\n ys_median = [y, y]\n xs_outliers = np.full(len(outliers), x)\n ys_outliers = outliers\n\n else:\n box_func = horz_perc_box\n xs_median = [y, y]\n ys_median = [x - widths / 2, x + widths / 2]\n xs_outliers = outliers\n ys_outliers = np.full(len(outliers), x)\n\n # Plot the medians\n ax.plot(\n xs_median,\n ys_median,\n **line_kws\n )\n\n # Plot outliers (if any)\n if len(outliers) > 0:\n ax.scatter(xs_outliers, ys_outliers,\n **flier_kws\n )\n\n # Construct a color map from the input color\n rgb = [hex_color, (1, 1, 1)]\n cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n # Make sure that the last boxes contain hue and are not pure white\n rgb = [hex_color, cmap(.85)]\n cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n\n # Update box_kws with `cmap` if not defined in dict until now\n box_kws.setdefault('cmap', cmap)\n\n boxes = [box_func(x, b[0], i, k, b[1])\n for i, b in enumerate(zip(box_ends, w_area))]\n\n collection = PatchCollection(boxes, **box_kws)\n\n # Set the color gradation, first box will have color=hex_color\n collection.set_array(np.array(np.linspace(1, 0, len(boxes))))\n\n # Plot the boxes\n ax.add_collection(collection)"},{"col":4,"comment":"null","endLoc":219,"header":"def test_log_tick_every(self, x)","id":3838,"name":"test_log_tick_every","nodeType":"Function","startLoc":216,"text":"def test_log_tick_every(self, x):\n\n with pytest.raises(RuntimeError, match=\"`every` not supported\"):\n Continuous(trans=\"log\").tick(every=2)"},{"col":4,"comment":"null","endLoc":230,"header":"def test_symlog_tick_default(self, x)","id":3839,"name":"test_symlog_tick_default","nodeType":"Function","startLoc":221,"text":"def test_symlog_tick_default(self, x):\n\n s = Continuous(trans=\"symlog\")._setup(x, Coordinate())\n a = PseudoAxis(s._matplotlib_scale)\n a.set_view_interval(-1050, 1050)\n ticks = a.major.locator()\n assert ticks[0] == -ticks[-1]\n pos_ticks = np.sort(np.unique(np.abs(ticks)))\n assert np.allclose(np.diff(np.log10(pos_ticks[1:])), 1)\n assert pos_ticks[0] == 0"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":175,"id":3840,"name":"kwargs","nodeType":"Attribute","startLoc":175,"text":"kwargs"},{"col":4,"comment":"null","endLoc":238,"header":"def test_label_formatter(self, x)","id":3841,"name":"test_label_formatter","nodeType":"Function","startLoc":232,"text":"def test_label_formatter(self, x):\n\n fmt = mpl.ticker.FormatStrFormatter(\"%.3f\")\n a, locs = self.setup_labels(x, fmt)\n labels = a.major.formatter.format_ticks(locs)\n for text in labels:\n assert re.match(r\"^\\d\\.\\d{3}$\", text)"},{"col":4,"comment":"null","endLoc":47,"header":"def test_int_bins(self, long_df)","id":3842,"name":"test_int_bins","nodeType":"Function","startLoc":41,"text":"def test_int_bins(self, long_df):\n\n n = 24\n h = Hist(bins=n)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (long_df[\"x\"].min(), long_df[\"x\"].max())\n assert bin_kws[\"bins\"] == n"},{"col":4,"comment":"null","endLoc":245,"header":"def test_label_like_pattern(self, x)","id":3843,"name":"test_label_like_pattern","nodeType":"Function","startLoc":240,"text":"def test_label_like_pattern(self, x):\n\n a, locs = self.setup_labels(x, like=\".4f\")\n labels = a.major.formatter.format_ticks(locs)\n for text in labels:\n assert re.match(r\"^\\d\\.\\d{4}$\", text)"},{"col":4,"comment":"null","endLoc":54,"header":"def test_array_bins(self, long_df)","id":3844,"name":"test_array_bins","nodeType":"Function","startLoc":49,"text":"def test_array_bins(self, long_df):\n\n bins = [-3, -2, 1, 2, 3]\n h = Hist(bins=bins)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert_array_equal(bin_kws[\"bins\"], bins)"},{"col":4,"comment":"null","endLoc":252,"header":"def test_label_like_string(self, x)","id":3845,"name":"test_label_like_string","nodeType":"Function","startLoc":247,"text":"def test_label_like_string(self, x):\n\n a, locs = self.setup_labels(x, like=\"x = {x:.1f}\")\n labels = a.major.formatter.format_ticks(locs)\n for text in labels:\n assert re.match(r\"^x = \\d\\.\\d$\", text)"},{"col":4,"comment":"null","endLoc":63,"header":"def test_binwidth(self, long_df)","id":3846,"name":"test_binwidth","nodeType":"Function","startLoc":56,"text":"def test_binwidth(self, long_df):\n\n binwidth = .5\n h = Hist(binwidth=binwidth)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n n_bins = bin_kws[\"bins\"]\n left, right = bin_kws[\"range\"]\n assert (right - left) / n_bins == pytest.approx(binwidth)"},{"col":4,"comment":"null","endLoc":259,"header":"def test_label_like_function(self, x)","id":3847,"name":"test_label_like_function","nodeType":"Function","startLoc":254,"text":"def test_label_like_function(self, x):\n\n a, locs = self.setup_labels(x, like=\"{:^5.1f}\".format)\n labels = a.major.formatter.format_ticks(locs)\n for text in labels:\n assert re.match(r\"^ \\d\\.\\d $\", text)"},{"col":4,"comment":"null","endLoc":266,"header":"def test_label_base(self, x)","id":3848,"name":"test_label_base","nodeType":"Function","startLoc":261,"text":"def test_label_base(self, x):\n\n a, locs = self.setup_labels(100 * x, base=2)\n labels = a.major.formatter.format_ticks(locs)\n for text in labels[1:]:\n assert not text or \"2^\" in text"},{"col":4,"comment":"null","endLoc":70,"header":"def test_binrange(self, long_df)","id":3849,"name":"test_binrange","nodeType":"Function","startLoc":65,"text":"def test_binrange(self, long_df):\n\n binrange = (-4, 4)\n h = Hist(binrange=binrange)\n bin_kws = h._define_bin_params(long_df, \"x\", \"continuous\")\n assert bin_kws[\"range\"] == binrange"},{"col":4,"comment":"null","endLoc":273,"header":"def test_label_unit(self, x)","id":3850,"name":"test_label_unit","nodeType":"Function","startLoc":268,"text":"def test_label_unit(self, x):\n\n a, locs = self.setup_labels(1000 * x, unit=\"g\")\n labels = a.major.formatter.format_ticks(locs)\n for text in labels[1:-1]:\n assert re.match(r\"^\\d+ mg$\", text)"},{"col":4,"comment":"null","endLoc":139,"header":"def test_color_scaled_as_strings(self)","id":3851,"name":"test_color_scaled_as_strings","nodeType":"Function","startLoc":131,"text":"def test_color_scaled_as_strings(self):\n\n colors = [\"C1\", \"dodgerblue\", \"#445566\"]\n m = self.mark()\n scales = {\"color\": lambda s: colors}\n\n actual = resolve_color(m, {\"color\": pd.Series([\"a\", \"b\", \"c\"])}, \"\", scales)\n expected = mpl.colors.to_rgba_array(colors)\n assert_array_equal(actual, expected)"},{"col":27,"endLoc":135,"id":3852,"nodeType":"Lambda","startLoc":135,"text":"lambda s: colors"},{"col":4,"comment":"null","endLoc":78,"header":"def test_discrete_bins(self, long_df)","id":3853,"name":"test_discrete_bins","nodeType":"Function","startLoc":72,"text":"def test_discrete_bins(self, long_df):\n\n h = Hist(discrete=True)\n x = long_df[\"x\"].astype(int)\n bin_kws = h._define_bin_params(long_df.assign(x=x), \"x\", \"continuous\")\n assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)"},{"col":4,"comment":"null","endLoc":158,"header":"def test_fillcolor(self)","id":3854,"name":"test_fillcolor","nodeType":"Function","startLoc":141,"text":"def test_fillcolor(self):\n\n c, a = \"green\", .8\n fa = .2\n m = self.mark(\n color=c, alpha=a,\n fillcolor=Mappable(depend=\"color\"), fillalpha=Mappable(fa),\n )\n\n assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a)\n assert resolve_color(m, {}, \"fill\") == mpl.colors.to_rgba(c, fa)\n\n df = pd.DataFrame(index=pd.RangeIndex(10))\n cs = [c] * len(df)\n assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a))\n assert_array_equal(\n resolve_color(m, df, \"fill\"), mpl.colors.to_rgba_array(cs, fa)\n )"},{"col":4,"comment":"null","endLoc":280,"header":"def test_label_unit_with_sep(self, x)","id":3855,"name":"test_label_unit_with_sep","nodeType":"Function","startLoc":275,"text":"def test_label_unit_with_sep(self, x):\n\n a, locs = self.setup_labels(1000 * x, unit=(\"\", \"g\"))\n labels = a.major.formatter.format_ticks(locs)\n for text in labels[1:-1]:\n assert re.match(r\"^\\d+mg$\", text)"},{"col":4,"comment":"null","endLoc":287,"header":"def test_label_empty_unit(self, x)","id":3856,"name":"test_label_empty_unit","nodeType":"Function","startLoc":282,"text":"def test_label_empty_unit(self, x):\n\n a, locs = self.setup_labels(1000 * x, unit=\"\")\n labels = a.major.formatter.format_ticks(locs)\n for text in labels[1:-1]:\n assert re.match(r\"^\\d+m$\", text)"},{"col":4,"comment":"null","endLoc":295,"header":"def test_label_base_from_transform(self, x)","id":3857,"name":"test_label_base_from_transform","nodeType":"Function","startLoc":289,"text":"def test_label_base_from_transform(self, x):\n\n s = Continuous(trans=\"log\")\n a = PseudoAxis(s._setup(x, Coordinate())._matplotlib_scale)\n a.set_view_interval(10, 1000)\n label, = a.major.formatter.format_ticks([100])\n assert r\"10^{2}\" in label"},{"col":4,"comment":"null","endLoc":87,"header":"def test_discrete_bins_from_nominal_scale(self, rng)","id":3858,"name":"test_discrete_bins_from_nominal_scale","nodeType":"Function","startLoc":80,"text":"def test_discrete_bins_from_nominal_scale(self, rng):\n\n h = Hist()\n x = rng.randint(0, 5, 10)\n df = pd.DataFrame({\"x\": x})\n bin_kws = h._define_bin_params(df, \"x\", \"nominal\")\n assert bin_kws[\"range\"] == (x.min() - .5, x.max() + .5)\n assert bin_kws[\"bins\"] == (x.max() - x.min() + 1)"},{"attributeType":"null","col":16,"comment":"null","endLoc":3,"id":3859,"name":"np","nodeType":"Attribute","startLoc":3,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":4,"id":3860,"name":"pd","nodeType":"Attribute","startLoc":4,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":3861,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"col":4,"comment":"null","endLoc":93,"header":"def test_count_stat(self, long_df, single_args)","id":3862,"name":"test_count_stat","nodeType":"Function","startLoc":89,"text":"def test_count_stat(self, long_df, single_args):\n\n h = Hist(stat=\"count\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == len(long_df)"},{"col":4,"comment":"null","endLoc":304,"header":"def test_label_type_checks(self)","id":3863,"name":"test_label_type_checks","nodeType":"Function","startLoc":297,"text":"def test_label_type_checks(self):\n\n s = Continuous()\n with pytest.raises(TypeError, match=\"Label formatter must be\"):\n s.label(\"{x}\")\n\n with pytest.raises(TypeError, match=\"`like` must be\"):\n s.label(like=2)"},{"className":"TestNominal","col":0,"comment":"null","endLoc":547,"id":3864,"nodeType":"Class","startLoc":307,"text":"class TestNominal:\n\n @pytest.fixture\n def x(self):\n return pd.Series([\"a\", \"c\", \"b\", \"c\"], name=\"x\")\n\n @pytest.fixture\n def y(self):\n return pd.Series([1, -1.5, 3, -1.5], name=\"y\")\n\n def test_coordinate_defaults(self, x):\n\n s = Nominal()._setup(x, Coordinate())\n assert_array_equal(s(x), np.array([0, 1, 2, 1], float))\n\n def test_coordinate_with_order(self, x):\n\n s = Nominal(order=[\"a\", \"b\", \"c\"])._setup(x, Coordinate())\n assert_array_equal(s(x), np.array([0, 2, 1, 2], float))\n\n def test_coordinate_with_subset_order(self, x):\n\n s = Nominal(order=[\"c\", \"a\"])._setup(x, Coordinate())\n assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))\n\n def test_coordinate_axis(self, x):\n\n ax = mpl.figure.Figure().subplots()\n s = Nominal()._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([0, 1, 2, 1], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [\"a\", \"c\", \"b\"]\n\n def test_coordinate_axis_with_order(self, x):\n\n order = [\"a\", \"b\", \"c\"]\n ax = mpl.figure.Figure().subplots()\n s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([0, 2, 1, 2], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == order\n\n def test_coordinate_axis_with_subset_order(self, x):\n\n order = [\"c\", \"a\"]\n ax = mpl.figure.Figure().subplots()\n s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [*order, \"\"]\n\n def test_coordinate_axis_with_category_dtype(self, x):\n\n order = [\"b\", \"a\", \"d\", \"c\"]\n x = x.astype(pd.CategoricalDtype(order))\n ax = mpl.figure.Figure().subplots()\n s = Nominal()._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([1, 3, 0, 3], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2, 3]) == order\n\n def test_coordinate_numeric_data(self, y):\n\n ax = mpl.figure.Figure().subplots()\n s = Nominal()._setup(y, Coordinate(), ax.yaxis)\n assert_array_equal(s(y), np.array([1, 0, 2, 0], float))\n f = ax.yaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [\"-1.5\", \"1.0\", \"3.0\"]\n\n def test_coordinate_numeric_data_with_order(self, y):\n\n order = [1, 4, -1.5]\n ax = mpl.figure.Figure().subplots()\n s = Nominal(order=order)._setup(y, Coordinate(), ax.yaxis)\n assert_array_equal(s(y), np.array([0, 2, np.nan, 2], float))\n f = ax.yaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [\"1.0\", \"4.0\", \"-1.5\"]\n\n def test_color_defaults(self, x):\n\n s = Nominal()._setup(x, Color())\n cs = color_palette()\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n def test_color_named_palette(self, x):\n\n pal = \"flare\"\n s = Nominal(pal)._setup(x, Color())\n cs = color_palette(pal, 3)\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n def test_color_list_palette(self, x):\n\n cs = color_palette(\"crest\", 3)\n s = Nominal(cs)._setup(x, Color())\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n def test_color_dict_palette(self, x):\n\n cs = color_palette(\"crest\", 3)\n pal = dict(zip(\"bac\", cs))\n s = Nominal(pal)._setup(x, Color())\n assert_array_equal(s(x), [cs[1], cs[2], cs[0], cs[2]])\n\n def test_color_numeric_data(self, y):\n\n s = Nominal()._setup(y, Color())\n cs = color_palette()\n assert_array_equal(s(y), [cs[1], cs[0], cs[2], cs[0]])\n\n def test_color_numeric_with_order_subset(self, y):\n\n s = Nominal(order=[-1.5, 1])._setup(y, Color())\n c1, c2 = color_palette(n_colors=2)\n null = (np.nan, np.nan, np.nan)\n assert_array_equal(s(y), [c2, c1, null, c1])\n\n @pytest.mark.xfail(reason=\"Need to sort out float/int order\")\n def test_color_numeric_int_float_mix(self):\n\n z = pd.Series([1, 2], name=\"z\")\n s = Nominal(order=[1.0, 2])._setup(z, Color())\n c1, c2 = color_palette(n_colors=2)\n null = (np.nan, np.nan, np.nan)\n assert_array_equal(s(z), [c1, null, c2])\n\n def test_color_alpha_in_palette(self, x):\n\n cs = [(.2, .2, .3, .5), (.1, .2, .3, 1), (.5, .6, .2, 0)]\n s = Nominal(cs)._setup(x, Color())\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])\n\n def test_color_unknown_palette(self, x):\n\n pal = \"not_a_palette\"\n err = f\"{pal} is not a valid palette name\"\n with pytest.raises(ValueError, match=err):\n Nominal(pal)._setup(x, Color())\n\n def test_object_defaults(self, x):\n\n class MockProperty(ObjectProperty):\n def _default_values(self, n):\n return list(\"xyz\"[:n])\n\n s = Nominal()._setup(x, MockProperty())\n assert s(x) == [\"x\", \"y\", \"z\", \"y\"]\n\n def test_object_list(self, x):\n\n vs = [\"x\", \"y\", \"z\"]\n s = Nominal(vs)._setup(x, ObjectProperty())\n assert s(x) == [\"x\", \"y\", \"z\", \"y\"]\n\n def test_object_dict(self, x):\n\n vs = {\"a\": \"x\", \"b\": \"y\", \"c\": \"z\"}\n s = Nominal(vs)._setup(x, ObjectProperty())\n assert s(x) == [\"x\", \"z\", \"y\", \"z\"]\n\n def test_object_order(self, x):\n\n vs = [\"x\", \"y\", \"z\"]\n s = Nominal(vs, order=[\"c\", \"a\", \"b\"])._setup(x, ObjectProperty())\n assert s(x) == [\"y\", \"x\", \"z\", \"x\"]\n\n def test_object_order_subset(self, x):\n\n vs = [\"x\", \"y\"]\n s = Nominal(vs, order=[\"a\", \"c\"])._setup(x, ObjectProperty())\n assert s(x) == [\"x\", \"y\", None, \"y\"]\n\n def test_objects_that_are_weird(self, x):\n\n vs = [(\"x\", 1), (None, None, 0), {}]\n s = Nominal(vs)._setup(x, ObjectProperty())\n assert s(x) == [vs[0], vs[1], vs[2], vs[1]]\n\n def test_alpha_default(self, x):\n\n s = Nominal()._setup(x, Alpha())\n assert_array_equal(s(x), [.95, .625, .3, .625])\n\n def test_fill(self):\n\n x = pd.Series([\"a\", \"a\", \"b\", \"a\"], name=\"x\")\n s = Nominal()._setup(x, Fill())\n assert_array_equal(s(x), [True, True, False, True])\n\n def test_fill_dict(self):\n\n x = pd.Series([\"a\", \"a\", \"b\", \"a\"], name=\"x\")\n vs = {\"a\": False, \"b\": True}\n s = Nominal(vs)._setup(x, Fill())\n assert_array_equal(s(x), [False, False, True, False])\n\n def test_fill_nunique_warning(self):\n\n x = pd.Series([\"a\", \"b\", \"c\", \"a\", \"b\"], name=\"x\")\n with pytest.warns(UserWarning, match=\"The variable assigned to fill\"):\n s = Nominal()._setup(x, Fill())\n assert_array_equal(s(x), [True, False, True, True, False])\n\n def test_interval_defaults(self, x):\n\n class MockProperty(IntervalProperty):\n _default_range = (1, 2)\n\n s = Nominal()._setup(x, MockProperty())\n assert_array_equal(s(x), [2, 1.5, 1, 1.5])\n\n def test_interval_tuple(self, x):\n\n s = Nominal((1, 2))._setup(x, IntervalProperty())\n assert_array_equal(s(x), [2, 1.5, 1, 1.5])\n\n def test_interval_tuple_numeric(self, y):\n\n s = Nominal((1, 2))._setup(y, IntervalProperty())\n assert_array_equal(s(y), [1.5, 2, 1, 2])\n\n def test_interval_list(self, x):\n\n vs = [2, 5, 4]\n s = Nominal(vs)._setup(x, IntervalProperty())\n assert_array_equal(s(x), [2, 5, 4, 5])\n\n def test_interval_dict(self, x):\n\n vs = {\"a\": 3, \"b\": 4, \"c\": 6}\n s = Nominal(vs)._setup(x, IntervalProperty())\n assert_array_equal(s(x), [3, 6, 4, 6])\n\n def test_interval_with_transform(self, x):\n\n class MockProperty(IntervalProperty):\n _forward = np.square\n _inverse = np.sqrt\n\n s = Nominal((2, 4))._setup(x, MockProperty())\n assert_array_equal(s(x), [4, np.sqrt(10), 2, np.sqrt(10)])"},{"col":4,"comment":"null","endLoc":311,"header":"@pytest.fixture\n def x(self)","id":3866,"name":"x","nodeType":"Function","startLoc":309,"text":"@pytest.fixture\n def x(self):\n return pd.Series([\"a\", \"c\", \"b\", \"c\"], name=\"x\")"},{"col":4,"comment":"null","endLoc":315,"header":"@pytest.fixture\n def y(self)","id":3867,"name":"y","nodeType":"Function","startLoc":313,"text":"@pytest.fixture\n def y(self):\n return pd.Series([1, -1.5, 3, -1.5], name=\"y\")"},{"col":4,"comment":"null","endLoc":320,"header":"def test_coordinate_defaults(self, x)","id":3868,"name":"test_coordinate_defaults","nodeType":"Function","startLoc":317,"text":"def test_coordinate_defaults(self, x):\n\n s = Nominal()._setup(x, Coordinate())\n assert_array_equal(s(x), np.array([0, 1, 2, 1], float))"},{"col":4,"comment":"null","endLoc":95,"header":"def test_nominal_default_palette_large(self)","id":3869,"name":"test_nominal_default_palette_large","nodeType":"Function","startLoc":88,"text":"def test_nominal_default_palette_large(self):\n\n vector = pd.Series(list(\"abcdefghijklmnopqrstuvwxyz\"))\n m = Color().get_mapping(Nominal(), vector)\n actual = m(np.arange(26))\n expected = color_palette(\"husl\", 26)\n for have, want in zip(actual, expected):\n assert same_color(have, want)"},{"col":4,"comment":"null","endLoc":105,"header":"def test_nominal_named_palette(self, cat_vector, cat_order)","id":3870,"name":"test_nominal_named_palette","nodeType":"Function","startLoc":97,"text":"def test_nominal_named_palette(self, cat_vector, cat_order):\n\n palette = \"Blues\"\n m = Color().get_mapping(Nominal(palette), cat_vector)\n n = len(cat_order)\n actual = m(np.arange(n))\n expected = color_palette(palette, n)\n for have, want in zip(actual, expected):\n assert same_color(have, want)"},{"col":4,"comment":"null","endLoc":114,"header":"def test_nominal_list_palette(self, cat_vector, cat_order)","id":3871,"name":"test_nominal_list_palette","nodeType":"Function","startLoc":107,"text":"def test_nominal_list_palette(self, cat_vector, cat_order):\n\n palette = color_palette(\"Reds\", len(cat_order))\n m = Color().get_mapping(Nominal(palette), cat_vector)\n actual = m(np.arange(len(palette)))\n expected = palette\n for have, want in zip(actual, expected):\n assert same_color(have, want)"},{"col":0,"comment":"Launch an interactive widget to create a dark sequential palette.\n\n This corresponds with the :func:`dark_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n input : {'husl', 'hls', 'rgb'}\n Color space for defining the seed value. Note that the default is\n different than the default input for :func:`dark_palette`.\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n ","endLoc":225,"header":"def choose_dark_palette(input=\"husl\", as_cmap=False)","id":3872,"name":"choose_dark_palette","nodeType":"Function","startLoc":143,"text":"def choose_dark_palette(input=\"husl\", as_cmap=False):\n \"\"\"Launch an interactive widget to create a dark sequential palette.\n\n This corresponds with the :func:`dark_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n input : {'husl', 'hls', 'rgb'}\n Color space for defining the seed value. Note that the default is\n different than the default input for :func:`dark_palette`.\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n dark_palette : Create a sequential palette with dark low values.\n light_palette : Create a sequential palette with bright low values.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n if input == \"rgb\":\n @interact\n def choose_dark_palette_rgb(r=(0., 1.),\n g=(0., 1.),\n b=(0., 1.),\n n=(3, 17)):\n color = r, g, b\n if as_cmap:\n colors = dark_palette(color, 256, input=\"rgb\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = dark_palette(color, n, input=\"rgb\")\n palplot(pal)\n\n elif input == \"hls\":\n @interact\n def choose_dark_palette_hls(h=(0., 1.),\n l=(0., 1.), # noqa: E741\n s=(0., 1.),\n n=(3, 17)):\n color = h, l, s\n if as_cmap:\n colors = dark_palette(color, 256, input=\"hls\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = dark_palette(color, n, input=\"hls\")\n palplot(pal)\n\n elif input == \"husl\":\n @interact\n def choose_dark_palette_husl(h=(0, 359),\n s=(0, 99),\n l=(0, 99), # noqa: E741\n n=(3, 17)):\n color = h, s, l\n if as_cmap:\n colors = dark_palette(color, 256, input=\"husl\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = dark_palette(color, n, input=\"husl\")\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal"},{"col":0,"comment":"Launch an interactive widget to create a light sequential palette.\n\n This corresponds with the :func:`light_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n input : {'husl', 'hls', 'rgb'}\n Color space for defining the seed value. Note that the default is\n different than the default input for :func:`light_palette`.\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n light_palette : Create a sequential palette with bright low values.\n dark_palette : Create a sequential palette with dark low values.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n ","endLoc":310,"header":"def choose_light_palette(input=\"husl\", as_cmap=False)","id":3873,"name":"choose_light_palette","nodeType":"Function","startLoc":228,"text":"def choose_light_palette(input=\"husl\", as_cmap=False):\n \"\"\"Launch an interactive widget to create a light sequential palette.\n\n This corresponds with the :func:`light_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n input : {'husl', 'hls', 'rgb'}\n Color space for defining the seed value. Note that the default is\n different than the default input for :func:`light_palette`.\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n light_palette : Create a sequential palette with bright low values.\n dark_palette : Create a sequential palette with dark low values.\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n if input == \"rgb\":\n @interact\n def choose_light_palette_rgb(r=(0., 1.),\n g=(0., 1.),\n b=(0., 1.),\n n=(3, 17)):\n color = r, g, b\n if as_cmap:\n colors = light_palette(color, 256, input=\"rgb\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = light_palette(color, n, input=\"rgb\")\n palplot(pal)\n\n elif input == \"hls\":\n @interact\n def choose_light_palette_hls(h=(0., 1.),\n l=(0., 1.), # noqa: E741\n s=(0., 1.),\n n=(3, 17)):\n color = h, l, s\n if as_cmap:\n colors = light_palette(color, 256, input=\"hls\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = light_palette(color, n, input=\"hls\")\n palplot(pal)\n\n elif input == \"husl\":\n @interact\n def choose_light_palette_husl(h=(0, 359),\n s=(0, 99),\n l=(0, 99), # noqa: E741\n n=(3, 17)):\n color = h, s, l\n if as_cmap:\n colors = light_palette(color, 256, input=\"husl\")\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = light_palette(color, n, input=\"husl\")\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal"},{"col":0,"comment":"Launch an interactive widget to choose a diverging color palette.\n\n This corresponds with the :func:`diverging_palette` function. This kind\n of palette is good for data that range between interesting low values\n and interesting high values with a meaningful midpoint. (For example,\n change scores relative to some baseline value).\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n diverging_palette : Create a diverging color palette or colormap.\n choose_colorbrewer_palette : Interactively choose palettes from the\n colorbrewer set, including diverging palettes.\n\n ","endLoc":369,"header":"def choose_diverging_palette(as_cmap=False)","id":3874,"name":"choose_diverging_palette","nodeType":"Function","startLoc":313,"text":"def choose_diverging_palette(as_cmap=False):\n \"\"\"Launch an interactive widget to choose a diverging color palette.\n\n This corresponds with the :func:`diverging_palette` function. This kind\n of palette is good for data that range between interesting low values\n and interesting high values with a meaningful midpoint. (For example,\n change scores relative to some baseline value).\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n diverging_palette : Create a diverging color palette or colormap.\n choose_colorbrewer_palette : Interactively choose palettes from the\n colorbrewer set, including diverging palettes.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n @interact\n def choose_diverging_palette(\n h_neg=IntSlider(min=0,\n max=359,\n value=220),\n h_pos=IntSlider(min=0,\n max=359,\n value=10),\n s=IntSlider(min=0, max=99, value=74),\n l=IntSlider(min=0, max=99, value=50), # noqa: E741\n sep=IntSlider(min=1, max=50, value=10),\n n=(2, 16),\n center=[\"light\", \"dark\"]\n ):\n if as_cmap:\n colors = diverging_palette(h_neg, h_pos, s, l, sep, 256, center)\n _update_lut(cmap, colors)\n _show_cmap(cmap)\n else:\n pal[:] = diverging_palette(h_neg, h_pos, s, l, sep, n, center)\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal"},{"col":0,"comment":"Launch an interactive widget to create a sequential cubehelix palette.\n\n This corresponds with the :func:`cubehelix_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values. The cubehelix system allows the\n palette to have more hue variance across the range, which can be helpful\n for distinguishing a wider range of values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n ","endLoc":426,"header":"def choose_cubehelix_palette(as_cmap=False)","id":3875,"name":"choose_cubehelix_palette","nodeType":"Function","startLoc":372,"text":"def choose_cubehelix_palette(as_cmap=False):\n \"\"\"Launch an interactive widget to create a sequential cubehelix palette.\n\n This corresponds with the :func:`cubehelix_palette` function. This kind\n of palette is good for data that range between relatively uninteresting\n low values and interesting high values. The cubehelix system allows the\n palette to have more hue variance across the range, which can be helpful\n for distinguishing a wider range of values.\n\n Requires IPython 2+ and must be used in the notebook.\n\n Parameters\n ----------\n as_cmap : bool\n If True, the return value is a matplotlib colormap rather than a\n list of discrete colors.\n\n Returns\n -------\n pal or cmap : list of colors or matplotlib colormap\n Object that can be passed to plotting functions.\n\n See Also\n --------\n cubehelix_palette : Create a sequential palette or colormap using the\n cubehelix system.\n\n \"\"\"\n pal = []\n if as_cmap:\n cmap = _init_mutable_colormap()\n\n @interact\n def choose_cubehelix(n_colors=IntSlider(min=2, max=16, value=9),\n start=FloatSlider(min=0, max=3, value=0),\n rot=FloatSlider(min=-1, max=1, value=.4),\n gamma=FloatSlider(min=0, max=5, value=1),\n hue=FloatSlider(min=0, max=1, value=.8),\n light=FloatSlider(min=0, max=1, value=.85),\n dark=FloatSlider(min=0, max=1, value=.15),\n reverse=False):\n\n if as_cmap:\n colors = cubehelix_palette(256, start, rot, gamma,\n hue, light, dark, reverse)\n _update_lut(cmap, np.c_[colors, np.ones(256)])\n _show_cmap(cmap)\n else:\n pal[:] = cubehelix_palette(n_colors, start, rot, gamma,\n hue, light, dark, reverse)\n palplot(pal)\n\n if as_cmap:\n return cmap\n return pal"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":3876,"name":"__all__","nodeType":"Attribute","startLoc":17,"text":"__all__"},{"col":0,"comment":"","endLoc":1,"header":"widgets.py#","id":3877,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n from ipywidgets import interact, FloatSlider, IntSlider\nexcept ImportError:\n def interact(f):\n msg = \"Interactive palettes require `ipywidgets`, which is not installed.\"\n raise ImportError(msg)\n\n__all__ = [\"choose_colorbrewer_palette\", \"choose_cubehelix_palette\",\n \"choose_dark_palette\", \"choose_light_palette\",\n \"choose_diverging_palette\"]"},{"attributeType":"null","col":8,"comment":"null","endLoc":183,"id":3878,"name":"color","nodeType":"Attribute","startLoc":183,"text":"color"},{"col":4,"comment":"null","endLoc":325,"header":"def test_coordinate_with_order(self, x)","id":3879,"name":"test_coordinate_with_order","nodeType":"Function","startLoc":322,"text":"def test_coordinate_with_order(self, x):\n\n s = Nominal(order=[\"a\", \"b\", \"c\"])._setup(x, Coordinate())\n assert_array_equal(s(x), np.array([0, 2, 1, 2], float))"},{"attributeType":"null","col":8,"comment":"null","endLoc":187,"id":3880,"name":"fig","nodeType":"Attribute","startLoc":187,"text":"fig"},{"id":3882,"name":"v0.10.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.10.0 (January 2020)\n----------------------\n\nThis is a major update that is being released simultaneously with version 0.9.1. It has all of the same features (and bugs!) as 0.9.1, but there are important changes to the dependencies.\n\nMost notably, all support for Python 2 has now been dropped. Support for Python 3.5 has also been dropped. Seaborn is now strictly compatible with Python 3.6+.\n\nMinimally supported versions of the dependent PyData libraries have also been increased, in some cases substantially. While seaborn has tended to be very conservative about maintaining compatibility with older dependencies, this was causing increasing pain during development. At the same time, these libraries are now much easier to install. Going forward, seaborn will likely stay close to the `Numpy community guidelines `_ for version support.\n\nThis release also removes a few previously-deprecated features:\n\n- The ``tsplot`` function and ``seaborn.timeseries`` module have been removed. Recall that ``tsplot`` was replaced with :func:`lineplot`.\n\n- The ``seaborn.apionly`` entry-point has been removed.\n\n- The ``seaborn.linearmodels`` module (previously renamed to ``seaborn.regression``) has been removed.\n"},{"id":3883,"name":"v0.11.0.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.11.0 (September 2020)\n------------------------\n\nThis is a major release with several important new features, enhancements to existing functions, and changes to the library. Highlights include an overhaul and modernization of the distributions plotting functions, more flexible data specification, new colormaps, and better narrative documentation.\n\nFor an overview of the new features and a guide to updating, see `this Medium post `_.\n\nRequired keyword arguments\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n|API|\n\nMost plotting functions now require all of their parameters to be specified using keyword arguments. To ease adaptation, code without keyword arguments will trigger a ``FutureWarning`` in v0.11. In a future release (v0.12 or v0.13, depending on release cadence), this will become an error. Once keyword arguments are fully enforced, the signature of the plotting functions will be reorganized to accept ``data`` as the first and only positional argument (:pr:`2052,2081`).\n\nModernization of distribution functions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe distribution module has been completely overhauled, modernizing the API and introducing several new functions and features within existing functions. Some new features are explained here; the :doc:`tutorial documentation ` has also been rewritten and serves as a good introduction to the functions.\n\nNew plotting functions\n^^^^^^^^^^^^^^^^^^^^^^\n\n|Feature| |Enhancement|\n\nFirst, three new functions, :func:`displot`, :func:`histplot` and :func:`ecdfplot` have been added (:pr:`2157`, :pr:`2125`, :pr:`2141`).\n\nThe figure-level :func:`displot` function is an interface to the various distribution plots (analogous to :func:`relplot` or :func:`catplot`). It can draw univariate or bivariate histograms, density curves, ECDFs, and rug plots on a :class:`FacetGrid`.\n\nThe axes-level :func:`histplot` function draws univariate or bivariate histograms with a number of features, including:\n\n- mapping multiple distributions with a ``hue`` semantic\n- normalization to show density, probability, or frequency statistics\n- flexible parameterization of bin size, including proper bins for discrete variables\n- adding a KDE fit to show a smoothed distribution over all bin statistics\n- experimental support for histograms over categorical and datetime variables.\n\nThe axes-level :func:`ecdfplot` function draws univariate empirical cumulative distribution functions, using a similar interface.\n\nChanges to existing functions\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n|API| |Feature| |Enhancement| |Defaults|\n\nSecond, the existing functions :func:`kdeplot` and :func:`rugplot` have been completely overhauled (:pr:`2060,2104`).\n\nThe overhauled functions now share a common API with the rest of seaborn, they can show conditional distributions by mapping a third variable with a ``hue`` semantic, and they have been improved in numerous other ways. The github pull request (:pr:`2104`) has a longer explanation of the changes and the motivation behind them.\n\nThis is a necessarily API-breaking change. The parameter names for the positional variables are now ``x`` and ``y``, and the old names have been deprecated. Efforts were made to handle and warn when using the deprecated API, but it is strongly suggested to check your plots carefully.\n\nAdditionally, the statsmodels-based computation of the KDE has been removed. Because there were some inconsistencies between the way different parameters (specifically, ``bw``, ``clip``, and ``cut``) were implemented by each backend, this may cause plots to look different with non-default parameters. Support for using non-Gaussian kernels, which was available only in the statsmodels backend, has been removed.\n\nOther new features include:\n\n- several options for representing multiple densities (using the ``multiple`` and ``common_norm`` parameters)\n- weighted density estimation (using the new ``weights`` parameter)\n- better control over the smoothing bandwidth (using the new ``bw_adjust`` parameter)\n- more meaningful parameterization of the contours that represent a bivariate density (using the ``thresh`` and ``levels`` parameters)\n- log-space density estimation (using the new ``log_scale`` parameter, or by scaling the data axis before plotting)\n- \"bivariate\" rug plots with a single function call (by assigning both ``x`` and ``y``)\n\nDeprecations\n^^^^^^^^^^^^\n\n|API|\n\nFinally, the :func:`distplot` function is now formally deprecated. Its features have been subsumed by :func:`displot` and :func:`histplot`. Some effort was made to gradually transition :func:`distplot` by adding the features in :func:`displot` and handling backwards compatibility, but this proved to be too difficult. The similarity in the names will likely cause some confusion during the transition, which is regrettable.\n\nRelated enhancements and changes\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n|API| |Feature| |Enhancement| |Defaults|\n\nThese additions facilitated new features (and forced changes) in :func:`jointplot` and :class:`JointGrid` (:pr:`2210`) and in :func:`pairplot` and :class:`PairGrid` (:pr:`2234`).\n\n- Added support for the ``hue`` semantic in :func:`jointplot`/:class:`JointGrid`. This support is lightweight and simply delegates the mapping to the underlying axes-level functions.\n\n- Delegated the handling of ``hue`` in :class:`PairGrid`/:func:`pairplot` to the plotting function when it understands ``hue``, meaning that (1) the zorder of scatterplot points will be determined by row in dataframe, (2) additional options for resolving hue (e.g. the ``multiple`` parameter) can be used, and (3) numeric hue variables can be naturally mapped when using :func:`scatterplot`.\n\n- Added ``kind=\"hist\"`` to :func:`jointplot`, which draws a bivariate histogram on the joint axes and univariate histograms on the marginal axes, as well as both ``kind=\"hist\"`` and ``kind=\"kde\"`` to :func:`pairplot`, which behaves likewise.\n\n- The various modes of :func:`jointplot` that plot marginal histograms now use :func:`histplot` rather than :func:`distplot`. This slightly changes the default appearance and affects the valid keyword arguments that can be passed to customize the plot. Likewise, the marginal histogram plots in :func:`pairplot` now use :func:`histplot`.\n\nStandardization and enhancements of data ingest\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n|Feature| |Enhancement| |Docs|\n\nThe code that processes input data has been refactored and enhanced. In v0.11, this new code takes effect for the relational and distribution modules; other modules will be refactored to use it in future releases (:pr:`2071`).\n\nThese changes should be transparent for most use-cases, although they allow a few new features:\n\n- Named variables for long-form data can refer to the named index of a :class:`pandas.DataFrame` or to levels in the case of a multi-index. Previously, it was necessary to call :meth:`pandas.DataFrame.reset_index` before using index variables (e.g., after a groupby operation).\n- :func:`relplot` now has the same flexibility as the axes-level functions to accept data in long- or wide-format and to accept data vectors (rather than named variables) in long-form mode.\n- The data parameter can now be a Python ``dict`` or an object that implements that interface. This is a new feature for wide-form data. For long-form data, it was previously supported but not documented.\n- A wide-form data object can have a mixture of types; the non-numeric types will be removed before plotting. Previously, this caused an error.\n- There are better error messages for other instances of data mis-specification.\n\nSee the new user guide chapter on :doc:`data formats ` for more information about what is supported.\n\nOther changes\n~~~~~~~~~~~~~\n\nDocumentation improvements\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- |Docs| Added two new chapters to the user guide, one giving an overview of the :doc:`types of functions in seaborn `, and one discussing the different :doc:`data formats ` that seaborn understands.\n\n- |Docs| Expanded the :doc:`color palette tutorial ` to give more background on color theory and better motivate the use of color in statistical graphics.\n\n- |Docs| Added more information to the :doc:`installation guidelines ` and streamlined the :doc:`introduction ` page.\n\n- |Docs| Improved cross-linking within the seaborn docs and between the seaborn and matplotlib docs.\n\nTheming\n^^^^^^^\n\n- |API| The :func:`set` function has been renamed to :func:`set_theme` for more clarity about what it does. For the foreseeable future, :func:`set` will remain as an alias, but it is recommended to update your code.\n\nRelational plots\n^^^^^^^^^^^^^^^^\n\n- |Enhancement| |Defaults| Reduced some of the surprising behavior of relational plot legends when using a numeric hue or size mapping (:pr:`2229`):\n\n - Added an \"auto\" mode (the new default) that chooses between \"brief\" and \"full\" legends based on the number of unique levels of each variable.\n - Modified the ticking algorithm for a \"brief\" legend to show up to 6 values and not to show values outside the limits of the data.\n - Changed the approach to the legend title: the normal matplotlib legend title is used when only one variable is assigned a semantic mapping, whereas the old approach of adding an invisible legend artist with a subtitle label is used only when multiple semantic variables are defined.\n - Modified legend subtitles to be left-aligned and to be drawn in the default legend title font size.\n\n- |Enhancement| |Defaults| Changed how functions that use different representations for numeric and categorical data handle vectors with an ``object`` data type. Previously, data was considered numeric if it could be coerced to a float representation without error. Now, object-typed vectors are considered numeric only when their contents are themselves numeric. As a consequence, numbers that are encoded as strings will now be treated as categorical data (:pr:`2084`).\n\n- |Enhancement| |Defaults| Plots with a ``style`` semantic can now generate an infinite number of unique dashes and/or markers by default. Previously, an error would be raised if the ``style`` variable had more levels than could be mapped using the default lists. The existing defaults were slightly modified as part of this change; if you need to exactly reproduce plots from earlier versions, refer to the `old defaults `_ (:pr:`2075`).\n\n- |Defaults| Changed how :func:`scatterplot` sets the default linewidth for the edges of the scatter points. New behavior is to scale with the point sizes themselves (on a plot-wise, not point-wise basis). This change also slightly reduces the default width when point sizes are not varied. Set ``linewidth=0.75`` to reproduce the previous behavior. (:pr:`2708`).\n\n- |Enhancement| Improved support for datetime variables in :func:`scatterplot` and :func:`lineplot` (:pr:`2138`).\n\n- |Fix| Fixed a bug where :func:`lineplot` did not pass the ``linestyle`` parameter down to matplotlib (:pr:`2095`).\n\n- |Fix| Adapted to a change in matplotlib that prevented passing vectors of literal values to ``c`` and ``s`` in :func:`scatterplot` (:pr:`2079`).\n\nCategorical plots\n^^^^^^^^^^^^^^^^^\n\n- |Enhancement| |Defaults| |Fix| Fixed a few computational issues in :func:`boxenplot` and improved its visual appearance (:pr:`2086`):\n\n - Changed the default method for computing the number of boxes to``k_depth=\"tukey\"``, as the previous default (``k_depth=\"proportion\"``) is based on a heuristic that produces too many boxes for small datasets.\n - Added the option to specify the specific number of boxes (e.g. ``k_depth=6``) or to plot boxes that will cover most of the data points (``k_depth=\"full\"``).\n - Added a new parameter, ``trust_alpha``, to control the number of boxes when ``k_depth=\"trustworthy\"``.\n - Changed the visual appearance of :func:`boxenplot` to more closely resemble :func:`boxplot`. Notably, thin boxes will remain visible when the edges are white.\n\n- |Enhancement| Allowed :func:`catplot` to use different values on the categorical axis of each facet when axis sharing is turned off (e.g. by specifying ``sharex=False``) (:pr:`2196`).\n\n- |Enhancement| Improved the error messages produced when categorical plots process the orientation parameter.\n\n- |Enhancement| Added an explicit warning in :func:`swarmplot` when more than 5% of the points overlap in the \"gutters\" of the swarm (:pr:`2045`).\n\nMulti-plot grids\n^^^^^^^^^^^^^^^^\n\n- |Feature| |Enhancement| |Defaults| A few small changes to make life easier when using :class:`PairGrid` (:pr:`2234`):\n\n - Added public access to the legend object through the ``legend`` attribute (also affects :class:`FacetGrid`).\n - The ``color`` and ``label`` parameters are no longer passed to the plotting functions when ``hue`` is not used.\n - The data is no longer converted to a numpy object before plotting on the marginal axes.\n - It is possible to specify only one of ``x_vars`` or ``y_vars``, using all variables for the unspecified dimension.\n - The ``layout_pad`` parameter is stored and used every time you call the :meth:`PairGrid.tight_layout` method.\n\n- |Feature| Added a ``tight_layout`` method to :class:`FacetGrid` and :class:`PairGrid`, which runs the :func:`matplotlib.pyplot.tight_layout` algorithm without interference from the external legend (:pr:`2073`).\n\n- |Feature| Added the ``axes_dict`` attribute to :class:`FacetGrid` for named access to the component axes (:pr:`2046`).\n\n- |Enhancement| Made :meth:`FacetGrid.set_axis_labels` clear labels from \"interior\" axes (:pr:`2046`).\n\n- |Feature| Added the ``marginal_ticks`` parameter to :class:`JointGrid` which, if set to ``True``, will show ticks on the count/density axis of the marginal plots (:pr:`2210`).\n\n- |Enhancement| Improved :meth:`FacetGrid.set_titles` with ``margin_titles=True``, such that texts representing the original row titles are removed before adding new ones (:pr:`2083`).\n\n- |Defaults| Changed the default value for ``dropna`` to ``False`` in :class:`FacetGrid`, :class:`PairGrid`, :class:`JointGrid`, and corresponding functions. As all or nearly all seaborn and matplotlib plotting functions handle missing data well, this option is no longer useful, but it causes problems in some edge cases. It may be deprecated in the future. (:pr:`2204`).\n\n- |Fix| Fixed a bug in :class:`PairGrid` that appeared when setting ``corner=True`` and ``despine=False`` (:pr:`2203`).\n\nColor palettes\n~~~~~~~~~~~~~~\n\n- |Docs| Improved and modernized the :doc:`color palettes chapter ` of the seaborn tutorial.\n\n- |Feature| Added two new perceptually-uniform colormaps: \"flare\" and \"crest\". The new colormaps are similar to \"rocket\" and \"mako\", but their luminance range is reduced. This makes them well suited to numeric mappings of line or scatter plots, which need contrast with the axes background at the extremes (:pr:`2237`).\n\n- |Enhancement| |Defaults| Enhanced numeric colormap functionality in several ways (:pr:`2237`):\n\n - Added string-based access within the :func:`color_palette` interface to :func:`dark_palette`, :func:`light_palette`, and :func:`blend_palette`. This means that anywhere you specify a palette in seaborn, a name like ``\"dark:blue\"`` will use :func:`dark_palette` with the input ``\"blue\"``.\n - Added the ``as_cmap`` parameter to :func:`color_palette` and changed internal code that uses a continuous colormap to take this route.\n - Tweaked the :func:`light_palette` and :func:`dark_palette` functions to use an endpoint that is a very desaturated version of the input color, rather than a pure gray. This produces smoother ramps. To exactly reproduce previous plots, use :func:`blend_palette` with ``\".13\"`` for dark or ``\".95\"`` for light.\n - Changed :func:`diverging_palette` to have a default value of ``sep=1``, which gives better results.\n\n- |Enhancement| Added a rich HTML representation to the object returned by :func:`color_palette` (:pr:`2225`).\n\n- |Fix| Fixed the ``\"{palette}_d\"`` logic to modify reversed colormaps and to use the correct direction of the luminance ramp in both cases.\n\nDeprecations and removals\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- |Enhancement| Removed an optional (and undocumented) dependency on BeautifulSoup (:pr:`2190`) in :func:`get_dataset_names`.\n\n- |API| Deprecated the ``axlabel`` function; use ``ax.set(xlabel=, ylabel=)`` instead.\n\n- |API| Deprecated the ``iqr`` function; use :func:`scipy.stats.iqr` instead.\n\n- |API| Final removal of the previously-deprecated ``annotate`` method on :class:`JointGrid`, along with related parameters.\n\n- |API| Final removal of the ``lvplot`` function (the previously-deprecated name for :func:`boxenplot`).\n"},{"id":3884,"name":"set_theme.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"flush-block\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"remarkable-confirmation\",\n \"metadata\": {},\n \"source\": [\n \"By default, seaborn plots will be made with the current values of the matplotlib rcParams:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"viral-highway\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.barplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"hungarian-poster\",\n \"metadata\": {},\n \"source\": [\n \"Calling this function with no arguments will activate seaborn's \\\"default\\\" theme:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"front-february\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_theme()\\n\",\n \"sns.barplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"daily-mills\",\n \"metadata\": {},\n \"source\": [\n \"Note that this will take effect for *all* matplotlib plots, including those not made using seaborn:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"essential-replica\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"plt.bar([\\\"A\\\", \\\"B\\\", \\\"C\\\"], [1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"naughty-edgar\",\n \"metadata\": {},\n \"source\": [\n \"The seaborn theme is decomposed into several distinct sets of parameters that you can control independently:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"latin-conversion\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_theme(style=\\\"whitegrid\\\", palette=\\\"pastel\\\")\\n\",\n \"sns.barplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"durable-cycling\",\n \"metadata\": {},\n \"source\": [\n \"Pass `None` to preserve the current values for a given set of parameters:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"blessed-chuck\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.set_theme(style=\\\"white\\\", palette=None)\\n\",\n \"sns.barplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"present-writing\",\n \"metadata\": {},\n \"source\": [\n \"You can also override any seaborn parameters or define additional parameters that are part of the matplotlib rc system but not included in the seaborn themes:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"floppy-effectiveness\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"custom_params = {\\\"axes.spines.right\\\": False, \\\"axes.spines.top\\\": False}\\n\",\n \"sns.set_theme(style=\\\"ticks\\\", rc=custom_params)\\n\",\n \"sns.barplot(x=[\\\"A\\\", \\\"B\\\", \\\"C\\\"], y=[1, 3, 2])\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"large-transfer\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"spreadsheet_heatmap.py","filePath":"examples","id":3885,"nodeType":"File","text":"\"\"\"\nAnnotated heatmaps\n==================\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_theme()\n\n# Load the example flights dataset and convert to long-form\nflights_long = sns.load_dataset(\"flights\")\nflights = flights_long.pivot(\"month\", \"year\", \"passengers\")\n\n# Draw a heatmap with the numeric values in each cell\nf, ax = plt.subplots(figsize=(9, 6))\nsns.heatmap(flights, annot=True, fmt=\"d\", linewidths=.5, ax=ax)\n"},{"attributeType":"null","col":28,"comment":"null","endLoc":6,"id":3886,"name":"plt","nodeType":"Attribute","startLoc":6,"text":"plt"},{"col":4,"comment":"null","endLoc":125,"header":"def test_nominal_dict_palette(self, cat_vector, cat_order)","id":3888,"name":"test_nominal_dict_palette","nodeType":"Function","startLoc":116,"text":"def test_nominal_dict_palette(self, cat_vector, cat_order):\n\n colors = color_palette(\"Greens\")\n palette = dict(zip(cat_order, colors))\n m = Color().get_mapping(Nominal(palette), cat_vector)\n n = len(cat_order)\n actual = m(np.arange(n))\n expected = colors\n for have, want in zip(actual, expected):\n assert same_color(have, want)"},{"col":4,"comment":"null","endLoc":330,"header":"def test_coordinate_with_subset_order(self, x)","id":3889,"name":"test_coordinate_with_subset_order","nodeType":"Function","startLoc":327,"text":"def test_coordinate_with_subset_order(self, x):\n\n s = Nominal(order=[\"c\", \"a\"])._setup(x, Coordinate())\n assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))"},{"attributeType":"null","col":13,"comment":"null","endLoc":187,"id":3890,"name":"ax","nodeType":"Attribute","startLoc":187,"text":"ax"},{"attributeType":"null","col":8,"comment":"null","endLoc":193,"id":3891,"name":"fig","nodeType":"Attribute","startLoc":193,"text":"fig"},{"col":4,"comment":"null","endLoc":338,"header":"def test_coordinate_axis(self, x)","id":3892,"name":"test_coordinate_axis","nodeType":"Function","startLoc":332,"text":"def test_coordinate_axis(self, x):\n\n ax = mpl.figure.Figure().subplots()\n s = Nominal()._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([0, 1, 2, 1], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [\"a\", \"c\", \"b\"]"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3893,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":3894,"name":"flights_long","nodeType":"Attribute","startLoc":11,"text":"flights_long"},{"attributeType":"null","col":13,"comment":"null","endLoc":193,"id":3895,"name":"axs","nodeType":"Attribute","startLoc":193,"text":"axs"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":197,"id":3896,"name":"font","nodeType":"Attribute","startLoc":197,"text":"font"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":3897,"name":"flights","nodeType":"Attribute","startLoc":12,"text":"flights"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":3898,"name":"f","nodeType":"Attribute","startLoc":15,"text":"f"},{"attributeType":"null","col":3,"comment":"null","endLoc":15,"id":3899,"name":"ax","nodeType":"Attribute","startLoc":15,"text":"ax"},{"col":0,"comment":"","endLoc":5,"header":"spreadsheet_heatmap.py#","id":3900,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nAnnotated heatmaps\n==================\n\n\"\"\"\n\nsns.set_theme()\n\nflights_long = sns.load_dataset(\"flights\")\n\nflights = flights_long.pivot(\"month\", \"year\", \"passengers\")\n\nf, ax = plt.subplots(figsize=(9, 6))\n\nsns.heatmap(flights, annot=True, fmt=\"d\", linewidths=.5, ax=ax)"},{"id":3901,"name":"objects.Range.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"penguins = load_dataset(\\\"penguins\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"576cbc86-f869-47b5-a98f-6ee727287a8b\",\n \"metadata\": {},\n \"source\": [\n \"This mark will often be used in the context of a stat transform that adds an errorbar interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"f6217b85-7479-49fd-aeda-9f435aa0473a\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"body_mass_g\\\", y=\\\"species\\\", color=\\\"sex\\\")\\n\",\n \" .add(so.Dot(), so.Agg(), so.Dodge())\\n\",\n \" .add(so.Range(), so.Est(errorbar=\\\"sd\\\"), so.Dodge())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"e156ea24-d8b4-4d67-acb5-750034be4dde\",\n \"metadata\": {},\n \"source\": [\n \"One feature (or potential gotcha) is that the mark will pick up properties like `linestyle` and `linewidth`; exclude those properties from the relevant layer if this behavior is undesired:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4bb63ebb-7733-4313-844c-cb7613298da3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"sex\\\", y=\\\"body_mass_g\\\", linestyle=\\\"species\\\")\\n\",\n \" .facet(\\\"species\\\")\\n\",\n \" .add(so.Line(marker=\\\"o\\\"), so.Agg())\\n\",\n \" .add(so.Range(), so.Est(errorbar=\\\"sd\\\"))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"5387e049-b343-49ea-a943-7dd9c090f184\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to directly assign the minimum and maximum values for the range:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4e795770-4481-4e23-a49b-e828a1f5cbbd\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" penguins\\n\",\n \" .rename_axis(index=\\\"penguin\\\")\\n\",\n \" .pipe(so.Plot, x=\\\"penguin\\\", ymin=\\\"bill_depth_mm\\\", ymax=\\\"bill_length_mm\\\")\\n\",\n \" .add(so.Range(), color=\\\"island\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"2191bec6-a02e-48e0-b92c-69c38826049d\",\n \"metadata\": {},\n \"source\": [\n \"When `min`/`max` variables are neither computed as part of a transform or explicitly assigned, the range will cover the full extent of the data at each unique observation on the orient axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"63c6352e-4ef5-4cff-940e-35fa5804b2c7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(penguins, x=\\\"sex\\\", y=\\\"body_mass_g\\\")\\n\",\n \" .facet(\\\"species\\\")\\n\",\n \" .add(so.Dots(pointsize=6))\\n\",\n \" .add(so.Range(linewidth=2))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c215deb1-e510-4631-b999-737f5f41cae2\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":4,"comment":"null","endLoc":347,"header":"def test_coordinate_axis_with_order(self, x)","id":3902,"name":"test_coordinate_axis_with_order","nodeType":"Function","startLoc":340,"text":"def test_coordinate_axis_with_order(self, x):\n\n order = [\"a\", \"b\", \"c\"]\n ax = mpl.figure.Figure().subplots()\n s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([0, 2, 1, 2], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == order"},{"id":3903,"name":"kdeplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns; sns.set_theme()\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Plot a univariate distribution along the x axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.kdeplot(data=tips, x=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Flip the plot by assigning the data variable to the y axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=tips, y=\\\"total_bill\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Plot distributions for each column of a wide-form dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"iris = sns.load_dataset(\\\"iris\\\")\\n\",\n \"sns.kdeplot(data=iris)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Use less smoothing:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=tips, x=\\\"total_bill\\\", bw_adjust=.2)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Use more smoothing, but don't smooth past the extreme data points:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"ax= sns.kdeplot(data=tips, x=\\\"total_bill\\\", bw_adjust=5, cut=0)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Plot conditional distributions with hue mapping of a second variable:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=tips, x=\\\"total_bill\\\", hue=\\\"time\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"\\\"Stack\\\" the conditional distributions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=tips, x=\\\"total_bill\\\", hue=\\\"time\\\", multiple=\\\"stack\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Normalize the stacked distribution at each value in the grid:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=tips, x=\\\"total_bill\\\", hue=\\\"time\\\", multiple=\\\"fill\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Estimate the cumulative distribution function(s), normalizing each subset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", hue=\\\"time\\\",\\n\",\n \" cumulative=True, common_norm=False, common_grid=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Estimate distribution from aggregated data, using weights:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips_agg = (tips\\n\",\n \" .groupby(\\\"size\\\")\\n\",\n \" .agg(total_bill=(\\\"total_bill\\\", \\\"mean\\\"), n=(\\\"total_bill\\\", \\\"count\\\"))\\n\",\n \")\\n\",\n \"sns.kdeplot(data=tips_agg, x=\\\"total_bill\\\", weights=\\\"n\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Map the data variable with log scaling:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"diamonds = sns.load_dataset(\\\"diamonds\\\")\\n\",\n \"sns.kdeplot(data=diamonds, x=\\\"price\\\", log_scale=True)\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Use numeric hue mapping:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=tips, x=\\\"total_bill\\\", hue=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Modify the appearance of the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", hue=\\\"size\\\",\\n\",\n \" fill=True, common_norm=False, palette=\\\"crest\\\",\\n\",\n \" alpha=.5, linewidth=0,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Plot a bivariate distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"geyser = sns.load_dataset(\\\"geyser\\\")\\n\",\n \"sns.kdeplot(data=geyser, x=\\\"waiting\\\", y=\\\"duration\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Map a third variable with a hue semantic to show conditional distributions:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(data=geyser, x=\\\"waiting\\\", y=\\\"duration\\\", hue=\\\"kind\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Show filled contours:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(\\n\",\n \" data=geyser, x=\\\"waiting\\\", y=\\\"duration\\\", hue=\\\"kind\\\", fill=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Show fewer contour levels, covering less of the distribution:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(\\n\",\n \" data=geyser, x=\\\"waiting\\\", y=\\\"duration\\\", hue=\\\"kind\\\",\\n\",\n \" levels=5, thresh=.2,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Fill the axes extent with a smooth distribution, using a different colormap:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.kdeplot(\\n\",\n \" data=geyser, x=\\\"waiting\\\", y=\\\"duration\\\",\\n\",\n \" fill=True, thresh=0, levels=100, cmap=\\\"mako\\\",\\n\",\n \")\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":3904,"name":"v0.10.1.rst","nodeType":"TextFile","path":"doc/whatsnew","text":"\nv0.10.1 (April 2020)\n--------------------\n\nThis is minor release with bug fixes for issues identified since 0.10.0.\n\n- Fixed a bug that appeared within the bootstrapping algorithm on 32-bit systems.\n\n- Fixed a bug where :func:`regplot` would crash on singleton inputs. Now a crash is avoided and regression estimation/plotting is skipped.\n\n- Fixed a bug where :func:`heatmap` would ignore user-specified under/over/bad values when recentering a colormap.\n\n- Fixed a bug where :func:`heatmap` would use values from masked cells when computing default colormap limits.\n\n- Fixed a bug where :func:`despine` would cause an error when trying to trim spines on a matplotlib categorical axis.\n\n- Adapted to a change in matplotlib that caused problems with single swarm plots.\n\n- Added the ``showfliers`` parameter to :func:`boxenplot` to suppress plotting of outlier data points, matching the API of :func:`boxplot`.\n\n- Avoided seeing an error from statmodels when data with an IQR of 0 is passed to :func:`kdeplot`.\n\n- Added the ``legend.title_fontsize`` to the :func:`plotting_context` definition.\n\n- Deprecated several utility functions that are no longer used internally (``percentiles``, ``sig_stars``, ``pmf_hist``, and ``sort_df``).\n"},{"id":3905,"name":"relplot.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"These examples will illustrate only some of the functionality that :func:`relplot` is capable of. For more information, consult the examples for :func:`scatterplot` and :func:`lineplot`, which are used when ``kind=\\\"scatter\\\"`` or ``kind=\\\"line\\\"``, respectively.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn as sns\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"sns.set_theme(style=\\\"ticks\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To illustrate ``kind=\\\"scatter\\\"`` (the default style of plot), we will use the \\\"tips\\\" dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"tips.head()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning ``x`` and ``y`` and any semantic mapping variables will draw a single plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"day\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning a ``col`` variable creates a faceted figure with multiple subplots arranged across the columns of the grid:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"day\\\", col=\\\"time\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Different variables can be assigned to facet on both the columns and rows:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"day\\\", col=\\\"time\\\", row=\\\"sex\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When the variable assigned to ``col`` has many levels, it can be \\\"wrapped\\\" across multiple rows:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"time\\\", col=\\\"day\\\", col_wrap=2)\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Assigning multiple semantic variables can show multi-dimensional relationships, but be mindful to avoid making an overly-complicated plot.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", col=\\\"time\\\",\\n\",\n \" hue=\\\"time\\\", size=\\\"size\\\", style=\\\"sex\\\",\\n\",\n \" palette=[\\\"b\\\", \\\"r\\\"], sizes=(10, 100)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When there is a natural continuity to one of the variables, it makes more sense to show lines instead of points. To draw the figure using :func:`lineplot`, set ``kind=\\\"line\\\"``. We will illustrate this effect with the \\\"fmri dataset:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"fmri = sns.load_dataset(\\\"fmri\\\")\\n\",\n \"fmri.head()\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Using ``kind=\\\"line\\\"`` offers the same flexibility for semantic mappings as ``kind=\\\"scatter\\\"``, but :func:`lineplot` transforms the data more before plotting. Observations are sorted by their ``x`` value, and repeated observations are aggregated. By default, the resulting plot shows the mean and 95% CI for each unit\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", col=\\\"region\\\",\\n\",\n \" hue=\\\"event\\\", style=\\\"event\\\", kind=\\\"line\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The size and shape of the figure is parametrized by the ``height`` and ``aspect`` ratio of each individual facet:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri,\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\",\\n\",\n \" hue=\\\"event\\\", style=\\\"event\\\", col=\\\"region\\\",\\n\",\n \" height=4, aspect=.7, kind=\\\"line\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The object returned by :func:`relplot` is always a :class:`FacetGrid`, which has several methods that allow you to quickly tweak the title, labels, and other aspects of the plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"g = sns.relplot(\\n\",\n \" data=fmri,\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\",\\n\",\n \" hue=\\\"event\\\", style=\\\"event\\\", col=\\\"region\\\",\\n\",\n \" height=4, aspect=.7, kind=\\\"line\\\"\\n\",\n \")\\n\",\n \"(g.map(plt.axhline, y=0, color=\\\".7\\\", dashes=(2, 1), zorder=0)\\n\",\n \" .set_axis_labels(\\\"Timepoint\\\", \\\"Percent signal change\\\")\\n\",\n \" .set_titles(\\\"Region: {col_name} cortex\\\")\\n\",\n \" .tight_layout(w_pad=0))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It is also possible to use wide-form data with :func:`relplot`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"flights_wide = sns.load_dataset(\\\"flights\\\").pivot(\\\"year\\\", \\\"month\\\", \\\"passengers\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Faceting is not an option in this case, but the plot will still take advantage of the external legend offered by :class:`FacetGrid`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=flights_wide, kind=\\\"line\\\")\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"id":3906,"name":"scale.rst","nodeType":"TextFile","path":"doc/_templates/autosummary","text":"{{ fullname | escape | underline}}\n\n.. currentmodule:: {{ module }}\n\n.. autoclass:: {{ objname }}\n\n .. automethod:: tick\n\n .. automethod:: label\n"},{"fileName":"simple_violinplots.py","filePath":"examples","id":3907,"nodeType":"File","text":"\"\"\"\nViolinplots with observations\n=============================\n\n\"\"\"\nimport numpy as np\nimport seaborn as sns\n\nsns.set_theme()\n\n# Create a random dataset across several variables\nrs = np.random.default_rng(0)\nn, p = 40, 8\nd = rs.normal(0, 2, (n, p))\nd += np.log(np.arange(1, p + 1)) * -5 + 10\n\n# Show each distribution with both violins and points\nsns.violinplot(data=d, palette=\"light:g\", inner=\"points\", orient=\"h\")\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":6,"id":3908,"name":"np","nodeType":"Attribute","startLoc":6,"text":"np"},{"col":4,"comment":"null","endLoc":356,"header":"def test_coordinate_axis_with_subset_order(self, x)","id":3909,"name":"test_coordinate_axis_with_subset_order","nodeType":"Function","startLoc":349,"text":"def test_coordinate_axis_with_subset_order(self, x):\n\n order = [\"c\", \"a\"]\n ax = mpl.figure.Figure().subplots()\n s = Nominal(order=order)._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([1, 0, np.nan, 0], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [*order, \"\"]"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3910,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":3911,"name":"rs","nodeType":"Attribute","startLoc":12,"text":"rs"},{"col":4,"comment":"null","endLoc":366,"header":"def test_coordinate_axis_with_category_dtype(self, x)","id":3912,"name":"test_coordinate_axis_with_category_dtype","nodeType":"Function","startLoc":358,"text":"def test_coordinate_axis_with_category_dtype(self, x):\n\n order = [\"b\", \"a\", \"d\", \"c\"]\n x = x.astype(pd.CategoricalDtype(order))\n ax = mpl.figure.Figure().subplots()\n s = Nominal()._setup(x, Coordinate(), ax.xaxis)\n assert_array_equal(s(x), np.array([1, 3, 0, 3], float))\n f = ax.xaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2, 3]) == order"},{"attributeType":"int","col":0,"comment":"null","endLoc":13,"id":3913,"name":"n","nodeType":"Attribute","startLoc":13,"text":"n"},{"attributeType":"int","col":3,"comment":"null","endLoc":13,"id":3914,"name":"p","nodeType":"Attribute","startLoc":13,"text":"p"},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":3915,"name":"d","nodeType":"Attribute","startLoc":14,"text":"d"},{"col":0,"comment":"","endLoc":5,"header":"simple_violinplots.py#","id":3916,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nViolinplots with observations\n=============================\n\n\"\"\"\n\nsns.set_theme()\n\nrs = np.random.default_rng(0)\n\nn, p = 40, 8\n\nd = rs.normal(0, 2, (n, p))\n\nd += np.log(np.arange(1, p + 1)) * -5 + 10\n\nsns.violinplot(data=d, palette=\"light:g\", inner=\"points\", orient=\"h\")"},{"col":4,"comment":"null","endLoc":374,"header":"def test_coordinate_numeric_data(self, y)","id":3917,"name":"test_coordinate_numeric_data","nodeType":"Function","startLoc":368,"text":"def test_coordinate_numeric_data(self, y):\n\n ax = mpl.figure.Figure().subplots()\n s = Nominal()._setup(y, Coordinate(), ax.yaxis)\n assert_array_equal(s(y), np.array([1, 0, 2, 0], float))\n f = ax.yaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [\"-1.5\", \"1.0\", \"3.0\"]"},{"id":3918,"name":"objects.Path.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"healthexp = load_dataset(\\\"healthexp\\\").sort_values([\\\"Country\\\", \\\"Year\\\"])\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"8c2781ed-190d-4155-99ac-0170b94de030\",\n \"metadata\": {},\n \"source\": [\n \"Unlike :class:`Line`, this mark does not sort observations before plotting, making it suitable for plotting trajectories through a variable space:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"199c0b22-1cbd-4b5a-bebe-f59afa79b9c6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p = so.Plot(healthexp, \\\"Spending_USD\\\", \\\"Life_Expectancy\\\", color=\\\"Country\\\")\\n\",\n \"p.add(so.Path())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"fb87bd85-024b-42f5-b458-3550271d7124\",\n \"metadata\": {},\n \"source\": [\n \"It otherwise offers the same set of options, including a number of properties that can be set or mapped:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"280de309-1c0d-4cdc-8f4c-a4f15da461cf\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p.add(so.Path(marker=\\\"o\\\", pointsize=2, linewidth=.75, fillcolor=\\\"w\\\"))\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"4e795770-4481-4e23-a49b-e828a1f5cbbd\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"fileName":"test_docstrings.py","filePath":"tests","id":3920,"nodeType":"File","text":"from seaborn._docstrings import DocstringComponents\n\n\nEXAMPLE_DICT = dict(\n param_a=\"\"\"\na : str\n The first parameter.\n \"\"\",\n)\n\n\nclass ExampleClass:\n def example_method(self):\n \"\"\"An example method.\n\n Parameters\n ----------\n a : str\n A method parameter.\n\n \"\"\"\n\n\ndef example_func():\n \"\"\"An example function.\n\n Parameters\n ----------\n a : str\n A function parameter.\n\n \"\"\"\n\n\nclass TestDocstringComponents:\n\n def test_from_dict(self):\n\n obj = DocstringComponents(EXAMPLE_DICT)\n assert obj.param_a == \"a : str\\n The first parameter.\"\n\n def test_from_nested_components(self):\n\n obj_inner = DocstringComponents(EXAMPLE_DICT)\n obj_outer = DocstringComponents.from_nested_components(inner=obj_inner)\n assert obj_outer.inner.param_a == \"a : str\\n The first parameter.\"\n\n def test_from_function(self):\n\n obj = DocstringComponents.from_function_params(example_func)\n assert obj.a == \"a : str\\n A function parameter.\"\n\n def test_from_method(self):\n\n obj = DocstringComponents.from_function_params(\n ExampleClass.example_method\n )\n assert obj.a == \"a : str\\n A method parameter.\"\n"},{"className":"ExampleClass","col":0,"comment":"null","endLoc":21,"id":3921,"nodeType":"Class","startLoc":12,"text":"class ExampleClass:\n def example_method(self):\n \"\"\"An example method.\n\n Parameters\n ----------\n a : str\n A method parameter.\n\n \"\"\""},{"col":4,"comment":"An example method.\n\n Parameters\n ----------\n a : str\n A method parameter.\n\n ","endLoc":21,"header":"def example_method(self)","id":3922,"name":"example_method","nodeType":"Function","startLoc":13,"text":"def example_method(self):\n \"\"\"An example method.\n\n Parameters\n ----------\n a : str\n A method parameter.\n\n \"\"\""},{"className":"TestDocstringComponents","col":0,"comment":"null","endLoc":58,"id":3923,"nodeType":"Class","startLoc":35,"text":"class TestDocstringComponents:\n\n def test_from_dict(self):\n\n obj = DocstringComponents(EXAMPLE_DICT)\n assert obj.param_a == \"a : str\\n The first parameter.\"\n\n def test_from_nested_components(self):\n\n obj_inner = DocstringComponents(EXAMPLE_DICT)\n obj_outer = DocstringComponents.from_nested_components(inner=obj_inner)\n assert obj_outer.inner.param_a == \"a : str\\n The first parameter.\"\n\n def test_from_function(self):\n\n obj = DocstringComponents.from_function_params(example_func)\n assert obj.a == \"a : str\\n A function parameter.\"\n\n def test_from_method(self):\n\n obj = DocstringComponents.from_function_params(\n ExampleClass.example_method\n )\n assert obj.a == \"a : str\\n A method parameter.\""},{"col":4,"comment":"null","endLoc":40,"header":"def test_from_dict(self)","id":3924,"name":"test_from_dict","nodeType":"Function","startLoc":37,"text":"def test_from_dict(self):\n\n obj = DocstringComponents(EXAMPLE_DICT)\n assert obj.param_a == \"a : str\\n The first parameter.\""},{"col":4,"comment":"null","endLoc":46,"header":"def test_from_nested_components(self)","id":3925,"name":"test_from_nested_components","nodeType":"Function","startLoc":42,"text":"def test_from_nested_components(self):\n\n obj_inner = DocstringComponents(EXAMPLE_DICT)\n obj_outer = DocstringComponents.from_nested_components(inner=obj_inner)\n assert obj_outer.inner.param_a == \"a : str\\n The first parameter.\""},{"col":4,"comment":"null","endLoc":51,"header":"def test_from_function(self)","id":3926,"name":"test_from_function","nodeType":"Function","startLoc":48,"text":"def test_from_function(self):\n\n obj = DocstringComponents.from_function_params(example_func)\n assert obj.a == \"a : str\\n A function parameter.\""},{"col":4,"comment":"null","endLoc":58,"header":"def test_from_method(self)","id":3927,"name":"test_from_method","nodeType":"Function","startLoc":53,"text":"def test_from_method(self):\n\n obj = DocstringComponents.from_function_params(\n ExampleClass.example_method\n )\n assert obj.a == \"a : str\\n A method parameter.\""},{"col":4,"comment":"null","endLoc":99,"header":"def test_probability_stat(self, long_df, single_args)","id":3928,"name":"test_probability_stat","nodeType":"Function","startLoc":95,"text":"def test_probability_stat(self, long_df, single_args):\n\n h = Hist(stat=\"probability\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 1"},{"col":4,"comment":"null","endLoc":383,"header":"def test_coordinate_numeric_data_with_order(self, y)","id":3929,"name":"test_coordinate_numeric_data_with_order","nodeType":"Function","startLoc":376,"text":"def test_coordinate_numeric_data_with_order(self, y):\n\n order = [1, 4, -1.5]\n ax = mpl.figure.Figure().subplots()\n s = Nominal(order=order)._setup(y, Coordinate(), ax.yaxis)\n assert_array_equal(s(y), np.array([0, 2, np.nan, 2], float))\n f = ax.yaxis.get_major_formatter()\n assert f.format_ticks([0, 1, 2]) == [\"1.0\", \"4.0\", \"-1.5\"]"},{"col":0,"comment":"An example function.\n\n Parameters\n ----------\n a : str\n A function parameter.\n\n ","endLoc":32,"header":"def example_func()","id":3930,"name":"example_func","nodeType":"Function","startLoc":24,"text":"def example_func():\n \"\"\"An example function.\n\n Parameters\n ----------\n a : str\n A function parameter.\n\n \"\"\""},{"attributeType":"dict","col":0,"comment":"null","endLoc":4,"id":3931,"name":"EXAMPLE_DICT","nodeType":"Attribute","startLoc":4,"text":"EXAMPLE_DICT"},{"col":4,"comment":"null","endLoc":105,"header":"def test_proportion_stat(self, long_df, single_args)","id":3932,"name":"test_proportion_stat","nodeType":"Function","startLoc":101,"text":"def test_proportion_stat(self, long_df, single_args):\n\n h = Hist(stat=\"proportion\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 1"},{"col":4,"comment":"null","endLoc":389,"header":"def test_color_defaults(self, x)","id":3933,"name":"test_color_defaults","nodeType":"Function","startLoc":385,"text":"def test_color_defaults(self, x):\n\n s = Nominal()._setup(x, Color())\n cs = color_palette()\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])"},{"col":4,"comment":"null","endLoc":111,"header":"def test_percent_stat(self, long_df, single_args)","id":3934,"name":"test_percent_stat","nodeType":"Function","startLoc":107,"text":"def test_percent_stat(self, long_df, single_args):\n\n h = Hist(stat=\"percent\")\n out = h(long_df, *single_args)\n assert out[\"y\"].sum() == 100"},{"attributeType":"null","col":8,"comment":"null","endLoc":210,"id":3935,"name":"fig","nodeType":"Attribute","startLoc":210,"text":"fig"},{"fileName":"utils.py","filePath":"seaborn","id":3936,"nodeType":"File","text":"\"\"\"Utility functions, mostly for internal use.\"\"\"\nimport os\nimport re\nimport inspect\nimport warnings\nimport colorsys\nfrom contextlib import contextmanager\nfrom urllib.request import urlopen, urlretrieve\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nfrom matplotlib.colors import to_rgb\nimport matplotlib.pyplot as plt\nfrom matplotlib.cbook import normalize_kwargs\n\nfrom .external.version import Version\nfrom .external.appdirs import user_cache_dir\n\n__all__ = [\"desaturate\", \"saturate\", \"set_hls_values\", \"move_legend\",\n \"despine\", \"get_dataset_names\", \"get_data_home\", \"load_dataset\"]\n\n\ndef ci_to_errsize(cis, heights):\n \"\"\"Convert intervals to error arguments relative to plot heights.\n\n Parameters\n ----------\n cis : 2 x n sequence\n sequence of confidence interval limits\n heights : n sequence\n sequence of plot heights\n\n Returns\n -------\n errsize : 2 x n array\n sequence of error size relative to height values in correct\n format as argument for plt.bar\n\n \"\"\"\n cis = np.atleast_2d(cis).reshape(2, -1)\n heights = np.atleast_1d(heights)\n errsize = []\n for i, (low, high) in enumerate(np.transpose(cis)):\n h = heights[i]\n elow = h - low\n ehigh = high - h\n errsize.append([elow, ehigh])\n\n errsize = np.asarray(errsize).T\n return errsize\n\n\ndef _normal_quantile_func(q):\n \"\"\"\n Compute the quantile function of the standard normal distribution.\n\n This wrapper exists because we are dropping scipy as a mandatory dependency\n but statistics.NormalDist was added to the standard library in 3.8.\n\n \"\"\"\n try:\n from statistics import NormalDist\n qf = np.vectorize(NormalDist().inv_cdf)\n except ImportError:\n try:\n from scipy.stats import norm\n qf = norm.ppf\n except ImportError:\n msg = (\n \"Standard normal quantile functions require either Python>=3.8 or scipy\"\n )\n raise RuntimeError(msg)\n return qf(q)\n\n\ndef _draw_figure(fig):\n \"\"\"Force draw of a matplotlib figure, accounting for back-compat.\"\"\"\n # See https://github.com/matplotlib/matplotlib/issues/19197 for context\n fig.canvas.draw()\n if fig.stale:\n try:\n fig.draw(fig.canvas.get_renderer())\n except AttributeError:\n pass\n\n\ndef _default_color(method, hue, color, kws):\n \"\"\"If needed, get a default color by using the matplotlib property cycle.\"\"\"\n if hue is not None:\n # This warning is probably user-friendly, but it's currently triggered\n # in a FacetGrid context and I don't want to mess with that logic right now\n # if color is not None:\n # msg = \"`color` is ignored when `hue` is assigned.\"\n # warnings.warn(msg)\n return None\n\n if color is not None:\n return color\n\n elif method.__name__ == \"plot\":\n\n color = _normalize_kwargs(kws, mpl.lines.Line2D).get(\"color\")\n scout, = method([], [], scalex=False, scaley=False, color=color)\n color = scout.get_color()\n scout.remove()\n\n elif method.__name__ == \"scatter\":\n\n # Matplotlib will raise if the size of x/y don't match s/c,\n # and the latter might be in the kws dict\n scout_size = max(\n np.atleast_1d(kws.get(key, [])).shape[0]\n for key in [\"s\", \"c\", \"fc\", \"facecolor\", \"facecolors\"]\n )\n scout_x = scout_y = np.full(scout_size, np.nan)\n\n scout = method(scout_x, scout_y, **kws)\n facecolors = scout.get_facecolors()\n\n if not len(facecolors):\n # Handle bug in matplotlib <= 3.2 (I think)\n # This will limit the ability to use non color= kwargs to specify\n # a color in versions of matplotlib with the bug, but trying to\n # work out what the user wanted by re-implementing the broken logic\n # of inspecting the kwargs is probably too brittle.\n single_color = False\n else:\n single_color = np.unique(facecolors, axis=0).shape[0] == 1\n\n # Allow the user to specify an array of colors through various kwargs\n if \"c\" not in kws and single_color:\n color = to_rgb(facecolors[0])\n\n scout.remove()\n\n elif method.__name__ == \"bar\":\n\n # bar() needs masked, not empty data, to generate a patch\n scout, = method([np.nan], [np.nan], **kws)\n color = to_rgb(scout.get_facecolor())\n scout.remove()\n\n elif method.__name__ == \"fill_between\":\n\n # There is a bug on matplotlib < 3.3 where fill_between with\n # datetime units and empty data will set incorrect autoscale limits\n # To workaround it, we'll always return the first color in the cycle.\n # https://github.com/matplotlib/matplotlib/issues/17586\n ax = method.__self__\n datetime_axis = any([\n isinstance(ax.xaxis.converter, mpl.dates.DateConverter),\n isinstance(ax.yaxis.converter, mpl.dates.DateConverter),\n ])\n if Version(mpl.__version__) < Version(\"3.3\") and datetime_axis:\n return \"C0\"\n\n kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)\n\n scout = method([], [], **kws)\n facecolor = scout.get_facecolor()\n color = to_rgb(facecolor[0])\n scout.remove()\n\n return color\n\n\ndef desaturate(color, prop):\n \"\"\"Decrease the saturation channel of a color by some percent.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n prop : float\n saturation channel of color will be multiplied by this value\n\n Returns\n -------\n new_color : rgb tuple\n desaturated color code in RGB tuple representation\n\n \"\"\"\n # Check inputs\n if not 0 <= prop <= 1:\n raise ValueError(\"prop must be between 0 and 1\")\n\n # Get rgb tuple rep\n rgb = to_rgb(color)\n\n # Convert to hls\n h, l, s = colorsys.rgb_to_hls(*rgb)\n\n # Desaturate the saturation channel\n s *= prop\n\n # Convert back to rgb\n new_color = colorsys.hls_to_rgb(h, l, s)\n\n return new_color\n\n\ndef saturate(color):\n \"\"\"Return a fully saturated color with the same hue.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n\n Returns\n -------\n new_color : rgb tuple\n saturated color code in RGB tuple representation\n\n \"\"\"\n return set_hls_values(color, s=1)\n\n\ndef set_hls_values(color, h=None, l=None, s=None): # noqa\n \"\"\"Independently manipulate the h, l, or s channels of a color.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n h, l, s : floats between 0 and 1, or None\n new values for each channel in hls space\n\n Returns\n -------\n new_color : rgb tuple\n new color code in RGB tuple representation\n\n \"\"\"\n # Get an RGB tuple representation\n rgb = to_rgb(color)\n vals = list(colorsys.rgb_to_hls(*rgb))\n for i, val in enumerate([h, l, s]):\n if val is not None:\n vals[i] = val\n\n rgb = colorsys.hls_to_rgb(*vals)\n return rgb\n\n\ndef axlabel(xlabel, ylabel, **kwargs):\n \"\"\"Grab current axis and label it.\n\n DEPRECATED: will be removed in a future version.\n\n \"\"\"\n msg = \"This function is deprecated and will be removed in a future version\"\n warnings.warn(msg, FutureWarning)\n ax = plt.gca()\n ax.set_xlabel(xlabel, **kwargs)\n ax.set_ylabel(ylabel, **kwargs)\n\n\ndef remove_na(vector):\n \"\"\"Helper method for removing null values from data vectors.\n\n Parameters\n ----------\n vector : vector object\n Must implement boolean masking with [] subscript syntax.\n\n Returns\n -------\n clean_clean : same type as ``vector``\n Vector of data with null values removed. May be a copy or a view.\n\n \"\"\"\n return vector[pd.notnull(vector)]\n\n\ndef get_color_cycle():\n \"\"\"Return the list of colors in the current matplotlib color cycle\n\n Parameters\n ----------\n None\n\n Returns\n -------\n colors : list\n List of matplotlib colors in the current cycle, or dark gray if\n the current color cycle is empty.\n \"\"\"\n cycler = mpl.rcParams['axes.prop_cycle']\n return cycler.by_key()['color'] if 'color' in cycler.keys else [\".15\"]\n\n\ndef despine(fig=None, ax=None, top=True, right=True, left=False,\n bottom=False, offset=None, trim=False):\n \"\"\"Remove the top and right spines from plot(s).\n\n fig : matplotlib figure, optional\n Figure to despine all axes of, defaults to the current figure.\n ax : matplotlib axes, optional\n Specific axes object to despine. Ignored if fig is provided.\n top, right, left, bottom : boolean, optional\n If True, remove that spine.\n offset : int or dict, optional\n Absolute distance, in points, spines should be moved away\n from the axes (negative values move spines inward). A single value\n applies to all spines; a dict can be used to set offset values per\n side.\n trim : bool, optional\n If True, limit spines to the smallest and largest major tick\n on each non-despined axis.\n\n Returns\n -------\n None\n\n \"\"\"\n # Get references to the axes we want\n if fig is None and ax is None:\n axes = plt.gcf().axes\n elif fig is not None:\n axes = fig.axes\n elif ax is not None:\n axes = [ax]\n\n for ax_i in axes:\n for side in [\"top\", \"right\", \"left\", \"bottom\"]:\n # Toggle the spine objects\n is_visible = not locals()[side]\n ax_i.spines[side].set_visible(is_visible)\n if offset is not None and is_visible:\n try:\n val = offset.get(side, 0)\n except AttributeError:\n val = offset\n ax_i.spines[side].set_position(('outward', val))\n\n # Potentially move the ticks\n if left and not right:\n maj_on = any(\n t.tick1line.get_visible()\n for t in ax_i.yaxis.majorTicks\n )\n min_on = any(\n t.tick1line.get_visible()\n for t in ax_i.yaxis.minorTicks\n )\n ax_i.yaxis.set_ticks_position(\"right\")\n for t in ax_i.yaxis.majorTicks:\n t.tick2line.set_visible(maj_on)\n for t in ax_i.yaxis.minorTicks:\n t.tick2line.set_visible(min_on)\n\n if bottom and not top:\n maj_on = any(\n t.tick1line.get_visible()\n for t in ax_i.xaxis.majorTicks\n )\n min_on = any(\n t.tick1line.get_visible()\n for t in ax_i.xaxis.minorTicks\n )\n ax_i.xaxis.set_ticks_position(\"top\")\n for t in ax_i.xaxis.majorTicks:\n t.tick2line.set_visible(maj_on)\n for t in ax_i.xaxis.minorTicks:\n t.tick2line.set_visible(min_on)\n\n if trim:\n # clip off the parts of the spines that extend past major ticks\n xticks = np.asarray(ax_i.get_xticks())\n if xticks.size:\n firsttick = np.compress(xticks >= min(ax_i.get_xlim()),\n xticks)[0]\n lasttick = np.compress(xticks <= max(ax_i.get_xlim()),\n xticks)[-1]\n ax_i.spines['bottom'].set_bounds(firsttick, lasttick)\n ax_i.spines['top'].set_bounds(firsttick, lasttick)\n newticks = xticks.compress(xticks <= lasttick)\n newticks = newticks.compress(newticks >= firsttick)\n ax_i.set_xticks(newticks)\n\n yticks = np.asarray(ax_i.get_yticks())\n if yticks.size:\n firsttick = np.compress(yticks >= min(ax_i.get_ylim()),\n yticks)[0]\n lasttick = np.compress(yticks <= max(ax_i.get_ylim()),\n yticks)[-1]\n ax_i.spines['left'].set_bounds(firsttick, lasttick)\n ax_i.spines['right'].set_bounds(firsttick, lasttick)\n newticks = yticks.compress(yticks <= lasttick)\n newticks = newticks.compress(newticks >= firsttick)\n ax_i.set_yticks(newticks)\n\n\ndef move_legend(obj, loc, **kwargs):\n \"\"\"\n Recreate a plot's legend at a new location.\n\n The name is a slight misnomer. Matplotlib legends do not expose public\n control over their position parameters. So this function creates a new legend,\n copying over the data from the original object, which is then removed.\n\n Parameters\n ----------\n obj : the object with the plot\n This argument can be either a seaborn or matplotlib object:\n\n - :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`\n - :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`\n\n loc : str or int\n Location argument, as in :meth:`matplotlib.axes.Axes.legend`.\n\n kwargs\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.\n\n Examples\n --------\n\n .. include:: ../docstrings/move_legend.rst\n\n \"\"\"\n # This is a somewhat hackish solution that will hopefully be obviated by\n # upstream improvements to matplotlib legends that make them easier to\n # modify after creation.\n\n from seaborn.axisgrid import Grid # Avoid circular import\n\n # Locate the legend object and a method to recreate the legend\n if isinstance(obj, Grid):\n old_legend = obj.legend\n legend_func = obj.figure.legend\n elif isinstance(obj, mpl.axes.Axes):\n old_legend = obj.legend_\n legend_func = obj.legend\n elif isinstance(obj, mpl.figure.Figure):\n if obj.legends:\n old_legend = obj.legends[-1]\n else:\n old_legend = None\n legend_func = obj.legend\n else:\n err = \"`obj` must be a seaborn Grid or matplotlib Axes or Figure instance.\"\n raise TypeError(err)\n\n if old_legend is None:\n err = f\"{obj} has no legend attached.\"\n raise ValueError(err)\n\n # Extract the components of the legend we need to reuse\n handles = old_legend.legendHandles\n labels = [t.get_text() for t in old_legend.get_texts()]\n\n # Extract legend properties that can be passed to the recreation method\n # (Vexingly, these don't all round-trip)\n legend_kws = inspect.signature(mpl.legend.Legend).parameters\n props = {k: v for k, v in old_legend.properties().items() if k in legend_kws}\n\n # Delegate default bbox_to_anchor rules to matplotlib\n props.pop(\"bbox_to_anchor\")\n\n # Try to propagate the existing title and font properties; respect new ones too\n title = props.pop(\"title\")\n if \"title\" in kwargs:\n title.set_text(kwargs.pop(\"title\"))\n title_kwargs = {k: v for k, v in kwargs.items() if k.startswith(\"title_\")}\n for key, val in title_kwargs.items():\n title.set(**{key[6:]: val})\n kwargs.pop(key)\n\n # Try to respect the frame visibility\n kwargs.setdefault(\"frameon\", old_legend.legendPatch.get_visible())\n\n # Remove the old legend and create the new one\n props.update(kwargs)\n old_legend.remove()\n new_legend = legend_func(handles, labels, loc=loc, **props)\n new_legend.set_title(title.get_text(), title.get_fontproperties())\n\n # Let the Grid object continue to track the correct legend object\n if isinstance(obj, Grid):\n obj._legend = new_legend\n\n\ndef _kde_support(data, bw, gridsize, cut, clip):\n \"\"\"Establish support for a kernel density estimate.\"\"\"\n support_min = max(data.min() - bw * cut, clip[0])\n support_max = min(data.max() + bw * cut, clip[1])\n support = np.linspace(support_min, support_max, gridsize)\n\n return support\n\n\ndef ci(a, which=95, axis=None):\n \"\"\"Return a percentile range from an array of values.\"\"\"\n p = 50 - which / 2, 50 + which / 2\n return np.nanpercentile(a, p, axis)\n\n\ndef get_dataset_names():\n \"\"\"Report available example datasets, useful for reporting issues.\n\n Requires an internet connection.\n\n \"\"\"\n url = \"https://github.com/mwaskom/seaborn-data\"\n with urlopen(url) as resp:\n html = resp.read()\n\n pat = r\"/mwaskom/seaborn-data/blob/master/(\\w*).csv\"\n datasets = re.findall(pat, html.decode())\n return datasets\n\n\ndef get_data_home(data_home=None):\n \"\"\"Return a path to the cache directory for example datasets.\n\n This directory is used by :func:`load_dataset`.\n\n If the ``data_home`` argument is not provided, it will use a directory\n specified by the `SEABORN_DATA` environment variable (if it exists)\n or otherwise default to an OS-appropriate user cache location.\n\n \"\"\"\n if data_home is None:\n data_home = os.environ.get(\"SEABORN_DATA\", user_cache_dir(\"seaborn\"))\n data_home = os.path.expanduser(data_home)\n if not os.path.exists(data_home):\n os.makedirs(data_home)\n return data_home\n\n\ndef load_dataset(name, cache=True, data_home=None, **kws):\n \"\"\"Load an example dataset from the online repository (requires internet).\n\n This function provides quick access to a small number of example datasets\n that are useful for documenting seaborn or generating reproducible examples\n for bug reports. It is not necessary for normal usage.\n\n Note that some of the datasets have a small amount of preprocessing applied\n to define a proper ordering for categorical variables.\n\n Use :func:`get_dataset_names` to see a list of available datasets.\n\n Parameters\n ----------\n name : str\n Name of the dataset (``{name}.csv`` on\n https://github.com/mwaskom/seaborn-data).\n cache : boolean, optional\n If True, try to load from the local cache first, and save to the cache\n if a download is required.\n data_home : string, optional\n The directory in which to cache data; see :func:`get_data_home`.\n kws : keys and values, optional\n Additional keyword arguments are passed to passed through to\n :func:`pandas.read_csv`.\n\n Returns\n -------\n df : :class:`pandas.DataFrame`\n Tabular data, possibly with some preprocessing applied.\n\n \"\"\"\n # A common beginner mistake is to assume that one's personal data needs\n # to be passed through this function to be usable with seaborn.\n # Let's provide a more helpful error than you would otherwise get.\n if isinstance(name, pd.DataFrame):\n err = (\n \"This function accepts only strings (the name of an example dataset). \"\n \"You passed a pandas DataFrame. If you have your own dataset, \"\n \"it is not necessary to use this function before plotting.\"\n )\n raise TypeError(err)\n\n url = f\"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/{name}.csv\"\n\n if cache:\n cache_path = os.path.join(get_data_home(data_home), os.path.basename(url))\n if not os.path.exists(cache_path):\n if name not in get_dataset_names():\n raise ValueError(f\"'{name}' is not one of the example datasets.\")\n urlretrieve(url, cache_path)\n full_path = cache_path\n else:\n full_path = url\n\n df = pd.read_csv(full_path, **kws)\n\n if df.iloc[-1].isnull().all():\n df = df.iloc[:-1]\n\n # Set some columns as a categorical type with ordered levels\n\n if name == \"tips\":\n df[\"day\"] = pd.Categorical(df[\"day\"], [\"Thur\", \"Fri\", \"Sat\", \"Sun\"])\n df[\"sex\"] = pd.Categorical(df[\"sex\"], [\"Male\", \"Female\"])\n df[\"time\"] = pd.Categorical(df[\"time\"], [\"Lunch\", \"Dinner\"])\n df[\"smoker\"] = pd.Categorical(df[\"smoker\"], [\"Yes\", \"No\"])\n\n elif name == \"flights\":\n months = df[\"month\"].str[:3]\n df[\"month\"] = pd.Categorical(months, months.unique())\n\n elif name == \"exercise\":\n df[\"time\"] = pd.Categorical(df[\"time\"], [\"1 min\", \"15 min\", \"30 min\"])\n df[\"kind\"] = pd.Categorical(df[\"kind\"], [\"rest\", \"walking\", \"running\"])\n df[\"diet\"] = pd.Categorical(df[\"diet\"], [\"no fat\", \"low fat\"])\n\n elif name == \"titanic\":\n df[\"class\"] = pd.Categorical(df[\"class\"], [\"First\", \"Second\", \"Third\"])\n df[\"deck\"] = pd.Categorical(df[\"deck\"], list(\"ABCDEFG\"))\n\n elif name == \"penguins\":\n df[\"sex\"] = df[\"sex\"].str.title()\n\n elif name == \"diamonds\":\n df[\"color\"] = pd.Categorical(\n df[\"color\"], [\"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"],\n )\n df[\"clarity\"] = pd.Categorical(\n df[\"clarity\"], [\"IF\", \"VVS1\", \"VVS2\", \"VS1\", \"VS2\", \"SI1\", \"SI2\", \"I1\"],\n )\n df[\"cut\"] = pd.Categorical(\n df[\"cut\"], [\"Ideal\", \"Premium\", \"Very Good\", \"Good\", \"Fair\"],\n )\n\n elif name == \"taxis\":\n df[\"pickup\"] = pd.to_datetime(df[\"pickup\"])\n df[\"dropoff\"] = pd.to_datetime(df[\"dropoff\"])\n\n elif name == \"seaice\":\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\n\n elif name == \"dowjones\":\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\n\n return df\n\n\ndef axis_ticklabels_overlap(labels):\n \"\"\"Return a boolean for whether the list of ticklabels have overlaps.\n\n Parameters\n ----------\n labels : list of matplotlib ticklabels\n\n Returns\n -------\n overlap : boolean\n True if any of the labels overlap.\n\n \"\"\"\n if not labels:\n return False\n try:\n bboxes = [l.get_window_extent() for l in labels]\n overlaps = [b.count_overlaps(bboxes) for b in bboxes]\n return max(overlaps) > 1\n except RuntimeError:\n # Issue on macos backend raises an error in the above code\n return False\n\n\ndef axes_ticklabels_overlap(ax):\n \"\"\"Return booleans for whether the x and y ticklabels on an Axes overlap.\n\n Parameters\n ----------\n ax : matplotlib Axes\n\n Returns\n -------\n x_overlap, y_overlap : booleans\n True when the labels on that axis overlap.\n\n \"\"\"\n return (axis_ticklabels_overlap(ax.get_xticklabels()),\n axis_ticklabels_overlap(ax.get_yticklabels()))\n\n\ndef locator_to_legend_entries(locator, limits, dtype):\n \"\"\"Return levels and formatted levels for brief numeric legends.\"\"\"\n raw_levels = locator.tick_values(*limits).astype(dtype)\n\n # The locator can return ticks outside the limits, clip them here\n raw_levels = [l for l in raw_levels if l >= limits[0] and l <= limits[1]]\n\n class dummy_axis:\n def get_view_interval(self):\n return limits\n\n if isinstance(locator, mpl.ticker.LogLocator):\n formatter = mpl.ticker.LogFormatter()\n else:\n formatter = mpl.ticker.ScalarFormatter()\n formatter.axis = dummy_axis()\n\n # TODO: The following two lines should be replaced\n # once pinned matplotlib>=3.1.0 with:\n # formatted_levels = formatter.format_ticks(raw_levels)\n formatter.set_locs(raw_levels)\n formatted_levels = [formatter(x) for x in raw_levels]\n\n return raw_levels, formatted_levels\n\n\ndef relative_luminance(color):\n \"\"\"Calculate the relative luminance of a color according to W3C standards\n\n Parameters\n ----------\n color : matplotlib color or sequence of matplotlib colors\n Hex code, rgb-tuple, or html color name.\n\n Returns\n -------\n luminance : float(s) between 0 and 1\n\n \"\"\"\n rgb = mpl.colors.colorConverter.to_rgba_array(color)[:, :3]\n rgb = np.where(rgb <= .03928, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)\n lum = rgb.dot([.2126, .7152, .0722])\n try:\n return lum.item()\n except ValueError:\n return lum\n\n\ndef to_utf8(obj):\n \"\"\"Return a string representing a Python object.\n\n Strings (i.e. type ``str``) are returned unchanged.\n\n Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.\n\n For other objects, the method ``__str__()`` is called, and the result is\n returned as a string.\n\n Parameters\n ----------\n obj : object\n Any Python object\n\n Returns\n -------\n s : str\n UTF-8-decoded string representation of ``obj``\n\n \"\"\"\n if isinstance(obj, str):\n return obj\n try:\n return obj.decode(encoding=\"utf-8\")\n except AttributeError: # obj is not bytes-like\n return str(obj)\n\n\ndef _normalize_kwargs(kws, artist):\n \"\"\"Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.\"\"\"\n _alias_map = {\n 'color': ['c'],\n 'linewidth': ['lw'],\n 'linestyle': ['ls'],\n 'facecolor': ['fc'],\n 'edgecolor': ['ec'],\n 'markerfacecolor': ['mfc'],\n 'markeredgecolor': ['mec'],\n 'markeredgewidth': ['mew'],\n 'markersize': ['ms']\n }\n try:\n kws = normalize_kwargs(kws, artist)\n except AttributeError:\n kws = normalize_kwargs(kws, _alias_map)\n return kws\n\n\ndef _check_argument(param, options, value):\n \"\"\"Raise if value for param is not in options.\"\"\"\n if value not in options:\n raise ValueError(\n f\"`{param}` must be one of {options}, but {repr(value)} was passed.\"\n )\n\n\ndef _assign_default_kwargs(kws, call_func, source_func):\n \"\"\"Assign default kwargs for call_func using values from source_func.\"\"\"\n # This exists so that axes-level functions and figure-level functions can\n # both call a Plotter method while having the default kwargs be defined in\n # the signature of the axes-level function.\n # An alternative would be to have a decorator on the method that sets its\n # defaults based on those defined in the axes-level function.\n # Then the figure-level function would not need to worry about defaults.\n # I am not sure which is better.\n needed = inspect.signature(call_func).parameters\n defaults = inspect.signature(source_func).parameters\n\n for param in needed:\n if param in defaults and param not in kws:\n kws[param] = defaults[param].default\n\n return kws\n\n\ndef adjust_legend_subtitles(legend):\n \"\"\"\n Make invisible-handle \"subtitles\" entries look more like titles.\n\n Note: This function is not part of the public API and may be changed or removed.\n\n \"\"\"\n # Legend title not in rcParams until 3.0\n font_size = plt.rcParams.get(\"legend.title_fontsize\", None)\n hpackers = legend.findobj(mpl.offsetbox.VPacker)[0].get_children()\n for hpack in hpackers:\n draw_area, text_area = hpack.get_children()\n handles = draw_area.get_children()\n if not all(artist.get_visible() for artist in handles):\n draw_area.set_width(0)\n for text in text_area.get_children():\n if font_size is not None:\n text.set_size(font_size)\n\n\ndef _deprecate_ci(errorbar, ci):\n \"\"\"\n Warn on usage of ci= and convert to appropriate errorbar= arg.\n\n ci was deprecated when errorbar was added in 0.12. It should not be removed\n completely for some time, but it can be moved out of function definitions\n (and extracted from kwargs) after one cycle.\n\n \"\"\"\n if ci != \"deprecated\":\n if ci is None:\n errorbar = None\n elif ci == \"sd\":\n errorbar = \"sd\"\n else:\n errorbar = (\"ci\", ci)\n msg = (\n \"\\n\\nThe `ci` parameter is deprecated. \"\n f\"Use `errorbar={repr(errorbar)}` for the same effect.\\n\"\n )\n warnings.warn(msg, FutureWarning, stacklevel=3)\n\n return errorbar\n\n\n@contextmanager\ndef _disable_autolayout():\n \"\"\"Context manager for preventing rc-controlled auto-layout behavior.\"\"\"\n # This is a workaround for an issue in matplotlib, for details see\n # https://github.com/mwaskom/seaborn/issues/2914\n # The only affect of this rcParam is to set the default value for\n # layout= in plt.figure, so we could just do that instead.\n # But then we would need to own the complexity of the transition\n # from tight_layout=True -> layout=\"tight\". This seems easier,\n # but can be removed when (if) that is simpler on the matplotlib side,\n # or if the layout algorithms are improved to handle figure legends.\n orig_val = mpl.rcParams[\"figure.autolayout\"]\n try:\n mpl.rcParams[\"figure.autolayout\"] = False\n yield\n finally:\n mpl.rcParams[\"figure.autolayout\"] = orig_val\n"},{"col":0,"comment":"Convert intervals to error arguments relative to plot heights.\n\n Parameters\n ----------\n cis : 2 x n sequence\n sequence of confidence interval limits\n heights : n sequence\n sequence of plot heights\n\n Returns\n -------\n errsize : 2 x n array\n sequence of error size relative to height values in correct\n format as argument for plt.bar\n\n ","endLoc":51,"header":"def ci_to_errsize(cis, heights)","id":3937,"name":"ci_to_errsize","nodeType":"Function","startLoc":24,"text":"def ci_to_errsize(cis, heights):\n \"\"\"Convert intervals to error arguments relative to plot heights.\n\n Parameters\n ----------\n cis : 2 x n sequence\n sequence of confidence interval limits\n heights : n sequence\n sequence of plot heights\n\n Returns\n -------\n errsize : 2 x n array\n sequence of error size relative to height values in correct\n format as argument for plt.bar\n\n \"\"\"\n cis = np.atleast_2d(cis).reshape(2, -1)\n heights = np.atleast_1d(heights)\n errsize = []\n for i, (low, high) in enumerate(np.transpose(cis)):\n h = heights[i]\n elow = h - low\n ehigh = high - h\n errsize.append([elow, ehigh])\n\n errsize = np.asarray(errsize).T\n return errsize"},{"attributeType":"null","col":13,"comment":"null","endLoc":210,"id":3938,"name":"axs","nodeType":"Attribute","startLoc":210,"text":"axs"},{"col":4,"comment":"null","endLoc":396,"header":"def test_color_named_palette(self, x)","id":3939,"name":"test_color_named_palette","nodeType":"Function","startLoc":391,"text":"def test_color_named_palette(self, x):\n\n pal = \"flare\"\n s = Nominal(pal)._setup(x, Color())\n cs = color_palette(pal, 3)\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":215,"id":3940,"name":"font","nodeType":"Attribute","startLoc":215,"text":"font"},{"col":4,"comment":"null","endLoc":402,"header":"def test_color_list_palette(self, x)","id":3941,"name":"test_color_list_palette","nodeType":"Function","startLoc":398,"text":"def test_color_list_palette(self, x):\n\n cs = color_palette(\"crest\", 3)\n s = Nominal(cs)._setup(x, Color())\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])"},{"col":4,"comment":"null","endLoc":117,"header":"def test_density_stat(self, long_df, single_args)","id":3942,"name":"test_density_stat","nodeType":"Function","startLoc":113,"text":"def test_density_stat(self, long_df, single_args):\n\n h = Hist(stat=\"density\")\n out = h(long_df, *single_args)\n assert (out[\"y\"] * out[\"space\"]).sum() == 1"},{"col":0,"comment":"Return a fully saturated color with the same hue.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n\n Returns\n -------\n new_color : rgb tuple\n saturated color code in RGB tuple representation\n\n ","endLoc":217,"header":"def saturate(color)","id":3943,"name":"saturate","nodeType":"Function","startLoc":203,"text":"def saturate(color):\n \"\"\"Return a fully saturated color with the same hue.\n\n Parameters\n ----------\n color : matplotlib color\n hex, rgb-tuple, or html color name\n\n Returns\n -------\n new_color : rgb tuple\n saturated color code in RGB tuple representation\n\n \"\"\"\n return set_hls_values(color, s=1)"},{"col":0,"comment":"Grab current axis and label it.\n\n DEPRECATED: will be removed in a future version.\n\n ","endLoc":257,"header":"def axlabel(xlabel, ylabel, **kwargs)","id":3944,"name":"axlabel","nodeType":"Function","startLoc":247,"text":"def axlabel(xlabel, ylabel, **kwargs):\n \"\"\"Grab current axis and label it.\n\n DEPRECATED: will be removed in a future version.\n\n \"\"\"\n msg = \"This function is deprecated and will be removed in a future version\"\n warnings.warn(msg, FutureWarning)\n ax = plt.gca()\n ax.set_xlabel(xlabel, **kwargs)\n ax.set_ylabel(ylabel, **kwargs)"},{"col":4,"comment":"null","endLoc":409,"header":"def test_color_dict_palette(self, x)","id":3945,"name":"test_color_dict_palette","nodeType":"Function","startLoc":404,"text":"def test_color_dict_palette(self, x):\n\n cs = color_palette(\"crest\", 3)\n pal = dict(zip(\"bac\", cs))\n s = Nominal(pal)._setup(x, Color())\n assert_array_equal(s(x), [cs[1], cs[2], cs[0], cs[2]])"},{"col":0,"comment":"Return booleans for whether the x and y ticklabels on an Axes overlap.\n\n Parameters\n ----------\n ax : matplotlib Axes\n\n Returns\n -------\n x_overlap, y_overlap : booleans\n True when the labels on that axis overlap.\n\n ","endLoc":680,"header":"def axes_ticklabels_overlap(ax)","id":3946,"name":"axes_ticklabels_overlap","nodeType":"Function","startLoc":666,"text":"def axes_ticklabels_overlap(ax):\n \"\"\"Return booleans for whether the x and y ticklabels on an Axes overlap.\n\n Parameters\n ----------\n ax : matplotlib Axes\n\n Returns\n -------\n x_overlap, y_overlap : booleans\n True when the labels on that axis overlap.\n\n \"\"\"\n return (axis_ticklabels_overlap(ax.get_xticklabels()),\n axis_ticklabels_overlap(ax.get_yticklabels()))"},{"col":4,"comment":"null","endLoc":123,"header":"def test_frequency_stat(self, long_df, single_args)","id":3947,"name":"test_frequency_stat","nodeType":"Function","startLoc":119,"text":"def test_frequency_stat(self, long_df, single_args):\n\n h = Hist(stat=\"frequency\")\n out = h(long_df, *single_args)\n assert (out[\"y\"] * out[\"space\"]).sum() == len(long_df)"},{"col":4,"comment":"null","endLoc":161,"header":"def test_despine_specific_axes(self)","id":3948,"name":"test_despine_specific_axes","nodeType":"Function","startLoc":150,"text":"def test_despine_specific_axes(self):\n f, (ax1, ax2) = plt.subplots(2, 1)\n\n utils.despine(ax=ax2)\n\n for side in self.sides:\n assert ax1.spines[side].get_visible()\n\n for side in self.outer_sides:\n assert ~ax2.spines[side].get_visible()\n for side in self.inner_sides:\n assert ax2.spines[side].get_visible()"},{"col":4,"comment":"null","endLoc":178,"header":"def test_despine_with_offset(self)","id":3949,"name":"test_despine_with_offset","nodeType":"Function","startLoc":163,"text":"def test_despine_with_offset(self):\n f, ax = plt.subplots()\n\n for side in self.sides:\n pos = ax.spines[side].get_position()\n assert pos == self.original_position\n\n utils.despine(ax=ax, offset=self.offset)\n\n for side in self.sides:\n is_visible = ax.spines[side].get_visible()\n new_position = ax.spines[side].get_position()\n if is_visible:\n assert new_position == self.offset_position\n else:\n assert new_position == self.original_position"},{"col":4,"comment":"null","endLoc":191,"header":"def test_despine_side_specific_offset(self)","id":3950,"name":"test_despine_side_specific_offset","nodeType":"Function","startLoc":180,"text":"def test_despine_side_specific_offset(self):\n\n f, ax = plt.subplots()\n utils.despine(ax=ax, offset=dict(left=self.offset))\n\n for side in self.sides:\n is_visible = ax.spines[side].get_visible()\n new_position = ax.spines[side].get_position()\n if is_visible and side == \"left\":\n assert new_position == self.offset_position\n else:\n assert new_position == self.original_position"},{"col":4,"comment":"null","endLoc":128,"header":"def test_invalid_stat(self)","id":3951,"name":"test_invalid_stat","nodeType":"Function","startLoc":125,"text":"def test_invalid_stat(self):\n\n with pytest.raises(ValueError, match=\"The `stat` parameter for `Hist`\"):\n Hist(stat=\"invalid\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":20,"id":3952,"name":"__all__","nodeType":"Attribute","startLoc":20,"text":"__all__"},{"col":0,"comment":"","endLoc":1,"header":"utils.py#","id":3953,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Utility functions, mostly for internal use.\"\"\"\n\n__all__ = [\"desaturate\", \"saturate\", \"set_hls_values\", \"move_legend\",\n \"despine\", \"get_dataset_names\", \"get_data_home\", \"load_dataset\"]"},{"col":0,"comment":"","endLoc":1,"header":"generate_logos.py#","id":3954,"name":"","nodeType":"Function","startLoc":1,"text":"XY_CACHE = {}\n\nSTATIC_DIR = \"_static\"\n\nplt.rcParams[\"savefig.dpi\"] = 300\n\nif __name__ == \"__main__\":\n\n for bg in [\"white\", \"light\", \"dark\"]:\n\n color_idx = -1 if bg == \"dark\" else 0\n\n kwargs = dict(\n color_kws=dict(start=.3, rot=-.4, light=.8, dark=.3, reverse=True),\n ring=True, ring_idx=color_idx, edge=1,\n pdf_means=[8, 24], pdf_sigma=16,\n dy=1, y0=1.8, w=.5, h=12,\n hist_mean=2, hist_sigma=10, hist_y0=.6, lw=1, skip=6,\n scatter=True, pad=1.8, scale=.5,\n )\n color = sns.cubehelix_palette(**kwargs[\"color_kws\"])[color_idx]\n\n # ------------------------------------------------------------------------ #\n\n fig, ax = plt.subplots(figsize=(2, 2), facecolor=\"w\", dpi=100)\n logo(ax, **kwargs)\n savefig(fig, \"mark\", bg)\n\n # ------------------------------------------------------------------------ #\n\n fig, axs = plt.subplots(1, 2, figsize=(8, 2), dpi=100,\n gridspec_kw=dict(width_ratios=[1, 3]))\n logo(axs[0], **kwargs)\n\n font = {\n \"family\": \"avenir\",\n \"color\": color,\n \"weight\": \"regular\",\n \"size\": 120,\n }\n axs[1].text(.01, .35, \"seaborn\", ha=\"left\", va=\"center\",\n fontdict=font, transform=axs[1].transAxes)\n axs[1].set_axis_off()\n savefig(fig, \"wide\", bg)\n\n # ------------------------------------------------------------------------ #\n\n fig, axs = plt.subplots(2, 1, figsize=(2, 2.5), dpi=100,\n gridspec_kw=dict(height_ratios=[4, 1]))\n\n logo(axs[0], **kwargs)\n\n font = {\n \"family\": \"avenir\",\n \"color\": color,\n \"weight\": \"regular\",\n \"size\": 34,\n }\n axs[1].text(.5, 1, \"seaborn\", ha=\"center\", va=\"top\",\n fontdict=font, transform=axs[1].transAxes)\n axs[1].set_axis_off()\n savefig(fig, \"tall\", bg)"},{"id":3955,"name":"relational.ipynb","nodeType":"TextFile","path":"doc/_tutorial","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _relational_tutorial:\\n\",\n \"\\n\",\n \".. currentmodule:: seaborn\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Visualizing statistical relationships\\n\",\n \"=====================================\\n\",\n \"\\n\",\n \"Statistical analysis is a process of understanding how variables in a dataset relate to each other and how those relationships depend on other variables. Visualization can be a core component of this process because, when data are visualized properly, the human visual system can see trends and patterns that indicate a relationship.\\n\",\n \"\\n\",\n \"We will discuss three seaborn functions in this tutorial. The one we will use most is :func:`relplot`. This is a :doc:`figure-level function ` for visualizing statistical relationships using two common approaches: scatter plots and line plots. :func:`relplot` combines a :class:`FacetGrid` with one of two axes-level functions:\\n\",\n \"\\n\",\n \"- :func:`scatterplot` (with ``kind=\\\"scatter\\\"``; the default)\\n\",\n \"- :func:`lineplot` (with ``kind=\\\"line\\\"``)\\n\",\n \"\\n\",\n \"As we will see, these functions can be quite illuminating because they use simple and easily-understood representations of data that can nevertheless represent complex dataset structures. They can do so because they plot two-dimensional graphics that can be enhanced by mapping up to three additional variables using the semantics of hue, size, and style.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"import numpy as np\\n\",\n \"import pandas as pd\\n\",\n \"import matplotlib.pyplot as plt\\n\",\n \"import seaborn as sns\\n\",\n \"sns.set_theme(style=\\\"darkgrid\\\")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"%matplotlib inline\\n\",\n \"np.random.seed(sum(map(ord, \\\"relational\\\")))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _scatterplot_tutorial:\\n\",\n \"\\n\",\n \"Relating variables with scatter plots\\n\",\n \"-------------------------------------\\n\",\n \"\\n\",\n \"The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two variables using a cloud of points, where each point represents an observation in the dataset. This depiction allows the eye to infer a substantial amount of information about whether there is any meaningful relationship between them.\\n\",\n \"\\n\",\n \"There are several ways to draw a scatter plot in seaborn. The most basic, which should be used when both variables are numeric, is the :func:`scatterplot` function. In the :ref:`categorical visualization tutorial `, we will see specialized tools for using scatterplots to visualize categorical data. The :func:`scatterplot` is the default ``kind`` in :func:`relplot` (it can also be forced by setting ``kind=\\\"scatter\\\"``):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"tips = sns.load_dataset(\\\"tips\\\")\\n\",\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable. In seaborn, this is referred to as using a \\\"hue semantic\\\", because the color of the point gains meaning:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To emphasize the difference between the classes, and to improve accessibility, you can use a different marker style for each class:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips,\\n\",\n \" x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\", style=\\\"smoker\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to represent four variables by changing the hue and style of each point independently. But this should be done carefully, because the eye is much less sensitive to shape than to color:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips,\\n\",\n \" x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\", style=\\\"time\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In the examples above, the hue semantic was categorical, so the default :ref:`qualitative palette ` was applied. If the hue semantic is numeric (specifically, if it can be cast to float), the default coloring switches to a sequential palette:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"size\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"In both cases, you can customize the color palette. There are many options for doing so. Here, we customize a sequential palette using the string interface to :func:`cubehelix_palette`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips, \\n\",\n \" x=\\\"total_bill\\\", y=\\\"tip\\\",\\n\",\n \" hue=\\\"size\\\", palette=\\\"ch:r=-.5,l=.75\\\"\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The third kind of semantic variable changes the size of each point:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\", size=\\\"size\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Unlike with :func:`matplotlib.pyplot.scatter`, the literal value of the variable is not used to pick the area of the point. Instead, the range of values in data units is normalized into a range in area units. This range can be customized:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips, x=\\\"total_bill\\\", y=\\\"tip\\\",\\n\",\n \" size=\\\"size\\\", sizes=(15, 200)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"More examples for customizing how the different semantics are used to show statistical relationships are shown in the :func:`scatterplot` API examples.\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \".. _lineplot_tutorial:\\n\",\n \"\\n\",\n \"Emphasizing continuity with line plots\\n\",\n \"--------------------------------------\\n\",\n \"\\n\",\n \"Scatter plots are highly effective, but there is no universally optimal type of visualisation. Instead, the visual representation should be adapted for the specifics of the dataset and to the question you are trying to answer with the plot.\\n\",\n \"\\n\",\n \"With some datasets, you may want to understand changes in one variable as a function of time, or a similarly continuous variable. In this situation, a good choice is to draw a line plot. In seaborn, this can be accomplished by the :func:`lineplot` function, either directly or with :func:`relplot` by setting ``kind=\\\"line\\\"``:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"dowjones = sns.load_dataset(\\\"dowjones\\\")\\n\",\n \"sns.relplot(data=dowjones, x=\\\"Date\\\", y=\\\"Price\\\", kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Aggregation and representing uncertainty\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"More complex datasets will have multiple measurements for the same value of the ``x`` variable. The default behavior in seaborn is to aggregate the multiple measurements at each ``x`` value by plotting the mean and the 95% confidence interval around the mean:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"fmri = sns.load_dataset(\\\"fmri\\\")\\n\",\n \"sns.relplot(data=fmri, x=\\\"timepoint\\\", y=\\\"signal\\\", kind=\\\"line\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The confidence intervals are computed using bootstrapping, which can be time-intensive for larger datasets. It's therefore possible to disable them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", errorbar=None,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Another good option, especially with larger data, is to represent the spread of the distribution at each timepoint by plotting the standard deviation instead of a confidence interval:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", errorbar=\\\"sd\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"To turn off aggregation altogether, set the ``estimator`` parameter to ``None`` This might produce a strange effect when the data have multiple observations at each point.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\",\\n\",\n \" estimator=None,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Plotting subsets of data with semantic mappings\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"The :func:`lineplot` function has the same flexibility as :func:`scatterplot`: it can show up to three additional variables by modifying the hue, size, and style of the plot elements. It does so using the same API as :func:`scatterplot`, meaning that we don't need to stop and think about the parameters that control the look of lines vs. points in matplotlib.\\n\",\n \"\\n\",\n \"Using semantics in :func:`lineplot` will also determine how the data get aggregated. For example, adding a hue semantic with two levels splits the plot into two lines and error bands, coloring each to indicate which subset of the data they correspond to.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Adding a style semantic to a line plot changes the pattern of dashes in the line by default:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\",\\n\",\n \" hue=\\\"region\\\", style=\\\"event\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"But you can identify subsets by the markers used at each observation, either together with the dashes or instead of them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"region\\\", style=\\\"event\\\",\\n\",\n \" dashes=False, markers=True,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"As with scatter plots, be cautious about making line plots using multiple semantics. While sometimes informative, they can also be difficult to parse and interpret. But even when you are only examining changes across one additional variable, it can be useful to alter both the color and style of the lines. This can make the plot more accessible when printed to black-and-white or viewed by someone with color blindness:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\", style=\\\"event\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When you are working with repeated measures data (that is, you have units that were sampled multiple times), you can also plot each sampling unit separately without distinguishing them through semantics. This avoids cluttering the legend:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri.query(\\\"event == 'stim'\\\"), kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"region\\\",\\n\",\n \" units=\\\"subject\\\", estimator=None,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The default colormap and handling of the legend in :func:`lineplot` also depends on whether the hue semantic is categorical or numeric:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"dots = sns.load_dataset(\\\"dots\\\").query(\\\"align == 'dots'\\\")\\n\",\n \"sns.relplot(\\n\",\n \" data=dots, kind=\\\"line\\\",\\n\",\n \" x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n \" hue=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It may happen that, even though the ``hue`` variable is numeric, it is poorly represented by a linear color scale. That's the case here, where the levels of the ``hue`` variable are logarithmically scaled. You can provide specific color values for each line by passing a list or dictionary:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"palette = sns.cubehelix_palette(light=.8, n_colors=6)\\n\",\n \"sns.relplot(\\n\",\n \" data=dots, kind=\\\"line\\\", \\n\",\n \" x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n \" hue=\\\"coherence\\\", style=\\\"choice\\\", palette=palette,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Or you can alter how the colormap is normalized:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"from matplotlib.colors import LogNorm\\n\",\n \"palette = sns.cubehelix_palette(light=.7, n_colors=6)\\n\",\n \"sns.relplot(\\n\",\n \" data=dots.query(\\\"coherence > 0\\\"), kind=\\\"line\\\",\\n\",\n \" x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n \" hue=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n \" hue_norm=LogNorm(),\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"The third semantic, size, changes the width of the lines:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=dots, kind=\\\"line\\\",\\n\",\n \" x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n \" size=\\\"coherence\\\", style=\\\"choice\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"While the ``size`` variable will typically be numeric, it's also possible to map a categorical variable with the width of the lines. Be cautious when doing so, because it will be difficult to distinguish much more than \\\"thick\\\" vs \\\"thin\\\" lines. However, dashes can be hard to perceive when lines have high-frequency variability, so using different widths may be more effective in that case:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=dots, kind=\\\"line\\\",\\n\",\n \" x=\\\"time\\\", y=\\\"firing_rate\\\",\\n\",\n \" hue=\\\"coherence\\\", size=\\\"choice\\\", palette=palette,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Controlling sorting and orientation\\n\",\n \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\",\n \"\\n\",\n \"Because :func:`lineplot` assumes that you are most often trying to draw ``y`` as a function of ``x``, the default behavior is to sort the data by the ``x`` values before plotting. However, this can be disabled:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"healthexp = sns.load_dataset(\\\"healthexp\\\").sort_values(\\\"Year\\\")\\n\",\n \"sns.relplot(\\n\",\n \" data=healthexp, kind=\\\"line\\\",\\n\",\n \" x=\\\"Spending_USD\\\", y=\\\"Life_Expectancy\\\", hue=\\\"Country\\\",\\n\",\n \" sort=False\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"It's also possible to sort (and aggregate) along the y axis:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"signal\\\", y=\\\"timepoint\\\", hue=\\\"event\\\",\\n\",\n \" orient=\\\"y\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"Showing multiple relationships with facets\\n\",\n \"------------------------------------------\\n\",\n \"\\n\",\n \"We've emphasized in this tutorial that, while these functions *can* show several semantic variables at once, it's not always effective to do so. But what about when you do want to understand how a relationship between two variables depends on more than one other variable?\\n\",\n \"\\n\",\n \"The best approach may be to make more than one plot. Because :func:`relplot` is based on the :class:`FacetGrid`, this is easy to do. To show the influence of an additional variable, instead of assigning it to one of the semantic roles in the plot, use it to \\\"facet\\\" the visualization. This means that you make multiple axes and plot subsets of the data on each of them:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=tips,\\n\",\n \" x=\\\"total_bill\\\", y=\\\"tip\\\", hue=\\\"smoker\\\", col=\\\"time\\\",\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"You can also show the influence of two variables this way: one by faceting on the columns and one by faceting on the rows. As you start adding more variables to the grid, you may want to decrease the figure size. Remember that the size :class:`FacetGrid` is parameterized by the height and aspect ratio of *each facet*:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"subject_number = fmri[\\\"subject\\\"].str[1:].astype(int)\\n\",\n \"fmri= fmri.iloc[subject_number.argsort()]\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri, kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"subject\\\",\\n\",\n \" col=\\\"region\\\", row=\\\"event\\\", height=3,\\n\",\n \" estimator=None\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"When you want to examine effects across many levels of a variable, it can be a good idea to facet that variable on the columns and then \\\"wrap\\\" the facets into the rows:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"sns.relplot(\\n\",\n \" data=fmri.query(\\\"region == 'frontal'\\\"), kind=\\\"line\\\",\\n\",\n \" x=\\\"timepoint\\\", y=\\\"signal\\\", hue=\\\"event\\\", style=\\\"event\\\",\\n\",\n \" col=\\\"subject\\\", col_wrap=5,\\n\",\n \" height=3, aspect=.75, linewidth=2.5,\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"metadata\": {},\n \"source\": [\n \"These visualizations, which are sometimes called \\\"lattice\\\" plots or \\\"small-multiples\\\", are very effective because they present the data in a format that makes it easy for the eye to detect both overall patterns and deviations from those patterns. While you should make use of the flexibility afforded by :func:`scatterplot` and :func:`relplot`, always try to keep in mind that several simple plots are usually more effective than one complex plot.\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"},{"fileName":"strip_regplot.py","filePath":"examples","id":3956,"nodeType":"File","text":"\"\"\"\nRegression fit over a strip plot\n================================\n\n_thumb: .53, .5\n\"\"\"\nimport seaborn as sns\nsns.set_theme()\n\nmpg = sns.load_dataset(\"mpg\")\nsns.catplot(\n data=mpg, x=\"cylinders\", y=\"acceleration\", hue=\"weight\",\n native_scale=True, zorder=1\n)\nsns.regplot(\n data=mpg, x=\"cylinders\", y=\"acceleration\",\n scatter=False, truncate=False, order=2, color=\".2\",\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3957,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"col":4,"comment":"null","endLoc":134,"header":"def test_cumulative_count(self, long_df, single_args)","id":3958,"name":"test_cumulative_count","nodeType":"Function","startLoc":130,"text":"def test_cumulative_count(self, long_df, single_args):\n\n h = Hist(stat=\"count\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == len(long_df)"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":3959,"name":"mpg","nodeType":"Attribute","startLoc":10,"text":"mpg"},{"id":3960,"name":"objects.Plot.scale.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"diamonds = load_dataset(\\\"diamonds\\\")\\n\",\n \"mpg = load_dataset(\\\"mpg\\\").query(\\\"cylinders in [4, 6, 8]\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"bd43bcc6-b060-49c2-a429-8ea0ab046e2c\",\n \"metadata\": {},\n \"source\": [\n \"Passing the name of a function, such as `\\\"log\\\"` or `\\\"symlog\\\"` will set the scale's transform:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"84b84cc1-ef1c-461e-b4af-4ce6e99886d1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p1 = so.Plot(diamonds, x=\\\"carat\\\", y=\\\"price\\\")\\n\",\n \"p1.add(so.Dots()).scale(y=\\\"log\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b5ea9f7f-c776-48af-a4be-0053c3c12036\",\n \"metadata\": {},\n \"source\": [\n \"String arguments can also specify the the name of a palette that defines the output values (or \\\"range\\\") of the scale:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e1f64d2f-6abd-48aa-9bab-c3e4614d0302\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p1.add(so.Dots(), color=\\\"clarity\\\").scale(color=\\\"crest\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"37df8672-33b1-49a8-b702-a87c8b95db99\",\n \"metadata\": {},\n \"source\": [\n \"The scale's range can alternatively be specified as a tuple of min/max values:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"371b8abd-ddfb-42f9-b730-f75b0e7b5fd6\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p1.add(so.Dots(), pointsize=\\\"carat\\\").scale(pointsize=(2, 10))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"f0c4ead3-e950-48e4-9c81-c8734a8458d0\",\n \"metadata\": {},\n \"source\": [\n \"The tuple format can also be used for a color scale:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"678fd8b2-b031-4ec6-a567-a6711f722cbd\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p1.add(so.Dots(), color=\\\"carat\\\").scale(color=(\\\".4\\\", \\\"#68d\\\"))\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"b6445ab7-2ec1-40be-95bc-9df0a5750bf5\",\n \"metadata\": {},\n \"source\": [\n \"For more control pass a scale object, such as :class:`Continuous`, which allows you to specify the input domain (`norm`), output range (`values`), and nonlinear transform (`trans`):\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d6a219ef-b50e-442e-82e9-8ae9e2cdb825\",\n \"metadata\": {\n \"tags\": []\n },\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" p1.add(so.Dots(), color=\\\"carat\\\")\\n\",\n \" .scale(color=so.Continuous((\\\".4\\\", \\\"#68d\\\"), norm=(1, 3), trans=\\\"sqrt\\\"))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"737e73a9-a0d5-4311-8c5c-4ca42f9194bf\",\n \"metadata\": {\n \"tags\": []\n },\n \"source\": [\n \"The scale objects also offer an interface for configuring the location of the scale ticks (including in the legend) and the formatting of the tick labels:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"cfaa426a-1a97-4b6f-91b6-ee378eabf194\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" p1.add(so.Dots(), color=\\\"price\\\")\\n\",\n \" .scale(\\n\",\n \" x=so.Continuous(trans=\\\"sqrt\\\").tick(every=.5),\\n\",\n \" y=so.Continuous().label(like=\\\"${x:g}\\\"),\\n\",\n \" color=so.Continuous(\\\"ch:.2\\\").tick(upto=4).label(unit=\\\"\\\"),\\n\",\n \" )\\n\",\n \" .label(y=\\\"\\\")\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"d4013795-fd5d-4a53-b145-e87f876a0684\",\n \"metadata\": {},\n \"source\": [\n \"If the scale includes a nonlinear transform, it will be applied *before* any statistical transforms:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"e9bf321f-c482-4d25-bb3b-7c499930b0d1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" p1.add(so.Dots(color=\\\".7\\\"))\\n\",\n \" .add(so.Line(), so.PolyFit(order=2))\\n\",\n \" .scale(y=\\\"log\\\")\\n\",\n \" .limit(y=(250, 25000))\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"00ac5844-efb1-4683-a8ff-e864d0c68dff\",\n \"metadata\": {},\n \"source\": [\n \"The scale is also relevant for when numerical data should be treated as categories. Consider the following histogram:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"04d5e6ae-30b2-495b-be1a-d99d6ffd4f44\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p2 = so.Plot(mpg, \\\"cylinders\\\").add(so.Bar(), so.Hist())\\n\",\n \"p2\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"9b3dafad-aae0-4862-b1b2-bb76b75a9cec\",\n \"metadata\": {},\n \"source\": [\n \"By default, the plot gives `cylinders` a continuous scale, since it is a vector of floats. But assigning a :class:`Nominal` scale causes the histogram to bin observations properly:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"0f89331a-69fc-4714-adfb-0568690c1b66\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p2.scale(x=so.Nominal())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"78880057-f4a7-40a1-a619-20d4b3be34dc\",\n \"metadata\": {},\n \"source\": [\n \"The default behavior for semantic mappings also depends on input data types and can be modified by the scale. Consider the sequential mapping applied to the colors in this plot:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"653abbc6-8227-48eb-9e1d-31587e6ef46d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p3 = (\\n\",\n \" so.Plot(mpg, \\\"weight\\\", \\\"acceleration\\\", color=\\\"cylinders\\\")\\n\",\n \" .add(so.Dot(), marker=\\\"origin\\\")\\n\",\n \")\\n\",\n \"p3\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"6ce5c9a8-5051-43b1-973c-fb9fb35ba399\",\n \"metadata\": {},\n \"source\": [\n \"Passing the name of a qualitative palette will select a :class:`Nominal` scale:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"218d6619-1fe3-4412-a2fc-efed4f542db7\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p3.scale(color=\\\"deep\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"d2362247-6e0e-48fb-bbe4-2149f96785ae\",\n \"metadata\": {},\n \"source\": [\n \"A :class:`Nominal` scale is also implied when the output values are given as a list or dictionary:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"8bdf57da-cb05-4347-87ec-fac2c3763f12\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p3.scale(\\n\",\n \" color=[\\\"#49b\\\", \\\"#a6a\\\", \\\"#5b8\\\"],\\n\",\n \" marker={\\\"japan\\\": \\\".\\\", \\\"europe\\\": \\\"+\\\", \\\"usa\\\": \\\"*\\\"},\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"a7d92be7-9e96-4850-a26a-090c5ae9857b\",\n \"metadata\": {},\n \"source\": [\n \"Pass a :class:`Nominal` object directly to control the order of the category mappings:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"a3c7eeb9-351f-484d-b0af-e18341569de3\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"p3.scale(\\n\",\n \" color=so.Nominal([\\\"#008fd5\\\", \\\"#fc4f30\\\", \\\"#e5ae38\\\"]),\\n\",\n \" marker=so.Nominal(order=[\\\"japan\\\", \\\"europe\\\", \\\"usa\\\"])\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d8885056-fd98-4964-a4a1-8c0344960409\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":0,"comment":"","endLoc":6,"header":"strip_regplot.py#","id":3961,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nRegression fit over a strip plot\n================================\n\n_thumb: .53, .5\n\"\"\"\n\nsns.set_theme()\n\nmpg = sns.load_dataset(\"mpg\")\n\nsns.catplot(\n data=mpg, x=\"cylinders\", y=\"acceleration\", hue=\"weight\",\n native_scale=True, zorder=1\n)\n\nsns.regplot(\n data=mpg, x=\"cylinders\", y=\"acceleration\",\n scatter=False, truncate=False, order=2, color=\".2\",\n)"},{"col":4,"comment":"null","endLoc":140,"header":"def test_cumulative_proportion(self, long_df, single_args)","id":3962,"name":"test_cumulative_proportion","nodeType":"Function","startLoc":136,"text":"def test_cumulative_proportion(self, long_df, single_args):\n\n h = Hist(stat=\"proportion\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == 1"},{"fileName":"multiple_ecdf.py","filePath":"examples","id":3963,"nodeType":"File","text":"\"\"\"\nFacetted ECDF plots\n===================\n\n_thumb: .30, .49\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"ticks\")\nmpg = sns.load_dataset(\"mpg\")\n\ncolors = (250, 70, 50), (350, 70, 50)\ncmap = sns.blend_palette(colors, input=\"husl\", as_cmap=True)\nsns.displot(\n mpg,\n x=\"displacement\", col=\"origin\", hue=\"model_year\",\n kind=\"ecdf\", aspect=.75, linewidth=2, palette=cmap,\n)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":3964,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":9,"id":3965,"name":"mpg","nodeType":"Attribute","startLoc":9,"text":"mpg"},{"col":4,"comment":"null","endLoc":146,"header":"def test_cumulative_density(self, long_df, single_args)","id":3966,"name":"test_cumulative_density","nodeType":"Function","startLoc":142,"text":"def test_cumulative_density(self, long_df, single_args):\n\n h = Hist(stat=\"density\", cumulative=True)\n out = h(long_df, *single_args)\n assert out[\"y\"].max() == 1"},{"attributeType":"((int, int, int), (int, int, int))","col":0,"comment":"null","endLoc":11,"id":3967,"name":"colors","nodeType":"Attribute","startLoc":11,"text":"colors"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":3968,"name":"cmap","nodeType":"Attribute","startLoc":12,"text":"cmap"},{"col":4,"comment":"null","endLoc":152,"header":"def test_common_norm_default(self, long_df, triple_args)","id":3969,"name":"test_common_norm_default","nodeType":"Function","startLoc":148,"text":"def test_common_norm_default(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\")\n out = h(long_df, *triple_args)\n assert out[\"y\"].sum() == pytest.approx(100)"},{"col":0,"comment":"","endLoc":6,"header":"multiple_ecdf.py#","id":3970,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nFacetted ECDF plots\n===================\n\n_thumb: .30, .49\n\"\"\"\n\nsns.set_theme(style=\"ticks\")\n\nmpg = sns.load_dataset(\"mpg\")\n\ncolors = (250, 70, 50), (350, 70, 50)\n\ncmap = sns.blend_palette(colors, input=\"husl\", as_cmap=True)\n\nsns.displot(\n mpg,\n x=\"displacement\", col=\"origin\", hue=\"model_year\",\n kind=\"ecdf\", aspect=.75, linewidth=2, palette=cmap,\n)"},{"col":4,"comment":"null","endLoc":159,"header":"def test_common_norm_false(self, long_df, triple_args)","id":3971,"name":"test_common_norm_false","nodeType":"Function","startLoc":154,"text":"def test_common_norm_false(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\", common_norm=False)\n out = h(long_df, *triple_args)\n for _, out_part in out.groupby([\"a\", \"s\"]):\n assert out_part[\"y\"].sum() == pytest.approx(100)"},{"col":4,"comment":"null","endLoc":166,"header":"def test_common_norm_subset(self, long_df, triple_args)","id":3972,"name":"test_common_norm_subset","nodeType":"Function","startLoc":161,"text":"def test_common_norm_subset(self, long_df, triple_args):\n\n h = Hist(stat=\"percent\", common_norm=[\"a\"])\n out = h(long_df, *triple_args)\n for _, out_part in out.groupby(\"a\"):\n assert out_part[\"y\"].sum() == pytest.approx(100)"},{"col":4,"comment":"null","endLoc":205,"header":"def test_despine_with_offset_specific_axes(self)","id":3973,"name":"test_despine_with_offset_specific_axes","nodeType":"Function","startLoc":193,"text":"def test_despine_with_offset_specific_axes(self):\n f, (ax1, ax2) = plt.subplots(2, 1)\n\n utils.despine(offset=self.offset, ax=ax2)\n\n for side in self.sides:\n pos1 = ax1.spines[side].get_position()\n pos2 = ax2.spines[side].get_position()\n assert pos1 == self.original_position\n if ax2.spines[side].get_visible():\n assert pos2 == self.offset_position\n else:\n assert pos2 == self.original_position"},{"col":4,"comment":"null","endLoc":216,"header":"def test_despine_trim_spines(self)","id":3974,"name":"test_despine_trim_spines","nodeType":"Function","startLoc":207,"text":"def test_despine_trim_spines(self):\n\n f, ax = plt.subplots()\n ax.plot([1, 2, 3], [1, 2, 3])\n ax.set_xlim(.75, 3.25)\n\n utils.despine(trim=True)\n for side in self.inner_sides:\n bounds = ax.spines[side].get_bounds()\n assert bounds == (1, 3)"},{"col":4,"comment":"null","endLoc":228,"header":"def test_despine_trim_inverted(self)","id":3975,"name":"test_despine_trim_inverted","nodeType":"Function","startLoc":218,"text":"def test_despine_trim_inverted(self):\n\n f, ax = plt.subplots()\n ax.plot([1, 2, 3], [1, 2, 3])\n ax.set_ylim(.85, 3.15)\n ax.invert_yaxis()\n\n utils.despine(trim=True)\n for side in self.inner_sides:\n bounds = ax.spines[side].get_bounds()\n assert bounds == (1, 3)"},{"col":4,"comment":"null","endLoc":172,"header":"def test_common_norm_warning(self, long_df, triple_args)","id":3976,"name":"test_common_norm_warning","nodeType":"Function","startLoc":168,"text":"def test_common_norm_warning(self, long_df, triple_args):\n\n h = Hist(common_norm=[\"b\"])\n with pytest.warns(UserWarning, match=\"Undefined variable(s)\"):\n h(long_df, *triple_args)"},{"col":4,"comment":"null","endLoc":236,"header":"def test_despine_trim_noticks(self)","id":3977,"name":"test_despine_trim_noticks","nodeType":"Function","startLoc":230,"text":"def test_despine_trim_noticks(self):\n\n f, ax = plt.subplots()\n ax.plot([1, 2, 3], [1, 2, 3])\n ax.set_yticks([])\n utils.despine(trim=True)\n assert ax.get_yticks().size == 0"},{"col":4,"comment":"null","endLoc":249,"header":"def test_despine_trim_categorical(self)","id":3978,"name":"test_despine_trim_categorical","nodeType":"Function","startLoc":238,"text":"def test_despine_trim_categorical(self):\n\n f, ax = plt.subplots()\n ax.plot([\"a\", \"b\", \"c\"], [1, 2, 3])\n\n utils.despine(trim=True)\n\n bounds = ax.spines[\"left\"].get_bounds()\n assert bounds == (1, 3)\n\n bounds = ax.spines[\"bottom\"].get_bounds()\n assert bounds == (0, 2)"},{"col":4,"comment":"null","endLoc":283,"header":"def test_despine_moved_ticks(self)","id":3979,"name":"test_despine_moved_ticks","nodeType":"Function","startLoc":251,"text":"def test_despine_moved_ticks(self):\n\n f, ax = plt.subplots()\n for t in ax.yaxis.majorTicks:\n t.tick1line.set_visible(True)\n utils.despine(ax=ax, left=True, right=False)\n for t in ax.yaxis.majorTicks:\n assert t.tick2line.get_visible()\n plt.close(f)\n\n f, ax = plt.subplots()\n for t in ax.yaxis.majorTicks:\n t.tick1line.set_visible(False)\n utils.despine(ax=ax, left=True, right=False)\n for t in ax.yaxis.majorTicks:\n assert not t.tick2line.get_visible()\n plt.close(f)\n\n f, ax = plt.subplots()\n for t in ax.xaxis.majorTicks:\n t.tick1line.set_visible(True)\n utils.despine(ax=ax, bottom=True, top=False)\n for t in ax.xaxis.majorTicks:\n assert t.tick2line.get_visible()\n plt.close(f)\n\n f, ax = plt.subplots()\n for t in ax.xaxis.majorTicks:\n t.tick1line.set_visible(False)\n utils.despine(ax=ax, bottom=True, top=False)\n for t in ax.xaxis.majorTicks:\n assert not t.tick2line.get_visible()\n plt.close(f)"},{"col":4,"comment":"null","endLoc":181,"header":"def test_common_bins_default(self, long_df, triple_args)","id":3980,"name":"test_common_bins_default","nodeType":"Function","startLoc":174,"text":"def test_common_bins_default(self, long_df, triple_args):\n\n h = Hist()\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby([\"a\", \"s\"]):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == 1"},{"attributeType":"list","col":4,"comment":"null","endLoc":127,"id":3981,"name":"sides","nodeType":"Attribute","startLoc":127,"text":"sides"},{"attributeType":"list","col":4,"comment":"null","endLoc":128,"id":3982,"name":"outer_sides","nodeType":"Attribute","startLoc":128,"text":"outer_sides"},{"attributeType":"list","col":4,"comment":"null","endLoc":129,"id":3983,"name":"inner_sides","nodeType":"Attribute","startLoc":129,"text":"inner_sides"},{"attributeType":"int","col":4,"comment":"null","endLoc":131,"id":3984,"name":"offset","nodeType":"Attribute","startLoc":131,"text":"offset"},{"attributeType":"(str, int)","col":4,"comment":"null","endLoc":132,"id":3985,"name":"original_position","nodeType":"Attribute","startLoc":132,"text":"original_position"},{"attributeType":"(str, int)","col":4,"comment":"null","endLoc":133,"id":3986,"name":"offset_position","nodeType":"Attribute","startLoc":133,"text":"offset_position"},{"col":0,"comment":"Test behavior of ci_to_errsize.","endLoc":74,"header":"def test_ci_to_errsize()","id":3987,"name":"test_ci_to_errsize","nodeType":"Function","startLoc":63,"text":"def test_ci_to_errsize():\n \"\"\"Test behavior of ci_to_errsize.\"\"\"\n cis = [[.5, .5],\n [1.25, 1.5]]\n\n heights = [1, 1.5]\n\n actual_errsize = np.array([[.5, 1],\n [.25, 0]])\n\n test_errsize = utils.ci_to_errsize(cis, heights)\n assert_array_equal(actual_errsize, test_errsize)"},{"col":0,"comment":"Test color desaturation.","endLoc":89,"header":"def test_desaturate()","id":3990,"name":"test_desaturate","nodeType":"Function","startLoc":77,"text":"def test_desaturate():\n \"\"\"Test color desaturation.\"\"\"\n out1 = utils.desaturate(\"red\", .5)\n assert out1 == (.75, .25, .25)\n\n out2 = utils.desaturate(\"#00FF00\", .5)\n assert out2 == (.25, .75, .25)\n\n out3 = utils.desaturate((0, 0, 1), .5)\n assert out3 == (.25, .25, .75)\n\n out4 = utils.desaturate(\"red\", .5)\n assert out4 == (.75, .25, .25)"},{"col":0,"comment":"","endLoc":1,"header":"test_docstrings.py#","id":3991,"name":"","nodeType":"Function","startLoc":1,"text":"EXAMPLE_DICT = dict(\n param_a=\"\"\"\na : str\n The first parameter.\n \"\"\",\n)"},{"id":3992,"name":"objects.Plot.pair.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"raw\",\n \"id\": \"ac7814b6-1e2c-4f0e-991b-7fe78fca4346\",\n \"metadata\": {},\n \"source\": [\n \".. currentmodule:: seaborn.objects\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"9252d5a5-8af1-4f99-b799-ee044329fb23\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"mpg = load_dataset(\\\"mpg\\\")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"a6ee48da-ff1e-41eb-95ec-9f2dd12bdb63\",\n \"metadata\": {},\n \"source\": [\n \"Plot one dependent variable against multiple independent variables by assigning `y` and pairing on `x`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"56ab58b6-ccdf-4938-a8e0-cbe2de8d6749\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg, y=\\\"acceleration\\\")\\n\",\n \" .pair(x=[\\\"displacement\\\", \\\"weight\\\"])\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"c37e0543-d022-4079-b58a-8f8af90b29c8\",\n \"metadata\": {},\n \"source\": [\n \"Show multiple pairwise relationships by passing lists to both `x` and `y`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"39b5298d-d578-4284-8fab-415d2c03022d\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg)\\n\",\n \" .pair(x=[\\\"displacement\\\", \\\"weight\\\"], y=[\\\"horsepower\\\", \\\"acceleration\\\"])\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"09bf54ad-bf55-4e26-8566-5af62bf29c51\",\n \"metadata\": {},\n \"source\": [\n \"When providing lists for both `x` and `y`, pass `cross=False` to pair each position in the list rather than showing all pairwise relationships:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c70ca7d8-79ee-4c7a-ae91-2088e965b1f4\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg)\\n\",\n \" .pair(\\n\",\n \" x=[\\\"weight\\\", \\\"acceleration\\\"],\\n\",\n \" y=[\\\"displacement\\\", \\\"horsepower\\\"],\\n\",\n \" cross=False,\\n\",\n \" )\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"79beadec-038d-40f0-8783-749474d48eac\",\n \"metadata\": {},\n \"source\": [\n \"When plotting against several `x` or `y` variables, it is possible to `wrap` the subplots to produce a two-dimensional grid:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2bf2d87f-a940-426c-bdff-8bf80696b7a1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg, y=\\\"mpg\\\")\\n\",\n \" .pair(x=[\\\"displacement\\\", \\\"weight\\\", \\\"horsepower\\\", \\\"cylinders\\\"], wrap=2)\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"6304faed-2466-49eb-a8c2-d9d635938b78\",\n \"metadata\": {},\n \"source\": [\n \"Pairing can be combined with faceting, either pairing on `y` and faceting on `col` or pairing on `x` and faceting on `row`:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"bea235cd-e9c1-4119-a683-871e60b149ec\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg, x=\\\"weight\\\")\\n\",\n \" .pair(y=[\\\"horsepower\\\", \\\"acceleration\\\"])\\n\",\n \" .facet(col=\\\"origin\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"markdown\",\n \"id\": \"ded931d2-95f1-4e09-8e24-f8b687f8f052\",\n \"metadata\": {},\n \"source\": [\n \"While typically convenient to assign pairing variables as references to the common `data`, it's also possible to pass a list of vectors:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"66e0cb77-094b-4144-b086-15bab106ca9f\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg[\\\"weight\\\"])\\n\",\n \" .pair(y=[mpg[\\\"horsepower\\\"], mpg[\\\"acceleration\\\"]])\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"7bef3310-87f6-44f6-be6a-e30effaa7a70\",\n \"metadata\": {},\n \"source\": [\n \"When customizing the plot through methods like :meth:`Plot.label`, :meth:`Plot.limit`, or :meth:`Plot.scale`, you can refer to the individual coordinate variables as `x0`, `x1`, etc.:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d6ce8868-55c0-4c44-8fed-937771b762ee\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(mpg, y=\\\"mpg\\\")\\n\",\n \" .pair(x=[\\\"weight\\\", \\\"displacement\\\"])\\n\",\n \" .label(x0=\\\"Weight (lb)\\\", x1=\\\"Displacement (cu in)\\\", y=\\\"MPG\\\")\\n\",\n \" .add(so.Dots())\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"358d409f-8b7c-4901-8eec-b2cf51731483\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"col":0,"comment":"Test that pct outside of [0, 1] raises exception.","endLoc":95,"header":"def test_desaturation_prop()","id":3993,"name":"test_desaturation_prop","nodeType":"Function","startLoc":92,"text":"def test_desaturation_prop():\n \"\"\"Test that pct outside of [0, 1] raises exception.\"\"\"\n with pytest.raises(ValueError):\n utils.desaturate(\"blue\", 50)"},{"col":0,"comment":"Test performance of saturation function.","endLoc":101,"header":"def test_saturate()","id":3994,"name":"test_saturate","nodeType":"Function","startLoc":98,"text":"def test_saturate():\n \"\"\"Test performance of saturation function.\"\"\"\n out = utils.saturate((.75, .25, .25))\n assert out == (1, 0, 0)"},{"fileName":"cache_datasets.py","filePath":"ci","id":3995,"nodeType":"File","text":"\"\"\"\nCache test datasets before running tests / building docs.\n\nAvoids race conditions that would arise from parallelization.\n\"\"\"\nimport pathlib\nimport re\n\nfrom seaborn import load_dataset\n\npath = pathlib.Path(\".\")\npy_files = path.rglob(\"*.py\")\nipynb_files = path.rglob(\"*.ipynb\")\n\ndatasets = []\n\nfor fname in py_files:\n with open(fname) as fid:\n datasets += re.findall(r\"load_dataset\\(['\\\"](\\w+)['\\\"]\", fid.read())\n\nfor p in ipynb_files:\n with p.open() as fid:\n datasets += re.findall(r\"load_dataset\\(\\\\['\\\"](\\w+)\\\\['\\\"]\", fid.read())\n\nfor name in sorted(set(datasets)):\n print(f\"Caching {name}\")\n load_dataset(name)\n"},{"col":0,"comment":"Test the to_utf8 function: object to string","endLoc":122,"header":"@pytest.mark.parametrize(\n \"s,exp\",\n [\n (\"a\", \"a\"),\n (\"abc\", \"abc\"),\n (b\"a\", \"a\"),\n (b\"abc\", \"abc\"),\n (bytearray(\"abc\", \"utf-8\"), \"abc\"),\n (bytearray(), \"\"),\n (1, \"1\"),\n (0, \"0\"),\n ([], str([])),\n ],\n)\ndef test_to_utf8(s, exp)","id":3996,"name":"test_to_utf8","nodeType":"Function","startLoc":104,"text":"@pytest.mark.parametrize(\n \"s,exp\",\n [\n (\"a\", \"a\"),\n (\"abc\", \"abc\"),\n (b\"a\", \"a\"),\n (b\"abc\", \"abc\"),\n (bytearray(\"abc\", \"utf-8\"), \"abc\"),\n (bytearray(), \"\"),\n (1, \"1\"),\n (0, \"0\"),\n ([], str([])),\n ],\n)\ndef test_to_utf8(s, exp):\n \"\"\"Test the to_utf8 function: object to string\"\"\"\n u = utils.to_utf8(s)\n assert type(u) == str\n assert u == exp"},{"attributeType":"Path","col":0,"comment":"null","endLoc":11,"id":3997,"name":"path","nodeType":"Attribute","startLoc":11,"text":"path"},{"col":4,"comment":"null","endLoc":190,"header":"def test_common_bins_false(self, long_df, triple_args)","id":3998,"name":"test_common_bins_false","nodeType":"Function","startLoc":183,"text":"def test_common_bins_false(self, long_df, triple_args):\n\n h = Hist(common_bins=False)\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby([\"a\", \"s\"]):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == len(out.groupby([\"a\", \"s\"]))"},{"col":4,"comment":"null","endLoc":131,"header":"def test_nominal_dict_with_missing_keys(self, cat_vector, cat_order)","id":3999,"name":"test_nominal_dict_with_missing_keys","nodeType":"Function","startLoc":127,"text":"def test_nominal_dict_with_missing_keys(self, cat_vector, cat_order):\n\n palette = dict(zip(cat_order[1:], color_palette(\"Purples\")))\n with pytest.raises(ValueError, match=\"No entry in color dict\"):\n Color(\"color\").get_mapping(Nominal(palette), cat_vector)"},{"col":4,"comment":"Use matplotlib to draw a letter value plot on an Axes.","endLoc":2040,"header":"def draw_letter_value_plot(self, ax, box_kws=None, flier_kws=None,\n line_kws=None)","id":4000,"name":"draw_letter_value_plot","nodeType":"Function","startLoc":1977,"text":"def draw_letter_value_plot(self, ax, box_kws=None, flier_kws=None,\n line_kws=None):\n \"\"\"Use matplotlib to draw a letter value plot on an Axes.\"\"\"\n\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = remove_na(group_data)\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n color = self.colors[i]\n\n self._lvplot(box_data,\n positions=[i],\n color=color,\n widths=self.width,\n ax=ax,\n box_kws=box_kws,\n flier_kws=flier_kws,\n line_kws=line_kws)\n\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = remove_na(group_data[hue_mask])\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n color = self.colors[j]\n center = i + offsets[j]\n self._lvplot(box_data,\n positions=[center],\n color=color,\n widths=self.nested_width,\n ax=ax,\n box_kws=box_kws,\n flier_kws=flier_kws,\n line_kws=line_kws)\n\n # Autoscale the values axis to make sure all patches are visible\n ax.autoscale_view(scalex=self.orient == \"h\", scaley=self.orient == \"v\")"},{"fileName":"base.py","filePath":"seaborn/_marks","id":4001,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass, fields, field\nimport textwrap\nfrom typing import Any, Callable, Union\nfrom collections.abc import Generator\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\n\nfrom numpy import ndarray\nfrom pandas import DataFrame\nfrom matplotlib.artist import Artist\n\nfrom seaborn._core.scales import Scale\nfrom seaborn._core.properties import (\n PROPERTIES,\n Property,\n RGBATuple,\n DashPattern,\n DashPatternWithOffset,\n)\n\n\nclass Mappable:\n def __init__(\n self,\n val: Any = None,\n depend: str | None = None,\n rc: str | None = None,\n auto: bool = False,\n grouping: bool = True,\n ):\n \"\"\"\n Property that can be mapped from data or set directly, with flexible defaults.\n\n Parameters\n ----------\n val : Any\n Use this value as the default.\n depend : str\n Use the value of this feature as the default.\n rc : str\n Use the value of this rcParam as the default.\n auto : bool\n The default value will depend on other parameters at compile time.\n grouping : bool\n If True, use the mapped variable to define groups.\n\n \"\"\"\n if depend is not None:\n assert depend in PROPERTIES\n if rc is not None:\n assert rc in mpl.rcParams\n\n self._val = val\n self._rc = rc\n self._depend = depend\n self._auto = auto\n self._grouping = grouping\n\n def __repr__(self):\n \"\"\"Nice formatting for when object appears in Mark init signature.\"\"\"\n if self._val is not None:\n s = f\"<{repr(self._val)}>\"\n elif self._depend is not None:\n s = f\"\"\n elif self._rc is not None:\n s = f\"\"\n elif self._auto:\n s = \"\"\n else:\n s = \"\"\n return s\n\n @property\n def depend(self) -> Any:\n \"\"\"Return the name of the feature to source a default value from.\"\"\"\n return self._depend\n\n @property\n def grouping(self) -> bool:\n return self._grouping\n\n @property\n def default(self) -> Any:\n \"\"\"Get the default value for this feature, or access the relevant rcParam.\"\"\"\n if self._val is not None:\n return self._val\n return mpl.rcParams.get(self._rc)\n\n\n# TODO where is the right place to put this kind of type aliasing?\n\nMappableBool = Union[bool, Mappable]\nMappableString = Union[str, Mappable]\nMappableFloat = Union[float, Mappable]\nMappableColor = Union[str, tuple, Mappable]\nMappableStyle = Union[str, DashPattern, DashPatternWithOffset, Mappable]\n\n\n@dataclass\nclass Mark:\n \"\"\"Base class for objects that visually represent data.\"\"\"\n\n artist_kws: dict = field(default_factory=dict)\n\n @property\n def _mappable_props(self):\n return {\n f.name: getattr(self, f.name) for f in fields(self)\n if isinstance(f.default, Mappable)\n }\n\n @property\n def _grouping_props(self):\n # TODO does it make sense to have variation within a Mark's\n # properties about whether they are grouping?\n return [\n f.name for f in fields(self)\n if isinstance(f.default, Mappable) and f.default.grouping\n ]\n\n # TODO make this method private? Would extender every need to call directly?\n def _resolve(\n self,\n data: DataFrame | dict[str, Any],\n name: str,\n scales: dict[str, Scale] | None = None,\n ) -> Any:\n \"\"\"Obtain default, specified, or mapped value for a named feature.\n\n Parameters\n ----------\n data : DataFrame or dict with scalar values\n Container with data values for features that will be semantically mapped.\n name : string\n Identity of the feature / semantic.\n scales: dict\n Mapping from variable to corresponding scale object.\n\n Returns\n -------\n value or array of values\n Outer return type depends on whether `data` is a dict (implying that\n we want a single value) or DataFrame (implying that we want an array\n of values with matching length).\n\n \"\"\"\n feature = self._mappable_props[name]\n prop = PROPERTIES.get(name, Property(name))\n directly_specified = not isinstance(feature, Mappable)\n return_multiple = isinstance(data, pd.DataFrame)\n return_array = return_multiple and not name.endswith(\"style\")\n\n # Special case width because it needs to be resolved and added to the dataframe\n # during layer prep (so the Move operations use it properly).\n # TODO how does width *scaling* work, e.g. for violin width by count?\n if name == \"width\":\n directly_specified = directly_specified and name not in data\n\n if directly_specified:\n feature = prop.standardize(feature)\n if return_multiple:\n feature = [feature] * len(data)\n if return_array:\n feature = np.array(feature)\n return feature\n\n if name in data:\n if scales is None or name not in scales:\n # TODO Might this obviate the identity scale? Just don't add a scale?\n feature = data[name]\n else:\n feature = scales[name](data[name])\n if return_array:\n feature = np.asarray(feature)\n return feature\n\n if feature.depend is not None:\n # TODO add source_func or similar to transform the source value?\n # e.g. set linewidth as a proportion of pointsize?\n return self._resolve(data, feature.depend, scales)\n\n default = prop.standardize(feature.default)\n if return_multiple:\n default = [default] * len(data)\n if return_array:\n default = np.array(default)\n return default\n\n def _infer_orient(self, scales: dict) -> str: # TODO type scales\n\n # TODO The original version of this (in seaborn._oldcore) did more checking.\n # Paring that down here for the prototype to see what restrictions make sense.\n\n # TODO rethink this to map from scale type to \"DV priority\" and use that?\n # e.g. Nominal > Discrete > Continuous\n\n x = 0 if \"x\" not in scales else scales[\"x\"]._priority\n y = 0 if \"y\" not in scales else scales[\"y\"]._priority\n\n if y > x:\n return \"y\"\n else:\n return \"x\"\n\n def _plot(\n self,\n split_generator: Callable[[], Generator],\n scales: dict[str, Scale],\n orient: str,\n ) -> None:\n \"\"\"Main interface for creating a plot.\"\"\"\n raise NotImplementedError()\n\n def _legend_artist(\n self, variables: list[str], value: Any, scales: dict[str, Scale],\n ) -> Artist:\n\n return None\n\n\ndef resolve_properties(\n mark: Mark, data: DataFrame, scales: dict[str, Scale]\n) -> dict[str, Any]:\n\n props = {\n name: mark._resolve(data, name, scales) for name in mark._mappable_props\n }\n return props\n\n\ndef resolve_color(\n mark: Mark,\n data: DataFrame | dict,\n prefix: str = \"\",\n scales: dict[str, Scale] | None = None,\n) -> RGBATuple | ndarray:\n \"\"\"\n Obtain a default, specified, or mapped value for a color feature.\n\n This method exists separately to support the relationship between a\n color and its corresponding alpha. We want to respect alpha values that\n are passed in specified (or mapped) color values but also make use of a\n separate `alpha` variable, which can be mapped. This approach may also\n be extended to support mapping of specific color channels (i.e.\n luminance, chroma) in the future.\n\n Parameters\n ----------\n mark :\n Mark with the color property.\n data :\n Container with data values for features that will be semantically mapped.\n prefix :\n Support \"color\", \"fillcolor\", etc.\n\n \"\"\"\n color = mark._resolve(data, f\"{prefix}color\", scales)\n\n if f\"{prefix}alpha\" in mark._mappable_props:\n alpha = mark._resolve(data, f\"{prefix}alpha\", scales)\n else:\n alpha = mark._resolve(data, \"alpha\", scales)\n\n def visible(x, axis=None):\n \"\"\"Detect \"invisible\" colors to set alpha appropriately.\"\"\"\n # TODO First clause only needed to handle non-rgba arrays,\n # which we are trying to handle upstream\n return np.array(x).dtype.kind != \"f\" or np.isfinite(x).all(axis)\n\n # Second check here catches vectors of strings with identity scale\n # It could probably be handled better upstream. This is a tricky problem\n if np.ndim(color) < 2 and all(isinstance(x, float) for x in color):\n if len(color) == 4:\n return mpl.colors.to_rgba(color)\n alpha = alpha if visible(color) else np.nan\n return mpl.colors.to_rgba(color, alpha)\n else:\n if np.ndim(color) == 2 and color.shape[1] == 4:\n return mpl.colors.to_rgba_array(color)\n alpha = np.where(visible(color, axis=1), alpha, np.nan)\n return mpl.colors.to_rgba_array(color, alpha)\n\n # TODO should we be implementing fill here too?\n # (i.e. set fillalpha to 0 when fill=False)\n\n\ndef document_properties(mark):\n\n properties = [f.name for f in fields(mark) if isinstance(f.default, Mappable)]\n text = [\n \"\",\n \" This mark defines the following properties:\",\n textwrap.fill(\n \", \".join([f\"|{p}|\" for p in properties]),\n width=78, initial_indent=\" \" * 8, subsequent_indent=\" \" * 8,\n ),\n ]\n\n docstring_lines = mark.__doc__.split(\"\\n\")\n new_docstring = \"\\n\".join([\n *docstring_lines[:2],\n *text,\n *docstring_lines[2:],\n ])\n mark.__doc__ = new_docstring\n return mark\n"},{"col":4,"comment":"null","endLoc":194,"header":"@overload # `default` and `default_factory` are optional and mutually exclusive.\n def field(\n *,\n default: _T,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T","id":4002,"name":"field","nodeType":"Function","startLoc":185,"text":"@overload # `default` and `default_factory` are optional and mutually exclusive.\n def field(\n *,\n default: _T,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T: ..."},{"col":4,"comment":"null","endLoc":204,"header":"@overload\n def field(\n *,\n default_factory: Callable[[], _T],\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T","id":4003,"name":"field","nodeType":"Function","startLoc":195,"text":"@overload\n def field(\n *,\n default_factory: Callable[[], _T],\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T: ..."},{"col":4,"comment":"null","endLoc":213,"header":"@overload\n def field(\n *,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> Any","id":4004,"name":"field","nodeType":"Function","startLoc":205,"text":"@overload\n def field(\n *,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> Any: ..."},{"col":0,"comment":"","endLoc":1,"header":"base.py#","id":4005,"name":"","nodeType":"Function","startLoc":1,"text":"MappableBool = Union[bool, Mappable]\n\nMappableString = Union[str, Mappable]\n\nMappableFloat = Union[float, Mappable]\n\nMappableColor = Union[str, tuple, Mappable]\n\nMappableStyle = Union[str, DashPattern, DashPatternWithOffset, Mappable]"},{"fileName":"test_aggregation.py","filePath":"tests/_stats","id":4009,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\n\nimport pytest\nfrom pandas.testing import assert_frame_equal\n\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.aggregation import Agg, Est\n\n\nclass AggregationFixtures:\n\n @pytest.fixture\n def df(self, rng):\n\n n = 30\n return pd.DataFrame(dict(\n x=rng.uniform(0, 7, n).round(),\n y=rng.normal(size=n),\n color=rng.choice([\"a\", \"b\", \"c\"], n),\n group=rng.choice([\"x\", \"y\"], n),\n ))\n\n def get_groupby(self, df, orient):\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n cols = [c for c in df if c != other]\n return GroupBy(cols)\n\n\nclass TestAgg(AggregationFixtures):\n\n def test_default(self, df):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Agg()(df, gb, ori, {})\n\n expected = df.groupby(\"x\", as_index=False)[\"y\"].mean()\n assert_frame_equal(res, expected)\n\n def test_default_multi(self, df):\n\n ori = \"x\"\n gb = self.get_groupby(df, ori)\n res = Agg()(df, gb, ori, {})\n\n grp = [\"x\", \"color\", \"group\"]\n index = pd.MultiIndex.from_product(\n [sorted(df[\"x\"].unique()), df[\"color\"].unique(), df[\"group\"].unique()],\n names=[\"x\", \"color\", \"group\"]\n )\n expected = (\n df\n .groupby(grp)\n .agg(\"mean\")\n .reindex(index=index)\n .dropna()\n .reset_index()\n .reindex(columns=df.columns)\n )\n assert_frame_equal(res, expected)\n\n @pytest.mark.parametrize(\"func\", [\"max\", lambda x: float(len(x) % 2)])\n def test_func(self, df, func):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Agg(func)(df, gb, ori, {})\n\n expected = df.groupby(\"x\", as_index=False)[\"y\"].agg(func)\n assert_frame_equal(res, expected)\n\n\nclass TestEst(AggregationFixtures):\n\n # Note: Most of the underlying code is exercised in tests/test_statistics\n\n @pytest.mark.parametrize(\"func\", [np.mean, \"mean\"])\n def test_mean_sd(self, df, func):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Est(func, \"sd\")(df, gb, ori, {})\n\n grouped = df.groupby(\"x\", as_index=False)[\"y\"]\n est = grouped.mean()\n err = grouped.std().fillna(0) # fillna needed only on pinned tests\n expected = est.assign(ymin=est[\"y\"] - err[\"y\"], ymax=est[\"y\"] + err[\"y\"])\n assert_frame_equal(res, expected)\n\n def test_sd_single_obs(self):\n\n y = 1.5\n ori = \"x\"\n df = pd.DataFrame([{\"x\": \"a\", \"y\": y}])\n gb = self.get_groupby(df, ori)\n res = Est(\"mean\", \"sd\")(df, gb, ori, {})\n expected = df.assign(ymin=y, ymax=y)\n assert_frame_equal(res, expected)\n\n def test_median_pi(self, df):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Est(\"median\", (\"pi\", 100))(df, gb, ori, {})\n\n grouped = df.groupby(\"x\", as_index=False)[\"y\"]\n est = grouped.median()\n expected = est.assign(ymin=grouped.min()[\"y\"], ymax=grouped.max()[\"y\"])\n assert_frame_equal(res, expected)\n\n def test_seed(self, df):\n\n ori = \"x\"\n gb = self.get_groupby(df, ori)\n args = df, gb, ori, {}\n res1 = Est(\"mean\", \"ci\", seed=99)(*args)\n res2 = Est(\"mean\", \"ci\", seed=99)(*args)\n assert_frame_equal(res1, res2)\n"},{"className":"AggregationFixtures","col":0,"comment":"null","endLoc":29,"id":4010,"nodeType":"Class","startLoc":12,"text":"class AggregationFixtures:\n\n @pytest.fixture\n def df(self, rng):\n\n n = 30\n return pd.DataFrame(dict(\n x=rng.uniform(0, 7, n).round(),\n y=rng.normal(size=n),\n color=rng.choice([\"a\", \"b\", \"c\"], n),\n group=rng.choice([\"x\", \"y\"], n),\n ))\n\n def get_groupby(self, df, orient):\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n cols = [c for c in df if c != other]\n return GroupBy(cols)"},{"col":4,"comment":"null","endLoc":23,"header":"@pytest.fixture\n def df(self, rng)","id":4011,"name":"df","nodeType":"Function","startLoc":14,"text":"@pytest.fixture\n def df(self, rng):\n\n n = 30\n return pd.DataFrame(dict(\n x=rng.uniform(0, 7, n).round(),\n y=rng.normal(size=n),\n color=rng.choice([\"a\", \"b\", \"c\"], n),\n group=rng.choice([\"x\", \"y\"], n),\n ))"},{"col":4,"comment":"null","endLoc":199,"header":"def test_common_bins_subset(self, long_df, triple_args)","id":4012,"name":"test_common_bins_subset","nodeType":"Function","startLoc":192,"text":"def test_common_bins_subset(self, long_df, triple_args):\n\n h = Hist(common_bins=False)\n out = h(long_df, *triple_args)\n bins = []\n for _, out_part in out.groupby(\"a\"):\n bins.append(tuple(out_part[\"x\"]))\n assert len(set(bins)) == out[\"a\"].nunique()"},{"col":4,"comment":"null","endLoc":205,"header":"def test_common_bins_warning(self, long_df, triple_args)","id":4013,"name":"test_common_bins_warning","nodeType":"Function","startLoc":201,"text":"def test_common_bins_warning(self, long_df, triple_args):\n\n h = Hist(common_bins=[\"b\"])\n with pytest.warns(UserWarning, match=\"Undefined variable(s)\"):\n h(long_df, *triple_args)"},{"col":4,"comment":"null","endLoc":213,"header":"def test_histogram_single(self, long_df, single_args)","id":4014,"name":"test_histogram_single","nodeType":"Function","startLoc":207,"text":"def test_histogram_single(self, long_df, single_args):\n\n h = Hist()\n out = h(long_df, *single_args)\n hist, edges = np.histogram(long_df[\"x\"], bins=\"auto\")\n assert_array_equal(out[\"y\"], hist)\n assert_array_equal(out[\"space\"], np.diff(edges))"},{"col":0,"comment":"null","endLoc":303,"header":"def test_ticklabels_overlap()","id":4015,"name":"test_ticklabels_overlap","nodeType":"Function","startLoc":286,"text":"def test_ticklabels_overlap():\n\n rcmod.set()\n f, ax = plt.subplots(figsize=(2, 2))\n f.tight_layout() # This gets the Agg renderer working\n\n assert not utils.axis_ticklabels_overlap(ax.get_xticklabels())\n\n big_strings = \"abcdefgh\", \"ijklmnop\"\n ax.set_xlim(-.5, 1.5)\n ax.set_xticks([0, 1])\n ax.set_xticklabels(big_strings)\n\n assert utils.axis_ticklabels_overlap(ax.get_xticklabels())\n\n x, y = utils.axes_ticklabels_overlap(ax)\n assert x\n assert not y"},{"col":4,"comment":"null","endLoc":224,"header":"def test_histogram_multiple(self, long_df, triple_args)","id":4016,"name":"test_histogram_multiple","nodeType":"Function","startLoc":215,"text":"def test_histogram_multiple(self, long_df, triple_args):\n\n h = Hist()\n out = h(long_df, *triple_args)\n bins = np.histogram_bin_edges(long_df[\"x\"], \"auto\")\n for (a, s), out_part in out.groupby([\"a\", \"s\"]):\n x = long_df.loc[(long_df[\"a\"] == a) & (long_df[\"s\"] == s), \"x\"]\n hist, edges = np.histogram(x, bins=bins)\n assert_array_equal(out_part[\"y\"], hist)\n assert_array_equal(out_part[\"space\"], np.diff(edges))"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":4017,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":4018,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"col":4,"comment":"null","endLoc":139,"header":"def test_nominal_list_too_short(self, cat_vector, cat_order)","id":4019,"name":"test_nominal_list_too_short","nodeType":"Function","startLoc":133,"text":"def test_nominal_list_too_short(self, cat_vector, cat_order):\n\n n = len(cat_order) - 1\n palette = color_palette(\"Oranges\", n)\n msg = rf\"The edgecolor list has fewer values \\({n}\\) than needed \\({n + 1}\\)\"\n with pytest.warns(UserWarning, match=msg):\n Color(\"edgecolor\").get_mapping(Nominal(palette), cat_vector)"},{"col":0,"comment":"null","endLoc":335,"header":"def test_locator_to_legend_entries()","id":4020,"name":"test_locator_to_legend_entries","nodeType":"Function","startLoc":306,"text":"def test_locator_to_legend_entries():\n\n locator = mpl.ticker.MaxNLocator(nbins=3)\n limits = (0.09, 0.4)\n levels, str_levels = utils.locator_to_legend_entries(\n locator, limits, float\n )\n assert str_levels == [\"0.15\", \"0.30\"]\n\n limits = (0.8, 0.9)\n levels, str_levels = utils.locator_to_legend_entries(\n locator, limits, float\n )\n assert str_levels == [\"0.80\", \"0.84\", \"0.88\"]\n\n limits = (1, 6)\n levels, str_levels = utils.locator_to_legend_entries(locator, limits, int)\n assert str_levels == [\"2\", \"4\", \"6\"]\n\n locator = mpl.ticker.LogLocator(numticks=5)\n limits = (5, 1425)\n levels, str_levels = utils.locator_to_legend_entries(locator, limits, int)\n if Version(mpl.__version__) >= Version(\"3.1\"):\n assert str_levels == ['10', '100', '1000']\n\n limits = (0.00003, 0.02)\n _, str_levels = utils.locator_to_legend_entries(locator, limits, float)\n for i, exp in enumerate([4, 3, 2]):\n # Use regex as mpl switched to minus sign, not hyphen, in 3.6\n assert re.match(f\"1e.0{exp}\", str_levels[i])"},{"fileName":"__init__.py","filePath":"tests/_marks","id":4021,"nodeType":"File","text":""},{"id":4022,"name":"citing.rst","nodeType":"TextFile","path":"doc","text":".. _citing:\n\nCiting and logo\n===============\n\nCiting seaborn\n--------------\n\nIf seaborn is integral to a scientific publication, please cite it.\nA paper describing seaborn has been published in the `Journal of Open Source Software `_.\nHere is a ready-made BibTeX entry:\n\n.. highlight:: none\n\n::\n\n @article{Waskom2021,\n doi = {10.21105/joss.03021},\n url = {https://doi.org/10.21105/joss.03021},\n year = {2021},\n publisher = {The Open Journal},\n volume = {6},\n number = {60},\n pages = {3021},\n author = {Michael L. Waskom},\n title = {seaborn: statistical data visualization},\n journal = {Journal of Open Source Software}\n }\n\nIn most situations where seaborn is cited, a citation to `matplotlib `_ would also be appropriate.\n\nLogo files\n----------\n\nAdditional logo files, including hi-res PNGs and images suitable for use over a dark background, are available\n`on GitHub `_.\n\nWide logo\n~~~~~~~~~\n\n.. image:: _static/logo-wide-lightbg.svg\n :width: 400px\n\nTall logo\n~~~~~~~~~\n\n.. image:: _static/logo-tall-lightbg.svg\n :width: 150px\n\nLogo mark\n~~~~~~~~~\n\n.. image:: _static/logo-mark-lightbg.svg\n :width: 150px\n\nCredit to `Matthias Bussonnier `_ for the initial design\nand implementation of the logo.\n"},{"col":4,"comment":"null","endLoc":147,"header":"def test_nominal_list_too_long(self, cat_vector, cat_order)","id":4023,"name":"test_nominal_list_too_long","nodeType":"Function","startLoc":141,"text":"def test_nominal_list_too_long(self, cat_vector, cat_order):\n\n n = len(cat_order) + 1\n palette = color_palette(\"Oranges\", n)\n msg = rf\"The edgecolor list has more values \\({n}\\) than needed \\({n - 1}\\)\"\n with pytest.warns(UserWarning, match=msg):\n Color(\"edgecolor\").get_mapping(Nominal(palette), cat_vector)"},{"col":4,"comment":"null","endLoc":153,"header":"def test_continuous_default_palette(self, num_vector)","id":4024,"name":"test_continuous_default_palette","nodeType":"Function","startLoc":149,"text":"def test_continuous_default_palette(self, num_vector):\n\n cmap = color_palette(\"ch:\", as_cmap=True)\n m = Color().get_mapping(Continuous(), num_vector)\n self.assert_same_rgb(m(num_vector), cmap(num_vector))"},{"col":0,"comment":"null","endLoc":384,"header":"def test_move_legend_matplotlib_objects()","id":4025,"name":"test_move_legend_matplotlib_objects","nodeType":"Function","startLoc":338,"text":"def test_move_legend_matplotlib_objects():\n\n fig, ax = plt.subplots()\n\n colors = \"C2\", \"C5\"\n labels = \"first label\", \"second label\"\n title = \"the legend\"\n\n for color, label in zip(colors, labels):\n ax.plot([0, 1], color=color, label=label)\n ax.legend(loc=\"upper right\", title=title)\n utils._draw_figure(fig)\n xfm = ax.transAxes.inverted().transform\n\n # --- Test axes legend\n\n old_pos = xfm(ax.legend_.legendPatch.get_extents())\n\n new_fontsize = 14\n utils.move_legend(ax, \"lower left\", title_fontsize=new_fontsize)\n utils._draw_figure(fig)\n new_pos = xfm(ax.legend_.legendPatch.get_extents())\n\n assert (new_pos < old_pos).all()\n assert ax.legend_.get_title().get_text() == title\n assert ax.legend_.get_title().get_size() == new_fontsize\n\n # --- Test title replacement\n\n new_title = \"new title\"\n utils.move_legend(ax, \"lower left\", title=new_title)\n utils._draw_figure(fig)\n assert ax.legend_.get_title().get_text() == new_title\n\n # --- Test figure legend\n\n fig.legend(loc=\"upper right\", title=title)\n _draw_figure(fig)\n xfm = fig.transFigure.inverted().transform\n old_pos = xfm(fig.legends[0].legendPatch.get_extents())\n\n utils.move_legend(fig, \"lower left\", title=new_title)\n _draw_figure(fig)\n\n new_pos = xfm(fig.legends[0].legendPatch.get_extents())\n assert (new_pos < old_pos).all()\n assert fig.legends[0].get_title().get_text() == new_title"},{"col":4,"comment":"null","endLoc":160,"header":"def test_continuous_named_palette(self, num_vector)","id":4026,"name":"test_continuous_named_palette","nodeType":"Function","startLoc":155,"text":"def test_continuous_named_palette(self, num_vector):\n\n pal = \"flare\"\n cmap = color_palette(pal, as_cmap=True)\n m = Color().get_mapping(Continuous(pal), num_vector)\n self.assert_same_rgb(m(num_vector), cmap(num_vector))"},{"col":4,"comment":"null","endLoc":167,"header":"def test_continuous_tuple_palette(self, num_vector)","id":4027,"name":"test_continuous_tuple_palette","nodeType":"Function","startLoc":162,"text":"def test_continuous_tuple_palette(self, num_vector):\n\n vals = (\"blue\", \"red\")\n cmap = color_palette(\"blend:\" + \",\".join(vals), as_cmap=True)\n m = Color().get_mapping(Continuous(vals), num_vector)\n self.assert_same_rgb(m(num_vector), cmap(num_vector))"},{"col":4,"comment":"null","endLoc":173,"header":"def test_continuous_callable_palette(self, num_vector)","id":4028,"name":"test_continuous_callable_palette","nodeType":"Function","startLoc":169,"text":"def test_continuous_callable_palette(self, num_vector):\n\n cmap = get_colormap(\"viridis\")\n m = Color().get_mapping(Continuous(cmap), num_vector)\n self.assert_same_rgb(m(num_vector), cmap(num_vector))"},{"col":4,"comment":"null","endLoc":179,"header":"def test_continuous_missing(self)","id":4029,"name":"test_continuous_missing","nodeType":"Function","startLoc":175,"text":"def test_continuous_missing(self):\n\n x = pd.Series([1, 2, np.nan, 4])\n m = Color().get_mapping(Continuous(), x)\n assert np.isnan(m(x)[2]).all()"},{"col":4,"comment":"null","endLoc":184,"header":"def test_bad_scale_values_continuous(self, num_vector)","id":4030,"name":"test_bad_scale_values_continuous","nodeType":"Function","startLoc":181,"text":"def test_bad_scale_values_continuous(self, num_vector):\n\n with pytest.raises(TypeError, match=\"Scale values for color with a Continuous\"):\n Color().get_mapping(Continuous([\"r\", \"g\", \"b\"]), num_vector)"},{"col":0,"comment":"null","endLoc":412,"header":"def test_move_legend_grid_object(long_df)","id":4031,"name":"test_move_legend_grid_object","nodeType":"Function","startLoc":387,"text":"def test_move_legend_grid_object(long_df):\n\n from seaborn.axisgrid import FacetGrid\n\n hue_var = \"a\"\n g = FacetGrid(long_df, hue=hue_var)\n g.map(plt.plot, \"x\", \"y\")\n\n g.add_legend()\n _draw_figure(g.figure)\n\n xfm = g.figure.transFigure.inverted().transform\n old_pos = xfm(g.legend.legendPatch.get_extents())\n\n fontsize = 20\n utils.move_legend(g, \"lower left\", title_fontsize=fontsize)\n _draw_figure(g.figure)\n\n new_pos = xfm(g.legend.legendPatch.get_extents())\n assert (new_pos < old_pos).all()\n assert g.legend.get_title().get_text() == hue_var\n assert g.legend.get_title().get_size() == fontsize\n\n assert g.legend.legendHandles\n for i, h in enumerate(g.legend.legendHandles):\n assert mpl.colors.to_rgb(h.get_color()) == mpl.colors.to_rgb(f\"C{i}\")"},{"col":4,"comment":"null","endLoc":189,"header":"def test_bad_scale_values_nominal(self, cat_vector)","id":4032,"name":"test_bad_scale_values_nominal","nodeType":"Function","startLoc":186,"text":"def test_bad_scale_values_nominal(self, cat_vector):\n\n with pytest.raises(TypeError, match=\"Scale values for color with a Nominal\"):\n Color().get_mapping(Nominal(get_colormap(\"viridis\")), cat_vector)"},{"col":4,"comment":"null","endLoc":415,"header":"def test_color_numeric_data(self, y)","id":4033,"name":"test_color_numeric_data","nodeType":"Function","startLoc":411,"text":"def test_color_numeric_data(self, y):\n\n s = Nominal()._setup(y, Color())\n cs = color_palette()\n assert_array_equal(s(y), [cs[1], cs[0], cs[2], cs[0]])"},{"col":4,"comment":"null","endLoc":194,"header":"def test_bad_inference_arg(self, cat_vector)","id":4034,"name":"test_bad_inference_arg","nodeType":"Function","startLoc":191,"text":"def test_bad_inference_arg(self, cat_vector):\n\n with pytest.raises(TypeError, match=\"A single scale argument for color\"):\n Color().infer_scale(123, cat_vector)"},{"col":4,"comment":"null","endLoc":203,"header":"@pytest.mark.parametrize(\n \"data_type,scale_class\",\n [(\"cat\", Nominal), (\"num\", Continuous)]\n )\n def test_default(self, data_type, scale_class, vectors)","id":4035,"name":"test_default","nodeType":"Function","startLoc":196,"text":"@pytest.mark.parametrize(\n \"data_type,scale_class\",\n [(\"cat\", Nominal), (\"num\", Continuous)]\n )\n def test_default(self, data_type, scale_class, vectors):\n\n scale = Color().default_scale(vectors[data_type])\n assert isinstance(scale, scale_class)"},{"col":4,"comment":"null","endLoc":422,"header":"def test_color_numeric_with_order_subset(self, y)","id":4036,"name":"test_color_numeric_with_order_subset","nodeType":"Function","startLoc":417,"text":"def test_color_numeric_with_order_subset(self, y):\n\n s = Nominal(order=[-1.5, 1])._setup(y, Color())\n c1, c2 = color_palette(n_colors=2)\n null = (np.nan, np.nan, np.nan)\n assert_array_equal(s(y), [c2, c1, null, c1])"},{"col":4,"comment":"null","endLoc":208,"header":"def test_default_numeric_data_category_dtype(self, num_vector)","id":4037,"name":"test_default_numeric_data_category_dtype","nodeType":"Function","startLoc":205,"text":"def test_default_numeric_data_category_dtype(self, num_vector):\n\n scale = Color().default_scale(num_vector.astype(\"category\"))\n assert isinstance(scale, Nominal)"},{"col":4,"comment":"null","endLoc":431,"header":"@pytest.mark.xfail(reason=\"Need to sort out float/int order\")\n def test_color_numeric_int_float_mix(self)","id":4038,"name":"test_color_numeric_int_float_mix","nodeType":"Function","startLoc":424,"text":"@pytest.mark.xfail(reason=\"Need to sort out float/int order\")\n def test_color_numeric_int_float_mix(self):\n\n z = pd.Series([1, 2], name=\"z\")\n s = Nominal(order=[1.0, 2])._setup(z, Color())\n c1, c2 = color_palette(n_colors=2)\n null = (np.nan, np.nan, np.nan)\n assert_array_equal(s(z), [c1, null, c2])"},{"col":0,"comment":"null","endLoc":425,"header":"def test_move_legend_input_checks()","id":4039,"name":"test_move_legend_input_checks","nodeType":"Function","startLoc":415,"text":"def test_move_legend_input_checks():\n\n ax = plt.figure().subplots()\n with pytest.raises(TypeError):\n utils.move_legend(ax.xaxis, \"best\")\n\n with pytest.raises(ValueError):\n utils.move_legend(ax, \"best\")\n\n with pytest.raises(ValueError):\n utils.move_legend(ax.figure, \"best\")"},{"col":4,"comment":"null","endLoc":437,"header":"def test_color_alpha_in_palette(self, x)","id":4040,"name":"test_color_alpha_in_palette","nodeType":"Function","startLoc":433,"text":"def test_color_alpha_in_palette(self, x):\n\n cs = [(.2, .2, .3, .5), (.1, .2, .3, 1), (.5, .6, .2, 0)]\n s = Nominal(cs)._setup(x, Color())\n assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])"},{"col":0,"comment":"null","endLoc":430,"header":"def check_load_dataset(name)","id":4041,"name":"check_load_dataset","nodeType":"Function","startLoc":428,"text":"def check_load_dataset(name):\n ds = load_dataset(name, cache=False)\n assert isinstance(ds, pd.DataFrame)"},{"col":0,"comment":"null","endLoc":441,"header":"def check_load_cached_dataset(name)","id":4042,"name":"check_load_cached_dataset","nodeType":"Function","startLoc":433,"text":"def check_load_cached_dataset(name):\n # Test the caching using a temporary file.\n with tempfile.TemporaryDirectory() as tmpdir:\n # download and cache\n ds = load_dataset(name, cache=True, data_home=tmpdir)\n\n # use cached version\n ds2 = load_dataset(name, cache=True, data_home=tmpdir)\n assert_frame_equal(ds, ds2)"},{"col":4,"comment":"null","endLoc":444,"header":"def test_color_unknown_palette(self, x)","id":4043,"name":"test_color_unknown_palette","nodeType":"Function","startLoc":439,"text":"def test_color_unknown_palette(self, x):\n\n pal = \"not_a_palette\"\n err = f\"{pal} is not a valid palette name\"\n with pytest.raises(ValueError, match=err):\n Nominal(pal)._setup(x, Color())"},{"col":4,"comment":"null","endLoc":214,"header":"def test_default_binary_data(self)","id":4044,"name":"test_default_binary_data","nodeType":"Function","startLoc":210,"text":"def test_default_binary_data(self):\n\n x = pd.Series([0, 0, 1, 0, 1], dtype=int)\n scale = Color().default_scale(x)\n assert isinstance(scale, Continuous)"},{"fileName":"distributions.py","filePath":"seaborn","id":4045,"nodeType":"File","text":"\"\"\"Plotting functions for visualizing distributions.\"\"\"\nfrom numbers import Number\nfrom functools import partial\nimport math\nimport textwrap\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as tx\nfrom matplotlib.colors import to_rgba\nfrom matplotlib.collections import LineCollection\n\nfrom ._oldcore import (\n VectorPlotter,\n)\n\n# We have moved univariate histogram computation over to the new Hist class,\n# but still use the older Histogram for bivariate computation.\nfrom ._statistics import ECDF, Histogram, KDE\nfrom ._stats.histogram import Hist\n\nfrom .axisgrid import (\n FacetGrid,\n _facet_docs,\n)\nfrom .utils import (\n remove_na,\n _kde_support,\n _normalize_kwargs,\n _check_argument,\n _assign_default_kwargs,\n _default_color,\n)\nfrom .palettes import color_palette\nfrom .external import husl\nfrom .external.kde import gaussian_kde\nfrom ._docstrings import (\n DocstringComponents,\n _core_docs,\n)\n\n\n__all__ = [\"displot\", \"histplot\", \"kdeplot\", \"ecdfplot\", \"rugplot\", \"distplot\"]\n\n# ==================================================================================== #\n# Module documentation\n# ==================================================================================== #\n\n_dist_params = dict(\n\n multiple=\"\"\"\nmultiple : {{\"layer\", \"stack\", \"fill\"}}\n Method for drawing multiple elements when semantic mapping creates subsets.\n Only relevant with univariate data.\n \"\"\",\n log_scale=\"\"\"\nlog_scale : bool or number, or pair of bools or numbers\n Set axis scale(s) to log. A single value sets the data axis for univariate\n distributions and both axes for bivariate distributions. A pair of values\n sets each axis independently. Numeric values are interpreted as the desired\n base (default 10). If `False`, defer to the existing Axes scale.\n \"\"\",\n legend=\"\"\"\nlegend : bool\n If False, suppress the legend for semantic variables.\n \"\"\",\n cbar=\"\"\"\ncbar : bool\n If True, add a colorbar to annotate the color mapping in a bivariate plot.\n Note: Does not currently support plots with a ``hue`` variable well.\n \"\"\",\n cbar_ax=\"\"\"\ncbar_ax : :class:`matplotlib.axes.Axes`\n Pre-existing axes for the colorbar.\n \"\"\",\n cbar_kws=\"\"\"\ncbar_kws : dict\n Additional parameters passed to :meth:`matplotlib.figure.Figure.colorbar`.\n \"\"\",\n)\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n facets=DocstringComponents(_facet_docs),\n dist=DocstringComponents(_dist_params),\n kde=DocstringComponents.from_function_params(KDE.__init__),\n hist=DocstringComponents.from_function_params(Histogram.__init__),\n ecdf=DocstringComponents.from_function_params(ECDF.__init__),\n)\n\n\n# ==================================================================================== #\n# Internal API\n# ==================================================================================== #\n\n\nclass _DistributionPlotter(VectorPlotter):\n\n semantics = \"x\", \"y\", \"hue\", \"weights\"\n\n wide_structure = {\"x\": \"@values\", \"hue\": \"@columns\"}\n flat_structure = {\"x\": \"@values\"}\n\n def __init__(\n self,\n data=None,\n variables={},\n ):\n\n super().__init__(data=data, variables=variables)\n\n @property\n def univariate(self):\n \"\"\"Return True if only x or y are used.\"\"\"\n # TODO this could go down to core, but putting it here now.\n # We'd want to be conceptually clear that univariate only applies\n # to x/y and not to other semantics, which can exist.\n # We haven't settled on a good conceptual name for x/y.\n return bool({\"x\", \"y\"} - set(self.variables))\n\n @property\n def data_variable(self):\n \"\"\"Return the variable with data for univariate plots.\"\"\"\n # TODO This could also be in core, but it should have a better name.\n if not self.univariate:\n raise AttributeError(\"This is not a univariate plot\")\n return {\"x\", \"y\"}.intersection(self.variables).pop()\n\n @property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n # TODO see above points about where this should go\n return bool({\"x\", \"y\"} & set(self.variables))\n\n def _add_legend(\n self,\n ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,\n ):\n \"\"\"Add artists that reflect semantic mappings and put then in a legend.\"\"\"\n # TODO note that this doesn't handle numeric mappings like the relational plots\n handles = []\n labels = []\n for level in self._hue_map.levels:\n color = self._hue_map(level)\n\n kws = self._artist_kws(\n artist_kws, fill, element, multiple, color, alpha\n )\n\n # color gets added to the kws to workaround an issue with barplot's color\n # cycle integration but it causes problems in this context where we are\n # setting artist properties directly, so pop it off here\n if \"facecolor\" in kws:\n kws.pop(\"color\", None)\n\n handles.append(artist(**kws))\n labels.append(level)\n\n if isinstance(ax_obj, mpl.axes.Axes):\n ax_obj.legend(handles, labels, title=self.variables[\"hue\"], **legend_kws)\n else: # i.e. a FacetGrid. TODO make this better\n legend_data = dict(zip(labels, handles))\n ax_obj.add_legend(\n legend_data,\n title=self.variables[\"hue\"],\n label_order=self.var_levels[\"hue\"],\n **legend_kws\n )\n\n def _artist_kws(self, kws, fill, element, multiple, color, alpha):\n \"\"\"Handle differences between artists in filled/unfilled plots.\"\"\"\n kws = kws.copy()\n if fill:\n kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)\n kws.setdefault(\"facecolor\", to_rgba(color, alpha))\n\n if element == \"bars\":\n # Make bar() interface with property cycle correctly\n # https://github.com/matplotlib/matplotlib/issues/19385\n kws[\"color\"] = \"none\"\n\n if multiple in [\"stack\", \"fill\"] or element == \"bars\":\n kws.setdefault(\"edgecolor\", mpl.rcParams[\"patch.edgecolor\"])\n else:\n kws.setdefault(\"edgecolor\", to_rgba(color, 1))\n elif element == \"bars\":\n kws[\"facecolor\"] = \"none\"\n kws[\"edgecolor\"] = to_rgba(color, alpha)\n else:\n kws[\"color\"] = to_rgba(color, alpha)\n return kws\n\n def _quantile_to_level(self, data, quantile):\n \"\"\"Return data levels corresponding to quantile cuts of mass.\"\"\"\n isoprop = np.asarray(quantile)\n values = np.ravel(data)\n sorted_values = np.sort(values)[::-1]\n normalized_values = np.cumsum(sorted_values) / values.sum()\n idx = np.searchsorted(normalized_values, 1 - isoprop)\n levels = np.take(sorted_values, idx, mode=\"clip\")\n return levels\n\n def _cmap_from_color(self, color):\n \"\"\"Return a sequential colormap given a color seed.\"\"\"\n # Like so much else here, this is broadly useful, but keeping it\n # in this class to signify that I haven't thought overly hard about it...\n r, g, b, _ = to_rgba(color)\n h, s, _ = husl.rgb_to_husl(r, g, b)\n xx = np.linspace(-1, 1, int(1.15 * 256))[:256]\n ramp = np.zeros((256, 3))\n ramp[:, 0] = h\n ramp[:, 1] = s * np.cos(xx)\n ramp[:, 2] = np.linspace(35, 80, 256)\n colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1)\n return mpl.colors.ListedColormap(colors[::-1])\n\n def _default_discrete(self):\n \"\"\"Find default values for discrete hist estimation based on variable type.\"\"\"\n if self.univariate:\n discrete = self.var_types[self.data_variable] == \"categorical\"\n else:\n discrete_x = self.var_types[\"x\"] == \"categorical\"\n discrete_y = self.var_types[\"y\"] == \"categorical\"\n discrete = discrete_x, discrete_y\n return discrete\n\n def _resolve_multiple(self, curves, multiple):\n \"\"\"Modify the density data structure to handle multiple densities.\"\"\"\n\n # Default baselines have all densities starting at 0\n baselines = {k: np.zeros_like(v) for k, v in curves.items()}\n\n # TODO we should have some central clearinghouse for checking if any\n # \"grouping\" (terminnology?) semantics have been assigned\n if \"hue\" not in self.variables:\n return curves, baselines\n\n if multiple in (\"stack\", \"fill\"):\n\n # Setting stack or fill means that the curves share a\n # support grid / set of bin edges, so we can make a dataframe\n # Reverse the column order to plot from top to bottom\n curves = pd.DataFrame(curves).iloc[:, ::-1]\n\n # Find column groups that are nested within col/row variables\n column_groups = {}\n for i, keyd in enumerate(map(dict, curves.columns)):\n facet_key = keyd.get(\"col\", None), keyd.get(\"row\", None)\n column_groups.setdefault(facet_key, [])\n column_groups[facet_key].append(i)\n\n baselines = curves.copy()\n for col_idxs in column_groups.values():\n cols = curves.columns[col_idxs]\n\n norm_constant = curves[cols].sum(axis=\"columns\")\n\n # Take the cumulative sum to stack\n curves[cols] = curves[cols].cumsum(axis=\"columns\")\n\n # Normalize by row sum to fill\n if multiple == \"fill\":\n curves[cols] = curves[cols].div(norm_constant, axis=\"index\")\n\n # Define where each segment starts\n baselines[cols] = curves[cols].shift(1, axis=1).fillna(0)\n\n if multiple == \"dodge\":\n\n # Account for the unique semantic (non-faceting) levels\n # This will require rethiniking if we add other semantics!\n hue_levels = self.var_levels[\"hue\"]\n n = len(hue_levels)\n for key in curves:\n level = dict(key)[\"hue\"]\n hist = curves[key].reset_index(name=\"heights\")\n level_idx = hue_levels.index(level)\n if self._log_scaled(self.data_variable):\n log_min = np.log10(hist[\"edges\"])\n log_max = np.log10(hist[\"edges\"] + hist[\"widths\"])\n log_width = (log_max - log_min) / n\n new_min = np.power(10, log_min + level_idx * log_width)\n new_max = np.power(10, log_min + (level_idx + 1) * log_width)\n hist[\"widths\"] = new_max - new_min\n hist[\"edges\"] = new_min\n else:\n hist[\"widths\"] /= n\n hist[\"edges\"] += level_idx * hist[\"widths\"]\n\n curves[key] = hist.set_index([\"edges\", \"widths\"])[\"heights\"]\n\n return curves, baselines\n\n # -------------------------------------------------------------------------------- #\n # Computation\n # -------------------------------------------------------------------------------- #\n\n def _compute_univariate_density(\n self,\n data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular=True,\n ):\n\n # Initialize the estimator object\n estimator = KDE(**estimate_kws)\n\n if set(self.variables) - {\"x\", \"y\"}:\n if common_grid:\n all_observations = self.comp_data.dropna()\n estimator.define_support(all_observations[data_variable])\n else:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n if common_norm and \"weights\" in all_data:\n whole_weight = all_data[\"weights\"].sum()\n else:\n whole_weight = len(all_data)\n\n densities = {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set and remove nulls\n observations = sub_data[data_variable]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n part_weight = weights.sum()\n else:\n weights = None\n part_weight = len(sub_data)\n\n # Estimate the density of observations at this level\n variance = np.nan_to_num(observations.var())\n singular = len(observations) < 2 or math.isclose(variance, 0)\n try:\n if not singular:\n # Convoluted approach needed because numerical failures\n # can manifest in a few different ways.\n density, support = estimator(observations, weights=weights)\n except np.linalg.LinAlgError:\n singular = True\n\n if singular:\n msg = (\n \"Dataset has 0 variance; skipping density estimate. \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning, stacklevel=4)\n continue\n\n if log_scale:\n support = np.power(10, support)\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= part_weight / whole_weight\n\n # Store the density for this level\n key = tuple(sub_vars.items())\n densities[key] = pd.Series(density, index=support)\n\n return densities\n\n # -------------------------------------------------------------------------------- #\n # Plotting\n # -------------------------------------------------------------------------------- #\n\n def plot_univariate_histogram(\n self,\n multiple,\n element,\n fill,\n common_norm,\n common_bins,\n shrink,\n kde,\n kde_kws,\n color,\n legend,\n line_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # -- Default keyword dicts\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n estimate_kws = {} if estimate_kws is None else estimate_kws.copy()\n\n # -- Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\", \"dodge\"], multiple)\n _check_argument(\"element\", [\"bars\", \"step\", \"poly\"], element)\n\n auto_bins_with_weights = (\n \"weights\" in self.variables\n and estimate_kws[\"bins\"] == \"auto\"\n and estimate_kws[\"binwidth\"] is None\n and not estimate_kws[\"discrete\"]\n )\n if auto_bins_with_weights:\n msg = (\n \"`bins` cannot be 'auto' when using weights. \"\n \"Setting `bins=10`, but you will likely want to adjust.\"\n )\n warnings.warn(msg, UserWarning)\n estimate_kws[\"bins\"] = 10\n\n # Simplify downstream code if we are not normalizing\n if estimate_kws[\"stat\"] == \"count\":\n common_norm = False\n\n orient = self.data_variable\n\n # Now initialize the Histogram estimator\n estimator = Hist(**estimate_kws)\n histograms = {}\n\n # Do pre-compute housekeeping related to multiple groups\n all_data = self.comp_data.dropna()\n all_weights = all_data.get(\"weights\", None)\n\n multiple_histograms = set(self.variables) - {\"x\", \"y\"}\n if multiple_histograms:\n if common_bins:\n bin_kws = estimator._define_bin_params(all_data, orient, None)\n else:\n common_norm = False\n\n if common_norm and all_weights is not None:\n whole_weight = all_weights.sum()\n else:\n whole_weight = len(all_data)\n\n # Estimate the smoothed kernel densities, for use later\n if kde:\n # TODO alternatively, clip at min/max bins?\n kde_kws.setdefault(\"cut\", 0)\n kde_kws[\"cumulative\"] = estimate_kws[\"cumulative\"]\n log_scale = self._log_scaled(self.data_variable)\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_bins,\n kde_kws,\n log_scale,\n warn_singular=False,\n )\n\n # First pass through the data to compute the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Prepare the relevant data\n key = tuple(sub_vars.items())\n orient = self.data_variable\n\n if \"weights\" in self.variables:\n sub_data[\"weight\"] = sub_data.pop(\"weights\")\n part_weight = sub_data[\"weight\"].sum()\n else:\n part_weight = len(sub_data)\n\n # Do the histogram computation\n if not (multiple_histograms and common_bins):\n bin_kws = estimator._define_bin_params(sub_data, orient, None)\n res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws))\n heights = res[estimator.stat].to_numpy()\n widths = res[\"space\"].to_numpy()\n edges = res[orient].to_numpy() - widths / 2\n\n # Convert edges back to original units for plotting\n if self._log_scaled(self.data_variable):\n widths = np.power(10, edges + widths) - np.power(10, edges)\n edges = np.power(10, edges)\n\n # Rescale the smoothed curve to match the histogram\n if kde and key in densities:\n density = densities[key]\n if estimator.cumulative:\n hist_norm = heights.max()\n else:\n hist_norm = (heights * widths).sum()\n densities[key] *= hist_norm\n\n # Pack the histogram data and metadata together\n edges = edges + (1 - shrink) / 2 * widths\n widths *= shrink\n index = pd.MultiIndex.from_arrays([\n pd.Index(edges, name=\"edges\"),\n pd.Index(widths, name=\"widths\"),\n ])\n hist = pd.Series(heights, index=index, name=\"heights\")\n\n # Apply scaling to normalize across groups\n if common_norm:\n hist *= part_weight / whole_weight\n\n # Store the finalized histogram data for future plotting\n histograms[key] = hist\n\n # Modify the histogram and density data to resolve multiple groups\n histograms, baselines = self._resolve_multiple(histograms, multiple)\n if kde:\n densities, _ = self._resolve_multiple(\n densities, None if multiple == \"dodge\" else multiple\n )\n\n # Set autoscaling-related meta\n sticky_stat = (0, 1) if multiple == \"fill\" else (0, np.inf)\n if multiple == \"fill\":\n # Filled plots should not have any margins\n bin_vals = histograms.index.to_frame()\n edges = bin_vals[\"edges\"]\n widths = bin_vals[\"widths\"]\n sticky_data = (\n edges.min(),\n edges.max() + widths.loc[edges.idxmax()]\n )\n else:\n sticky_data = []\n\n # --- Handle default visual attributes\n\n # Note: default linewidth is determined after plotting\n\n # Default alpha should depend on other parameters\n if fill:\n # Note: will need to account for other grouping semantics if added\n if \"hue\" in self.variables and multiple == \"layer\":\n default_alpha = .5 if element == \"bars\" else .25\n elif kde:\n default_alpha = .5\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n hist_artists = []\n\n # Go back through the dataset and draw the plots\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n key = tuple(sub_vars.items())\n hist = histograms[key].rename(\"heights\").reset_index()\n bottom = np.asarray(baselines[key])\n\n ax = self._get_axes(sub_vars)\n\n # Define the matplotlib attributes that depend on semantic mapping\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, element, multiple, sub_color, alpha\n )\n\n if element == \"bars\":\n\n # Use matplotlib bar plotting\n\n plot_func = ax.bar if self.data_variable == \"x\" else ax.barh\n artists = plot_func(\n hist[\"edges\"],\n hist[\"heights\"] - bottom,\n hist[\"widths\"],\n bottom,\n align=\"edge\",\n **artist_kws,\n )\n\n for bar in artists:\n if self.data_variable == \"x\":\n bar.sticky_edges.x[:] = sticky_data\n bar.sticky_edges.y[:] = sticky_stat\n else:\n bar.sticky_edges.x[:] = sticky_stat\n bar.sticky_edges.y[:] = sticky_data\n\n hist_artists.extend(artists)\n\n else:\n\n # Use either fill_between or plot to draw hull of histogram\n if element == \"step\":\n\n final = hist.iloc[-1]\n x = np.append(hist[\"edges\"], final[\"edges\"] + final[\"widths\"])\n y = np.append(hist[\"heights\"], final[\"heights\"])\n b = np.append(bottom, bottom[-1])\n\n if self.data_variable == \"x\":\n step = \"post\"\n drawstyle = \"steps-post\"\n else:\n step = \"post\" # fillbetweenx handles mapping internally\n drawstyle = \"steps-pre\"\n\n elif element == \"poly\":\n\n x = hist[\"edges\"] + hist[\"widths\"] / 2\n y = hist[\"heights\"]\n b = bottom\n\n step = None\n drawstyle = None\n\n if self.data_variable == \"x\":\n if fill:\n artist = ax.fill_between(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_data\n artist.sticky_edges.y[:] = sticky_stat\n else:\n if fill:\n artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_stat\n artist.sticky_edges.y[:] = sticky_data\n\n hist_artists.append(artist)\n\n if kde:\n\n # Add in the density curves\n\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n\n if \"x\" in self.variables:\n line_args = support, density\n sticky_x, sticky_y = None, (0, np.inf)\n else:\n line_args = density, support\n sticky_x, sticky_y = (0, np.inf), None\n\n line_kws[\"color\"] = to_rgba(sub_color, 1)\n line, = ax.plot(\n *line_args, **line_kws,\n )\n\n if sticky_x is not None:\n line.sticky_edges.x[:] = sticky_x\n if sticky_y is not None:\n line.sticky_edges.y[:] = sticky_y\n\n if element == \"bars\" and \"linewidth\" not in plot_kws:\n\n # Now we handle linewidth, which depends on the scaling of the plot\n\n # We will base everything on the minimum bin width\n hist_metadata = pd.concat([\n # Use .items for generality over dict or df\n h.index.to_frame() for _, h in histograms.items()\n ]).reset_index(drop=True)\n thin_bar_idx = hist_metadata[\"widths\"].idxmin()\n binwidth = hist_metadata.loc[thin_bar_idx, \"widths\"]\n left_edge = hist_metadata.loc[thin_bar_idx, \"edges\"]\n\n # Set initial value\n default_linewidth = math.inf\n\n # Loop through subsets based only on facet variables\n for sub_vars, _ in self.iter_data():\n\n ax = self._get_axes(sub_vars)\n\n # Needed in some cases to get valid transforms.\n # Innocuous in other cases?\n ax.autoscale_view()\n\n # Convert binwidth from data coordinates to pixels\n pts_x, pts_y = 72 / ax.figure.dpi * abs(\n ax.transData.transform([left_edge + binwidth] * 2)\n - ax.transData.transform([left_edge] * 2)\n )\n if self.data_variable == \"x\":\n binwidth_points = pts_x\n else:\n binwidth_points = pts_y\n\n # The relative size of the lines depends on the appearance\n # This is a provisional value and may need more tweaking\n default_linewidth = min(.1 * binwidth_points, default_linewidth)\n\n # Set the attributes\n for bar in hist_artists:\n\n # Don't let the lines get too thick\n max_linewidth = bar.get_linewidth()\n if not fill:\n max_linewidth *= 1.5\n\n linewidth = min(default_linewidth, max_linewidth)\n\n # If not filling, don't let lines disappear\n if not fill:\n min_linewidth = .5\n linewidth = max(linewidth, min_linewidth)\n\n bar.set_linewidth(linewidth)\n\n # --- Finalize the plot ----\n\n # Axis labels\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = estimator.stat.capitalize()\n if self.data_variable == \"y\":\n default_x = estimator.stat.capitalize()\n self._add_axis_labels(ax, default_x, default_y)\n\n # Legend for semantic variables\n if \"hue\" in self.variables and legend:\n\n if fill or element == \"bars\":\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, element, multiple, alpha, plot_kws, {},\n )\n\n def plot_bivariate_histogram(\n self,\n common_bins, common_norm,\n thresh, pthresh, pmax,\n color, legend,\n cbar, cbar_ax, cbar_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # Default keyword dicts\n cbar_kws = {} if cbar_kws is None else cbar_kws.copy()\n\n # Now initialize the Histogram estimator\n estimator = Histogram(**estimate_kws)\n\n # Do pre-compute housekeeping related to multiple groups\n if set(self.variables) - {\"x\", \"y\"}:\n all_data = self.comp_data.dropna()\n if common_bins:\n estimator.define_bin_params(\n all_data[\"x\"],\n all_data[\"y\"],\n all_data.get(\"weights\", None),\n )\n else:\n common_norm = False\n\n # -- Determine colormap threshold and norm based on the full data\n\n full_heights = []\n for _, sub_data in self.iter_data(from_comp_data=True):\n sub_heights, _ = estimator(\n sub_data[\"x\"], sub_data[\"y\"], sub_data.get(\"weights\", None)\n )\n full_heights.append(sub_heights)\n\n common_color_norm = not set(self.variables) - {\"x\", \"y\"} or common_norm\n\n if pthresh is not None and common_color_norm:\n thresh = self._quantile_to_level(full_heights, pthresh)\n\n plot_kws.setdefault(\"vmin\", 0)\n if common_color_norm:\n if pmax is not None:\n vmax = self._quantile_to_level(full_heights, pmax)\n else:\n vmax = plot_kws.pop(\"vmax\", max(map(np.max, full_heights)))\n else:\n vmax = None\n\n # Get a default color\n # (We won't follow the color cycle here, as multiple plots are unlikely)\n if color is None:\n color = \"C0\"\n\n # --- Loop over data (subsets) and draw the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n if sub_data.empty:\n continue\n\n # Do the histogram computation\n heights, (x_edges, y_edges) = estimator(\n sub_data[\"x\"],\n sub_data[\"y\"],\n weights=sub_data.get(\"weights\", None),\n )\n\n # Check for log scaling on the data axis\n if self._log_scaled(\"x\"):\n x_edges = np.power(10, x_edges)\n if self._log_scaled(\"y\"):\n y_edges = np.power(10, y_edges)\n\n # Apply scaling to normalize across groups\n if estimator.stat != \"count\" and common_norm:\n heights *= len(sub_data) / len(all_data)\n\n # Define the specific kwargs for this artist\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n color = self._hue_map(sub_vars[\"hue\"])\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n else:\n cmap = artist_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n elif cmap is None:\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n\n # Set the upper norm on the colormap\n if not common_color_norm and pmax is not None:\n vmax = self._quantile_to_level(heights, pmax)\n if vmax is not None:\n artist_kws[\"vmax\"] = vmax\n\n # Make cells at or below the threshold transparent\n if not common_color_norm and pthresh:\n thresh = self._quantile_to_level(heights, pthresh)\n if thresh is not None:\n heights = np.ma.masked_less_equal(heights, thresh)\n\n # Get the axes for this plot\n ax = self._get_axes(sub_vars)\n\n # pcolormesh is going to turn the grid off, but we want to keep it\n # I'm not sure if there's a better way to get the grid state\n x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()])\n y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()])\n\n mesh = ax.pcolormesh(\n x_edges,\n y_edges,\n heights.T,\n **artist_kws,\n )\n\n # pcolormesh sets sticky edges, but we only want them if not thresholding\n if thresh is not None:\n mesh.sticky_edges.x[:] = []\n mesh.sticky_edges.y[:] = []\n\n # Add an optional colorbar\n # Note, we want to improve this. When hue is used, it will stack\n # multiple colorbars with redundant ticks in an ugly way.\n # But it's going to take some work to have multiple colorbars that\n # share ticks nicely.\n if cbar:\n ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws)\n\n # Reset the grid state\n if x_grid:\n ax.grid(True, axis=\"x\")\n if y_grid:\n ax.grid(True, axis=\"y\")\n\n # --- Finalize the plot\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n artist = partial(mpl.patches.Patch)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, True, False, \"layer\", 1, artist_kws, {},\n )\n\n def plot_univariate_density(\n self,\n multiple,\n common_norm,\n common_grid,\n warn_singular,\n fill,\n color,\n legend,\n estimate_kws,\n **plot_kws,\n ):\n\n # Handle conditional defaults\n if fill is None:\n fill = multiple in (\"stack\", \"fill\")\n\n # Preprocess the matplotlib keyword dictionaries\n if fill:\n artist = mpl.collections.PolyCollection\n else:\n artist = mpl.lines.Line2D\n plot_kws = _normalize_kwargs(plot_kws, artist)\n\n # Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\"], multiple)\n\n # Always share the evaluation grid when stacking\n subsets = bool(set(self.variables) - {\"x\", \"y\"})\n if subsets and multiple in (\"stack\", \"fill\"):\n common_grid = True\n\n # Check if the data axis is log scaled\n log_scale = self._log_scaled(self.data_variable)\n\n # Do the computation\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular,\n )\n\n # Adjust densities based on the `multiple` rule\n densities, baselines = self._resolve_multiple(densities, multiple)\n\n # Control the interaction with autoscaling by defining sticky_edges\n # i.e. we don't want autoscale margins below the density curve\n sticky_density = (0, 1) if multiple == \"fill\" else (0, np.inf)\n\n if multiple == \"fill\":\n # Filled plots should not have any margins\n sticky_support = densities.index.min(), densities.index.max()\n else:\n sticky_support = []\n\n if fill:\n if multiple == \"layer\":\n default_alpha = .25\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n # Now iterate through the subsets and draw the densities\n # We go backwards so stacked densities read from top-to-bottom\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n # Extract the support grid and density curve for this level\n key = tuple(sub_vars.items())\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n fill_from = baselines[key]\n\n ax = self._get_axes(sub_vars)\n\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, False, multiple, sub_color, alpha\n )\n\n # Either plot a curve with observation values on the x axis\n if \"x\" in self.variables:\n\n if fill:\n artist = ax.fill_between(support, fill_from, density, **artist_kws)\n\n else:\n artist, = ax.plot(support, density, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_support\n artist.sticky_edges.y[:] = sticky_density\n\n # Or plot a curve with observation values on the y axis\n else:\n if fill:\n artist = ax.fill_betweenx(support, fill_from, density, **artist_kws)\n else:\n artist, = ax.plot(density, support, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_density\n artist.sticky_edges.y[:] = sticky_support\n\n # --- Finalize the plot ----\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = \"Density\"\n if self.data_variable == \"y\":\n default_x = \"Density\"\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, multiple, alpha, plot_kws, {},\n )\n\n def plot_bivariate_density(\n self,\n common_norm,\n fill,\n levels,\n thresh,\n color,\n legend,\n cbar,\n warn_singular,\n cbar_ax,\n cbar_kws,\n estimate_kws,\n **contour_kws,\n ):\n\n contour_kws = contour_kws.copy()\n\n estimator = KDE(**estimate_kws)\n\n if not set(self.variables) - {\"x\", \"y\"}:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n\n # Loop through the subsets and estimate the KDEs\n densities, supports = {}, {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set\n observations = sub_data[[\"x\", \"y\"]]\n min_variance = observations.var().fillna(0).min()\n observations = observations[\"x\"], observations[\"y\"]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n else:\n weights = None\n\n # Estimate the density of observations at this level\n singular = math.isclose(min_variance, 0)\n try:\n if not singular:\n density, support = estimator(*observations, weights=weights)\n except np.linalg.LinAlgError:\n # Testing for 0 variance doesn't catch all cases where scipy raises,\n # but we can also get a ValueError, so we need this convoluted approach\n singular = True\n\n if singular:\n msg = (\n \"KDE cannot be estimated (0 variance or perfect covariance). \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning, stacklevel=3)\n continue\n\n # Transform the support grid back to the original scale\n xx, yy = support\n if self._log_scaled(\"x\"):\n xx = np.power(10, xx)\n if self._log_scaled(\"y\"):\n yy = np.power(10, yy)\n support = xx, yy\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= len(sub_data) / len(all_data)\n\n key = tuple(sub_vars.items())\n densities[key] = density\n supports[key] = support\n\n # Define a grid of iso-proportion levels\n if thresh is None:\n thresh = 0\n if isinstance(levels, Number):\n levels = np.linspace(thresh, 1, levels)\n else:\n if min(levels) < 0 or max(levels) > 1:\n raise ValueError(\"levels must be in [0, 1]\")\n\n # Transform from iso-proportions to iso-densities\n if common_norm:\n common_levels = self._quantile_to_level(\n list(densities.values()), levels,\n )\n draw_levels = {k: common_levels for k in densities}\n else:\n draw_levels = {\n k: self._quantile_to_level(d, levels)\n for k, d in densities.items()\n }\n\n # Define the coloring of the contours\n if \"hue\" in self.variables:\n for param in [\"cmap\", \"colors\"]:\n if param in contour_kws:\n msg = f\"{param} parameter ignored when using hue mapping.\"\n warnings.warn(msg, UserWarning)\n contour_kws.pop(param)\n else:\n\n # Work out a default coloring of the contours\n coloring_given = set(contour_kws) & {\"cmap\", \"colors\"}\n if fill and not coloring_given:\n cmap = self._cmap_from_color(color)\n contour_kws[\"cmap\"] = cmap\n if not fill and not coloring_given:\n contour_kws[\"colors\"] = [color]\n\n # Use our internal colormap lookup\n cmap = contour_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n if cmap is not None:\n contour_kws[\"cmap\"] = cmap\n\n # Loop through the subsets again and plot the data\n for sub_vars, _ in self.iter_data(\"hue\"):\n\n if \"hue\" in sub_vars:\n color = self._hue_map(sub_vars[\"hue\"])\n if fill:\n contour_kws[\"cmap\"] = self._cmap_from_color(color)\n else:\n contour_kws[\"colors\"] = [color]\n\n ax = self._get_axes(sub_vars)\n\n # Choose the function to plot with\n # TODO could add a pcolormesh based option as well\n # Which would look something like element=\"raster\"\n if fill:\n contour_func = ax.contourf\n else:\n contour_func = ax.contour\n\n key = tuple(sub_vars.items())\n if key not in densities:\n continue\n density = densities[key]\n xx, yy = supports[key]\n\n label = contour_kws.pop(\"label\", None)\n\n cset = contour_func(\n xx, yy, density,\n levels=draw_levels[key],\n **contour_kws,\n )\n\n if \"hue\" not in self.variables:\n cset.collections[0].set_label(label)\n\n # Add a color bar representing the contour heights\n # Note: this shows iso densities, not iso proportions\n # See more notes in histplot about how this could be improved\n if cbar:\n cbar_kws = {} if cbar_kws is None else cbar_kws\n ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)\n\n # --- Finalize the plot\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, \"layer\", 1, artist_kws, {},\n )\n\n def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws):\n\n estimator = ECDF(**estimate_kws)\n\n # Set the draw style to step the right way for the data variable\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n plot_kws[\"drawstyle\"] = drawstyles[self.data_variable]\n\n # Loop through the subsets, transform and plot the data\n for sub_vars, sub_data in self.iter_data(\n \"hue\", reverse=True, from_comp_data=True,\n ):\n\n # Compute the ECDF\n if sub_data.empty:\n continue\n\n observations = sub_data[self.data_variable]\n weights = sub_data.get(\"weights\", None)\n stat, vals = estimator(observations, weights=weights)\n\n # Assign attributes based on semantic mapping\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n artist_kws[\"color\"] = self._hue_map(sub_vars[\"hue\"])\n\n # Return the data variable to the linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(self.data_variable):\n vals = np.power(10, vals)\n vals[0] = -np.inf\n\n # Work out the orientation of the plot\n if self.data_variable == \"x\":\n plot_args = vals, stat\n stat_variable = \"y\"\n else:\n plot_args = stat, vals\n stat_variable = \"x\"\n\n if estimator.stat == \"count\":\n top_edge = len(observations)\n else:\n top_edge = 1\n\n # Draw the line for this subset\n ax = self._get_axes(sub_vars)\n artist, = ax.plot(*plot_args, **artist_kws)\n sticky_edges = getattr(artist.sticky_edges, stat_variable)\n sticky_edges[:] = 0, top_edge\n\n # --- Finalize the plot ----\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n stat = estimator.stat.capitalize()\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = stat\n if self.data_variable == \"y\":\n default_x = stat\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n artist = partial(mpl.lines.Line2D, [], [])\n alpha = plot_kws.get(\"alpha\", 1)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, False, False, None, alpha, plot_kws, {},\n )\n\n def plot_rug(self, height, expand_margins, legend, **kws):\n\n for sub_vars, sub_data, in self.iter_data(from_comp_data=True):\n\n ax = self._get_axes(sub_vars)\n\n kws.setdefault(\"linewidth\", 1)\n\n if expand_margins:\n xmarg, ymarg = ax.margins()\n if \"x\" in self.variables:\n ymarg += height * 2\n if \"y\" in self.variables:\n xmarg += height * 2\n ax.margins(x=xmarg, y=ymarg)\n\n if \"hue\" in self.variables:\n kws.pop(\"c\", None)\n kws.pop(\"color\", None)\n\n if \"x\" in self.variables:\n self._plot_single_rug(sub_data, \"x\", height, ax, kws)\n if \"y\" in self.variables:\n self._plot_single_rug(sub_data, \"y\", height, ax, kws)\n\n # --- Finalize the plot\n self._add_axis_labels(ax)\n if \"hue\" in self.variables and legend:\n # TODO ideally i'd like the legend artist to look like a rug\n legend_artist = partial(mpl.lines.Line2D, [], [])\n self._add_legend(\n ax, legend_artist, False, False, None, 1, {}, {},\n )\n\n def _plot_single_rug(self, sub_data, var, height, ax, kws):\n \"\"\"Draw a rugplot along one axis of the plot.\"\"\"\n vector = sub_data[var]\n n = len(vector)\n\n # Return data to linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(var):\n vector = np.power(10, vector)\n\n # We'll always add a single collection with varying colors\n if \"hue\" in self.variables:\n colors = self._hue_map(sub_data[\"hue\"])\n else:\n colors = None\n\n # Build the array of values for the LineCollection\n if var == \"x\":\n\n trans = tx.blended_transform_factory(ax.transData, ax.transAxes)\n xy_pairs = np.column_stack([\n np.repeat(vector, 2), np.tile([0, height], n)\n ])\n\n if var == \"y\":\n\n trans = tx.blended_transform_factory(ax.transAxes, ax.transData)\n xy_pairs = np.column_stack([\n np.tile([0, height], n), np.repeat(vector, 2)\n ])\n\n # Draw the lines on the plot\n line_segs = xy_pairs.reshape([n, 2, 2])\n ax.add_collection(LineCollection(\n line_segs, transform=trans, colors=colors, **kws\n ))\n\n ax.autoscale_view(scalex=var == \"x\", scaley=var == \"y\")\n\n\nclass _DistributionFacetPlotter(_DistributionPlotter):\n\n semantics = _DistributionPlotter.semantics + (\"col\", \"row\")\n\n\n# ==================================================================================== #\n# External API\n# ==================================================================================== #\n\ndef histplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Histogram computation parameters\n stat=\"count\", bins=\"auto\", binwidth=None, binrange=None,\n discrete=None, cumulative=False, common_bins=True, common_norm=True,\n # Histogram appearance parameters\n multiple=\"layer\", element=\"bars\", fill=True, shrink=1,\n # Histogram smoothing with a kernel density estimate\n kde=False, kde_kws=None, line_kws=None,\n # Bivariate histogram parameters\n thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n):\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, log_scale=log_scale)\n\n if p.univariate: # Note, bivariate plots won't cycle\n if fill:\n method = ax.bar if element == \"bars\" else ax.fill_between\n else:\n method = ax.plot\n color = _default_color(method, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # Default to discrete bins for categorical variables\n if discrete is None:\n discrete = p._default_discrete()\n\n estimate_kws = dict(\n stat=stat,\n bins=bins,\n binwidth=binwidth,\n binrange=binrange,\n discrete=discrete,\n cumulative=cumulative,\n )\n\n if p.univariate:\n\n p.plot_univariate_histogram(\n multiple=multiple,\n element=element,\n fill=fill,\n shrink=shrink,\n common_norm=common_norm,\n common_bins=common_bins,\n kde=kde,\n kde_kws=kde_kws,\n color=color,\n legend=legend,\n estimate_kws=estimate_kws,\n line_kws=line_kws,\n **kwargs,\n )\n\n else:\n\n p.plot_bivariate_histogram(\n common_bins=common_bins,\n common_norm=common_norm,\n thresh=thresh,\n pthresh=pthresh,\n pmax=pmax,\n color=color,\n legend=legend,\n cbar=cbar,\n cbar_ax=cbar_ax,\n cbar_kws=cbar_kws,\n estimate_kws=estimate_kws,\n **kwargs,\n )\n\n return ax\n\n\nhistplot.__doc__ = \"\"\"\\\nPlot univariate or bivariate histograms to show distributions of datasets.\n\nA histogram is a classic visualization tool that represents the distribution\nof one or more variables by counting the number of observations that fall within\ndiscrete bins.\n\nThis function can normalize the statistic computed within each bin to estimate\nfrequency, density or probability mass, and it can add a smooth curve obtained\nusing a kernel density estimate, similar to :func:`kdeplot`.\n\nMore information is provided in the :ref:`user guide `.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the contribution of the corresponding data points\n towards the count in each bin by these factors.\n{params.hist.stat}\n{params.hist.bins}\n{params.hist.binwidth}\n{params.hist.binrange}\ndiscrete : bool\n If True, default to ``binwidth=1`` and draw the bars so that they are\n centered on their corresponding data points. This avoids \"gaps\" that may\n otherwise appear when using discrete (integer) data.\ncumulative : bool\n If True, plot the cumulative counts as bins increase.\ncommon_bins : bool\n If True, use the same bins when semantic variables produce multiple\n plots. If using a reference rule to determine the bins, it will be computed\n with the full dataset.\ncommon_norm : bool\n If True and using a normalized statistic, the normalization will apply over\n the full dataset. Otherwise, normalize each histogram independently.\nmultiple : {{\"layer\", \"dodge\", \"stack\", \"fill\"}}\n Approach to resolving multiple elements when semantic mapping creates subsets.\n Only relevant with univariate data.\nelement : {{\"bars\", \"step\", \"poly\"}}\n Visual representation of the histogram statistic.\n Only relevant with univariate data.\nfill : bool\n If True, fill in the space under the histogram.\n Only relevant with univariate data.\nshrink : number\n Scale the width of each bar relative to the binwidth by this factor.\n Only relevant with univariate data.\nkde : bool\n If True, compute a kernel density estimate to smooth the distribution\n and show on the plot as (one or more) line(s).\n Only relevant with univariate data.\nkde_kws : dict\n Parameters that control the KDE computation, as in :func:`kdeplot`.\nline_kws : dict\n Parameters that control the KDE visualization, passed to\n :meth:`matplotlib.axes.Axes.plot`.\nthresh : number or None\n Cells with a statistic less than or equal to this value will be transparent.\n Only relevant with bivariate data.\npthresh : number or None\n Like ``thresh``, but a value in [0, 1] such that cells with aggregate counts\n (or other statistics, when used) up to this proportion of the total will be\n transparent.\npmax : number or None\n A value in [0, 1] that sets that saturation point for the colormap at a value\n such that cells below constitute this proportion of the total count (or\n other statistic, when used).\n{params.dist.cbar}\n{params.dist.cbar_ax}\n{params.dist.cbar_kws}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to one of the following matplotlib\n functions:\n\n - :meth:`matplotlib.axes.Axes.bar` (univariate, element=\"bars\")\n - :meth:`matplotlib.axes.Axes.fill_between` (univariate, other element, fill=True)\n - :meth:`matplotlib.axes.Axes.plot` (univariate, other element, fill=False)\n - :meth:`matplotlib.axes.Axes.pcolormesh` (bivariate)\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.kdeplot}\n{seealso.rugplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n\nNotes\n-----\n\nThe choice of bins for computing and plotting a histogram can exert\nsubstantial influence on the insights that one is able to draw from the\nvisualization. If the bins are too large, they may erase important features.\nOn the other hand, bins that are too small may be dominated by random\nvariability, obscuring the shape of the true underlying distribution. The\ndefault bin size is determined using a reference rule that depends on the\nsample size and variance. This works well in many cases, (i.e., with\n\"well-behaved\" data) but it fails in others. It is always a good to try\ndifferent bin sizes to be sure that you are not missing something important.\nThis function allows you to specify bins in several different ways, such as\nby setting the total number of bins to use, the width of each bin, or the\nspecific locations where the bins should break.\n\nExamples\n--------\n\n.. include:: ../docstrings/histplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef kdeplot(\n data=None, *, x=None, y=None, hue=None, weights=None,\n palette=None, hue_order=None, hue_norm=None, color=None, fill=None,\n multiple=\"layer\", common_norm=True, common_grid=False, cumulative=False,\n bw_method=\"scott\", bw_adjust=1, warn_singular=True, log_scale=None,\n levels=10, thresh=.05, gridsize=200, cut=3, clip=None,\n legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None,\n **kwargs,\n):\n\n # --- Start with backwards compatability for versions < 0.11.0 ----------------\n\n # Handle (past) deprecation of `data2`\n if \"data2\" in kwargs:\n msg = \"`data2` has been removed (replaced by `y`); please update your code.\"\n TypeError(msg)\n\n # Handle deprecation of `vertical`\n vertical = kwargs.pop(\"vertical\", None)\n if vertical is not None:\n if vertical:\n action_taken = \"assigning data to `y`.\"\n if x is None:\n data, y = y, data\n else:\n x, y = y, x\n else:\n action_taken = \"assigning data to `x`.\"\n msg = textwrap.dedent(f\"\"\"\\n\n The `vertical` parameter is deprecated; {action_taken}\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Handle deprecation of `bw`\n bw = kwargs.pop(\"bw\", None)\n if bw is not None:\n msg = textwrap.dedent(f\"\"\"\\n\n The `bw` parameter is deprecated in favor of `bw_method` and `bw_adjust`.\n Setting `bw_method={bw}`, but please see the docs for the new parameters\n and update your code. This will become an error in seaborn v0.13.0.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n bw_method = bw\n\n # Handle deprecation of `kernel`\n if kwargs.pop(\"kernel\", None) is not None:\n msg = textwrap.dedent(\"\"\"\\n\n Support for alternate kernels has been removed; using Gaussian kernel.\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Handle deprecation of shade_lowest\n shade_lowest = kwargs.pop(\"shade_lowest\", None)\n if shade_lowest is not None:\n if shade_lowest:\n thresh = 0\n msg = textwrap.dedent(f\"\"\"\\n\n `shade_lowest` has been replaced by `thresh`; setting `thresh={thresh}.\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # Handle \"soft\" deprecation of shade `shade` is not really the right\n # terminology here, but unlike some of the other deprecated parameters it\n # is probably very commonly used and much hard to remove. This is therefore\n # going to be a longer process where, first, `fill` will be introduced and\n # be used throughout the documentation. In 0.12, when kwarg-only\n # enforcement hits, we can remove the shade/shade_lowest out of the\n # function signature all together and pull them out of the kwargs. Then we\n # can actually fire a FutureWarning, and eventually remove.\n shade = kwargs.pop(\"shade\", None)\n if shade is not None:\n fill = shade\n msg = textwrap.dedent(f\"\"\"\\n\n `shade` is now deprecated in favor of `fill`; setting `fill={shade}`.\n This will become an error in seaborn v0.14.0; please update your code.\n \"\"\")\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n # Handle `n_levels`\n # This was never in the formal API but it was processed, and appeared in an\n # example. We can treat as an alias for `levels` now and deprecate later.\n levels = kwargs.pop(\"n_levels\", levels)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals()),\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, allowed_types=[\"numeric\", \"datetime\"], log_scale=log_scale)\n\n method = ax.fill_between if fill else ax.plot\n color = _default_color(method, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # Pack the kwargs for statistics.KDE\n estimate_kws = dict(\n bw_method=bw_method,\n bw_adjust=bw_adjust,\n gridsize=gridsize,\n cut=cut,\n clip=clip,\n cumulative=cumulative,\n )\n\n if p.univariate:\n\n plot_kws = kwargs.copy()\n\n p.plot_univariate_density(\n multiple=multiple,\n common_norm=common_norm,\n common_grid=common_grid,\n fill=fill,\n color=color,\n legend=legend,\n warn_singular=warn_singular,\n estimate_kws=estimate_kws,\n **plot_kws,\n )\n\n else:\n\n p.plot_bivariate_density(\n common_norm=common_norm,\n fill=fill,\n levels=levels,\n thresh=thresh,\n legend=legend,\n color=color,\n warn_singular=warn_singular,\n cbar=cbar,\n cbar_ax=cbar_ax,\n cbar_kws=cbar_kws,\n estimate_kws=estimate_kws,\n **kwargs,\n )\n\n return ax\n\n\nkdeplot.__doc__ = \"\"\"\\\nPlot univariate or bivariate distributions using kernel density estimation.\n\nA kernel density estimate (KDE) plot is a method for visualizing the\ndistribution of observations in a dataset, analogous to a histogram. KDE\nrepresents the data using a continuous probability density curve in one or\nmore dimensions.\n\nThe approach is explained further in the :ref:`user guide `.\n\nRelative to a histogram, KDE can produce a plot that is less cluttered and\nmore interpretable, especially when drawing multiple distributions. But it\nhas the potential to introduce distortions if the underlying distribution is\nbounded or not smooth. Like a histogram, the quality of the representation\nalso depends on the selection of good smoothing parameters.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the kernel density estimation using these values.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\nfill : bool or None\n If True, fill in the area under univariate density curves or between\n bivariate contours. If None, the default depends on ``multiple``.\n{params.dist.multiple}\ncommon_norm : bool\n If True, scale each conditional density by the number of observations\n such that the total area under all densities sums to 1. Otherwise,\n normalize each density independently.\ncommon_grid : bool\n If True, use the same evaluation grid for each kernel density estimate.\n Only relevant with univariate data.\n{params.kde.cumulative}\n{params.kde.bw_method}\n{params.kde.bw_adjust}\nwarn_singular : bool\n If True, issue a warning when trying to estimate the density of data\n with zero variance.\n{params.dist.log_scale}\nlevels : int or vector\n Number of contour levels or values to draw contours at. A vector argument\n must have increasing values in [0, 1]. Levels correspond to iso-proportions\n of the density: e.g., 20% of the probability mass will lie below the\n contour drawn for 0.2. Only relevant with bivariate data.\nthresh : number in [0, 1]\n Lowest iso-proportion level at which to draw a contour line. Ignored when\n ``levels`` is a vector. Only relevant with bivariate data.\ngridsize : int\n Number of points on each dimension of the evaluation grid.\n{params.kde.cut}\n{params.kde.clip}\n{params.dist.legend}\n{params.dist.cbar}\n{params.dist.cbar_ax}\n{params.dist.cbar_kws}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to one of the following matplotlib\n functions:\n\n - :meth:`matplotlib.axes.Axes.plot` (univariate, ``fill=False``),\n - :meth:`matplotlib.axes.Axes.fill_between` (univariate, ``fill=True``),\n - :meth:`matplotlib.axes.Axes.contour` (bivariate, ``fill=False``),\n - :meth:`matplotlib.axes.contourf` (bivariate, ``fill=True``).\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.histplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n{seealso.violinplot}\n\nNotes\n-----\n\nThe *bandwidth*, or standard deviation of the smoothing kernel, is an\nimportant parameter. Misspecification of the bandwidth can produce a\ndistorted representation of the data. Much like the choice of bin width in a\nhistogram, an over-smoothed curve can erase true features of a\ndistribution, while an under-smoothed curve can create false features out of\nrandom variability. The rule-of-thumb that sets the default bandwidth works\nbest when the true distribution is smooth, unimodal, and roughly bell-shaped.\nIt is always a good idea to check the default behavior by using ``bw_adjust``\nto increase or decrease the amount of smoothing.\n\nBecause the smoothing algorithm uses a Gaussian kernel, the estimated density\ncurve can extend to values that do not make sense for a particular dataset.\nFor example, the curve may be drawn over negative values when smoothing data\nthat are naturally positive. The ``cut`` and ``clip`` parameters can be used\nto control the extent of the curve, but datasets that have many observations\nclose to a natural boundary may be better served by a different visualization\nmethod.\n\nSimilar considerations apply when a dataset is naturally discrete or \"spiky\"\n(containing many repeated observations of the same value). Kernel density\nestimation will always produce a smooth curve, which would be misleading\nin these situations.\n\nThe units on the density axis are a common source of confusion. While kernel\ndensity estimation produces a probability distribution, the height of the curve\nat each point gives a density, not a probability. A probability can be obtained\nonly by integrating the density across a range. The curve is normalized so\nthat the integral over all possible values is 1, meaning that the scale of\nthe density axis depends on the data values.\n\nExamples\n--------\n\n.. include:: ../docstrings/kdeplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef ecdfplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Computation parameters\n stat=\"proportion\", complementary=False,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n):\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # We could support other semantics (size, style) here fairly easily\n # But it would make distplot a bit more complicated.\n # It's always possible to add features like that later, so I am going to defer.\n # It will be even easier to wait until after there is a more general/abstract\n # way to go from semantic specs to artist attributes.\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, log_scale=log_scale)\n\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # We could add this one day, but it's of dubious value\n if not p.univariate:\n raise NotImplementedError(\"Bivariate ECDF plots are not implemented\")\n\n estimate_kws = dict(\n stat=stat,\n complementary=complementary,\n )\n\n p.plot_univariate_ecdf(\n estimate_kws=estimate_kws,\n legend=legend,\n **kwargs,\n )\n\n return ax\n\n\necdfplot.__doc__ = \"\"\"\\\nPlot empirical cumulative distribution functions.\n\nAn ECDF represents the proportion or count of observations falling below each\nunique value in a dataset. Compared to a histogram or density plot, it has the\nadvantage that each observation is visualized directly, meaning that there are\nno binning or smoothing parameters that need to be adjusted. It also aids direct\ncomparisons between multiple distributions. A downside is that the relationship\nbetween the appearance of the plot and the basic properties of the distribution\n(such as its central tendency, variance, and the presence of any bimodality)\nmay not be as intuitive.\n\nMore information is provided in the :ref:`user guide `.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the contribution of the corresponding data points\n towards the cumulative distribution using these values.\n{params.ecdf.stat}\n{params.ecdf.complementary}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.plot`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.histplot}\n{seealso.kdeplot}\n{seealso.rugplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/ecdfplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef rugplot(\n data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True,\n palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs\n):\n\n # A note: I think it would make sense to add multiple= to rugplot and allow\n # rugs for different hue variables to be shifted orthogonal to the data axis\n # But is this stacking, or dodging?\n\n # A note: if we want to add a style semantic to rugplot,\n # we could make an option that draws the rug using scatterplot\n\n # A note, it would also be nice to offer some kind of histogram/density\n # rugplot, since alpha blending doesn't work great in the large n regime\n\n # --- Start with backwards compatability for versions < 0.11.0 ----------------\n\n a = kwargs.pop(\"a\", None)\n axis = kwargs.pop(\"axis\", None)\n\n if a is not None:\n data = a\n msg = textwrap.dedent(\"\"\"\\n\n The `a` parameter has been replaced; use `x`, `y`, and/or `data` instead.\n Please update your code; This will become an error in seaborn v0.13.0.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n if axis is not None:\n if axis == \"x\":\n x = data\n elif axis == \"y\":\n y = data\n msg = textwrap.dedent(f\"\"\"\\n\n The `axis` parameter has been deprecated; use the `{axis}` parameter instead.\n Please update your code; this will become an error in seaborn v0.13.0.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n vertical = kwargs.pop(\"vertical\", None)\n if vertical is not None:\n if vertical:\n action_taken = \"assigning data to `y`.\"\n if x is None:\n data, y = y, data\n else:\n x, y = y, x\n else:\n action_taken = \"assigning data to `x`.\"\n msg = textwrap.dedent(f\"\"\"\\n\n The `vertical` parameter is deprecated; {action_taken}\n This will become an error in seaborn v0.13.0; please update your code.\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n\n weights = None\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals()),\n )\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax)\n\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n p.plot_rug(height, expand_margins, legend, **kwargs)\n\n return ax\n\n\nrugplot.__doc__ = \"\"\"\\\nPlot marginal distributions by drawing ticks along the x and y axes.\n\nThis function is intended to complement other plots by showing the location\nof individual observations in an unobtrusive way.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nheight : float\n Proportion of axes extent covered by each rug element. Can be negative.\nexpand_margins : bool\n If True, increase the axes margins by the height of the rug to avoid\n overlap with other elements.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\nlegend : bool\n If False, do not add a legend for semantic variables.\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to\n :meth:`matplotlib.collections.LineCollection`\n\nReturns\n-------\n{returns.ax}\n\nExamples\n--------\n\n.. include:: ../docstrings/rugplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef displot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, row=None, col=None, weights=None,\n # Other plot parameters\n kind=\"hist\", rug=False, rug_kws=None, log_scale=None, legend=True,\n # Hue-mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Faceting parameters\n col_wrap=None, row_order=None, col_order=None,\n height=5, aspect=1, facet_kws=None,\n **kwargs,\n):\n\n p = _DistributionFacetPlotter(\n data=data,\n variables=_DistributionFacetPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n _check_argument(\"kind\", [\"hist\", \"kde\", \"ecdf\"], kind)\n\n # --- Initialize the FacetGrid object\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\n \"`displot` is a figure-level function and does not accept \"\n \"the ax= parameter. You may wish to try {}plot.\".format(kind)\n )\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n\n # Adapt the plot_data dataframe for use with FacetGrid\n grid_data = p.plot_data.rename(columns=p.variables)\n grid_data = grid_data.loc[:, ~grid_data.columns.duplicated()]\n\n col_name = p.variables.get(\"col\")\n row_name = p.variables.get(\"row\")\n\n if facet_kws is None:\n facet_kws = {}\n\n g = FacetGrid(\n data=grid_data, row=row_name, col=col_name,\n col_wrap=col_wrap, row_order=row_order,\n col_order=col_order, height=height,\n aspect=aspect,\n **facet_kws,\n )\n\n # Now attach the axes object to the plotter object\n if kind == \"kde\":\n allowed_types = [\"numeric\", \"datetime\"]\n else:\n allowed_types = None\n p._attach(g, allowed_types=allowed_types, log_scale=log_scale)\n\n # Check for a specification that lacks x/y data and return early\n if not p.has_xy_data:\n return g\n\n if color is None and hue is None:\n color = \"C0\"\n # XXX else warn if hue is not None?\n\n kwargs[\"legend\"] = legend\n\n # --- Draw the plots\n\n if kind == \"hist\":\n\n hist_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to Histogram\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, Histogram.__init__, histplot)\n\n estimate_kws = {}\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = hist_kws.pop(key, default_val)\n\n # Handle derivative defaults\n if estimate_kws[\"discrete\"] is None:\n estimate_kws[\"discrete\"] = p._default_discrete()\n\n hist_kws[\"estimate_kws\"] = estimate_kws\n\n hist_kws.setdefault(\"color\", color)\n\n if p.univariate:\n\n _assign_default_kwargs(hist_kws, p.plot_univariate_histogram, histplot)\n p.plot_univariate_histogram(**hist_kws)\n\n else:\n\n _assign_default_kwargs(hist_kws, p.plot_bivariate_histogram, histplot)\n p.plot_bivariate_histogram(**hist_kws)\n\n elif kind == \"kde\":\n\n kde_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to KDE\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, KDE.__init__, kdeplot)\n\n estimate_kws = {}\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = kde_kws.pop(key, default_val)\n\n kde_kws[\"estimate_kws\"] = estimate_kws\n kde_kws[\"color\"] = color\n\n if p.univariate:\n\n _assign_default_kwargs(kde_kws, p.plot_univariate_density, kdeplot)\n p.plot_univariate_density(**kde_kws)\n\n else:\n\n _assign_default_kwargs(kde_kws, p.plot_bivariate_density, kdeplot)\n p.plot_bivariate_density(**kde_kws)\n\n elif kind == \"ecdf\":\n\n ecdf_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to the estimator\n estimate_kws = {}\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, ECDF.__init__, ecdfplot)\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = ecdf_kws.pop(key, default_val)\n\n ecdf_kws[\"estimate_kws\"] = estimate_kws\n ecdf_kws[\"color\"] = color\n\n if p.univariate:\n\n _assign_default_kwargs(ecdf_kws, p.plot_univariate_ecdf, ecdfplot)\n p.plot_univariate_ecdf(**ecdf_kws)\n\n else:\n\n raise NotImplementedError(\"Bivariate ECDF plots are not implemented\")\n\n # All plot kinds can include a rug\n if rug:\n # TODO with expand_margins=True, each facet expands margins... annoying!\n if rug_kws is None:\n rug_kws = {}\n _assign_default_kwargs(rug_kws, p.plot_rug, rugplot)\n rug_kws[\"legend\"] = False\n if color is not None:\n rug_kws[\"color\"] = color\n p.plot_rug(**rug_kws)\n\n # Call FacetGrid annotation methods\n # Note that the legend is currently set inside the plotting method\n g.set_axis_labels(\n x_var=p.variables.get(\"x\", g.axes.flat[0].get_xlabel()),\n y_var=p.variables.get(\"y\", g.axes.flat[0].get_ylabel()),\n )\n g.set_titles()\n g.tight_layout()\n\n if data is not None and (x is not None or y is not None):\n if not isinstance(data, pd.DataFrame):\n data = pd.DataFrame(data)\n g.data = pd.merge(\n data,\n g.data[g.data.columns.difference(data.columns)],\n left_index=True,\n right_index=True,\n )\n else:\n wide_cols = {\n k: f\"_{k}_\" if v is None else v for k, v in p.variables.items()\n }\n g.data = p.plot_data.rename(columns=wide_cols)\n\n return g\n\n\ndisplot.__doc__ = \"\"\"\\\nFigure-level interface for drawing distribution plots onto a FacetGrid.\n\nThis function provides access to several approaches for visualizing the\nunivariate or bivariate distribution of data, including subsets of data\ndefined by semantic mapping and faceting across multiple subplots. The\n``kind`` parameter selects the approach to use:\n\n- :func:`histplot` (with ``kind=\"hist\"``; the default)\n- :func:`kdeplot` (with ``kind=\"kde\"``)\n- :func:`ecdfplot` (with ``kind=\"ecdf\"``; univariate-only)\n\nAdditionally, a :func:`rugplot` can be added to any kind of plot to show\nindividual observations.\n\nExtra keyword arguments are passed to the underlying function, so you should\nrefer to the documentation for each to understand the complete set of options\nfor making plots with this interface.\n\nSee the :doc:`distribution plots tutorial <../tutorial/distributions>` for a more\nin-depth discussion of the relative strengths and weaknesses of each approach.\nThe distinction between figure-level and axes-level functions is explained\nfurther in the :doc:`user guide <../tutorial/function_overview>`.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\n{params.facets.rowcol}\nkind : {{\"hist\", \"kde\", \"ecdf\"}}\n Approach for visualizing the data. Selects the underlying plotting function\n and determines the additional set of valid parameters.\nrug : bool\n If True, show each observation with marginal ticks (as in :func:`rugplot`).\nrug_kws : dict\n Parameters to control the appearance of the rug plot.\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\n{params.facets.col_wrap}\n{params.facets.rowcol_order}\n{params.facets.height}\n{params.facets.aspect}\n{params.facets.facet_kws}\nkwargs\n Other keyword arguments are documented with the relevant axes-level function:\n\n - :func:`histplot` (with ``kind=\"hist\"``)\n - :func:`kdeplot` (with ``kind=\"kde\"``)\n - :func:`ecdfplot` (with ``kind=\"ecdf\"``)\n\nReturns\n-------\n{returns.facetgrid}\n\nSee Also\n--------\n{seealso.histplot}\n{seealso.kdeplot}\n{seealso.rugplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n\nExamples\n--------\n\nSee the API documentation for the axes-level functions for more details\nabout the breadth of options available for each plot kind.\n\n.. include:: ../docstrings/displot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\n# =========================================================================== #\n# DEPRECATED FUNCTIONS LIVE BELOW HERE\n# =========================================================================== #\n\n\ndef _freedman_diaconis_bins(a):\n \"\"\"Calculate number of hist bins using Freedman-Diaconis rule.\"\"\"\n # From https://stats.stackexchange.com/questions/798/\n a = np.asarray(a)\n if len(a) < 2:\n return 1\n iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25]))\n h = 2 * iqr / (len(a) ** (1 / 3))\n # fall back to sqrt(a) bins if iqr is 0\n if h == 0:\n return int(np.sqrt(a.size))\n else:\n return int(np.ceil((a.max() - a.min()) / h))\n\n\ndef distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None,\n hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,\n color=None, vertical=False, norm_hist=False, axlabel=None,\n label=None, ax=None, x=None):\n \"\"\"\n DEPRECATED\n\n This function has been deprecated and will be removed in seaborn v0.14.0.\n It has been replaced by :func:`histplot` and :func:`displot`, two functions\n with a modern API and many more capabilities.\n\n For a guide to updating, please see this notebook:\n\n https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751\n\n \"\"\"\n\n if kde and not hist:\n axes_level_suggestion = (\n \"`kdeplot` (an axes-level function for kernel density plots)\"\n )\n else:\n axes_level_suggestion = (\n \"`histplot` (an axes-level function for histograms)\"\n )\n\n msg = textwrap.dedent(f\"\"\"\n\n `distplot` is a deprecated function and will be removed in seaborn v0.14.0.\n\n Please adapt your code to use either `displot` (a figure-level function with\n similar flexibility) or {axes_level_suggestion}.\n\n For a guide to updating your code to use the new functions, please see\n https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751\n \"\"\")\n warnings.warn(msg, UserWarning, stacklevel=2)\n\n if ax is None:\n ax = plt.gca()\n\n # Intelligently label the support axis\n label_ax = bool(axlabel)\n if axlabel is None and hasattr(a, \"name\"):\n axlabel = a.name\n if axlabel is not None:\n label_ax = True\n\n # Support new-style API\n if x is not None:\n a = x\n\n # Make a a 1-d float array\n a = np.asarray(a, float)\n if a.ndim > 1:\n a = a.squeeze()\n\n # Drop null values from array\n a = remove_na(a)\n\n # Decide if the hist is normed\n norm_hist = norm_hist or kde or (fit is not None)\n\n # Handle dictionary defaults\n hist_kws = {} if hist_kws is None else hist_kws.copy()\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n rug_kws = {} if rug_kws is None else rug_kws.copy()\n fit_kws = {} if fit_kws is None else fit_kws.copy()\n\n # Get the color from the current color cycle\n if color is None:\n if vertical:\n line, = ax.plot(0, a.mean())\n else:\n line, = ax.plot(a.mean(), 0)\n color = line.get_color()\n line.remove()\n\n # Plug the label into the right kwarg dictionary\n if label is not None:\n if hist:\n hist_kws[\"label\"] = label\n elif kde:\n kde_kws[\"label\"] = label\n elif rug:\n rug_kws[\"label\"] = label\n elif fit:\n fit_kws[\"label\"] = label\n\n if hist:\n if bins is None:\n bins = min(_freedman_diaconis_bins(a), 50)\n hist_kws.setdefault(\"alpha\", 0.4)\n hist_kws.setdefault(\"density\", norm_hist)\n\n orientation = \"horizontal\" if vertical else \"vertical\"\n hist_color = hist_kws.pop(\"color\", color)\n ax.hist(a, bins, orientation=orientation,\n color=hist_color, **hist_kws)\n if hist_color != color:\n hist_kws[\"color\"] = hist_color\n\n axis = \"y\" if vertical else \"x\"\n\n if kde:\n kde_color = kde_kws.pop(\"color\", color)\n kdeplot(**{axis: a}, ax=ax, color=kde_color, **kde_kws)\n if kde_color != color:\n kde_kws[\"color\"] = kde_color\n\n if rug:\n rug_color = rug_kws.pop(\"color\", color)\n rugplot(**{axis: a}, ax=ax, color=rug_color, **rug_kws)\n if rug_color != color:\n rug_kws[\"color\"] = rug_color\n\n if fit is not None:\n\n def pdf(x):\n return fit.pdf(x, *params)\n\n fit_color = fit_kws.pop(\"color\", \"#282828\")\n gridsize = fit_kws.pop(\"gridsize\", 200)\n cut = fit_kws.pop(\"cut\", 3)\n clip = fit_kws.pop(\"clip\", (-np.inf, np.inf))\n bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1)\n x = _kde_support(a, bw, gridsize, cut, clip)\n params = fit.fit(a)\n y = pdf(x)\n if vertical:\n x, y = y, x\n ax.plot(x, y, color=fit_color, **fit_kws)\n if fit_color != \"#282828\":\n fit_kws[\"color\"] = fit_color\n\n if label_ax:\n if vertical:\n ax.set_ylabel(axlabel)\n else:\n ax.set_xlabel(axlabel)\n\n return ax\n"},{"col":4,"comment":"null","endLoc":453,"header":"def test_object_defaults(self, x)","id":4046,"name":"test_object_defaults","nodeType":"Function","startLoc":446,"text":"def test_object_defaults(self, x):\n\n class MockProperty(ObjectProperty):\n def _default_values(self, n):\n return list(\"xyz\"[:n])\n\n s = Nominal()._setup(x, MockProperty())\n assert s(x) == [\"x\", \"y\", \"z\", \"y\"]"},{"col":4,"comment":"null","endLoc":235,"header":"@pytest.mark.parametrize(\n \"values,data_type,scale_class\",\n [\n (\"viridis\", \"cat\", Nominal), # Based on variable type\n (\"viridis\", \"num\", Continuous), # Based on variable type\n (\"muted\", \"num\", Nominal), # Based on qualitative palette\n ([\"r\", \"g\", \"b\"], \"num\", Nominal), # Based on list palette\n ({2","id":4047,"name":"test_inference","nodeType":"Function","startLoc":218,"text":"@pytest.mark.parametrize(\n \"values,data_type,scale_class\",\n [\n (\"viridis\", \"cat\", Nominal), # Based on variable type\n (\"viridis\", \"num\", Continuous), # Based on variable type\n (\"muted\", \"num\", Nominal), # Based on qualitative palette\n ([\"r\", \"g\", \"b\"], \"num\", Nominal), # Based on list palette\n ({2: \"r\", 4: \"g\", 8: \"b\"}, \"num\", Nominal), # Based on dict palette\n ((\"r\", \"b\"), \"num\", Continuous), # Based on tuple / variable type\n ((\"g\", \"m\"), \"cat\", Nominal), # Based on tuple / variable type\n (get_colormap(\"inferno\"), \"num\", Continuous), # Based on callable\n ]\n )\n def test_inference(self, values, data_type, scale_class, vectors):\n\n scale = Color().infer_scale(values, vectors[data_type])\n assert isinstance(scale, scale_class)\n assert scale.values == values"},{"className":"_DistributionFacetPlotter","col":0,"comment":"null","endLoc":1367,"id":4048,"nodeType":"Class","startLoc":1365,"text":"class _DistributionFacetPlotter(_DistributionPlotter):\n\n semantics = _DistributionPlotter.semantics + (\"col\", \"row\")"},{"attributeType":"(str, str, str, str, str, str)","col":4,"comment":"null","endLoc":1367,"id":4049,"name":"semantics","nodeType":"Attribute","startLoc":1367,"text":"semantics"},{"col":4,"comment":"null","endLoc":241,"header":"def test_inference_binary_data(self)","id":4050,"name":"test_inference_binary_data","nodeType":"Function","startLoc":237,"text":"def test_inference_binary_data(self):\n\n x = pd.Series([0, 0, 1, 0, 1], dtype=int)\n scale = Color().infer_scale(\"viridis\", x)\n assert isinstance(scale, Nominal)"},{"col":4,"comment":"null","endLoc":257,"header":"def test_standardization(self)","id":4051,"name":"test_standardization","nodeType":"Function","startLoc":243,"text":"def test_standardization(self):\n\n f = Color().standardize\n assert f(\"C3\") == to_rgb(\"C3\")\n assert f(\"dodgerblue\") == to_rgb(\"dodgerblue\")\n\n assert f((.1, .2, .3)) == (.1, .2, .3)\n assert f((.1, .2, .3, .4)) == (.1, .2, .3, .4)\n\n assert f(\"#123456\") == to_rgb(\"#123456\")\n assert f(\"#12345678\") == to_rgba(\"#12345678\")\n\n if Version(mpl.__version__) >= Version(\"3.4.0\"):\n assert f(\"#123\") == to_rgb(\"#123\")\n assert f(\"#1234\") == to_rgba(\"#1234\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":46,"id":4052,"name":"__all__","nodeType":"Attribute","startLoc":46,"text":"__all__"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":52,"id":4053,"name":"_dist_params","nodeType":"Attribute","startLoc":52,"text":"_dist_params"},{"col":4,"comment":"null","endLoc":459,"header":"def test_object_list(self, x)","id":4054,"name":"test_object_list","nodeType":"Function","startLoc":455,"text":"def test_object_list(self, x):\n\n vs = [\"x\", \"y\", \"z\"]\n s = Nominal(vs)._setup(x, ObjectProperty())\n assert s(x) == [\"x\", \"y\", \"z\", \"y\"]"},{"attributeType":"null","col":0,"comment":"null","endLoc":85,"id":4055,"name":"_param_docs","nodeType":"Attribute","startLoc":85,"text":"_param_docs"},{"col":4,"comment":"null","endLoc":465,"header":"def test_object_dict(self, x)","id":4056,"name":"test_object_dict","nodeType":"Function","startLoc":461,"text":"def test_object_dict(self, x):\n\n vs = {\"a\": \"x\", \"b\": \"y\", \"c\": \"z\"}\n s = Nominal(vs)._setup(x, ObjectProperty())\n assert s(x) == [\"x\", \"z\", \"y\", \"z\"]"},{"col":0,"comment":"","endLoc":1,"header":"distributions.py#","id":4058,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Plotting functions for visualizing distributions.\"\"\"\n\n__all__ = [\"displot\", \"histplot\", \"kdeplot\", \"ecdfplot\", \"rugplot\", \"distplot\"]\n\n_dist_params = dict(\n\n multiple=\"\"\"\nmultiple : {{\"layer\", \"stack\", \"fill\"}}\n Method for drawing multiple elements when semantic mapping creates subsets.\n Only relevant with univariate data.\n \"\"\",\n log_scale=\"\"\"\nlog_scale : bool or number, or pair of bools or numbers\n Set axis scale(s) to log. A single value sets the data axis for univariate\n distributions and both axes for bivariate distributions. A pair of values\n sets each axis independently. Numeric values are interpreted as the desired\n base (default 10). If `False`, defer to the existing Axes scale.\n \"\"\",\n legend=\"\"\"\nlegend : bool\n If False, suppress the legend for semantic variables.\n \"\"\",\n cbar=\"\"\"\ncbar : bool\n If True, add a colorbar to annotate the color mapping in a bivariate plot.\n Note: Does not currently support plots with a ``hue`` variable well.\n \"\"\",\n cbar_ax=\"\"\"\ncbar_ax : :class:`matplotlib.axes.Axes`\n Pre-existing axes for the colorbar.\n \"\"\",\n cbar_kws=\"\"\"\ncbar_kws : dict\n Additional parameters passed to :meth:`matplotlib.figure.Figure.colorbar`.\n \"\"\",\n)\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n facets=DocstringComponents(_facet_docs),\n dist=DocstringComponents(_dist_params),\n kde=DocstringComponents.from_function_params(KDE.__init__),\n hist=DocstringComponents.from_function_params(Histogram.__init__),\n ecdf=DocstringComponents.from_function_params(ECDF.__init__),\n)\n\nhistplot.__doc__ = \"\"\"\\\nPlot univariate or bivariate histograms to show distributions of datasets.\n\nA histogram is a classic visualization tool that represents the distribution\nof one or more variables by counting the number of observations that fall within\ndiscrete bins.\n\nThis function can normalize the statistic computed within each bin to estimate\nfrequency, density or probability mass, and it can add a smooth curve obtained\nusing a kernel density estimate, similar to :func:`kdeplot`.\n\nMore information is provided in the :ref:`user guide `.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the contribution of the corresponding data points\n towards the count in each bin by these factors.\n{params.hist.stat}\n{params.hist.bins}\n{params.hist.binwidth}\n{params.hist.binrange}\ndiscrete : bool\n If True, default to ``binwidth=1`` and draw the bars so that they are\n centered on their corresponding data points. This avoids \"gaps\" that may\n otherwise appear when using discrete (integer) data.\ncumulative : bool\n If True, plot the cumulative counts as bins increase.\ncommon_bins : bool\n If True, use the same bins when semantic variables produce multiple\n plots. If using a reference rule to determine the bins, it will be computed\n with the full dataset.\ncommon_norm : bool\n If True and using a normalized statistic, the normalization will apply over\n the full dataset. Otherwise, normalize each histogram independently.\nmultiple : {{\"layer\", \"dodge\", \"stack\", \"fill\"}}\n Approach to resolving multiple elements when semantic mapping creates subsets.\n Only relevant with univariate data.\nelement : {{\"bars\", \"step\", \"poly\"}}\n Visual representation of the histogram statistic.\n Only relevant with univariate data.\nfill : bool\n If True, fill in the space under the histogram.\n Only relevant with univariate data.\nshrink : number\n Scale the width of each bar relative to the binwidth by this factor.\n Only relevant with univariate data.\nkde : bool\n If True, compute a kernel density estimate to smooth the distribution\n and show on the plot as (one or more) line(s).\n Only relevant with univariate data.\nkde_kws : dict\n Parameters that control the KDE computation, as in :func:`kdeplot`.\nline_kws : dict\n Parameters that control the KDE visualization, passed to\n :meth:`matplotlib.axes.Axes.plot`.\nthresh : number or None\n Cells with a statistic less than or equal to this value will be transparent.\n Only relevant with bivariate data.\npthresh : number or None\n Like ``thresh``, but a value in [0, 1] such that cells with aggregate counts\n (or other statistics, when used) up to this proportion of the total will be\n transparent.\npmax : number or None\n A value in [0, 1] that sets that saturation point for the colormap at a value\n such that cells below constitute this proportion of the total count (or\n other statistic, when used).\n{params.dist.cbar}\n{params.dist.cbar_ax}\n{params.dist.cbar_kws}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to one of the following matplotlib\n functions:\n\n - :meth:`matplotlib.axes.Axes.bar` (univariate, element=\"bars\")\n - :meth:`matplotlib.axes.Axes.fill_between` (univariate, other element, fill=True)\n - :meth:`matplotlib.axes.Axes.plot` (univariate, other element, fill=False)\n - :meth:`matplotlib.axes.Axes.pcolormesh` (bivariate)\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.kdeplot}\n{seealso.rugplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n\nNotes\n-----\n\nThe choice of bins for computing and plotting a histogram can exert\nsubstantial influence on the insights that one is able to draw from the\nvisualization. If the bins are too large, they may erase important features.\nOn the other hand, bins that are too small may be dominated by random\nvariability, obscuring the shape of the true underlying distribution. The\ndefault bin size is determined using a reference rule that depends on the\nsample size and variance. This works well in many cases, (i.e., with\n\"well-behaved\" data) but it fails in others. It is always a good to try\ndifferent bin sizes to be sure that you are not missing something important.\nThis function allows you to specify bins in several different ways, such as\nby setting the total number of bins to use, the width of each bin, or the\nspecific locations where the bins should break.\n\nExamples\n--------\n\n.. include:: ../docstrings/histplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\nkdeplot.__doc__ = \"\"\"\\\nPlot univariate or bivariate distributions using kernel density estimation.\n\nA kernel density estimate (KDE) plot is a method for visualizing the\ndistribution of observations in a dataset, analogous to a histogram. KDE\nrepresents the data using a continuous probability density curve in one or\nmore dimensions.\n\nThe approach is explained further in the :ref:`user guide `.\n\nRelative to a histogram, KDE can produce a plot that is less cluttered and\nmore interpretable, especially when drawing multiple distributions. But it\nhas the potential to introduce distortions if the underlying distribution is\nbounded or not smooth. Like a histogram, the quality of the representation\nalso depends on the selection of good smoothing parameters.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the kernel density estimation using these values.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\nfill : bool or None\n If True, fill in the area under univariate density curves or between\n bivariate contours. If None, the default depends on ``multiple``.\n{params.dist.multiple}\ncommon_norm : bool\n If True, scale each conditional density by the number of observations\n such that the total area under all densities sums to 1. Otherwise,\n normalize each density independently.\ncommon_grid : bool\n If True, use the same evaluation grid for each kernel density estimate.\n Only relevant with univariate data.\n{params.kde.cumulative}\n{params.kde.bw_method}\n{params.kde.bw_adjust}\nwarn_singular : bool\n If True, issue a warning when trying to estimate the density of data\n with zero variance.\n{params.dist.log_scale}\nlevels : int or vector\n Number of contour levels or values to draw contours at. A vector argument\n must have increasing values in [0, 1]. Levels correspond to iso-proportions\n of the density: e.g., 20% of the probability mass will lie below the\n contour drawn for 0.2. Only relevant with bivariate data.\nthresh : number in [0, 1]\n Lowest iso-proportion level at which to draw a contour line. Ignored when\n ``levels`` is a vector. Only relevant with bivariate data.\ngridsize : int\n Number of points on each dimension of the evaluation grid.\n{params.kde.cut}\n{params.kde.clip}\n{params.dist.legend}\n{params.dist.cbar}\n{params.dist.cbar_ax}\n{params.dist.cbar_kws}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to one of the following matplotlib\n functions:\n\n - :meth:`matplotlib.axes.Axes.plot` (univariate, ``fill=False``),\n - :meth:`matplotlib.axes.Axes.fill_between` (univariate, ``fill=True``),\n - :meth:`matplotlib.axes.Axes.contour` (bivariate, ``fill=False``),\n - :meth:`matplotlib.axes.contourf` (bivariate, ``fill=True``).\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.histplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n{seealso.violinplot}\n\nNotes\n-----\n\nThe *bandwidth*, or standard deviation of the smoothing kernel, is an\nimportant parameter. Misspecification of the bandwidth can produce a\ndistorted representation of the data. Much like the choice of bin width in a\nhistogram, an over-smoothed curve can erase true features of a\ndistribution, while an under-smoothed curve can create false features out of\nrandom variability. The rule-of-thumb that sets the default bandwidth works\nbest when the true distribution is smooth, unimodal, and roughly bell-shaped.\nIt is always a good idea to check the default behavior by using ``bw_adjust``\nto increase or decrease the amount of smoothing.\n\nBecause the smoothing algorithm uses a Gaussian kernel, the estimated density\ncurve can extend to values that do not make sense for a particular dataset.\nFor example, the curve may be drawn over negative values when smoothing data\nthat are naturally positive. The ``cut`` and ``clip`` parameters can be used\nto control the extent of the curve, but datasets that have many observations\nclose to a natural boundary may be better served by a different visualization\nmethod.\n\nSimilar considerations apply when a dataset is naturally discrete or \"spiky\"\n(containing many repeated observations of the same value). Kernel density\nestimation will always produce a smooth curve, which would be misleading\nin these situations.\n\nThe units on the density axis are a common source of confusion. While kernel\ndensity estimation produces a probability distribution, the height of the curve\nat each point gives a density, not a probability. A probability can be obtained\nonly by integrating the density across a range. The curve is normalized so\nthat the integral over all possible values is 1, meaning that the scale of\nthe density axis depends on the data values.\n\nExamples\n--------\n\n.. include:: ../docstrings/kdeplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\necdfplot.__doc__ = \"\"\"\\\nPlot empirical cumulative distribution functions.\n\nAn ECDF represents the proportion or count of observations falling below each\nunique value in a dataset. Compared to a histogram or density plot, it has the\nadvantage that each observation is visualized directly, meaning that there are\nno binning or smoothing parameters that need to be adjusted. It also aids direct\ncomparisons between multiple distributions. A downside is that the relationship\nbetween the appearance of the plot and the basic properties of the distribution\n(such as its central tendency, variance, and the presence of any bimodality)\nmay not be as intuitive.\n\nMore information is provided in the :ref:`user guide `.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the contribution of the corresponding data points\n towards the cumulative distribution using these values.\n{params.ecdf.stat}\n{params.ecdf.complementary}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.plot`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.histplot}\n{seealso.kdeplot}\n{seealso.rugplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/ecdfplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\nrugplot.__doc__ = \"\"\"\\\nPlot marginal distributions by drawing ticks along the x and y axes.\n\nThis function is intended to complement other plots by showing the location\nof individual observations in an unobtrusive way.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nheight : float\n Proportion of axes extent covered by each rug element. Can be negative.\nexpand_margins : bool\n If True, increase the axes margins by the height of the rug to avoid\n overlap with other elements.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\nlegend : bool\n If False, do not add a legend for semantic variables.\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to\n :meth:`matplotlib.collections.LineCollection`\n\nReturns\n-------\n{returns.ax}\n\nExamples\n--------\n\n.. include:: ../docstrings/rugplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\ndisplot.__doc__ = \"\"\"\\\nFigure-level interface for drawing distribution plots onto a FacetGrid.\n\nThis function provides access to several approaches for visualizing the\nunivariate or bivariate distribution of data, including subsets of data\ndefined by semantic mapping and faceting across multiple subplots. The\n``kind`` parameter selects the approach to use:\n\n- :func:`histplot` (with ``kind=\"hist\"``; the default)\n- :func:`kdeplot` (with ``kind=\"kde\"``)\n- :func:`ecdfplot` (with ``kind=\"ecdf\"``; univariate-only)\n\nAdditionally, a :func:`rugplot` can be added to any kind of plot to show\nindividual observations.\n\nExtra keyword arguments are passed to the underlying function, so you should\nrefer to the documentation for each to understand the complete set of options\nfor making plots with this interface.\n\nSee the :doc:`distribution plots tutorial <../tutorial/distributions>` for a more\nin-depth discussion of the relative strengths and weaknesses of each approach.\nThe distinction between figure-level and axes-level functions is explained\nfurther in the :doc:`user guide <../tutorial/function_overview>`.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\n{params.facets.rowcol}\nkind : {{\"hist\", \"kde\", \"ecdf\"}}\n Approach for visualizing the data. Selects the underlying plotting function\n and determines the additional set of valid parameters.\nrug : bool\n If True, show each observation with marginal ticks (as in :func:`rugplot`).\nrug_kws : dict\n Parameters to control the appearance of the rug plot.\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\n{params.facets.col_wrap}\n{params.facets.rowcol_order}\n{params.facets.height}\n{params.facets.aspect}\n{params.facets.facet_kws}\nkwargs\n Other keyword arguments are documented with the relevant axes-level function:\n\n - :func:`histplot` (with ``kind=\"hist\"``)\n - :func:`kdeplot` (with ``kind=\"kde\"``)\n - :func:`ecdfplot` (with ``kind=\"ecdf\"``)\n\nReturns\n-------\n{returns.facetgrid}\n\nSee Also\n--------\n{seealso.histplot}\n{seealso.kdeplot}\n{seealso.rugplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n\nExamples\n--------\n\nSee the API documentation for the axes-level functions for more details\nabout the breadth of options available for each plot kind.\n\n.. include:: ../docstrings/displot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)"},{"col":4,"comment":"null","endLoc":471,"header":"def test_object_order(self, x)","id":4059,"name":"test_object_order","nodeType":"Function","startLoc":467,"text":"def test_object_order(self, x):\n\n vs = [\"x\", \"y\", \"z\"]\n s = Nominal(vs, order=[\"c\", \"a\", \"b\"])._setup(x, ObjectProperty())\n assert s(x) == [\"y\", \"x\", \"z\", \"x\"]"},{"className":"ObjectPropertyBase","col":0,"comment":"null","endLoc":356,"id":4060,"nodeType":"Class","startLoc":260,"text":"class ObjectPropertyBase(DataFixtures):\n\n def assert_equal(self, a, b):\n\n assert self.unpack(a) == self.unpack(b)\n\n def unpack(self, x):\n return x\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_default(self, data_type, vectors):\n\n scale = self.prop().default_scale(vectors[data_type])\n assert isinstance(scale, Nominal)\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_inference_list(self, data_type, vectors):\n\n scale = self.prop().infer_scale(self.values, vectors[data_type])\n assert isinstance(scale, Nominal)\n assert scale.values == self.values\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_inference_dict(self, data_type, vectors):\n\n x = vectors[data_type]\n values = dict(zip(categorical_order(x), self.values))\n scale = self.prop().infer_scale(values, x)\n assert isinstance(scale, Nominal)\n assert scale.values == values\n\n def test_dict_missing(self, cat_vector):\n\n levels = categorical_order(cat_vector)\n values = dict(zip(levels, self.values[:-1]))\n scale = Nominal(values)\n name = self.prop.__name__.lower()\n msg = f\"No entry in {name} dictionary for {repr(levels[-1])}\"\n with pytest.raises(ValueError, match=msg):\n self.prop().get_mapping(scale, cat_vector)\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_default(self, data_type, vectors):\n\n x = vectors[data_type]\n mapping = self.prop().get_mapping(Nominal(), x)\n n = x.nunique()\n for i, expected in enumerate(self.prop()._default_values(n)):\n actual, = mapping([i])\n self.assert_equal(actual, expected)\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_from_list(self, data_type, vectors):\n\n x = vectors[data_type]\n scale = Nominal(self.values)\n mapping = self.prop().get_mapping(scale, x)\n for i, expected in enumerate(self.standardized_values):\n actual, = mapping([i])\n self.assert_equal(actual, expected)\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_from_dict(self, data_type, vectors):\n\n x = vectors[data_type]\n levels = categorical_order(x)\n values = dict(zip(levels, self.values[::-1]))\n standardized_values = dict(zip(levels, self.standardized_values[::-1]))\n\n scale = Nominal(values)\n mapping = self.prop().get_mapping(scale, x)\n for i, level in enumerate(levels):\n actual, = mapping([i])\n expected = standardized_values[level]\n self.assert_equal(actual, expected)\n\n def test_mapping_with_null_value(self, cat_vector):\n\n mapping = self.prop().get_mapping(Nominal(self.values), cat_vector)\n actual = mapping(np.array([0, np.nan, 2]))\n v0, _, v2 = self.standardized_values\n expected = [v0, self.prop.null_value, v2]\n for a, b in zip(actual, expected):\n self.assert_equal(a, b)\n\n def test_unique_default_large_n(self):\n\n n = 24\n x = pd.Series(np.arange(n))\n mapping = self.prop().get_mapping(Nominal(), x)\n assert len({self.unpack(x_i) for x_i in mapping(x)}) == n\n\n def test_bad_scale_values(self, cat_vector):\n\n var_name = self.prop.__name__.lower()\n with pytest.raises(TypeError, match=f\"Scale values for a {var_name} variable\"):\n self.prop().get_mapping(Nominal((\"o\", \"s\")), cat_vector)"},{"col":4,"comment":"null","endLoc":264,"header":"def assert_equal(self, a, b)","id":4061,"name":"assert_equal","nodeType":"Function","startLoc":262,"text":"def assert_equal(self, a, b):\n\n assert self.unpack(a) == self.unpack(b)"},{"col":4,"comment":"null","endLoc":477,"header":"def test_object_order_subset(self, x)","id":4062,"name":"test_object_order_subset","nodeType":"Function","startLoc":473,"text":"def test_object_order_subset(self, x):\n\n vs = [\"x\", \"y\"]\n s = Nominal(vs, order=[\"a\", \"c\"])._setup(x, ObjectProperty())\n assert s(x) == [\"x\", \"y\", None, \"y\"]"},{"col":4,"comment":"null","endLoc":267,"header":"def unpack(self, x)","id":4063,"name":"unpack","nodeType":"Function","startLoc":266,"text":"def unpack(self, x):\n return x"},{"col":4,"comment":"null","endLoc":273,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_default(self, data_type, vectors)","id":4064,"name":"test_default","nodeType":"Function","startLoc":269,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_default(self, data_type, vectors):\n\n scale = self.prop().default_scale(vectors[data_type])\n assert isinstance(scale, Nominal)"},{"col":4,"comment":"null","endLoc":483,"header":"def test_objects_that_are_weird(self, x)","id":4065,"name":"test_objects_that_are_weird","nodeType":"Function","startLoc":479,"text":"def test_objects_that_are_weird(self, x):\n\n vs = [(\"x\", 1), (None, None, 0), {}]\n s = Nominal(vs)._setup(x, ObjectProperty())\n assert s(x) == [vs[0], vs[1], vs[2], vs[1]]"},{"col":4,"comment":"null","endLoc":280,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_inference_list(self, data_type, vectors)","id":4066,"name":"test_inference_list","nodeType":"Function","startLoc":275,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_inference_list(self, data_type, vectors):\n\n scale = self.prop().infer_scale(self.values, vectors[data_type])\n assert isinstance(scale, Nominal)\n assert scale.values == self.values"},{"col":4,"comment":"null","endLoc":488,"header":"def test_alpha_default(self, x)","id":4068,"name":"test_alpha_default","nodeType":"Function","startLoc":485,"text":"def test_alpha_default(self, x):\n\n s = Nominal()._setup(x, Alpha())\n assert_array_equal(s(x), [.95, .625, .3, .625])"},{"col":0,"comment":"null","endLoc":448,"header":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_get_dataset_names()","id":4069,"name":"test_get_dataset_names","nodeType":"Function","startLoc":444,"text":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_get_dataset_names():\n names = get_dataset_names()\n assert names\n assert \"tips\" in names"},{"col":0,"comment":"null","endLoc":459,"header":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_datasets()","id":4070,"name":"test_load_datasets","nodeType":"Function","startLoc":451,"text":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_datasets():\n\n # Heavy test to verify that we can load all available datasets\n for name in get_dataset_names():\n # unfortunately @network somehow obscures this generator so it\n # does not get in effect, so we need to call explicitly\n # yield check_load_dataset, name\n check_load_dataset(name)"},{"col":4,"comment":"null","endLoc":289,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_inference_dict(self, data_type, vectors)","id":4071,"name":"test_inference_dict","nodeType":"Function","startLoc":282,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_inference_dict(self, data_type, vectors):\n\n x = vectors[data_type]\n values = dict(zip(categorical_order(x), self.values))\n scale = self.prop().infer_scale(values, x)\n assert isinstance(scale, Nominal)\n assert scale.values == values"},{"col":0,"comment":"null","endLoc":468,"header":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_dataset_string_error()","id":4072,"name":"test_load_dataset_string_error","nodeType":"Function","startLoc":462,"text":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_dataset_string_error():\n\n name = \"bad_name\"\n err = f\"'{name}' is not one of the example datasets.\"\n with pytest.raises(ValueError, match=err):\n load_dataset(name)"},{"col":0,"comment":"null","endLoc":476,"header":"def test_load_dataset_passed_data_error()","id":4073,"name":"test_load_dataset_passed_data_error","nodeType":"Function","startLoc":471,"text":"def test_load_dataset_passed_data_error():\n\n df = pd.DataFrame()\n err = \"This function accepts only strings\"\n with pytest.raises(TypeError, match=err):\n load_dataset(df)"},{"col":0,"comment":"null","endLoc":487,"header":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_cached_datasets()","id":4074,"name":"test_load_cached_datasets","nodeType":"Function","startLoc":479,"text":"@_network(url=\"https://github.com/mwaskom/seaborn-data\")\ndef test_load_cached_datasets():\n\n # Heavy test to verify that we can load all available datasets\n for name in get_dataset_names():\n # unfortunately @network somehow obscures this generator so it\n # does not get in effect, so we need to call explicitly\n # yield check_load_dataset, name\n check_load_cached_dataset(name)"},{"col":4,"comment":"null","endLoc":494,"header":"def test_fill(self)","id":4075,"name":"test_fill","nodeType":"Function","startLoc":490,"text":"def test_fill(self):\n\n x = pd.Series([\"a\", \"a\", \"b\", \"a\"], name=\"x\")\n s = Nominal()._setup(x, Fill())\n assert_array_equal(s(x), [True, True, False, True])"},{"col":0,"comment":"Test relative luminance.","endLoc":506,"header":"def test_relative_luminance()","id":4076,"name":"test_relative_luminance","nodeType":"Function","startLoc":490,"text":"def test_relative_luminance():\n \"\"\"Test relative luminance.\"\"\"\n out1 = utils.relative_luminance(\"white\")\n assert out1 == 1\n\n out2 = utils.relative_luminance(\"#000000\")\n assert out2 == 0\n\n out3 = utils.relative_luminance((.25, .5, .75))\n assert out3 == pytest.approx(0.201624536)\n\n rgbs = mpl.cm.RdBu(np.linspace(0, 1, 10))\n lums1 = [utils.relative_luminance(rgb) for rgb in rgbs]\n lums2 = utils.relative_luminance(rgbs)\n\n for lum1, lum2 in zip(lums1, lums2):\n assert lum1 == pytest.approx(lum2)"},{"col":4,"comment":"null","endLoc":501,"header":"def test_fill_dict(self)","id":4077,"name":"test_fill_dict","nodeType":"Function","startLoc":496,"text":"def test_fill_dict(self):\n\n x = pd.Series([\"a\", \"a\", \"b\", \"a\"], name=\"x\")\n vs = {\"a\": False, \"b\": True}\n s = Nominal(vs)._setup(x, Fill())\n assert_array_equal(s(x), [False, False, True, False])"},{"col":4,"comment":"null","endLoc":508,"header":"def test_fill_nunique_warning(self)","id":4078,"name":"test_fill_nunique_warning","nodeType":"Function","startLoc":503,"text":"def test_fill_nunique_warning(self):\n\n x = pd.Series([\"a\", \"b\", \"c\", \"a\", \"b\"], name=\"x\")\n with pytest.warns(UserWarning, match=\"The variable assigned to fill\"):\n s = Nominal()._setup(x, Fill())\n assert_array_equal(s(x), [True, False, True, True, False])"},{"fileName":"histogram.py","filePath":"seaborn/_stats","id":4079,"nodeType":"File","text":"from __future__ import annotations\nfrom dataclasses import dataclass\nfrom warnings import warn\n\nimport numpy as np\nimport pandas as pd\n\nfrom seaborn._core.groupby import GroupBy\nfrom seaborn._stats.base import Stat\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from numpy.typing import ArrayLike\n\n\n@dataclass\nclass Hist(Stat):\n \"\"\"\n Bin observations, count them, and optionally normalize or cumulate.\n\n Parameters\n ----------\n stat : str\n Aggregate statistic to compute in each bin:\n\n - `count`: the number of observations\n - `density`: normalize so that the total area of the histogram equals 1\n - `percent`: normalize so that bar heights sum to 100\n - `probability` or `proportion`: normalize so that bar heights sum to 1\n - `frequency`: divide the number of observations by the bin width\n\n bins : str, int, or ArrayLike\n Generic parameter that can be the name of a reference rule, the number\n of bins, or the bin breaks. Passed to :func:`numpy.histogram_bin_edges`.\n binwidth : float\n Width of each bin; overrides `bins` but can be used with `binrange`.\n binrange : (min, max)\n Lowest and highest value for bin edges; can be used with either\n `bins` (when a number) or `binwidth`. Defaults to data extremes.\n common_norm : bool or list of variables\n When not `False`, the normalization is applied across groups. Use\n `True` to normalize across all groups, or pass variable name(s) that\n define normalization groups.\n common_bins : bool or list of variables\n When not `False`, the same bins are used for all groups. Use `True` to\n share bins across all groups, or pass variable name(s) to share within.\n cumulative : bool\n If True, cumulate the bin values.\n discrete : bool\n If True, set `binwidth` and `binrange` so that bins have unit width and\n are centered on integer values\n\n Notes\n -----\n\n The choice of bins for computing and plotting a histogram can exert\n substantial influence on the insights that one is able to draw from the\n visualization. If the bins are too large, they may erase important features.\n On the other hand, bins that are too small may be dominated by random\n variability, obscuring the shape of the true underlying distribution. The\n default bin size is determined using a reference rule that depends on the\n sample size and variance. This works well in many cases, (i.e., with\n \"well-behaved\" data) but it fails in others. It is always a good to try\n different bin sizes to be sure that you are not missing something important.\n This function allows you to specify bins in several different ways, such as\n by setting the total number of bins to use, the width of each bin, or the\n specific locations where the bins should break.\n\n\n Examples\n --------\n .. include:: ../docstrings/objects.Hist.rst\n\n \"\"\"\n stat: str = \"count\"\n bins: str | int | ArrayLike = \"auto\"\n binwidth: float | None = None\n binrange: tuple[float, float] | None = None\n common_norm: bool | list[str] = True\n common_bins: bool | list[str] = True\n cumulative: bool = False\n discrete: bool = False\n\n def __post_init__(self):\n\n stat_options = [\n \"count\", \"density\", \"percent\", \"probability\", \"proportion\", \"frequency\"\n ]\n self._check_param_one_of(\"stat\", stat_options)\n\n def _define_bin_edges(self, vals, weight, bins, binwidth, binrange, discrete):\n \"\"\"Inner function that takes bin parameters as arguments.\"\"\"\n vals = vals.dropna()\n\n if binrange is None:\n start, stop = vals.min(), vals.max()\n else:\n start, stop = binrange\n\n if discrete:\n bin_edges = np.arange(start - .5, stop + 1.5)\n elif binwidth is not None:\n step = binwidth\n bin_edges = np.arange(start, stop + step, step)\n else:\n bin_edges = np.histogram_bin_edges(vals, bins, binrange, weight)\n\n # TODO warning or cap on too many bins?\n\n return bin_edges\n\n def _define_bin_params(self, data, orient, scale_type):\n \"\"\"Given data, return numpy.histogram parameters to define bins.\"\"\"\n vals = data[orient]\n weights = data.get(\"weight\", None)\n\n # TODO We'll want this for ordinal / discrete scales too\n # (Do we need discrete as a parameter or just infer from scale?)\n discrete = self.discrete or scale_type == \"nominal\"\n\n bin_edges = self._define_bin_edges(\n vals, weights, self.bins, self.binwidth, self.binrange, discrete,\n )\n\n if isinstance(self.bins, (str, int)):\n n_bins = len(bin_edges) - 1\n bin_range = bin_edges.min(), bin_edges.max()\n bin_kws = dict(bins=n_bins, range=bin_range)\n else:\n bin_kws = dict(bins=bin_edges)\n\n return bin_kws\n\n def _get_bins_and_eval(self, data, orient, groupby, scale_type):\n\n bin_kws = self._define_bin_params(data, orient, scale_type)\n return groupby.apply(data, self._eval, orient, bin_kws)\n\n def _eval(self, data, orient, bin_kws):\n\n vals = data[orient]\n weights = data.get(\"weight\", None)\n\n density = self.stat == \"density\"\n hist, edges = np.histogram(vals, **bin_kws, weights=weights, density=density)\n\n width = np.diff(edges)\n center = edges[:-1] + width / 2\n\n return pd.DataFrame({orient: center, \"count\": hist, \"space\": width})\n\n def _normalize(self, data):\n\n hist = data[\"count\"]\n if self.stat == \"probability\" or self.stat == \"proportion\":\n hist = hist.astype(float) / hist.sum()\n elif self.stat == \"percent\":\n hist = hist.astype(float) / hist.sum() * 100\n elif self.stat == \"frequency\":\n hist = hist.astype(float) / data[\"space\"]\n\n if self.cumulative:\n if self.stat in [\"density\", \"frequency\"]:\n hist = (hist * data[\"space\"]).cumsum()\n else:\n hist = hist.cumsum()\n\n return data.assign(**{self.stat: hist})\n\n def __call__(self, data, groupby, orient, scales):\n\n scale_type = scales[orient].__class__.__name__.lower()\n grouping_vars = [v for v in data if v in groupby.order]\n if not grouping_vars or self.common_bins is True:\n bin_kws = self._define_bin_params(data, orient, scale_type)\n data = groupby.apply(data, self._eval, orient, bin_kws)\n else:\n if self.common_bins is False:\n bin_groupby = GroupBy(grouping_vars)\n else:\n bin_groupby = GroupBy(self.common_bins)\n undefined = set(self.common_bins) - set(grouping_vars)\n if undefined:\n param = f\"{self.__class__.__name__}.common_bins\"\n names = \", \".join(f\"{x!r}\" for x in undefined)\n msg = f\"Undefined variables(s) passed to `{param}`: {names}.\"\n warn(msg)\n data = bin_groupby.apply(\n data, self._get_bins_and_eval, orient, groupby, scale_type,\n )\n\n if not grouping_vars or self.common_norm is True:\n data = self._normalize(data)\n else:\n if self.common_norm is False:\n norm_grouper = grouping_vars\n else:\n norm_grouper = self.common_norm\n undefined = set(self.common_norm) - set(grouping_vars)\n if undefined:\n param = f\"{self.__class__.__name__}.common_norm\"\n names = \", \".join(f\"{x!r}\" for x in undefined)\n msg = f\"Undefined variables(s) passed to `{param}`: {names}.\"\n warn(msg)\n data = GroupBy(norm_grouper).apply(data, self._normalize)\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return data.assign(**{other: data[self.stat]})\n"},{"col":0,"comment":" Issue a warning, or maybe ignore it or raise an exception. ","endLoc":19,"header":"def warn(*args, **kwargs)","id":4080,"name":"warn","nodeType":"Function","startLoc":17,"text":"def warn(*args, **kwargs): # real signature unknown\n \"\"\" Issue a warning, or maybe ignore it or raise an exception. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":516,"header":"def test_interval_defaults(self, x)","id":4081,"name":"test_interval_defaults","nodeType":"Function","startLoc":510,"text":"def test_interval_defaults(self, x):\n\n class MockProperty(IntervalProperty):\n _default_range = (1, 2)\n\n s = Nominal()._setup(x, MockProperty())\n assert_array_equal(s(x), [2, 1.5, 1, 1.5])"},{"col":0,"comment":"","endLoc":1,"header":"histogram.py#","id":4082,"name":"","nodeType":"Function","startLoc":1,"text":"if TYPE_CHECKING:\n from numpy.typing import ArrayLike"},{"col":0,"comment":"null","endLoc":523,"header":"@pytest.mark.parametrize(\n \"cycler,result\",\n [\n (cycler(color=[\"y\"]), [\"y\"]),\n (cycler(color=[\"k\"]), [\"k\"]),\n (cycler(color=[\"k\", \"y\"]), [\"k\", \"y\"]),\n (cycler(color=[\"y\", \"k\"]), [\"y\", \"k\"]),\n (cycler(color=[\"b\", \"r\"]), [\"b\", \"r\"]),\n (cycler(color=[\"r\", \"b\"]), [\"r\", \"b\"]),\n (cycler(lw=[1, 2]), [\".15\"]), # no color in cycle\n ],\n)\ndef test_get_color_cycle(cycler, result)","id":4083,"name":"test_get_color_cycle","nodeType":"Function","startLoc":509,"text":"@pytest.mark.parametrize(\n \"cycler,result\",\n [\n (cycler(color=[\"y\"]), [\"y\"]),\n (cycler(color=[\"k\"]), [\"k\"]),\n (cycler(color=[\"k\", \"y\"]), [\"k\", \"y\"]),\n (cycler(color=[\"y\", \"k\"]), [\"y\", \"k\"]),\n (cycler(color=[\"b\", \"r\"]), [\"b\", \"r\"]),\n (cycler(color=[\"r\", \"b\"]), [\"r\", \"b\"]),\n (cycler(lw=[1, 2]), [\".15\"]), # no color in cycle\n ],\n)\ndef test_get_color_cycle(cycler, result):\n with mpl.rc_context(rc={\"axes.prop_cycle\": cycler}):\n assert get_color_cycle() == result"},{"id":4084,"name":"index.rst","nodeType":"TextFile","path":"doc","text":":html_theme.sidebar_secondary.remove:\n\nseaborn: statistical data visualization\n=======================================\n\n.. grid:: 6\n :gutter: 1\n\n .. grid-item::\n\n .. image:: example_thumbs/scatterplot_matrix_thumb.png\n :target: ./examples/scatterplot_matrix.html\n\n .. grid-item::\n\n .. image:: example_thumbs/errorband_lineplots_thumb.png\n :target: examples/errorband_lineplots.html\n\n .. grid-item::\n\n .. image:: example_thumbs/scatterplot_sizes_thumb.png\n :target: examples/scatterplot_sizes.html\n\n .. grid-item::\n\n .. image:: example_thumbs/timeseries_facets_thumb.png\n :target: examples/timeseries_facets.html\n\n .. grid-item::\n\n .. image:: example_thumbs/horizontal_boxplot_thumb.png\n :target: examples/horizontal_boxplot.html\n\n .. grid-item::\n\n .. image:: example_thumbs/regression_marginals_thumb.png\n :target: examples/regression_marginals.html\n\n.. grid:: 1 1 3 3\n\n .. grid-item::\n :columns: 12 12 6 6\n\n Seaborn is a Python data visualization library based on `matplotlib\n `_. It provides a high-level interface for drawing\n attractive and informative statistical graphics.\n\n For a brief introduction to the ideas behind the library, you can read the\n :doc:`introductory notes ` or the `paper\n `_. Visit the\n :doc:`installation page ` to see how you can download the package\n and get started with it. You can browse the :doc:`example gallery\n ` to see some of the things that you can do with seaborn,\n and then check out the :doc:`tutorials ` or :doc:`API reference `\n to find out how.\n\n To see the code or report a bug, please visit the `GitHub repository\n `_. General support questions are most at home\n on `stackoverflow `_, which\n has a dedicated channel for seaborn.\n\n .. grid-item-card:: Contents\n :columns: 12 12 2 2\n :class-title: sd-fs-5\n :class-body: sd-pl-4\n\n .. toctree::\n :maxdepth: 1\n\n Installing \n Gallery \n Tutorial \n API \n Releases \n Citing \n FAQ \n\n .. grid-item-card:: Features\n :columns: 12 12 4 4\n :class-title: sd-fs-5\n :class-body: sd-pl-3\n\n * :bdg-secondary:`New` Objects: :ref:`API ` | :doc:`Tutorial `\n * Relational plots: :ref:`API ` | :doc:`Tutorial `\n * Distribution plots: :ref:`API ` | :doc:`Tutorial `\n * Categorical plots: :ref:`API ` | :doc:`Tutorial `\n * Regression plots: :ref:`API ` | :doc:`Tutorial `\n * Multi-plot grids: :ref:`API ` | :doc:`Tutorial `\n * Figure theming: :ref:`API ` | :doc:`Tutorial `\n * Color palettes: :ref:`API ` | :doc:`Tutorial `\n"},{"col":4,"comment":"null","endLoc":521,"header":"def test_interval_tuple(self, x)","id":4085,"name":"test_interval_tuple","nodeType":"Function","startLoc":518,"text":"def test_interval_tuple(self, x):\n\n s = Nominal((1, 2))._setup(x, IntervalProperty())\n assert_array_equal(s(x), [2, 1.5, 1, 1.5])"},{"fileName":"set_nb_kernels.py","filePath":"doc/tools","id":4086,"nodeType":"File","text":"\"\"\"Recursively set the kernel name for all jupyter notebook files.\"\"\"\nimport sys\nfrom glob import glob\n\nimport nbformat\n\n\nif __name__ == \"__main__\":\n\n _, kernel_name = sys.argv\n\n nb_paths = glob(\"./**/*.ipynb\", recursive=True)\n for path in nb_paths:\n\n with open(path) as f:\n nb = nbformat.read(f, as_version=4)\n\n nb[\"metadata\"][\"kernelspec\"][\"name\"] = kernel_name\n nb[\"metadata\"][\"kernelspec\"][\"display_name\"] = kernel_name\n\n with open(path, \"w\") as f:\n nbformat.write(nb, f)\n"},{"attributeType":"str","col":4,"comment":"null","endLoc":10,"id":4087,"name":"_","nodeType":"Attribute","startLoc":10,"text":"_"},{"col":4,"comment":"null","endLoc":526,"header":"def test_interval_tuple_numeric(self, y)","id":4088,"name":"test_interval_tuple_numeric","nodeType":"Function","startLoc":523,"text":"def test_interval_tuple_numeric(self, y):\n\n s = Nominal((1, 2))._setup(y, IntervalProperty())\n assert_array_equal(s(y), [1.5, 2, 1, 2])"},{"col":4,"comment":"null","endLoc":532,"header":"def test_interval_list(self, x)","id":4089,"name":"test_interval_list","nodeType":"Function","startLoc":528,"text":"def test_interval_list(self, x):\n\n vs = [2, 5, 4]\n s = Nominal(vs)._setup(x, IntervalProperty())\n assert_array_equal(s(x), [2, 5, 4, 5])"},{"col":0,"comment":"null","endLoc":534,"header":"def test_remove_na()","id":4090,"name":"test_remove_na","nodeType":"Function","startLoc":526,"text":"def test_remove_na():\n\n a_array = np.array([1, 2, np.nan, 3])\n a_array_rm = remove_na(a_array)\n assert_array_equal(a_array_rm, np.array([1, 2, 3]))\n\n a_series = pd.Series([1, 2, np.nan, 3])\n a_series_rm = remove_na(a_series)\n assert_series_equal(a_series_rm, pd.Series([1., 2, 3], [0, 1, 3]))"},{"col":0,"comment":"null","endLoc":548,"header":"def test_assign_default_kwargs()","id":4091,"name":"test_assign_default_kwargs","nodeType":"Function","startLoc":537,"text":"def test_assign_default_kwargs():\n\n def f(a, b, c, d):\n pass\n\n def g(c=1, d=2):\n pass\n\n kws = {\"c\": 3}\n\n kws = _assign_default_kwargs(kws, f, g)\n assert kws == {\"c\": 3, \"d\": 2}"},{"col":0,"comment":"null","endLoc":558,"header":"def test_draw_figure()","id":4092,"name":"test_draw_figure","nodeType":"Function","startLoc":551,"text":"def test_draw_figure():\n\n f, ax = plt.subplots()\n ax.plot([\"a\", \"b\", \"c\"], [1, 2, 3])\n _draw_figure(f)\n assert not f.stale\n # ticklabels are not populated until a draw, but this may change\n assert ax.get_xticklabels()[0].get_text() == \"a\""},{"col":4,"comment":"null","endLoc":538,"header":"def test_interval_dict(self, x)","id":4093,"name":"test_interval_dict","nodeType":"Function","startLoc":534,"text":"def test_interval_dict(self, x):\n\n vs = {\"a\": 3, \"b\": 4, \"c\": 6}\n s = Nominal(vs)._setup(x, IntervalProperty())\n assert_array_equal(s(x), [3, 6, 4, 6])"},{"col":0,"comment":"null","endLoc":575,"header":"def test_deprecate_ci()","id":4094,"name":"test_deprecate_ci","nodeType":"Function","startLoc":561,"text":"def test_deprecate_ci():\n\n msg = \"\\n\\nThe `ci` parameter is deprecated. Use `errorbar=\"\n\n with pytest.warns(FutureWarning, match=msg + \"None\"):\n out = _deprecate_ci(None, None)\n assert out is None\n\n with pytest.warns(FutureWarning, match=msg + \"'sd'\"):\n out = _deprecate_ci(None, \"sd\")\n assert out == \"sd\"\n\n with pytest.warns(FutureWarning, match=msg + r\"\\('ci', 68\\)\"):\n out = _deprecate_ci(None, 68)\n assert out == (\"ci\", 68)"},{"col":4,"comment":"null","endLoc":547,"header":"def test_interval_with_transform(self, x)","id":4095,"name":"test_interval_with_transform","nodeType":"Function","startLoc":540,"text":"def test_interval_with_transform(self, x):\n\n class MockProperty(IntervalProperty):\n _forward = np.square\n _inverse = np.sqrt\n\n s = Nominal((2, 4))._setup(x, MockProperty())\n assert_array_equal(s(x), [4, np.sqrt(10), 2, np.sqrt(10)])"},{"attributeType":"null","col":0,"comment":"null","endLoc":35,"id":4096,"name":"a_norm","nodeType":"Attribute","startLoc":35,"text":"a_norm"},{"col":0,"comment":"","endLoc":1,"header":"test_utils.py#","id":4097,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Tests for seaborn utility functions.\"\"\"\n\na_norm = np.random.randn(100)"},{"col":4,"comment":"null","endLoc":299,"header":"def test_dict_missing(self, cat_vector)","id":4098,"name":"test_dict_missing","nodeType":"Function","startLoc":291,"text":"def test_dict_missing(self, cat_vector):\n\n levels = categorical_order(cat_vector)\n values = dict(zip(levels, self.values[:-1]))\n scale = Nominal(values)\n name = self.prop.__name__.lower()\n msg = f\"No entry in {name} dictionary for {repr(levels[-1])}\"\n with pytest.raises(ValueError, match=msg):\n self.prop().get_mapping(scale, cat_vector)"},{"className":"TestTemporal","col":0,"comment":"null","endLoc":651,"id":4099,"nodeType":"Class","startLoc":550,"text":"class TestTemporal:\n\n @pytest.fixture\n def t(self):\n dates = pd.to_datetime([\"1972-09-27\", \"1975-06-24\", \"1980-12-14\"])\n return pd.Series(dates, name=\"x\")\n\n @pytest.fixture\n def x(self, t):\n return pd.Series(mpl.dates.date2num(t), name=t.name)\n\n def test_coordinate_defaults(self, t, x):\n\n s = Temporal()._setup(t, Coordinate())\n assert_array_equal(s(t), x)\n\n def test_interval_defaults(self, t, x):\n\n s = Temporal()._setup(t, IntervalProperty())\n normed = (x - x.min()) / (x.max() - x.min())\n assert_array_equal(s(t), normed)\n\n def test_interval_with_range(self, t, x):\n\n values = (1, 3)\n s = Temporal((1, 3))._setup(t, IntervalProperty())\n normed = (x - x.min()) / (x.max() - x.min())\n expected = normed * (values[1] - values[0]) + values[0]\n assert_array_equal(s(t), expected)\n\n def test_interval_with_norm(self, t, x):\n\n norm = t[1], t[2]\n s = Temporal(norm=norm)._setup(t, IntervalProperty())\n n = mpl.dates.date2num(norm)\n normed = (x - n[0]) / (n[1] - n[0])\n assert_array_equal(s(t), normed)\n\n def test_color_defaults(self, t, x):\n\n cmap = color_palette(\"ch:\", as_cmap=True)\n s = Temporal()._setup(t, Color())\n normed = (x - x.min()) / (x.max() - x.min())\n assert_array_equal(s(t), cmap(normed)[:, :3]) # FIXME RGBA\n\n def test_color_named_values(self, t, x):\n\n name = \"viridis\"\n cmap = color_palette(name, as_cmap=True)\n s = Temporal(name)._setup(t, Color())\n normed = (x - x.min()) / (x.max() - x.min())\n assert_array_equal(s(t), cmap(normed)[:, :3]) # FIXME RGBA\n\n def test_coordinate_axis(self, t, x):\n\n ax = mpl.figure.Figure().subplots()\n s = Temporal()._setup(t, Coordinate(), ax.xaxis)\n assert_array_equal(s(t), x)\n locator = ax.xaxis.get_major_locator()\n formatter = ax.xaxis.get_major_formatter()\n assert isinstance(locator, mpl.dates.AutoDateLocator)\n assert isinstance(formatter, mpl.dates.AutoDateFormatter)\n\n @pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.3.0\"),\n reason=\"Test requires new matplotlib date epoch.\"\n )\n def test_tick_locator(self, t):\n\n locator = mpl.dates.YearLocator(month=3, day=15)\n s = Temporal().tick(locator)\n a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)\n a.set_view_interval(0, 365)\n assert 73 in a.major.locator()\n\n def test_tick_upto(self, t, x):\n\n n = 8\n ax = mpl.figure.Figure().subplots()\n Temporal().tick(upto=n)._setup(t, Coordinate(), ax.xaxis)\n locator = ax.xaxis.get_major_locator()\n assert set(locator.maxticks.values()) == {n}\n\n @pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.3.0\"),\n reason=\"Test requires new matplotlib date epoch.\"\n )\n def test_label_formatter(self, t):\n\n formatter = mpl.dates.DateFormatter(\"%Y\")\n s = Temporal().label(formatter)\n a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)\n a.set_view_interval(10, 1000)\n label, = a.major.formatter.format_ticks([100])\n assert label == \"1970\"\n\n def test_label_concise(self, t, x):\n\n ax = mpl.figure.Figure().subplots()\n Temporal().label(concise=True)._setup(t, Coordinate(), ax.xaxis)\n formatter = ax.xaxis.get_major_formatter()\n assert isinstance(formatter, mpl.dates.ConciseDateFormatter)"},{"col":4,"comment":"null","endLoc":555,"header":"@pytest.fixture\n def t(self)","id":4100,"name":"t","nodeType":"Function","startLoc":552,"text":"@pytest.fixture\n def t(self):\n dates = pd.to_datetime([\"1972-09-27\", \"1975-06-24\", \"1980-12-14\"])\n return pd.Series(dates, name=\"x\")"},{"col":4,"comment":"null","endLoc":559,"header":"@pytest.fixture\n def x(self, t)","id":4101,"name":"x","nodeType":"Function","startLoc":557,"text":"@pytest.fixture\n def x(self, t):\n return pd.Series(mpl.dates.date2num(t), name=t.name)"},{"col":4,"comment":"null","endLoc":564,"header":"def test_coordinate_defaults(self, t, x)","id":4102,"name":"test_coordinate_defaults","nodeType":"Function","startLoc":561,"text":"def test_coordinate_defaults(self, t, x):\n\n s = Temporal()._setup(t, Coordinate())\n assert_array_equal(s(t), x)"},{"fileName":"test_text.py","filePath":"tests/_marks","id":4103,"nodeType":"File","text":"\nimport numpy as np\nfrom matplotlib.colors import to_rgba\nfrom matplotlib.text import Text as MPLText\n\nfrom numpy.testing import assert_array_almost_equal\n\nfrom seaborn._core.plot import Plot\nfrom seaborn._marks.text import Text\n\n\nclass TestText:\n\n def get_texts(self, ax):\n if ax.texts:\n return list(ax.texts)\n else:\n # Compatibility with matplotlib < 3.5 (I think)\n return [a for a in ax.artists if isinstance(a, MPLText)]\n\n def test_simple(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n\n p = Plot(x, y, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n x_, y_ = text.get_position()\n assert x_ == x[i]\n assert y_ == y[i]\n assert text.get_text() == s[i]\n assert text.get_horizontalalignment() == \"center\"\n assert text.get_verticalalignment() == \"center_baseline\"\n\n def test_set_properties(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n color = \"red\"\n alpha = .6\n fontsize = 6\n valign = \"bottom\"\n\n m = Text(color=color, alpha=alpha, fontsize=fontsize, valign=valign)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n assert text.get_text() == s[i]\n assert text.get_color() == to_rgba(m.color, m.alpha)\n assert text.get_fontsize() == m.fontsize\n assert text.get_verticalalignment() == m.valign\n\n def test_mapped_properties(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n color = list(\"aab\")\n fontsize = [1, 2, 4]\n\n p = Plot(x, y, color=color, fontsize=fontsize, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n texts = self.get_texts(ax)\n assert texts[0].get_color() == texts[1].get_color()\n assert texts[0].get_color() != texts[2].get_color()\n assert (\n texts[0].get_fontsize()\n < texts[1].get_fontsize()\n < texts[2].get_fontsize()\n )\n\n def test_mapped_alignment(self):\n\n x = [1, 2]\n p = Plot(x=x, y=x, halign=x, valign=x, text=x).add(Text()).plot()\n ax = p._figure.axes[0]\n t1, t2 = self.get_texts(ax)\n assert t1.get_horizontalalignment() == \"left\"\n assert t2.get_horizontalalignment() == \"right\"\n assert t1.get_verticalalignment() == \"top\"\n assert t2.get_verticalalignment() == \"bottom\"\n\n def test_identity_fontsize(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n fs = [5, 8, 12]\n p = Plot(x, y, text=s, fontsize=fs).add(Text()).scale(fontsize=None).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n assert text.get_fontsize() == fs[i]\n\n def test_offset_centered(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n p = Plot(x, y, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n assert_array_almost_equal(text.get_transform().get_matrix(), ax_trans)\n\n def test_offset_valign(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n m = Text(valign=\"bottom\", fontsize=5, offset=.1)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n expected_shift_matrix = np.zeros((3, 3))\n expected_shift_matrix[1, -1] = m.offset * ax.figure.dpi / 72\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n shift_matrix = text.get_transform().get_matrix() - ax_trans\n assert_array_almost_equal(shift_matrix, expected_shift_matrix)\n\n def test_offset_halign(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n m = Text(halign=\"right\", fontsize=10, offset=.5)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n expected_shift_matrix = np.zeros((3, 3))\n expected_shift_matrix[0, -1] = -m.offset * ax.figure.dpi / 72\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n shift_matrix = text.get_transform().get_matrix() - ax_trans\n assert_array_almost_equal(shift_matrix, expected_shift_matrix)\n"},{"col":4,"comment":"null","endLoc":570,"header":"def test_interval_defaults(self, t, x)","id":4104,"name":"test_interval_defaults","nodeType":"Function","startLoc":566,"text":"def test_interval_defaults(self, t, x):\n\n s = Temporal()._setup(t, IntervalProperty())\n normed = (x - x.min()) / (x.max() - x.min())\n assert_array_equal(s(t), normed)"},{"col":4,"comment":"null","endLoc":578,"header":"def test_interval_with_range(self, t, x)","id":4105,"name":"test_interval_with_range","nodeType":"Function","startLoc":572,"text":"def test_interval_with_range(self, t, x):\n\n values = (1, 3)\n s = Temporal((1, 3))._setup(t, IntervalProperty())\n normed = (x - x.min()) / (x.max() - x.min())\n expected = normed * (values[1] - values[0]) + values[0]\n assert_array_equal(s(t), expected)"},{"col":4,"comment":"null","endLoc":586,"header":"def test_interval_with_norm(self, t, x)","id":4106,"name":"test_interval_with_norm","nodeType":"Function","startLoc":580,"text":"def test_interval_with_norm(self, t, x):\n\n norm = t[1], t[2]\n s = Temporal(norm=norm)._setup(t, IntervalProperty())\n n = mpl.dates.date2num(norm)\n normed = (x - n[0]) / (n[1] - n[0])\n assert_array_equal(s(t), normed)"},{"col":4,"comment":"null","endLoc":593,"header":"def test_color_defaults(self, t, x)","id":4107,"name":"test_color_defaults","nodeType":"Function","startLoc":588,"text":"def test_color_defaults(self, t, x):\n\n cmap = color_palette(\"ch:\", as_cmap=True)\n s = Temporal()._setup(t, Color())\n normed = (x - x.min()) / (x.max() - x.min())\n assert_array_equal(s(t), cmap(normed)[:, :3]) # FIXME RGBA"},{"col":4,"comment":"null","endLoc":309,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_default(self, data_type, vectors)","id":4108,"name":"test_mapping_default","nodeType":"Function","startLoc":301,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_default(self, data_type, vectors):\n\n x = vectors[data_type]\n mapping = self.prop().get_mapping(Nominal(), x)\n n = x.nunique()\n for i, expected in enumerate(self.prop()._default_values(n)):\n actual, = mapping([i])\n self.assert_equal(actual, expected)"},{"col":4,"comment":"null","endLoc":319,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_from_list(self, data_type, vectors)","id":4109,"name":"test_mapping_from_list","nodeType":"Function","startLoc":311,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_from_list(self, data_type, vectors):\n\n x = vectors[data_type]\n scale = Nominal(self.values)\n mapping = self.prop().get_mapping(scale, x)\n for i, expected in enumerate(self.standardized_values):\n actual, = mapping([i])\n self.assert_equal(actual, expected)"},{"col":4,"comment":"null","endLoc":334,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_from_dict(self, data_type, vectors)","id":4110,"name":"test_mapping_from_dict","nodeType":"Function","startLoc":321,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\"])\n def test_mapping_from_dict(self, data_type, vectors):\n\n x = vectors[data_type]\n levels = categorical_order(x)\n values = dict(zip(levels, self.values[::-1]))\n standardized_values = dict(zip(levels, self.standardized_values[::-1]))\n\n scale = Nominal(values)\n mapping = self.prop().get_mapping(scale, x)\n for i, level in enumerate(levels):\n actual, = mapping([i])\n expected = standardized_values[level]\n self.assert_equal(actual, expected)"},{"col":4,"comment":"null","endLoc":343,"header":"def test_mapping_with_null_value(self, cat_vector)","id":4111,"name":"test_mapping_with_null_value","nodeType":"Function","startLoc":336,"text":"def test_mapping_with_null_value(self, cat_vector):\n\n mapping = self.prop().get_mapping(Nominal(self.values), cat_vector)\n actual = mapping(np.array([0, np.nan, 2]))\n v0, _, v2 = self.standardized_values\n expected = [v0, self.prop.null_value, v2]\n for a, b in zip(actual, expected):\n self.assert_equal(a, b)"},{"col":4,"comment":"null","endLoc":601,"header":"def test_color_named_values(self, t, x)","id":4112,"name":"test_color_named_values","nodeType":"Function","startLoc":595,"text":"def test_color_named_values(self, t, x):\n\n name = \"viridis\"\n cmap = color_palette(name, as_cmap=True)\n s = Temporal(name)._setup(t, Color())\n normed = (x - x.min()) / (x.max() - x.min())\n assert_array_equal(s(t), cmap(normed)[:, :3]) # FIXME RGBA"},{"col":4,"comment":"null","endLoc":350,"header":"def test_unique_default_large_n(self)","id":4113,"name":"test_unique_default_large_n","nodeType":"Function","startLoc":345,"text":"def test_unique_default_large_n(self):\n\n n = 24\n x = pd.Series(np.arange(n))\n mapping = self.prop().get_mapping(Nominal(), x)\n assert len({self.unpack(x_i) for x_i in mapping(x)}) == n"},{"col":4,"comment":"null","endLoc":356,"header":"def test_bad_scale_values(self, cat_vector)","id":4114,"name":"test_bad_scale_values","nodeType":"Function","startLoc":352,"text":"def test_bad_scale_values(self, cat_vector):\n\n var_name = self.prop.__name__.lower()\n with pytest.raises(TypeError, match=f\"Scale values for a {var_name} variable\"):\n self.prop().get_mapping(Nominal((\"o\", \"s\")), cat_vector)"},{"className":"TestMarker","col":0,"comment":"null","endLoc":371,"id":4115,"nodeType":"Class","startLoc":359,"text":"class TestMarker(ObjectPropertyBase):\n\n prop = Marker\n values = [\"o\", (5, 2, 0), MarkerStyle(\"^\")]\n standardized_values = [MarkerStyle(x) for x in values]\n\n def unpack(self, x):\n return (\n x.get_path(),\n x.get_joinstyle(),\n x.get_transform().to_values(),\n x.get_fillstyle(),\n )"},{"col":4,"comment":"null","endLoc":371,"header":"def unpack(self, x)","id":4116,"name":"unpack","nodeType":"Function","startLoc":365,"text":"def unpack(self, x):\n return (\n x.get_path(),\n x.get_joinstyle(),\n x.get_transform().to_values(),\n x.get_fillstyle(),\n )"},{"attributeType":"Marker","col":4,"comment":"null","endLoc":361,"id":4117,"name":"prop","nodeType":"Attribute","startLoc":361,"text":"prop"},{"attributeType":"list","col":4,"comment":"null","endLoc":362,"id":4118,"name":"values","nodeType":"Attribute","startLoc":362,"text":"values"},{"attributeType":"list","col":4,"comment":"null","endLoc":363,"id":4119,"name":"standardized_values","nodeType":"Attribute","startLoc":363,"text":"standardized_values"},{"className":"TestLineStyle","col":0,"comment":"null","endLoc":396,"id":4120,"nodeType":"Class","startLoc":374,"text":"class TestLineStyle(ObjectPropertyBase):\n\n prop = LineStyle\n values = [\"solid\", \"--\", (1, .5)]\n standardized_values = [LineStyle._get_dash_pattern(x) for x in values]\n\n def test_bad_type(self):\n\n p = LineStyle()\n with pytest.raises(TypeError, match=\"^Linestyle must be .+, not list.$\"):\n p.standardize([1, 2])\n\n def test_bad_style(self):\n\n p = LineStyle()\n with pytest.raises(ValueError, match=\"^Linestyle string must be .+, not 'o'.$\"):\n p.standardize(\"o\")\n\n def test_bad_dashes(self):\n\n p = LineStyle()\n with pytest.raises(TypeError, match=\"^Invalid dash pattern\"):\n p.standardize((1, 2, \"x\"))"},{"col":4,"comment":"null","endLoc":384,"header":"def test_bad_type(self)","id":4121,"name":"test_bad_type","nodeType":"Function","startLoc":380,"text":"def test_bad_type(self):\n\n p = LineStyle()\n with pytest.raises(TypeError, match=\"^Linestyle must be .+, not list.$\"):\n p.standardize([1, 2])"},{"col":4,"comment":"null","endLoc":611,"header":"def test_coordinate_axis(self, t, x)","id":4122,"name":"test_coordinate_axis","nodeType":"Function","startLoc":603,"text":"def test_coordinate_axis(self, t, x):\n\n ax = mpl.figure.Figure().subplots()\n s = Temporal()._setup(t, Coordinate(), ax.xaxis)\n assert_array_equal(s(t), x)\n locator = ax.xaxis.get_major_locator()\n formatter = ax.xaxis.get_major_formatter()\n assert isinstance(locator, mpl.dates.AutoDateLocator)\n assert isinstance(formatter, mpl.dates.AutoDateFormatter)"},{"col":4,"comment":"null","endLoc":623,"header":"@pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.3.0\"),\n reason=\"Test requires new matplotlib date epoch.\"\n )\n def test_tick_locator(self, t)","id":4123,"name":"test_tick_locator","nodeType":"Function","startLoc":613,"text":"@pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.3.0\"),\n reason=\"Test requires new matplotlib date epoch.\"\n )\n def test_tick_locator(self, t):\n\n locator = mpl.dates.YearLocator(month=3, day=15)\n s = Temporal().tick(locator)\n a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)\n a.set_view_interval(0, 365)\n assert 73 in a.major.locator()"},{"col":4,"comment":"null","endLoc":390,"header":"def test_bad_style(self)","id":4124,"name":"test_bad_style","nodeType":"Function","startLoc":386,"text":"def test_bad_style(self):\n\n p = LineStyle()\n with pytest.raises(ValueError, match=\"^Linestyle string must be .+, not 'o'.$\"):\n p.standardize(\"o\")"},{"col":4,"comment":"null","endLoc":631,"header":"def test_tick_upto(self, t, x)","id":4125,"name":"test_tick_upto","nodeType":"Function","startLoc":625,"text":"def test_tick_upto(self, t, x):\n\n n = 8\n ax = mpl.figure.Figure().subplots()\n Temporal().tick(upto=n)._setup(t, Coordinate(), ax.xaxis)\n locator = ax.xaxis.get_major_locator()\n assert set(locator.maxticks.values()) == {n}"},{"col":4,"comment":"null","endLoc":396,"header":"def test_bad_dashes(self)","id":4126,"name":"test_bad_dashes","nodeType":"Function","startLoc":392,"text":"def test_bad_dashes(self):\n\n p = LineStyle()\n with pytest.raises(TypeError, match=\"^Invalid dash pattern\"):\n p.standardize((1, 2, \"x\"))"},{"attributeType":"LineStyle","col":4,"comment":"null","endLoc":376,"id":4127,"name":"prop","nodeType":"Attribute","startLoc":376,"text":"prop"},{"attributeType":"list","col":4,"comment":"null","endLoc":377,"id":4128,"name":"values","nodeType":"Attribute","startLoc":377,"text":"values"},{"attributeType":"list","col":4,"comment":"null","endLoc":378,"id":4129,"name":"standardized_values","nodeType":"Attribute","startLoc":378,"text":"standardized_values"},{"className":"TestFill","col":0,"comment":"null","endLoc":478,"id":4130,"nodeType":"Class","startLoc":399,"text":"class TestFill(DataFixtures):\n\n @pytest.fixture\n def vectors(self):\n\n return {\n \"cat\": pd.Series([\"a\", \"a\", \"b\"]),\n \"num\": pd.Series([1, 1, 2]),\n \"bool\": pd.Series([True, True, False])\n }\n\n @pytest.fixture\n def cat_vector(self, vectors):\n return vectors[\"cat\"]\n\n @pytest.fixture\n def num_vector(self, vectors):\n return vectors[\"num\"]\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_default(self, data_type, vectors):\n\n x = vectors[data_type]\n scale = Fill().default_scale(x)\n assert isinstance(scale, Nominal)\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_inference_list(self, data_type, vectors):\n\n x = vectors[data_type]\n scale = Fill().infer_scale([True, False], x)\n assert isinstance(scale, Nominal)\n assert scale.values == [True, False]\n\n @pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_inference_dict(self, data_type, vectors):\n\n x = vectors[data_type]\n values = dict(zip(x.unique(), [True, False]))\n scale = Fill().infer_scale(values, x)\n assert isinstance(scale, Nominal)\n assert scale.values == values\n\n def test_mapping_categorical_data(self, cat_vector):\n\n mapping = Fill().get_mapping(Nominal(), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [True, False, True])\n\n def test_mapping_numeric_data(self, num_vector):\n\n mapping = Fill().get_mapping(Nominal(), num_vector)\n assert_array_equal(mapping([0, 1, 0]), [True, False, True])\n\n def test_mapping_list(self, cat_vector):\n\n mapping = Fill().get_mapping(Nominal([False, True]), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [False, True, False])\n\n def test_mapping_truthy_list(self, cat_vector):\n\n mapping = Fill().get_mapping(Nominal([0, 1]), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [False, True, False])\n\n def test_mapping_dict(self, cat_vector):\n\n values = dict(zip(cat_vector.unique(), [False, True]))\n mapping = Fill().get_mapping(Nominal(values), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [False, True, False])\n\n def test_cycle_warning(self):\n\n x = pd.Series([\"a\", \"b\", \"c\"])\n with pytest.warns(UserWarning, match=\"The variable assigned to fill\"):\n Fill().get_mapping(Nominal(), x)\n\n def test_values_error(self):\n\n x = pd.Series([\"a\", \"b\"])\n with pytest.raises(TypeError, match=\"Scale values for fill must be\"):\n Fill().get_mapping(Nominal(\"bad_values\"), x)"},{"col":4,"comment":"null","endLoc":408,"header":"@pytest.fixture\n def vectors(self)","id":4131,"name":"vectors","nodeType":"Function","startLoc":401,"text":"@pytest.fixture\n def vectors(self):\n\n return {\n \"cat\": pd.Series([\"a\", \"a\", \"b\"]),\n \"num\": pd.Series([1, 1, 2]),\n \"bool\": pd.Series([True, True, False])\n }"},{"col":4,"comment":"null","endLoc":412,"header":"@pytest.fixture\n def cat_vector(self, vectors)","id":4132,"name":"cat_vector","nodeType":"Function","startLoc":410,"text":"@pytest.fixture\n def cat_vector(self, vectors):\n return vectors[\"cat\"]"},{"col":4,"comment":"null","endLoc":416,"header":"@pytest.fixture\n def num_vector(self, vectors)","id":4133,"name":"num_vector","nodeType":"Function","startLoc":414,"text":"@pytest.fixture\n def num_vector(self, vectors):\n return vectors[\"num\"]"},{"col":4,"comment":"null","endLoc":423,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_default(self, data_type, vectors)","id":4134,"name":"test_default","nodeType":"Function","startLoc":418,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_default(self, data_type, vectors):\n\n x = vectors[data_type]\n scale = Fill().default_scale(x)\n assert isinstance(scale, Nominal)"},{"col":4,"comment":"null","endLoc":431,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_inference_list(self, data_type, vectors)","id":4135,"name":"test_inference_list","nodeType":"Function","startLoc":425,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_inference_list(self, data_type, vectors):\n\n x = vectors[data_type]\n scale = Fill().infer_scale([True, False], x)\n assert isinstance(scale, Nominal)\n assert scale.values == [True, False]"},{"col":4,"comment":"null","endLoc":440,"header":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_inference_dict(self, data_type, vectors)","id":4136,"name":"test_inference_dict","nodeType":"Function","startLoc":433,"text":"@pytest.mark.parametrize(\"data_type\", [\"cat\", \"num\", \"bool\"])\n def test_inference_dict(self, data_type, vectors):\n\n x = vectors[data_type]\n values = dict(zip(x.unique(), [True, False]))\n scale = Fill().infer_scale(values, x)\n assert isinstance(scale, Nominal)\n assert scale.values == values"},{"col":4,"comment":"null","endLoc":644,"header":"@pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.3.0\"),\n reason=\"Test requires new matplotlib date epoch.\"\n )\n def test_label_formatter(self, t)","id":4137,"name":"test_label_formatter","nodeType":"Function","startLoc":633,"text":"@pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.3.0\"),\n reason=\"Test requires new matplotlib date epoch.\"\n )\n def test_label_formatter(self, t):\n\n formatter = mpl.dates.DateFormatter(\"%Y\")\n s = Temporal().label(formatter)\n a = PseudoAxis(s._setup(t, Coordinate())._matplotlib_scale)\n a.set_view_interval(10, 1000)\n label, = a.major.formatter.format_ticks([100])\n assert label == \"1970\""},{"col":4,"comment":"null","endLoc":651,"header":"def test_label_concise(self, t, x)","id":4138,"name":"test_label_concise","nodeType":"Function","startLoc":646,"text":"def test_label_concise(self, t, x):\n\n ax = mpl.figure.Figure().subplots()\n Temporal().label(concise=True)._setup(t, Coordinate(), ax.xaxis)\n formatter = ax.xaxis.get_major_formatter()\n assert isinstance(formatter, mpl.dates.ConciseDateFormatter)"},{"col":4,"comment":"null","endLoc":445,"header":"def test_mapping_categorical_data(self, cat_vector)","id":4139,"name":"test_mapping_categorical_data","nodeType":"Function","startLoc":442,"text":"def test_mapping_categorical_data(self, cat_vector):\n\n mapping = Fill().get_mapping(Nominal(), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [True, False, True])"},{"attributeType":"null","col":16,"comment":"null","endLoc":3,"id":4140,"name":"np","nodeType":"Attribute","startLoc":3,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":4,"id":4141,"name":"pd","nodeType":"Attribute","startLoc":4,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":5,"id":4142,"name":"mpl","nodeType":"Attribute","startLoc":5,"text":"mpl"},{"col":4,"comment":"null","endLoc":450,"header":"def test_mapping_numeric_data(self, num_vector)","id":4143,"name":"test_mapping_numeric_data","nodeType":"Function","startLoc":447,"text":"def test_mapping_numeric_data(self, num_vector):\n\n mapping = Fill().get_mapping(Nominal(), num_vector)\n assert_array_equal(mapping([0, 1, 0]), [True, False, True])"},{"col":4,"comment":"null","endLoc":455,"header":"def test_mapping_list(self, cat_vector)","id":4144,"name":"test_mapping_list","nodeType":"Function","startLoc":452,"text":"def test_mapping_list(self, cat_vector):\n\n mapping = Fill().get_mapping(Nominal([False, True]), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [False, True, False])"},{"col":4,"comment":"null","endLoc":460,"header":"def test_mapping_truthy_list(self, cat_vector)","id":4145,"name":"test_mapping_truthy_list","nodeType":"Function","startLoc":457,"text":"def test_mapping_truthy_list(self, cat_vector):\n\n mapping = Fill().get_mapping(Nominal([0, 1]), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [False, True, False])"},{"fileName":"crayons.py","filePath":"seaborn/colors","id":4146,"nodeType":"File","text":"crayons = {'Almond': '#EFDECD',\n 'Antique Brass': '#CD9575',\n 'Apricot': '#FDD9B5',\n 'Aquamarine': '#78DBE2',\n 'Asparagus': '#87A96B',\n 'Atomic Tangerine': '#FFA474',\n 'Banana Mania': '#FAE7B5',\n 'Beaver': '#9F8170',\n 'Bittersweet': '#FD7C6E',\n 'Black': '#000000',\n 'Blue': '#1F75FE',\n 'Blue Bell': '#A2A2D0',\n 'Blue Green': '#0D98BA',\n 'Blue Violet': '#7366BD',\n 'Blush': '#DE5D83',\n 'Brick Red': '#CB4154',\n 'Brown': '#B4674D',\n 'Burnt Orange': '#FF7F49',\n 'Burnt Sienna': '#EA7E5D',\n 'Cadet Blue': '#B0B7C6',\n 'Canary': '#FFFF99',\n 'Caribbean Green': '#00CC99',\n 'Carnation Pink': '#FFAACC',\n 'Cerise': '#DD4492',\n 'Cerulean': '#1DACD6',\n 'Chestnut': '#BC5D58',\n 'Copper': '#DD9475',\n 'Cornflower': '#9ACEEB',\n 'Cotton Candy': '#FFBCD9',\n 'Dandelion': '#FDDB6D',\n 'Denim': '#2B6CC4',\n 'Desert Sand': '#EFCDB8',\n 'Eggplant': '#6E5160',\n 'Electric Lime': '#CEFF1D',\n 'Fern': '#71BC78',\n 'Forest Green': '#6DAE81',\n 'Fuchsia': '#C364C5',\n 'Fuzzy Wuzzy': '#CC6666',\n 'Gold': '#E7C697',\n 'Goldenrod': '#FCD975',\n 'Granny Smith Apple': '#A8E4A0',\n 'Gray': '#95918C',\n 'Green': '#1CAC78',\n 'Green Yellow': '#F0E891',\n 'Hot Magenta': '#FF1DCE',\n 'Inchworm': '#B2EC5D',\n 'Indigo': '#5D76CB',\n 'Jazzberry Jam': '#CA3767',\n 'Jungle Green': '#3BB08F',\n 'Laser Lemon': '#FEFE22',\n 'Lavender': '#FCB4D5',\n 'Macaroni and Cheese': '#FFBD88',\n 'Magenta': '#F664AF',\n 'Mahogany': '#CD4A4C',\n 'Manatee': '#979AAA',\n 'Mango Tango': '#FF8243',\n 'Maroon': '#C8385A',\n 'Mauvelous': '#EF98AA',\n 'Melon': '#FDBCB4',\n 'Midnight Blue': '#1A4876',\n 'Mountain Meadow': '#30BA8F',\n 'Navy Blue': '#1974D2',\n 'Neon Carrot': '#FFA343',\n 'Olive Green': '#BAB86C',\n 'Orange': '#FF7538',\n 'Orchid': '#E6A8D7',\n 'Outer Space': '#414A4C',\n 'Outrageous Orange': '#FF6E4A',\n 'Pacific Blue': '#1CA9C9',\n 'Peach': '#FFCFAB',\n 'Periwinkle': '#C5D0E6',\n 'Piggy Pink': '#FDDDE6',\n 'Pine Green': '#158078',\n 'Pink Flamingo': '#FC74FD',\n 'Pink Sherbert': '#F78FA7',\n 'Plum': '#8E4585',\n 'Purple Heart': '#7442C8',\n \"Purple Mountains' Majesty\": '#9D81BA',\n 'Purple Pizzazz': '#FE4EDA',\n 'Radical Red': '#FF496C',\n 'Raw Sienna': '#D68A59',\n 'Razzle Dazzle Rose': '#FF48D0',\n 'Razzmatazz': '#E3256B',\n 'Red': '#EE204D',\n 'Red Orange': '#FF5349',\n 'Red Violet': '#C0448F',\n \"Robin's Egg Blue\": '#1FCECB',\n 'Royal Purple': '#7851A9',\n 'Salmon': '#FF9BAA',\n 'Scarlet': '#FC2847',\n \"Screamin' Green\": '#76FF7A',\n 'Sea Green': '#93DFB8',\n 'Sepia': '#A5694F',\n 'Shadow': '#8A795D',\n 'Shamrock': '#45CEA2',\n 'Shocking Pink': '#FB7EFD',\n 'Silver': '#CDC5C2',\n 'Sky Blue': '#80DAEB',\n 'Spring Green': '#ECEABE',\n 'Sunglow': '#FFCF48',\n 'Sunset Orange': '#FD5E53',\n 'Tan': '#FAA76C',\n 'Tickle Me Pink': '#FC89AC',\n 'Timberwolf': '#DBD7D2',\n 'Tropical Rain Forest': '#17806D',\n 'Tumbleweed': '#DEAA88',\n 'Turquoise Blue': '#77DDE7',\n 'Unmellow Yellow': '#FFFF66',\n 'Violet (Purple)': '#926EAE',\n 'Violet Red': '#F75394',\n 'Vivid Tangerine': '#FFA089',\n 'Vivid Violet': '#8F509D',\n 'White': '#FFFFFF',\n 'Wild Blue Yonder': '#A2ADD0',\n 'Wild Strawberry': '#FF43A4',\n 'Wild Watermelon': '#FC6C85',\n 'Wisteria': '#CDA4DE',\n 'Yellow': '#FCE883',\n 'Yellow Green': '#C5E384',\n 'Yellow Orange': '#FFAE42'}\n"},{"col":0,"comment":"","endLoc":120,"header":"crayons.py#","id":4147,"name":"","nodeType":"Function","startLoc":1,"text":"crayons = {'Almond': '#EFDECD',\n 'Antique Brass': '#CD9575',\n 'Apricot': '#FDD9B5',\n 'Aquamarine': '#78DBE2',\n 'Asparagus': '#87A96B',\n 'Atomic Tangerine': '#FFA474',\n 'Banana Mania': '#FAE7B5',\n 'Beaver': '#9F8170',\n 'Bittersweet': '#FD7C6E',\n 'Black': '#000000',\n 'Blue': '#1F75FE',\n 'Blue Bell': '#A2A2D0',\n 'Blue Green': '#0D98BA',\n 'Blue Violet': '#7366BD',\n 'Blush': '#DE5D83',\n 'Brick Red': '#CB4154',\n 'Brown': '#B4674D',\n 'Burnt Orange': '#FF7F49',\n 'Burnt Sienna': '#EA7E5D',\n 'Cadet Blue': '#B0B7C6',\n 'Canary': '#FFFF99',\n 'Caribbean Green': '#00CC99',\n 'Carnation Pink': '#FFAACC',\n 'Cerise': '#DD4492',\n 'Cerulean': '#1DACD6',\n 'Chestnut': '#BC5D58',\n 'Copper': '#DD9475',\n 'Cornflower': '#9ACEEB',\n 'Cotton Candy': '#FFBCD9',\n 'Dandelion': '#FDDB6D',\n 'Denim': '#2B6CC4',\n 'Desert Sand': '#EFCDB8',\n 'Eggplant': '#6E5160',\n 'Electric Lime': '#CEFF1D',\n 'Fern': '#71BC78',\n 'Forest Green': '#6DAE81',\n 'Fuchsia': '#C364C5',\n 'Fuzzy Wuzzy': '#CC6666',\n 'Gold': '#E7C697',\n 'Goldenrod': '#FCD975',\n 'Granny Smith Apple': '#A8E4A0',\n 'Gray': '#95918C',\n 'Green': '#1CAC78',\n 'Green Yellow': '#F0E891',\n 'Hot Magenta': '#FF1DCE',\n 'Inchworm': '#B2EC5D',\n 'Indigo': '#5D76CB',\n 'Jazzberry Jam': '#CA3767',\n 'Jungle Green': '#3BB08F',\n 'Laser Lemon': '#FEFE22',\n 'Lavender': '#FCB4D5',\n 'Macaroni and Cheese': '#FFBD88',\n 'Magenta': '#F664AF',\n 'Mahogany': '#CD4A4C',\n 'Manatee': '#979AAA',\n 'Mango Tango': '#FF8243',\n 'Maroon': '#C8385A',\n 'Mauvelous': '#EF98AA',\n 'Melon': '#FDBCB4',\n 'Midnight Blue': '#1A4876',\n 'Mountain Meadow': '#30BA8F',\n 'Navy Blue': '#1974D2',\n 'Neon Carrot': '#FFA343',\n 'Olive Green': '#BAB86C',\n 'Orange': '#FF7538',\n 'Orchid': '#E6A8D7',\n 'Outer Space': '#414A4C',\n 'Outrageous Orange': '#FF6E4A',\n 'Pacific Blue': '#1CA9C9',\n 'Peach': '#FFCFAB',\n 'Periwinkle': '#C5D0E6',\n 'Piggy Pink': '#FDDDE6',\n 'Pine Green': '#158078',\n 'Pink Flamingo': '#FC74FD',\n 'Pink Sherbert': '#F78FA7',\n 'Plum': '#8E4585',\n 'Purple Heart': '#7442C8',\n \"Purple Mountains' Majesty\": '#9D81BA',\n 'Purple Pizzazz': '#FE4EDA',\n 'Radical Red': '#FF496C',\n 'Raw Sienna': '#D68A59',\n 'Razzle Dazzle Rose': '#FF48D0',\n 'Razzmatazz': '#E3256B',\n 'Red': '#EE204D',\n 'Red Orange': '#FF5349',\n 'Red Violet': '#C0448F',\n \"Robin's Egg Blue\": '#1FCECB',\n 'Royal Purple': '#7851A9',\n 'Salmon': '#FF9BAA',\n 'Scarlet': '#FC2847',\n \"Screamin' Green\": '#76FF7A',\n 'Sea Green': '#93DFB8',\n 'Sepia': '#A5694F',\n 'Shadow': '#8A795D',\n 'Shamrock': '#45CEA2',\n 'Shocking Pink': '#FB7EFD',\n 'Silver': '#CDC5C2',\n 'Sky Blue': '#80DAEB',\n 'Spring Green': '#ECEABE',\n 'Sunglow': '#FFCF48',\n 'Sunset Orange': '#FD5E53',\n 'Tan': '#FAA76C',\n 'Tickle Me Pink': '#FC89AC',\n 'Timberwolf': '#DBD7D2',\n 'Tropical Rain Forest': '#17806D',\n 'Tumbleweed': '#DEAA88',\n 'Turquoise Blue': '#77DDE7',\n 'Unmellow Yellow': '#FFFF66',\n 'Violet (Purple)': '#926EAE',\n 'Violet Red': '#F75394',\n 'Vivid Tangerine': '#FFA089',\n 'Vivid Violet': '#8F509D',\n 'White': '#FFFFFF',\n 'Wild Blue Yonder': '#A2ADD0',\n 'Wild Strawberry': '#FF43A4',\n 'Wild Watermelon': '#FC6C85',\n 'Wisteria': '#CDA4DE',\n 'Yellow': '#FCE883',\n 'Yellow Green': '#C5E384',\n 'Yellow Orange': '#FFAE42'}"},{"col":4,"comment":"null","endLoc":466,"header":"def test_mapping_dict(self, cat_vector)","id":4148,"name":"test_mapping_dict","nodeType":"Function","startLoc":462,"text":"def test_mapping_dict(self, cat_vector):\n\n values = dict(zip(cat_vector.unique(), [False, True]))\n mapping = Fill().get_mapping(Nominal(values), cat_vector)\n assert_array_equal(mapping([0, 1, 0]), [False, True, False])"},{"fileName":"scatter_bubbles.py","filePath":"examples","id":4149,"nodeType":"File","text":"\"\"\"\nScatterplot with varying point sizes and hues\n==============================================\n\n_thumb: .45, .5\n\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"white\")\n\n# Load the example mpg dataset\nmpg = sns.load_dataset(\"mpg\")\n\n# Plot miles per gallon against horsepower with other semantics\nsns.relplot(x=\"horsepower\", y=\"mpg\", hue=\"origin\", size=\"weight\",\n sizes=(40, 400), alpha=.5, palette=\"muted\",\n height=6, data=mpg)\n"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":4150,"name":"sns","nodeType":"Attribute","startLoc":8,"text":"sns"},{"col":4,"comment":"null","endLoc":472,"header":"def test_cycle_warning(self)","id":4151,"name":"test_cycle_warning","nodeType":"Function","startLoc":468,"text":"def test_cycle_warning(self):\n\n x = pd.Series([\"a\", \"b\", \"c\"])\n with pytest.warns(UserWarning, match=\"The variable assigned to fill\"):\n Fill().get_mapping(Nominal(), x)"},{"col":4,"comment":"null","endLoc":478,"header":"def test_values_error(self)","id":4152,"name":"test_values_error","nodeType":"Function","startLoc":474,"text":"def test_values_error(self):\n\n x = pd.Series([\"a\", \"b\"])\n with pytest.raises(TypeError, match=\"Scale values for fill must be\"):\n Fill().get_mapping(Nominal(\"bad_values\"), x)"},{"className":"IntervalBase","col":0,"comment":"null","endLoc":540,"id":4153,"nodeType":"Class","startLoc":481,"text":"class IntervalBase(DataFixtures):\n\n def norm(self, x):\n return (x - x.min()) / (x.max() - x.min())\n\n @pytest.mark.parametrize(\"data_type,scale_class\", [\n (\"cat\", Nominal),\n (\"num\", Continuous),\n ])\n def test_default(self, data_type, scale_class, vectors):\n\n x = vectors[data_type]\n scale = self.prop().default_scale(x)\n assert isinstance(scale, scale_class)\n\n @pytest.mark.parametrize(\"arg,data_type,scale_class\", [\n ((1, 3), \"cat\", Nominal),\n ((1, 3), \"num\", Continuous),\n ([1, 2, 3], \"cat\", Nominal),\n ([1, 2, 3], \"num\", Nominal),\n ({\"a\": 1, \"b\": 3, \"c\": 2}, \"cat\", Nominal),\n ({2: 1, 4: 3, 8: 2}, \"num\", Nominal),\n ])\n def test_inference(self, arg, data_type, scale_class, vectors):\n\n x = vectors[data_type]\n scale = self.prop().infer_scale(arg, x)\n assert isinstance(scale, scale_class)\n assert scale.values == arg\n\n def test_mapped_interval_numeric(self, num_vector):\n\n mapping = self.prop().get_mapping(Continuous(), num_vector)\n assert_array_equal(mapping([0, 1]), self.prop().default_range)\n\n def test_mapped_interval_categorical(self, cat_vector):\n\n mapping = self.prop().get_mapping(Nominal(), cat_vector)\n n = cat_vector.nunique()\n assert_array_equal(mapping([n - 1, 0]), self.prop().default_range)\n\n def test_bad_scale_values_numeric_data(self, num_vector):\n\n prop_name = self.prop.__name__.lower()\n err_stem = (\n f\"Values for {prop_name} variables with Continuous scale must be 2-tuple\"\n )\n\n with pytest.raises(TypeError, match=f\"{err_stem}; not .\"):\n self.prop().get_mapping(Continuous(\"abc\"), num_vector)\n\n with pytest.raises(TypeError, match=f\"{err_stem}; not 3-tuple.\"):\n self.prop().get_mapping(Continuous((1, 2, 3)), num_vector)\n\n def test_bad_scale_values_categorical_data(self, cat_vector):\n\n prop_name = self.prop.__name__.lower()\n err_text = f\"Values for {prop_name} variables with Nominal scale\"\n with pytest.raises(TypeError, match=err_text):\n self.prop().get_mapping(Nominal(\"abc\"), cat_vector)"},{"col":4,"comment":"null","endLoc":484,"header":"def norm(self, x)","id":4154,"name":"norm","nodeType":"Function","startLoc":483,"text":"def norm(self, x):\n return (x - x.min()) / (x.max() - x.min())"},{"col":4,"comment":"null","endLoc":494,"header":"@pytest.mark.parametrize(\"data_type,scale_class\", [\n (\"cat\", Nominal),\n (\"num\", Continuous),\n ])\n def test_default(self, data_type, scale_class, vectors)","id":4155,"name":"test_default","nodeType":"Function","startLoc":486,"text":"@pytest.mark.parametrize(\"data_type,scale_class\", [\n (\"cat\", Nominal),\n (\"num\", Continuous),\n ])\n def test_default(self, data_type, scale_class, vectors):\n\n x = vectors[data_type]\n scale = self.prop().default_scale(x)\n assert isinstance(scale, scale_class)"},{"col":4,"comment":"null","endLoc":509,"header":"@pytest.mark.parametrize(\"arg,data_type,scale_class\", [\n ((1, 3), \"cat\", Nominal),\n ((1, 3), \"num\", Continuous),\n ([1, 2, 3], \"cat\", Nominal),\n ([1, 2, 3], \"num\", Nominal),\n ({\"a\"","id":4156,"name":"test_inference","nodeType":"Function","startLoc":496,"text":"@pytest.mark.parametrize(\"arg,data_type,scale_class\", [\n ((1, 3), \"cat\", Nominal),\n ((1, 3), \"num\", Continuous),\n ([1, 2, 3], \"cat\", Nominal),\n ([1, 2, 3], \"num\", Nominal),\n ({\"a\": 1, \"b\": 3, \"c\": 2}, \"cat\", Nominal),\n ({2: 1, 4: 3, 8: 2}, \"num\", Nominal),\n ])\n def test_inference(self, arg, data_type, scale_class, vectors):\n\n x = vectors[data_type]\n scale = self.prop().infer_scale(arg, x)\n assert isinstance(scale, scale_class)\n assert scale.values == arg"},{"col":4,"comment":"null","endLoc":514,"header":"def test_mapped_interval_numeric(self, num_vector)","id":4157,"name":"test_mapped_interval_numeric","nodeType":"Function","startLoc":511,"text":"def test_mapped_interval_numeric(self, num_vector):\n\n mapping = self.prop().get_mapping(Continuous(), num_vector)\n assert_array_equal(mapping([0, 1]), self.prop().default_range)"},{"col":4,"comment":"null","endLoc":520,"header":"def test_mapped_interval_categorical(self, cat_vector)","id":4158,"name":"test_mapped_interval_categorical","nodeType":"Function","startLoc":516,"text":"def test_mapped_interval_categorical(self, cat_vector):\n\n mapping = self.prop().get_mapping(Nominal(), cat_vector)\n n = cat_vector.nunique()\n assert_array_equal(mapping([n - 1, 0]), self.prop().default_range)"},{"col":4,"comment":"null","endLoc":533,"header":"def test_bad_scale_values_numeric_data(self, num_vector)","id":4159,"name":"test_bad_scale_values_numeric_data","nodeType":"Function","startLoc":522,"text":"def test_bad_scale_values_numeric_data(self, num_vector):\n\n prop_name = self.prop.__name__.lower()\n err_stem = (\n f\"Values for {prop_name} variables with Continuous scale must be 2-tuple\"\n )\n\n with pytest.raises(TypeError, match=f\"{err_stem}; not .\"):\n self.prop().get_mapping(Continuous(\"abc\"), num_vector)\n\n with pytest.raises(TypeError, match=f\"{err_stem}; not 3-tuple.\"):\n self.prop().get_mapping(Continuous((1, 2, 3)), num_vector)"},{"col":4,"comment":"null","endLoc":540,"header":"def test_bad_scale_values_categorical_data(self, cat_vector)","id":4160,"name":"test_bad_scale_values_categorical_data","nodeType":"Function","startLoc":535,"text":"def test_bad_scale_values_categorical_data(self, cat_vector):\n\n prop_name = self.prop.__name__.lower()\n err_text = f\"Values for {prop_name} variables with Nominal scale\"\n with pytest.raises(TypeError, match=err_text):\n self.prop().get_mapping(Nominal(\"abc\"), cat_vector)"},{"className":"TestAlpha","col":0,"comment":"null","endLoc":544,"id":4161,"nodeType":"Class","startLoc":543,"text":"class TestAlpha(IntervalBase):\n prop = Alpha"},{"attributeType":"Alpha","col":4,"comment":"null","endLoc":544,"id":4162,"name":"prop","nodeType":"Attribute","startLoc":544,"text":"prop"},{"className":"TestLineWidth","col":0,"comment":"null","endLoc":553,"id":4163,"nodeType":"Class","startLoc":547,"text":"class TestLineWidth(IntervalBase):\n prop = LineWidth\n\n def test_rcparam_default(self):\n\n with mpl.rc_context({\"lines.linewidth\": 2}):\n assert self.prop().default_range == (1, 4)"},{"col":4,"comment":"null","endLoc":553,"header":"def test_rcparam_default(self)","id":4164,"name":"test_rcparam_default","nodeType":"Function","startLoc":550,"text":"def test_rcparam_default(self):\n\n with mpl.rc_context({\"lines.linewidth\": 2}):\n assert self.prop().default_range == (1, 4)"},{"attributeType":"LineWidth","col":4,"comment":"null","endLoc":548,"id":4165,"name":"prop","nodeType":"Attribute","startLoc":548,"text":"prop"},{"className":"TestEdgeWidth","col":0,"comment":"null","endLoc":562,"id":4166,"nodeType":"Class","startLoc":556,"text":"class TestEdgeWidth(IntervalBase):\n prop = EdgeWidth\n\n def test_rcparam_default(self):\n\n with mpl.rc_context({\"patch.linewidth\": 2}):\n assert self.prop().default_range == (1, 4)"},{"col":4,"comment":"null","endLoc":562,"header":"def test_rcparam_default(self)","id":4167,"name":"test_rcparam_default","nodeType":"Function","startLoc":559,"text":"def test_rcparam_default(self):\n\n with mpl.rc_context({\"patch.linewidth\": 2}):\n assert self.prop().default_range == (1, 4)"},{"attributeType":"EdgeWidth","col":4,"comment":"null","endLoc":557,"id":4168,"name":"prop","nodeType":"Attribute","startLoc":557,"text":"prop"},{"className":"TestPointSize","col":0,"comment":"null","endLoc":582,"id":4169,"nodeType":"Class","startLoc":565,"text":"class TestPointSize(IntervalBase):\n prop = PointSize\n\n def test_areal_scaling_numeric(self, num_vector):\n\n limits = 5, 10\n scale = Continuous(limits)\n mapping = self.prop().get_mapping(scale, num_vector)\n x = np.linspace(0, 1, 6)\n expected = np.sqrt(np.linspace(*np.square(limits), num=len(x)))\n assert_array_equal(mapping(x), expected)\n\n def test_areal_scaling_categorical(self, cat_vector):\n\n limits = (2, 4)\n scale = Nominal(limits)\n mapping = self.prop().get_mapping(scale, cat_vector)\n assert_array_equal(mapping(np.arange(3)), [4, np.sqrt(10), 2])"},{"col":4,"comment":"null","endLoc":575,"header":"def test_areal_scaling_numeric(self, num_vector)","id":4170,"name":"test_areal_scaling_numeric","nodeType":"Function","startLoc":568,"text":"def test_areal_scaling_numeric(self, num_vector):\n\n limits = 5, 10\n scale = Continuous(limits)\n mapping = self.prop().get_mapping(scale, num_vector)\n x = np.linspace(0, 1, 6)\n expected = np.sqrt(np.linspace(*np.square(limits), num=len(x)))\n assert_array_equal(mapping(x), expected)"},{"col":4,"comment":"null","endLoc":582,"header":"def test_areal_scaling_categorical(self, cat_vector)","id":4171,"name":"test_areal_scaling_categorical","nodeType":"Function","startLoc":577,"text":"def test_areal_scaling_categorical(self, cat_vector):\n\n limits = (2, 4)\n scale = Nominal(limits)\n mapping = self.prop().get_mapping(scale, cat_vector)\n assert_array_equal(mapping(np.arange(3)), [4, np.sqrt(10), 2])"},{"attributeType":"PointSize","col":4,"comment":"null","endLoc":566,"id":4172,"name":"prop","nodeType":"Attribute","startLoc":566,"text":"prop"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":4173,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":4174,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":4,"id":4175,"name":"mpl","nodeType":"Attribute","startLoc":4,"text":"mpl"},{"fileName":"radial_facets.py","filePath":"examples","id":4176,"nodeType":"File","text":"\"\"\"\nFacetGrid with custom projection\n================================\n\n_thumb: .33, .5\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nsns.set_theme()\n\n# Generate an example radial datast\nr = np.linspace(0, 10, num=100)\ndf = pd.DataFrame({'r': r, 'slow': r, 'medium': 2 * r, 'fast': 4 * r})\n\n# Convert the dataframe to long-form or \"tidy\" format\ndf = pd.melt(df, id_vars=['r'], var_name='speed', value_name='theta')\n\n# Set up a grid of axes with a polar projection\ng = sns.FacetGrid(df, col=\"speed\", hue=\"speed\",\n subplot_kws=dict(projection='polar'), height=4.5,\n sharex=False, sharey=False, despine=False)\n\n# Draw a scatterplot onto each axes in the grid\ng.map(sns.scatterplot, \"theta\", \"r\")\n"},{"attributeType":"null","col":16,"comment":"null","endLoc":8,"id":4177,"name":"np","nodeType":"Attribute","startLoc":8,"text":"np"},{"col":4,"comment":"Make the plot.","endLoc":2047,"header":"def plot(self, ax, box_kws, flier_kws, line_kws)","id":4178,"name":"plot","nodeType":"Function","startLoc":2042,"text":"def plot(self, ax, box_kws, flier_kws, line_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_letter_value_plot(ax, box_kws, flier_kws, line_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()"},{"attributeType":"{__lt__}","col":8,"comment":"null","endLoc":1753,"id":4179,"name":"saturation","nodeType":"Attribute","startLoc":1753,"text":"self.saturation"},{"attributeType":"{__gt__, __le__}","col":8,"comment":"null","endLoc":1775,"id":4180,"name":"outlier_prop","nodeType":"Attribute","startLoc":1775,"text":"self.outlier_prop"},{"attributeType":"null","col":8,"comment":"null","endLoc":1752,"id":4181,"name":"dodge","nodeType":"Attribute","startLoc":1752,"text":"self.dodge"},{"col":4,"comment":"null","endLoc":29,"header":"def get_groupby(self, df, orient)","id":4182,"name":"get_groupby","nodeType":"Function","startLoc":25,"text":"def get_groupby(self, df, orient):\n\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n cols = [c for c in df if c != other]\n return GroupBy(cols)"},{"attributeType":"bool","col":8,"comment":"null","endLoc":1782,"id":4183,"name":"showfliers","nodeType":"Attribute","startLoc":1782,"text":"self.showfliers"},{"attributeType":"null","col":8,"comment":"null","endLoc":1751,"id":4184,"name":"width","nodeType":"Attribute","startLoc":1751,"text":"self.width"},{"attributeType":"Number","col":8,"comment":"null","endLoc":1760,"id":4185,"name":"k_depth","nodeType":"Attribute","startLoc":1760,"text":"self.k_depth"},{"attributeType":"null","col":8,"comment":"null","endLoc":1770,"id":4186,"name":"scale","nodeType":"Attribute","startLoc":1770,"text":"self.scale"},{"attributeType":"null","col":8,"comment":"null","endLoc":1780,"id":4187,"name":"trust_alpha","nodeType":"Attribute","startLoc":1780,"text":"self.trust_alpha"},{"attributeType":"null","col":8,"comment":"null","endLoc":1764,"id":4188,"name":"linewidth","nodeType":"Attribute","startLoc":1764,"text":"self.linewidth"},{"className":"Beeswarm","col":0,"comment":"Modifies a scatterplot artist to show a beeswarm plot.","endLoc":3542,"id":4189,"nodeType":"Class","startLoc":3348,"text":"class Beeswarm:\n \"\"\"Modifies a scatterplot artist to show a beeswarm plot.\"\"\"\n def __init__(self, orient=\"v\", width=0.8, warn_thresh=.05):\n\n # XXX should we keep the orient parameterization or specify the swarm axis?\n\n self.orient = orient\n self.width = width\n self.warn_thresh = warn_thresh\n\n def __call__(self, points, center):\n \"\"\"Swarm `points`, a PathCollection, around the `center` position.\"\"\"\n # Convert from point size (area) to diameter\n\n ax = points.axes\n dpi = ax.figure.dpi\n\n # Get the original positions of the points\n orig_xy_data = points.get_offsets()\n\n # Reset the categorical positions to the center line\n cat_idx = 1 if self.orient == \"h\" else 0\n orig_xy_data[:, cat_idx] = center\n\n # Transform the data coordinates to point coordinates.\n # We'll figure out the swarm positions in the latter\n # and then convert back to data coordinates and replot\n orig_x_data, orig_y_data = orig_xy_data.T\n orig_xy = ax.transData.transform(orig_xy_data)\n\n # Order the variables so that x is the categorical axis\n if self.orient == \"h\":\n orig_xy = orig_xy[:, [1, 0]]\n\n # Add a column with each point's radius\n sizes = points.get_sizes()\n if sizes.size == 1:\n sizes = np.repeat(sizes, orig_xy.shape[0])\n edge = points.get_linewidth().item()\n radii = (np.sqrt(sizes) + edge) / 2 * (dpi / 72)\n orig_xy = np.c_[orig_xy, radii]\n\n # Sort along the value axis to facilitate the beeswarm\n sorter = np.argsort(orig_xy[:, 1])\n orig_xyr = orig_xy[sorter]\n\n # Adjust points along the categorical axis to prevent overlaps\n new_xyr = np.empty_like(orig_xyr)\n new_xyr[sorter] = self.beeswarm(orig_xyr)\n\n # Transform the point coordinates back to data coordinates\n if self.orient == \"h\":\n new_xy = new_xyr[:, [1, 0]]\n else:\n new_xy = new_xyr[:, :2]\n new_x_data, new_y_data = ax.transData.inverted().transform(new_xy).T\n\n swarm_axis = {\"h\": \"y\", \"v\": \"x\"}[self.orient]\n log_scale = getattr(ax, f\"get_{swarm_axis}scale\")() == \"log\"\n\n # Add gutters\n if self.orient == \"h\":\n self.add_gutters(new_y_data, center, log_scale=log_scale)\n else:\n self.add_gutters(new_x_data, center, log_scale=log_scale)\n\n # Reposition the points so they do not overlap\n if self.orient == \"h\":\n points.set_offsets(np.c_[orig_x_data, new_y_data])\n else:\n points.set_offsets(np.c_[new_x_data, orig_y_data])\n\n def beeswarm(self, orig_xyr):\n \"\"\"Adjust x position of points to avoid overlaps.\"\"\"\n # In this method, `x` is always the categorical axis\n # Center of the swarm, in point coordinates\n midline = orig_xyr[0, 0]\n\n # Start the swarm with the first point\n swarm = np.atleast_2d(orig_xyr[0])\n\n # Loop over the remaining points\n for xyr_i in orig_xyr[1:]:\n\n # Find the points in the swarm that could possibly\n # overlap with the point we are currently placing\n neighbors = self.could_overlap(xyr_i, swarm)\n\n # Find positions that would be valid individually\n # with respect to each of the swarm neighbors\n candidates = self.position_candidates(xyr_i, neighbors)\n\n # Sort candidates by their centrality\n offsets = np.abs(candidates[:, 0] - midline)\n candidates = candidates[np.argsort(offsets)]\n\n # Find the first candidate that does not overlap any neighbors\n new_xyr_i = self.first_non_overlapping_candidate(candidates, neighbors)\n\n # Place it into the swarm\n swarm = np.vstack([swarm, new_xyr_i])\n\n return swarm\n\n def could_overlap(self, xyr_i, swarm):\n \"\"\"Return a list of all swarm points that could overlap with target.\"\"\"\n # Because we work backwards through the swarm and can short-circuit,\n # the for-loop is faster than vectorization\n _, y_i, r_i = xyr_i\n neighbors = []\n for xyr_j in reversed(swarm):\n _, y_j, r_j = xyr_j\n if (y_i - y_j) < (r_i + r_j):\n neighbors.append(xyr_j)\n else:\n break\n return np.array(neighbors)[::-1]\n\n def position_candidates(self, xyr_i, neighbors):\n \"\"\"Return a list of coordinates that might be valid by adjusting x.\"\"\"\n candidates = [xyr_i]\n x_i, y_i, r_i = xyr_i\n left_first = True\n for x_j, y_j, r_j in neighbors:\n dy = y_i - y_j\n dx = np.sqrt(max((r_i + r_j) ** 2 - dy ** 2, 0)) * 1.05\n cl, cr = (x_j - dx, y_i, r_i), (x_j + dx, y_i, r_i)\n if left_first:\n new_candidates = [cl, cr]\n else:\n new_candidates = [cr, cl]\n candidates.extend(new_candidates)\n left_first = not left_first\n return np.array(candidates)\n\n def first_non_overlapping_candidate(self, candidates, neighbors):\n \"\"\"Find the first candidate that does not overlap with the swarm.\"\"\"\n\n # If we have no neighbors, all candidates are good.\n if len(neighbors) == 0:\n return candidates[0]\n\n neighbors_x = neighbors[:, 0]\n neighbors_y = neighbors[:, 1]\n neighbors_r = neighbors[:, 2]\n\n for xyr_i in candidates:\n\n x_i, y_i, r_i = xyr_i\n\n dx = neighbors_x - x_i\n dy = neighbors_y - y_i\n sq_distances = np.square(dx) + np.square(dy)\n\n sep_needed = np.square(neighbors_r + r_i)\n\n # Good candidate does not overlap any of neighbors which means that\n # squared distance between candidate and any of the neighbors has\n # to be at least square of the summed radii\n good_candidate = np.all(sq_distances >= sep_needed)\n\n if good_candidate:\n return xyr_i\n\n raise RuntimeError(\n \"No non-overlapping candidates found. This should not happen.\"\n )\n\n def add_gutters(self, points, center, log_scale=False):\n \"\"\"Stop points from extending beyond their territory.\"\"\"\n half_width = self.width / 2\n if log_scale:\n low_gutter = 10 ** (np.log10(center) - half_width)\n else:\n low_gutter = center - half_width\n off_low = points < low_gutter\n if off_low.any():\n points[off_low] = low_gutter\n if log_scale:\n high_gutter = 10 ** (np.log10(center) + half_width)\n else:\n high_gutter = center + half_width\n off_high = points > high_gutter\n if off_high.any():\n points[off_high] = high_gutter\n\n gutter_prop = (off_high + off_low).sum() / len(points)\n if gutter_prop > self.warn_thresh:\n msg = (\n \"{:.1%} of the points cannot be placed; you may want \"\n \"to decrease the size of the markers or use stripplot.\"\n ).format(gutter_prop)\n warnings.warn(msg, UserWarning)\n\n return points"},{"attributeType":"str","col":8,"comment":"null","endLoc":3354,"id":4190,"name":"orient","nodeType":"Attribute","startLoc":3354,"text":"self.orient"},{"attributeType":"float","col":8,"comment":"null","endLoc":3355,"id":4191,"name":"width","nodeType":"Attribute","startLoc":3355,"text":"self.width"},{"attributeType":"float","col":8,"comment":"null","endLoc":3356,"id":4192,"name":"warn_thresh","nodeType":"Attribute","startLoc":3356,"text":"self.warn_thresh"},{"col":0,"comment":"null","endLoc":2952,"header":"def countplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n dodge=True, ax=None, **kwargs\n)","id":4193,"name":"countplot","nodeType":"Function","startLoc":2915,"text":"def countplot(\n data=None, *, x=None, y=None, hue=None, order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75, width=.8,\n dodge=True, ax=None, **kwargs\n):\n\n estimator = \"size\"\n errorbar = None\n n_boot = 0\n units = None\n seed = None\n errcolor = None\n errwidth = None\n capsize = None\n\n if x is None and y is not None:\n orient = \"h\"\n x = y\n elif y is None and x is not None:\n orient = \"v\"\n y = x\n elif x is not None and y is not None:\n raise ValueError(\"Cannot pass values for both `x` and `y`\")\n\n plotter = _CountPlotter(\n x, y, hue, data, order, hue_order,\n estimator, errorbar, n_boot, units, seed,\n orient, color, palette, saturation,\n width, errcolor, errwidth, capsize, dodge\n )\n\n plotter.value_label = \"count\"\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax"},{"className":"TestAgg","col":0,"comment":"null","endLoc":75,"id":4194,"nodeType":"Class","startLoc":32,"text":"class TestAgg(AggregationFixtures):\n\n def test_default(self, df):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Agg()(df, gb, ori, {})\n\n expected = df.groupby(\"x\", as_index=False)[\"y\"].mean()\n assert_frame_equal(res, expected)\n\n def test_default_multi(self, df):\n\n ori = \"x\"\n gb = self.get_groupby(df, ori)\n res = Agg()(df, gb, ori, {})\n\n grp = [\"x\", \"color\", \"group\"]\n index = pd.MultiIndex.from_product(\n [sorted(df[\"x\"].unique()), df[\"color\"].unique(), df[\"group\"].unique()],\n names=[\"x\", \"color\", \"group\"]\n )\n expected = (\n df\n .groupby(grp)\n .agg(\"mean\")\n .reindex(index=index)\n .dropna()\n .reset_index()\n .reindex(columns=df.columns)\n )\n assert_frame_equal(res, expected)\n\n @pytest.mark.parametrize(\"func\", [\"max\", lambda x: float(len(x) % 2)])\n def test_func(self, df, func):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Agg(func)(df, gb, ori, {})\n\n expected = df.groupby(\"x\", as_index=False)[\"y\"].agg(func)\n assert_frame_equal(res, expected)"},{"col":4,"comment":"null","endLoc":42,"header":"def test_default(self, df)","id":4195,"name":"test_default","nodeType":"Function","startLoc":34,"text":"def test_default(self, df):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Agg()(df, gb, ori, {})\n\n expected = df.groupby(\"x\", as_index=False)[\"y\"].mean()\n assert_frame_equal(res, expected)"},{"attributeType":"bool","col":4,"comment":"null","endLoc":11,"id":4196,"name":"_no_scipy","nodeType":"Attribute","startLoc":11,"text":"_no_scipy"},{"attributeType":"null","col":0,"comment":"null","endLoc":34,"id":4197,"name":"__all__","nodeType":"Attribute","startLoc":34,"text":"__all__"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":2050,"id":4198,"name":"_categorical_docs","nodeType":"Attribute","startLoc":2050,"text":"_categorical_docs"},{"col":0,"comment":"","endLoc":1,"header":"categorical.py#","id":4199,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n from scipy.stats import gaussian_kde\n _no_scipy = False\nexcept ImportError:\n from .external.kde import gaussian_kde\n _no_scipy = True\n\n__all__ = [\n \"catplot\",\n \"stripplot\", \"swarmplot\",\n \"boxplot\", \"violinplot\", \"boxenplot\",\n \"pointplot\", \"barplot\", \"countplot\",\n]\n\n_categorical_docs = dict(\n\n # Shared narrative docs\n categorical_narrative=dedent(\"\"\"\\\n .. note::\n This function always treats one of the variables as categorical and\n draws data at ordinal positions (0, 1, ... n) on the relevant axis,\n even when the data has a numeric or date type.\n\n See the :ref:`tutorial ` for more information.\\\n \"\"\"),\n\n new_categorical_narrative=dedent(\"\"\"\\\n .. note::\n By default, this function treats one of the variables as categorical\n and draws data at ordinal positions (0, 1, ... n) on the relevant axis.\n This can be disabled with the `native_scale` parameter.\n\n See the :ref:`tutorial ` for more information.\\\n \"\"\"),\n\n # Shared function parameters\n input_params=dedent(\"\"\"\\\n x, y, hue : names of variables in ``data`` or vector data, optional\n Inputs for plotting long-form data. See examples for interpretation.\\\n \"\"\"),\n string_input_params=dedent(\"\"\"\\\n x, y, hue : names of variables in ``data``\n Inputs for plotting long-form data. See examples for interpretation.\\\n \"\"\"),\n categorical_data=dedent(\"\"\"\\\n data : DataFrame, array, or list of arrays, optional\n Dataset for plotting. If ``x`` and ``y`` are absent, this is\n interpreted as wide-form. Otherwise it is expected to be long-form.\\\n \"\"\"),\n long_form_data=dedent(\"\"\"\\\n data : DataFrame\n Long-form (tidy) dataset for plotting. Each column should correspond\n to a variable, and each row should correspond to an observation.\\\n \"\"\"),\n order_vars=dedent(\"\"\"\\\n order, hue_order : lists of strings, optional\n Order to plot the categorical levels in; otherwise the levels are\n inferred from the data objects.\\\n \"\"\"),\n stat_api_params=dedent(\"\"\"\\\n estimator : string or callable that maps vector -> scalar, optional\n Statistical function to estimate within each categorical bin.\n errorbar : string, (string, number) tuple, callable or None\n Name of errorbar method (either \"ci\", \"pi\", \"se\", or \"sd\"), or a tuple\n with a method name and a level parameter, or a function that maps from a\n vector to a (min, max) interval, or None to hide errorbar.\n n_boot : int, optional\n Number of bootstrap samples used to compute confidence intervals.\n units : name of variable in ``data`` or vector data, optional\n Identifier of sampling units, which will be used to perform a\n multilevel bootstrap and account for repeated measures design.\n seed : int, numpy.random.Generator, or numpy.random.RandomState, optional\n Seed or random number generator for reproducible bootstrapping.\\\n \"\"\"),\n orient=dedent(\"\"\"\\\n orient : \"v\" | \"h\", optional\n Orientation of the plot (vertical or horizontal). This is usually\n inferred based on the type of the input variables, but it can be used\n to resolve ambiguity when both `x` and `y` are numeric or when\n plotting wide-form data.\\\n \"\"\"),\n color=dedent(\"\"\"\\\n color : matplotlib color, optional\n Single color for the elements in the plot.\\\n \"\"\"),\n palette=dedent(\"\"\"\\\n palette : palette name, list, or dict, optional\n Color palette that maps the hue variable. If the palette is a dictionary,\n keys should be names of levels and values should be matplotlib colors.\\\n \"\"\"),\n hue_norm=dedent(\"\"\"\\\n hue_norm : tuple or :class:`matplotlib.colors.Normalize` object\n Normalization in data units for colormap applied to the `hue`\n variable when it is numeric. Not relevant if `hue` is categorical.\\\n \"\"\"),\n saturation=dedent(\"\"\"\\\n saturation : float, optional\n Proportion of the original saturation to draw colors at. Large patches\n often look better with slightly desaturated colors, but set this to\n `1` if you want the plot colors to perfectly match the input color.\\\n \"\"\"),\n capsize=dedent(\"\"\"\\\n capsize : float, optional\n Width of the \"caps\" on error bars./\n \"\"\"),\n errwidth=dedent(\"\"\"\\\n errwidth : float, optional\n Thickness of error bar lines (and caps).\\\n \"\"\"),\n width=dedent(\"\"\"\\\n width : float, optional\n Width of a full element when not using hue nesting, or width of all the\n elements for one level of the major grouping variable.\\\n \"\"\"),\n dodge=dedent(\"\"\"\\\n dodge : bool, optional\n When hue nesting is used, whether elements should be shifted along the\n categorical axis.\\\n \"\"\"),\n linewidth=dedent(\"\"\"\\\n linewidth : float, optional\n Width of the gray lines that frame the plot elements.\\\n \"\"\"),\n native_scale=dedent(\"\"\"\\\n native_scale : bool, optional\n When True, numeric or datetime values on the categorical axis will maintain\n their original scaling rather than being converted to fixed indices.\\\n \"\"\"),\n formatter=dedent(\"\"\"\\\n formatter : callable, optional\n Function for converting categorical data into strings. Affects both grouping\n and tick labels.\\\n \"\"\"),\n legend=dedent(\"\"\"\\\nlegend : \"auto\", \"brief\", \"full\", or False\n How to draw the legend. If \"brief\", numeric `hue` and `size`\n variables will be represented with a sample of evenly spaced values.\n If \"full\", every group will get an entry in the legend. If \"auto\",\n choose between brief or full representation based on number of levels.\n If `False`, no legend data is added and no legend is drawn.\n \"\"\"),\n ax_in=dedent(\"\"\"\\\n ax : matplotlib Axes, optional\n Axes object to draw the plot onto, otherwise uses the current Axes.\\\n \"\"\"),\n ax_out=dedent(\"\"\"\\\n ax : matplotlib Axes\n Returns the Axes object with the plot drawn onto it.\\\n \"\"\"),\n\n # Shared see also\n boxplot=dedent(\"\"\"\\\n boxplot : A traditional box-and-whisker plot with a similar API.\\\n \"\"\"),\n violinplot=dedent(\"\"\"\\\n violinplot : A combination of boxplot and kernel density estimation.\\\n \"\"\"),\n stripplot=dedent(\"\"\"\\\n stripplot : A scatterplot where one variable is categorical. Can be used\n in conjunction with other plots to show each observation.\\\n \"\"\"),\n swarmplot=dedent(\"\"\"\\\n swarmplot : A categorical scatterplot where the points do not overlap. Can\n be used with other plots to show each observation.\\\n \"\"\"),\n barplot=dedent(\"\"\"\\\n barplot : Show point estimates and confidence intervals using bars.\\\n \"\"\"),\n countplot=dedent(\"\"\"\\\n countplot : Show the counts of observations in each categorical bin.\\\n \"\"\"),\n pointplot=dedent(\"\"\"\\\n pointplot : Show point estimates and confidence intervals using scatterplot\n glyphs.\\\n \"\"\"),\n catplot=dedent(\"\"\"\\\n catplot : Combine a categorical plot with a :class:`FacetGrid`.\\\n \"\"\"),\n boxenplot=dedent(\"\"\"\\\n boxenplot : An enhanced boxplot for larger datasets.\\\n \"\"\"),\n\n)\n\n_categorical_docs.update(_facet_docs)\n\nboxplot.__doc__ = dedent(\"\"\"\\\n Draw a box plot to show distributions with respect to categories.\n\n A box plot (or box-and-whisker plot) shows the distribution of quantitative\n data in a way that facilitates comparisons between variables or across\n levels of a categorical variable. The box shows the quartiles of the\n dataset while the whiskers extend to show the rest of the distribution,\n except for points that are determined to be \"outliers\" using a method\n that is a function of the inter-quartile range.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n {dodge}\n fliersize : float, optional\n Size of the markers used to indicate outlier observations.\n {linewidth}\n whis : float, optional\n Maximum length of the plot whiskers as proportion of the\n interquartile range. Whiskers extend to the furthest datapoint\n within that range. More extreme points are marked as outliers.\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.boxplot`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {violinplot}\n {stripplot}\n {swarmplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/boxplot.rst\n\n \"\"\").format(**_categorical_docs)\n\nviolinplot.__doc__ = dedent(\"\"\"\\\n Draw a combination of boxplot and kernel density estimate.\n\n A violin plot plays a similar role as a box and whisker plot. It shows the\n distribution of quantitative data across several levels of one (or more)\n categorical variables such that those distributions can be compared. Unlike\n a box plot, in which all of the plot components correspond to actual\n datapoints, the violin plot features a kernel density estimation of the\n underlying distribution.\n\n This can be an effective and attractive way to show multiple distributions\n of data at once, but keep in mind that the estimation procedure is\n influenced by the sample size, and violins for relatively small samples\n might look misleadingly smooth.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n bw : {{'scott', 'silverman', float}}, optional\n Either the name of a reference rule or the scale factor to use when\n computing the kernel bandwidth. The actual kernel size will be\n determined by multiplying the scale factor by the standard deviation of\n the data within each bin.\n cut : float, optional\n Distance, in units of bandwidth size, to extend the density past the\n extreme datapoints. Set to 0 to limit the violin range within the range\n of the observed data (i.e., to have the same effect as ``trim=True`` in\n ``ggplot``.\n scale : {{\"area\", \"count\", \"width\"}}, optional\n The method used to scale the width of each violin. If ``area``, each\n violin will have the same area. If ``count``, the width of the violins\n will be scaled by the number of observations in that bin. If ``width``,\n each violin will have the same width.\n scale_hue : bool, optional\n When nesting violins using a ``hue`` variable, this parameter\n determines whether the scaling is computed within each level of the\n major grouping variable (``scale_hue=True``) or across all the violins\n on the plot (``scale_hue=False``).\n gridsize : int, optional\n Number of points in the discrete grid used to compute the kernel\n density estimate.\n {width}\n inner : {{\"box\", \"quartile\", \"point\", \"stick\", None}}, optional\n Representation of the datapoints in the violin interior. If ``box``,\n draw a miniature boxplot. If ``quartiles``, draw the quartiles of the\n distribution. If ``point`` or ``stick``, show each underlying\n datapoint. Using ``None`` will draw unadorned violins.\n split : bool, optional\n When using hue nesting with a variable that takes two levels, setting\n ``split`` to True will draw half of a violin for each level. This can\n make it easier to directly compare the distributions.\n {dodge}\n {orient}\n {linewidth}\n {color}\n {palette}\n {saturation}\n {ax_in}\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {boxplot}\n {stripplot}\n {swarmplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/violinplot.rst\n\n \"\"\").format(**_categorical_docs)\n\nboxenplot.__doc__ = dedent(\"\"\"\\\n Draw an enhanced box plot for larger datasets.\n\n This style of plot was originally named a \"letter value\" plot because it\n shows a large number of quantiles that are defined as \"letter values\". It\n is similar to a box plot in plotting a nonparametric representation of a\n distribution in which all features correspond to actual observations. By\n plotting more quantiles, it provides more information about the shape of\n the distribution, particularly in the tails. For a more extensive\n explanation, you can read the paper that introduced the plot:\n https://vita.had.co.nz/papers/letter-value-plot.html\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n {dodge}\n k_depth : {{\"tukey\", \"proportion\", \"trustworthy\", \"full\"}} or scalar\n The number of boxes, and by extension number of percentiles, to draw.\n All methods are detailed in Wickham's paper. Each makes different\n assumptions about the number of outliers and leverages different\n statistical properties. If \"proportion\", draw no more than\n `outlier_prop` extreme observations. If \"full\", draw `log(n)+1` boxes.\n {linewidth}\n scale : {{\"exponential\", \"linear\", \"area\"}}, optional\n Method to use for the width of the letter value boxes. All give similar\n results visually. \"linear\" reduces the width by a constant linear\n factor, \"exponential\" uses the proportion of data not covered, \"area\"\n is proportional to the percentage of data covered.\n outlier_prop : float, optional\n Proportion of data believed to be outliers. Must be in the range\n (0, 1]. Used to determine the number of boxes to plot when\n `k_depth=\"proportion\"`.\n trust_alpha : float, optional\n Confidence level for a box to be plotted. Used to determine the\n number of boxes to plot when `k_depth=\"trustworthy\"`. Must be in the\n range (0, 1).\n showfliers : bool, optional\n If False, suppress the plotting of outliers.\n {ax_in}\n box_kws: dict, optional\n Keyword arguments for the box artists; passed to\n :class:`matplotlib.patches.Rectangle`.\n line_kws: dict, optional\n Keyword arguments for the line denoting the median; passed to\n :meth:`matplotlib.axes.Axes.plot`.\n flier_kws: dict, optional\n Keyword arguments for the scatter denoting the outlier observations;\n passed to :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {violinplot}\n {boxplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/boxenplot.rst\n\n \"\"\").format(**_categorical_docs)\n\nstripplot.__doc__ = dedent(\"\"\"\\\n Draw a categorical scatterplot using jitter to reduce overplotting.\n\n A strip plot can be drawn on its own, but it is also a good complement\n to a box or violin plot in cases where you want to show all observations\n along with some representation of the underlying distribution.\n\n {new_categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n jitter : float, ``True``/``1`` is special-cased, optional\n Amount of jitter (only along the categorical axis) to apply. This\n can be useful when you have many points and they overlap, so that\n it is easier to see the distribution. You can specify the amount\n of jitter (half the width of the uniform random variable support),\n or just use ``True`` for a good default.\n dodge : bool, optional\n When using ``hue`` nesting, setting this to ``True`` will separate\n the strips for different hue levels along the categorical axis.\n Otherwise, the points for each level will be plotted on top of\n each other.\n {orient}\n {color}\n {palette}\n size : float, optional\n Radius of the markers, in points.\n edgecolor : matplotlib color, \"gray\" is special-cased, optional\n Color of the lines around each point. If you pass ``\"gray\"``, the\n brightness is determined by the color palette used for the body\n of the points.\n {linewidth}\n {native_scale}\n {formatter}\n {legend}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {swarmplot}\n {boxplot}\n {violinplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/stripplot.rst\n\n \"\"\").format(**_categorical_docs)\n\nswarmplot.__doc__ = dedent(\"\"\"\\\n Draw a categorical scatterplot with points adjusted to be non-overlapping.\n\n This function is similar to :func:`stripplot`, but the points are adjusted\n (only along the categorical axis) so that they don't overlap. This gives a\n better representation of the distribution of values, but it does not scale\n well to large numbers of observations. This style of plot is sometimes\n called a \"beeswarm\".\n\n A swarm plot can be drawn on its own, but it is also a good complement\n to a box or violin plot in cases where you want to show all observations\n along with some representation of the underlying distribution.\n\n {new_categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n dodge : bool, optional\n When using ``hue`` nesting, setting this to ``True`` will separate\n the strips for different hue levels along the categorical axis.\n Otherwise, the points for each level will be plotted in one swarm.\n {orient}\n {color}\n {palette}\n size : float, optional\n Radius of the markers, in points.\n edgecolor : matplotlib color, \"gray\" is special-cased, optional\n Color of the lines around each point. If you pass ``\"gray\"``, the\n brightness is determined by the color palette used for the body\n of the points.\n {linewidth}\n {native_scale}\n {formatter}\n {legend}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {boxplot}\n {violinplot}\n {stripplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/swarmplot.rst\n\n \"\"\").format(**_categorical_docs)\n\nbarplot.__doc__ = dedent(\"\"\"\\\n Show point estimates and errors as rectangular bars.\n\n A bar plot represents an estimate of central tendency for a numeric\n variable with the height of each rectangle and provides some indication of\n the uncertainty around that estimate using error bars. Bar plots include 0\n in the quantitative axis range, and they are a good choice when 0 is a\n meaningful value for the quantitative variable, and you want to make\n comparisons against it.\n\n For datasets where 0 is not a meaningful value, a point plot will allow you\n to focus on differences between levels of one or more categorical\n variables.\n\n It is also important to keep in mind that a bar plot shows only the mean\n (or other estimator) value, but in many cases it may be more informative to\n show the distribution of values at each level of the categorical variables.\n In that case, other approaches such as a box or violin plot may be more\n appropriate.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {stat_api_params}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n errcolor : matplotlib color\n Color used for the error bar lines.\n {errwidth}\n {capsize}\n {dodge}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {countplot}\n {pointplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/barplot.rst\n\n\n \"\"\").format(**_categorical_docs)\n\npointplot.__doc__ = dedent(\"\"\"\\\n Show point estimates and errors using dot marks.\n\n A point plot represents an estimate of central tendency for a numeric\n variable by the position of the dot and provides some indication of the\n uncertainty around that estimate using error bars.\n\n Point plots can be more useful than bar plots for focusing comparisons\n between different levels of one or more categorical variables. They are\n particularly adept at showing interactions: how the relationship between\n levels of one categorical variable changes across levels of a second\n categorical variable. The lines that join each point from the same `hue`\n level allow interactions to be judged by differences in slope, which is\n easier for the eyes than comparing the heights of several groups of points\n or bars.\n\n It is important to keep in mind that a point plot shows only the mean (or\n other estimator) value, but in many cases it may be more informative to\n show the distribution of values at each level of the categorical variables.\n In that case, other approaches such as a box or violin plot may be more\n appropriate.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {stat_api_params}\n markers : string or list of strings, optional\n Markers to use for each of the ``hue`` levels.\n linestyles : string or list of strings, optional\n Line styles to use for each of the ``hue`` levels.\n dodge : bool or float, optional\n Amount to separate the points for each level of the ``hue`` variable\n along the categorical axis.\n join : bool, optional\n If ``True``, lines will be drawn between point estimates at the same\n ``hue`` level.\n scale : float, optional\n Scale factor for the plot elements.\n {orient}\n {color}\n {palette}\n {errwidth}\n {capsize}\n {ax_in}\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {barplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/pointplot.rst\n\n \"\"\").format(**_categorical_docs)\n\ncountplot.__doc__ = dedent(\"\"\"\\\n Show the counts of observations in each categorical bin using bars.\n\n A count plot can be thought of as a histogram across a categorical, instead\n of quantitative, variable. The basic API and options are identical to those\n for :func:`barplot`, so you can compare counts across nested variables.\n\n Note that the newer :func:`histplot` function offers more functionality, although\n its default behavior is somewhat different.\n\n {categorical_narrative}\n\n Parameters\n ----------\n {categorical_data}\n {input_params}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {dodge}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {barplot}\n {catplot}\n\n Examples\n --------\n\n .. include:: ../docstrings/countplot.rst\n\n \"\"\").format(**_categorical_docs)\n\ncatplot.__doc__ = dedent(\"\"\"\\\n Figure-level interface for drawing categorical plots onto a FacetGrid.\n\n This function provides access to several axes-level functions that\n show the relationship between a numerical and one or more categorical\n variables using one of several visual representations. The `kind`\n parameter selects the underlying axes-level function to use:\n\n Categorical scatterplots:\n\n - :func:`stripplot` (with `kind=\"strip\"`; the default)\n - :func:`swarmplot` (with `kind=\"swarm\"`)\n\n Categorical distribution plots:\n\n - :func:`boxplot` (with `kind=\"box\"`)\n - :func:`violinplot` (with `kind=\"violin\"`)\n - :func:`boxenplot` (with `kind=\"boxen\"`)\n\n Categorical estimate plots:\n\n - :func:`pointplot` (with `kind=\"point\"`)\n - :func:`barplot` (with `kind=\"bar\"`)\n - :func:`countplot` (with `kind=\"count\"`)\n\n Extra keyword arguments are passed to the underlying function, so you\n should refer to the documentation for each to see kind-specific options.\n\n Note that unlike when using the axes-level functions directly, data must be\n passed in a long-form DataFrame with variables specified by passing strings\n to `x`, `y`, `hue`, etc.\n\n {categorical_narrative}\n\n After plotting, the :class:`FacetGrid` with the plot is returned and can\n be used directly to tweak supporting plot details or add other layers.\n\n Parameters\n ----------\n {long_form_data}\n {string_input_params}\n row, col : names of variables in `data`, optional\n Categorical variables that will determine the faceting of the grid.\n {col_wrap}\n {stat_api_params}\n {order_vars}\n row_order, col_order : lists of strings, optional\n Order to organize the rows and/or columns of the grid in, otherwise the\n orders are inferred from the data objects.\n {height}\n {aspect}\n kind : str, optional\n The kind of plot to draw, corresponds to the name of a categorical\n axes-level plotting function. Options are: \"strip\", \"swarm\", \"box\", \"violin\",\n \"boxen\", \"point\", \"bar\", or \"count\".\n {native_scale}\n {formatter}\n {orient}\n {color}\n {palette}\n {hue_norm}\n legend : str or bool, optional\n Set to `False` to disable the legend. With `strip` or `swarm` plots,\n this also accepts a string, as described in the axes-level docstrings.\n {legend_out}\n {share_xy}\n {margin_titles}\n facet_kws : dict, optional\n Dictionary of other keyword arguments to pass to :class:`FacetGrid`.\n kwargs : key, value pairings\n Other keyword arguments are passed through to the underlying plotting\n function.\n\n Returns\n -------\n g : :class:`FacetGrid`\n Returns the :class:`FacetGrid` object with the plot on it for further\n tweaking.\n\n Examples\n --------\n\n .. include:: ../docstrings/catplot.rst\n\n \"\"\").format(**_categorical_docs)"},{"col":4,"comment":"null","endLoc":64,"header":"def test_default_multi(self, df)","id":4200,"name":"test_default_multi","nodeType":"Function","startLoc":44,"text":"def test_default_multi(self, df):\n\n ori = \"x\"\n gb = self.get_groupby(df, ori)\n res = Agg()(df, gb, ori, {})\n\n grp = [\"x\", \"color\", \"group\"]\n index = pd.MultiIndex.from_product(\n [sorted(df[\"x\"].unique()), df[\"color\"].unique(), df[\"group\"].unique()],\n names=[\"x\", \"color\", \"group\"]\n )\n expected = (\n df\n .groupby(grp)\n .agg(\"mean\")\n .reindex(index=index)\n .dropna()\n .reset_index()\n .reindex(columns=df.columns)\n )\n assert_frame_equal(res, expected)"},{"col":4,"comment":"null","endLoc":75,"header":"@pytest.mark.parametrize(\"func\", [\"max\", lambda x: float(len(x) % 2)])\n def test_func(self, df, func)","id":4201,"name":"test_func","nodeType":"Function","startLoc":66,"text":"@pytest.mark.parametrize(\"func\", [\"max\", lambda x: float(len(x) % 2)])\n def test_func(self, df, func):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Agg(func)(df, gb, ori, {})\n\n expected = df.groupby(\"x\", as_index=False)[\"y\"].agg(func)\n assert_frame_equal(res, expected)"},{"col":45,"endLoc":66,"id":4202,"nodeType":"Lambda","startLoc":66,"text":"lambda x: float(len(x) % 2)"},{"className":"TestEst","col":0,"comment":"null","endLoc":125,"id":4203,"nodeType":"Class","startLoc":78,"text":"class TestEst(AggregationFixtures):\n\n # Note: Most of the underlying code is exercised in tests/test_statistics\n\n @pytest.mark.parametrize(\"func\", [np.mean, \"mean\"])\n def test_mean_sd(self, df, func):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Est(func, \"sd\")(df, gb, ori, {})\n\n grouped = df.groupby(\"x\", as_index=False)[\"y\"]\n est = grouped.mean()\n err = grouped.std().fillna(0) # fillna needed only on pinned tests\n expected = est.assign(ymin=est[\"y\"] - err[\"y\"], ymax=est[\"y\"] + err[\"y\"])\n assert_frame_equal(res, expected)\n\n def test_sd_single_obs(self):\n\n y = 1.5\n ori = \"x\"\n df = pd.DataFrame([{\"x\": \"a\", \"y\": y}])\n gb = self.get_groupby(df, ori)\n res = Est(\"mean\", \"sd\")(df, gb, ori, {})\n expected = df.assign(ymin=y, ymax=y)\n assert_frame_equal(res, expected)\n\n def test_median_pi(self, df):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Est(\"median\", (\"pi\", 100))(df, gb, ori, {})\n\n grouped = df.groupby(\"x\", as_index=False)[\"y\"]\n est = grouped.median()\n expected = est.assign(ymin=grouped.min()[\"y\"], ymax=grouped.max()[\"y\"])\n assert_frame_equal(res, expected)\n\n def test_seed(self, df):\n\n ori = \"x\"\n gb = self.get_groupby(df, ori)\n args = df, gb, ori, {}\n res1 = Est(\"mean\", \"ci\", seed=99)(*args)\n res2 = Est(\"mean\", \"ci\", seed=99)(*args)\n assert_frame_equal(res1, res2)"},{"col":4,"comment":"null","endLoc":94,"header":"@pytest.mark.parametrize(\"func\", [np.mean, \"mean\"])\n def test_mean_sd(self, df, func)","id":4204,"name":"test_mean_sd","nodeType":"Function","startLoc":82,"text":"@pytest.mark.parametrize(\"func\", [np.mean, \"mean\"])\n def test_mean_sd(self, df, func):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Est(func, \"sd\")(df, gb, ori, {})\n\n grouped = df.groupby(\"x\", as_index=False)[\"y\"]\n est = grouped.mean()\n err = grouped.std().fillna(0) # fillna needed only on pinned tests\n expected = est.assign(ymin=est[\"y\"] - err[\"y\"], ymax=est[\"y\"] + err[\"y\"])\n assert_frame_equal(res, expected)"},{"attributeType":"str","col":7,"comment":"null","endLoc":10,"id":4205,"name":"kernel_name","nodeType":"Attribute","startLoc":10,"text":"kernel_name"},{"attributeType":"list","col":4,"comment":"null","endLoc":12,"id":4206,"name":"nb_paths","nodeType":"Attribute","startLoc":12,"text":"nb_paths"},{"attributeType":"str","col":8,"comment":"null","endLoc":13,"id":4207,"name":"path","nodeType":"Attribute","startLoc":13,"text":"path"},{"attributeType":"TextIO","col":27,"comment":"null","endLoc":15,"id":4208,"name":"f","nodeType":"Attribute","startLoc":15,"text":"f"},{"fileName":"test_core.py","filePath":"tests","id":4209,"nodeType":"File","text":"import itertools\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport pytest\nfrom numpy.testing import assert_array_equal\nfrom pandas.testing import assert_frame_equal\n\nfrom seaborn.axisgrid import FacetGrid\nfrom seaborn._compat import get_colormap\nfrom seaborn._oldcore import (\n SemanticMapping,\n HueMapping,\n SizeMapping,\n StyleMapping,\n VectorPlotter,\n variable_type,\n infer_orient,\n unique_dashes,\n unique_markers,\n categorical_order,\n)\n\nfrom seaborn.palettes import color_palette\n\n\ntry:\n from pandas import NA as PD_NA\nexcept ImportError:\n PD_NA = None\n\n\n@pytest.fixture(params=[\n dict(x=\"x\", y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"a\", y=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"a\"),\n dict(x=\"x\", y=\"y\", size=\"a\"),\n dict(x=\"x\", y=\"y\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"s\"),\n dict(x=\"x\", y=\"y\", size=\"s\"),\n dict(x=\"x\", y=\"y\", style=\"s\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", size=\"b\", style=\"b\"),\n])\ndef long_variables(request):\n return request.param\n\n\nclass TestSemanticMapping:\n\n def test_call_lookup(self):\n\n m = SemanticMapping(VectorPlotter())\n lookup_table = dict(zip(\"abc\", (1, 2, 3)))\n m.lookup_table = lookup_table\n for key, val in lookup_table.items():\n assert m(key) == val\n\n\nclass TestHueMapping:\n\n def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n palette = \"Set2\"\n p = HueMapping.map(p_orig, palette=palette)\n assert p is p_orig\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.palette == palette\n\n def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.map_type is None\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.map_type == p.var_types[\"hue\"]\n\n def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n palette = \"muted\"\n hue_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_hue(palette=palette, order=hue_order)\n assert p is p_orig\n assert p._hue_map.palette == palette\n assert p._hue_map.levels == hue_order\n\n def test_hue_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, hue=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.palette is None\n assert m.cmap is None\n assert m.norm is None\n assert m.lookup_table is None\n\n def test_hue_map_categorical(self, wide_df, long_df):\n\n p = VectorPlotter(data=wide_df)\n m = HueMapping(p)\n assert m.levels == wide_df.columns.to_list()\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test named palette\n palette = \"Blues\"\n expected_colors = color_palette(palette, wide_df.shape[1])\n expected_lookup_table = dict(zip(wide_df.columns, expected_colors))\n m = HueMapping(p, palette=palette)\n assert m.palette == \"Blues\"\n assert m.lookup_table == expected_lookup_table\n\n # Test list palette\n palette = color_palette(\"Reds\", wide_df.shape[1])\n expected_lookup_table = dict(zip(wide_df.columns, palette))\n m = HueMapping(p, palette=palette)\n assert m.palette == palette\n assert m.lookup_table == expected_lookup_table\n\n # Test dict palette\n colors = color_palette(\"Set1\", 8)\n palette = dict(zip(wide_df.columns, colors))\n m = HueMapping(p, palette=palette)\n assert m.palette == palette\n assert m.lookup_table == palette\n\n # Test dict with missing keys\n palette = dict(zip(wide_df.columns[:-1], colors))\n with pytest.raises(ValueError):\n HueMapping(p, palette=palette)\n\n # Test list with wrong number of colors\n palette = colors[:-1]\n with pytest.warns(UserWarning):\n HueMapping(p, palette=palette)\n\n # Test hue order\n hue_order = [\"a\", \"c\", \"d\"]\n m = HueMapping(p, order=hue_order)\n assert m.levels == hue_order\n\n # Test long data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"a\"))\n m = HueMapping(p)\n assert m.levels == categorical_order(long_df[\"a\"])\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test default palette\n m = HueMapping(p)\n hue_levels = categorical_order(long_df[\"a\"])\n expected_colors = color_palette(n_colors=len(hue_levels))\n expected_lookup_table = dict(zip(hue_levels, expected_colors))\n assert m.lookup_table == expected_lookup_table\n\n # Test missing data\n m = HueMapping(p)\n assert m(np.nan) == (0, 0, 0, 0)\n\n # Test default palette with many levels\n x = y = np.arange(26)\n hue = pd.Series(list(\"abcdefghijklmnopqrstuvwxyz\"))\n p = VectorPlotter(variables=dict(x=x, y=y, hue=hue))\n m = HueMapping(p)\n expected_colors = color_palette(\"husl\", n_colors=len(hue))\n expected_lookup_table = dict(zip(hue, expected_colors))\n assert m.lookup_table == expected_lookup_table\n\n # Test binary data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"c\"))\n m = HueMapping(p)\n assert m.levels == [0, 1]\n assert m.map_type == \"categorical\"\n\n for val in [0, 1]:\n p = VectorPlotter(\n data=long_df[long_df[\"c\"] == val],\n variables=dict(x=\"x\", y=\"y\", hue=\"c\"),\n )\n m = HueMapping(p)\n assert m.levels == [val]\n assert m.map_type == \"categorical\"\n\n # Test Timestamp data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"t\"))\n m = HueMapping(p)\n assert m.levels == [pd.Timestamp(t) for t in long_df[\"t\"].unique()]\n assert m.map_type == \"datetime\"\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", hue=\"a_cat\"))\n m = HueMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n assert m.map_type == \"categorical\"\n\n # Test numeric data with category type\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s_cat\")\n )\n m = HueMapping(p)\n assert m.levels == categorical_order(long_df[\"s_cat\"])\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test categorical palette specified for numeric data\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s\")\n )\n palette = \"deep\"\n levels = categorical_order(long_df[\"s\"])\n expected_colors = color_palette(palette, n_colors=len(levels))\n expected_lookup_table = dict(zip(levels, expected_colors))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == expected_lookup_table\n assert m.map_type == \"categorical\"\n\n def test_hue_map_numeric(self, long_df):\n\n vals = np.concatenate([np.linspace(0, 1, 256), [-.1, 1.1, np.nan]])\n\n # Test default colormap\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s\")\n )\n hue_levels = list(np.sort(long_df[\"s\"].unique()))\n m = HueMapping(p)\n assert m.levels == hue_levels\n assert m.map_type == \"numeric\"\n assert m.cmap.name == \"seaborn_cubehelix\"\n\n # Test named colormap\n palette = \"Purples\"\n m = HueMapping(p, palette=palette)\n assert_array_equal(m.cmap(vals), get_colormap(palette)(vals))\n\n # Test colormap object\n palette = get_colormap(\"Greens\")\n m = HueMapping(p, palette=palette)\n assert_array_equal(m.cmap(vals), palette(vals))\n\n # Test cubehelix shorthand\n palette = \"ch:2,0,light=.2\"\n m = HueMapping(p, palette=palette)\n assert isinstance(m.cmap, mpl.colors.ListedColormap)\n\n # Test specified hue limits\n hue_norm = 1, 4\n m = HueMapping(p, norm=hue_norm)\n assert isinstance(m.norm, mpl.colors.Normalize)\n assert m.norm.vmin == hue_norm[0]\n assert m.norm.vmax == hue_norm[1]\n\n # Test Normalize object\n hue_norm = mpl.colors.PowerNorm(2, vmin=1, vmax=10)\n m = HueMapping(p, norm=hue_norm)\n assert m.norm is hue_norm\n\n # Test default colormap values\n hmin, hmax = p.plot_data[\"hue\"].min(), p.plot_data[\"hue\"].max()\n m = HueMapping(p)\n assert m.lookup_table[hmin] == pytest.approx(m.cmap(0.0))\n assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))\n\n # Test specified colormap values\n hue_norm = hmin - 1, hmax - 1\n m = HueMapping(p, norm=hue_norm)\n norm_min = (hmin - hue_norm[0]) / (hue_norm[1] - hue_norm[0])\n assert m.lookup_table[hmin] == pytest.approx(m.cmap(norm_min))\n assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))\n\n # Test list of colors\n hue_levels = list(np.sort(long_df[\"s\"].unique()))\n palette = color_palette(\"Blues\", len(hue_levels))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == dict(zip(hue_levels, palette))\n\n palette = color_palette(\"Blues\", len(hue_levels) + 1)\n with pytest.warns(UserWarning):\n HueMapping(p, palette=palette)\n\n # Test dictionary of colors\n palette = dict(zip(hue_levels, color_palette(\"Reds\")))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == palette\n\n palette.pop(hue_levels[0])\n with pytest.raises(ValueError):\n HueMapping(p, palette=palette)\n\n # Test invalid palette\n with pytest.raises(ValueError):\n HueMapping(p, palette=\"not a valid palette\")\n\n # Test bad norm argument\n with pytest.raises(ValueError):\n HueMapping(p, norm=\"not a norm\")\n\n def test_hue_map_without_hue_dataa(self, long_df):\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n with pytest.warns(UserWarning, match=\"Ignoring `palette`\"):\n HueMapping(p, palette=\"viridis\")\n\n\nclass TestSizeMapping:\n\n def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\")\n )\n sizes = 1, 6\n p = SizeMapping.map(p_orig, sizes=sizes)\n assert p is p_orig\n assert isinstance(p._size_map, SizeMapping)\n assert min(p._size_map.lookup_table.values()) == sizes[0]\n assert max(p._size_map.lookup_table.values()) == sizes[1]\n\n def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._size_map, SizeMapping)\n assert p._size_map.map_type is None\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n assert isinstance(p._size_map, SizeMapping)\n assert p._size_map.map_type == p.var_types[\"size\"]\n\n def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n sizes = [1, 4, 2]\n size_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_size(sizes=sizes, order=size_order)\n assert p is p_orig\n assert p._size_map.lookup_table == dict(zip(size_order, sizes))\n assert p._size_map.levels == size_order\n\n def test_size_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, size=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.norm is None\n assert m.lookup_table is None\n\n def test_map_size_numeric(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n )\n\n # Test default range of keys in the lookup table values\n m = SizeMapping(p)\n size_values = m.lookup_table.values()\n value_range = min(size_values), max(size_values)\n assert value_range == p._default_size_range\n\n # Test specified range of size values\n sizes = 1, 5\n m = SizeMapping(p, sizes=sizes)\n size_values = m.lookup_table.values()\n assert min(size_values), max(size_values) == sizes\n\n # Test size values with normalization range\n norm = 1, 10\n m = SizeMapping(p, sizes=sizes, norm=norm)\n normalize = mpl.colors.Normalize(*norm, clip=True)\n for key, val in m.lookup_table.items():\n assert val == sizes[0] + (sizes[1] - sizes[0]) * normalize(key)\n\n # Test size values with normalization object\n norm = mpl.colors.LogNorm(1, 10, clip=False)\n m = SizeMapping(p, sizes=sizes, norm=norm)\n assert m.norm.clip\n for key, val in m.lookup_table.items():\n assert val == sizes[0] + (sizes[1] - sizes[0]) * norm(key)\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=\"bad_sizes\")\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=(1, 2, 3))\n\n # Test bad norm argument\n with pytest.raises(ValueError):\n SizeMapping(p, norm=\"bad_norm\")\n\n def test_map_size_categorical(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n # Test specified size order\n levels = p.plot_data[\"size\"].unique()\n sizes = [1, 4, 6]\n order = [levels[1], levels[2], levels[0]]\n m = SizeMapping(p, sizes=sizes, order=order)\n assert m.lookup_table == dict(zip(order, sizes))\n\n # Test list of sizes\n order = categorical_order(p.plot_data[\"size\"])\n sizes = list(np.random.rand(len(levels)))\n m = SizeMapping(p, sizes=sizes)\n assert m.lookup_table == dict(zip(order, sizes))\n\n # Test dict of sizes\n sizes = dict(zip(levels, np.random.rand(len(levels))))\n m = SizeMapping(p, sizes=sizes)\n assert m.lookup_table == sizes\n\n # Test specified size range\n sizes = (2, 5)\n m = SizeMapping(p, sizes=sizes)\n values = np.linspace(*sizes, len(m.levels))[::-1]\n assert m.lookup_table == dict(zip(m.levels, values))\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", size=\"a_cat\"))\n m = SizeMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n assert m.map_type == \"categorical\"\n\n # Test sizes list with wrong length\n sizes = list(np.random.rand(len(levels) + 1))\n with pytest.warns(UserWarning):\n SizeMapping(p, sizes=sizes)\n\n # Test sizes dict with missing levels\n sizes = dict(zip(levels, np.random.rand(len(levels) - 1)))\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=sizes)\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=\"bad_size\")\n\n\nclass TestStyleMapping:\n\n def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\")\n )\n markers = [\"s\", \"p\", \"h\"]\n p = StyleMapping.map(p_orig, markers=markers)\n assert p is p_orig\n assert isinstance(p._style_map, StyleMapping)\n assert p._style_map(p._style_map.levels, \"marker\") == markers\n\n def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._style_map, StyleMapping)\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n assert isinstance(p._style_map, StyleMapping)\n\n def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n markers = [\"s\", \"p\", \"h\"]\n style_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_style(markers=markers, order=style_order)\n assert p is p_orig\n assert p._style_map.levels == style_order\n assert p._style_map(style_order, \"marker\") == markers\n\n def test_style_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, style=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.lookup_table is None\n\n def test_map_style(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n\n # Test defaults\n m = StyleMapping(p, markers=True, dashes=True)\n\n n = len(m.levels)\n for key, dashes in zip(m.levels, unique_dashes(n)):\n assert m(key, \"dashes\") == dashes\n\n actual_marker_paths = {\n k: mpl.markers.MarkerStyle(m(k, \"marker\")).get_path()\n for k in m.levels\n }\n expected_marker_paths = {\n k: mpl.markers.MarkerStyle(m).get_path()\n for k, m in zip(m.levels, unique_markers(n))\n }\n assert actual_marker_paths == expected_marker_paths\n\n # Test lists\n markers, dashes = [\"o\", \"s\", \"d\"], [(1, 0), (1, 1), (2, 1, 3, 1)]\n m = StyleMapping(p, markers=markers, dashes=dashes)\n for key, mark, dash in zip(m.levels, markers, dashes):\n assert m(key, \"marker\") == mark\n assert m(key, \"dashes\") == dash\n\n # Test dicts\n markers = dict(zip(p.plot_data[\"style\"].unique(), markers))\n dashes = dict(zip(p.plot_data[\"style\"].unique(), dashes))\n m = StyleMapping(p, markers=markers, dashes=dashes)\n for key in m.levels:\n assert m(key, \"marker\") == markers[key]\n assert m(key, \"dashes\") == dashes[key]\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", style=\"a_cat\"))\n m = StyleMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n\n # Test style order with defaults\n order = p.plot_data[\"style\"].unique()[[1, 2, 0]]\n m = StyleMapping(p, markers=True, dashes=True, order=order)\n n = len(order)\n for key, mark, dash in zip(order, unique_markers(n), unique_dashes(n)):\n assert m(key, \"dashes\") == dash\n assert m(key, \"marker\") == mark\n obj = mpl.markers.MarkerStyle(mark)\n path = obj.get_path().transformed(obj.get_transform())\n assert_array_equal(m(key, \"path\").vertices, path.vertices)\n\n # Test too many levels with style lists\n with pytest.warns(UserWarning):\n StyleMapping(p, markers=[\"o\", \"s\"], dashes=False)\n\n with pytest.warns(UserWarning):\n StyleMapping(p, markers=False, dashes=[(2, 1)])\n\n # Test missing keys with style dicts\n markers, dashes = {\"a\": \"o\", \"b\": \"s\"}, False\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n markers, dashes = False, {\"a\": (1, 0), \"b\": (2, 1)}\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n # Test mixture of filled and unfilled markers\n markers, dashes = [\"o\", \"x\", \"s\"], None\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n\nclass TestVectorPlotter:\n\n def test_flat_variables(self, flat_data):\n\n p = VectorPlotter()\n p.assign_variables(data=flat_data)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_data)\n\n try:\n expected_x = flat_data.index\n expected_x_name = flat_data.index.name\n except AttributeError:\n expected_x = np.arange(len(flat_data))\n expected_x_name = None\n\n x = p.plot_data[\"x\"]\n assert_array_equal(x, expected_x)\n\n expected_y = flat_data\n expected_y_name = getattr(flat_data, \"name\", None)\n\n y = p.plot_data[\"y\"]\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] == expected_x_name\n assert p.variables[\"y\"] == expected_y_name\n\n def test_long_df(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(data=long_df, variables=long_variables)\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_df_with_index(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_df.set_index(\"a\"),\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_df_with_multiindex(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_df.set_index([\"a\", \"x\"]),\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_dict(self, long_dict, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_dict,\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], pd.Series(long_dict[val]))\n\n @pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_long_vectors(self, long_df, long_variables, vector_type):\n\n variables = {key: long_df[val] for key, val in long_variables.items()}\n if vector_type == \"numpy\":\n variables = {key: val.to_numpy() for key, val in variables.items()}\n elif vector_type == \"list\":\n variables = {key: val.to_list() for key, val in variables.items()}\n\n p = VectorPlotter()\n p.assign_variables(variables=variables)\n assert p.input_format == \"long\"\n\n assert list(p.variables) == list(long_variables)\n if vector_type == \"series\":\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_undefined_variables(self, long_df):\n\n p = VectorPlotter()\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"not_in_df\"),\n )\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"x\", y=\"not_in_df\"),\n )\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"not_in_df\"),\n )\n\n @pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg):\n\n p = VectorPlotter()\n p.assign_variables(data=arg)\n assert not p.variables\n\n if not isinstance(arg, pd.DataFrame):\n p = VectorPlotter()\n p.assign_variables(variables=dict(x=arg, y=arg))\n assert not p.variables\n\n def test_units(self, repeated_df):\n\n p = VectorPlotter()\n p.assign_variables(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", units=\"u\"),\n )\n assert_array_equal(p.plot_data[\"units\"], repeated_df[\"u\"])\n\n @pytest.mark.parametrize(\"name\", [3, 4.5])\n def test_long_numeric_name(self, long_df, name):\n\n long_df[name] = long_df[\"x\"]\n p = VectorPlotter()\n p.assign_variables(data=long_df, variables={\"x\": name})\n assert_array_equal(p.plot_data[\"x\"], long_df[name])\n assert p.variables[\"x\"] == name\n\n def test_long_hierarchical_index(self, rng):\n\n cols = pd.MultiIndex.from_product([[\"a\"], [\"x\", \"y\"]])\n data = rng.uniform(size=(50, 2))\n df = pd.DataFrame(data, columns=cols)\n\n name = (\"a\", \"y\")\n var = \"y\"\n\n p = VectorPlotter()\n p.assign_variables(data=df, variables={var: name})\n assert_array_equal(p.plot_data[var], df[name])\n assert p.variables[var] == name\n\n def test_long_scalar_and_data(self, long_df):\n\n val = 22\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": val})\n assert (p.plot_data[\"y\"] == val).all()\n assert p.variables[\"y\"] is None\n\n def test_wide_semantic_error(self, wide_df):\n\n err = \"The following variable cannot be assigned with wide-form data: `hue`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=wide_df, variables={\"hue\": \"a\"})\n\n def test_long_unknown_error(self, long_df):\n\n err = \"Could not interpret value `what` for parameter `hue`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": \"what\"})\n\n def test_long_unmatched_size_error(self, long_df, flat_array):\n\n err = \"Length of ndarray vectors must match length of `data`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": flat_array})\n\n def test_wide_categorical_columns(self, wide_df):\n\n wide_df.columns = pd.CategoricalIndex(wide_df.columns)\n p = VectorPlotter(data=wide_df)\n assert_array_equal(p.plot_data[\"hue\"].unique(), [\"a\", \"b\", \"c\"])\n\n def test_iter_data_quantitites(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n out = p.iter_data(\"hue\")\n assert len(list(out)) == 1\n\n var = \"a\"\n n_subsets = len(long_df[var].unique())\n\n semantics = [\"hue\", \"size\", \"style\"]\n for semantic in semantics:\n\n p = VectorPlotter(\n data=long_df,\n variables={\"x\": \"x\", \"y\": \"y\", semantic: var},\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n var = \"a\"\n n_subsets = len(long_df[var].unique())\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var, style=var),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n # --\n\n out = p.iter_data(semantics, reverse=True)\n assert len(list(out)) == n_subsets\n\n # --\n\n var1, var2 = \"a\", \"s\"\n\n n_subsets = len(long_df[var1].unique())\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, style=var2),\n )\n out = p.iter_data([\"hue\"])\n assert len(list(out)) == n_subsets\n\n n_subsets = len(set(list(map(tuple, long_df[[var1, var2]].values))))\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, style=var2),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2, style=var1),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n # --\n\n var1, var2, var3 = \"a\", \"s\", \"b\"\n cols = [var1, var2, var3]\n n_subsets = len(set(list(map(tuple, long_df[cols].values))))\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2, style=var3),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n def test_iter_data_keys(self, long_df):\n\n semantics = [\"hue\", \"size\", \"style\"]\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert sub_vars == {}\n\n # --\n\n var = \"a\"\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert list(sub_vars) == [\"hue\"]\n assert sub_vars[\"hue\"] in long_df[var].values\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=var),\n )\n for sub_vars, _ in p.iter_data(\"size\"):\n assert list(sub_vars) == [\"size\"]\n assert sub_vars[\"size\"] in long_df[var].values\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var, style=var),\n )\n for sub_vars, _ in p.iter_data(semantics):\n assert list(sub_vars) == [\"hue\", \"style\"]\n assert sub_vars[\"hue\"] in long_df[var].values\n assert sub_vars[\"style\"] in long_df[var].values\n assert sub_vars[\"hue\"] == sub_vars[\"style\"]\n\n var1, var2 = \"a\", \"s\"\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2),\n )\n for sub_vars, _ in p.iter_data(semantics):\n assert list(sub_vars) == [\"hue\", \"size\"]\n assert sub_vars[\"hue\"] in long_df[var1].values\n assert sub_vars[\"size\"] in long_df[var2].values\n\n semantics = [\"hue\", \"col\", \"row\"]\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, col=var2),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert list(sub_vars) == [\"hue\", \"col\"]\n assert sub_vars[\"hue\"] in long_df[var1].values\n assert sub_vars[\"col\"] in long_df[var2].values\n\n def test_iter_data_values(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n\n p.sort = True\n _, sub_data = next(p.iter_data(\"hue\"))\n assert_frame_equal(sub_data, p.plot_data)\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n\n for sub_vars, sub_data in p.iter_data(\"hue\"):\n rows = p.plot_data[\"hue\"] == sub_vars[\"hue\"]\n assert_frame_equal(sub_data, p.plot_data[rows])\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"s\"),\n )\n for sub_vars, sub_data in p.iter_data([\"hue\", \"size\"]):\n rows = p.plot_data[\"hue\"] == sub_vars[\"hue\"]\n rows &= p.plot_data[\"size\"] == sub_vars[\"size\"]\n assert_frame_equal(sub_data, p.plot_data[rows])\n\n def test_iter_data_reverse(self, long_df):\n\n reversed_order = categorical_order(long_df[\"a\"])[::-1]\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n iterator = p.iter_data(\"hue\", reverse=True)\n for i, (sub_vars, _) in enumerate(iterator):\n assert sub_vars[\"hue\"] == reversed_order[i]\n\n def test_iter_data_dropna(self, missing_df):\n\n p = VectorPlotter(\n data=missing_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n for _, sub_df in p.iter_data(\"hue\"):\n assert not sub_df.isna().any().any()\n\n some_missing = False\n for _, sub_df in p.iter_data(\"hue\", dropna=False):\n some_missing |= sub_df.isna().any().any()\n assert some_missing\n\n def test_axis_labels(self, long_df):\n\n f, ax = plt.subplots()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"a\"))\n\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(y=\"a\"))\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"\"\n assert ax.get_ylabel() == \"a\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"a\"))\n\n p._add_axis_labels(ax, default_y=\"default\")\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"default\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(y=\"a\"))\n p._add_axis_labels(ax, default_x=\"default\", default_y=\"default\")\n assert ax.get_xlabel() == \"default\"\n assert ax.get_ylabel() == \"a\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"a\"))\n ax.set(xlabel=\"existing\", ylabel=\"also existing\")\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"existing\"\n assert ax.get_ylabel() == \"also existing\"\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p._add_axis_labels(ax1)\n p._add_axis_labels(ax2)\n\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n assert ax1.yaxis.label.get_visible()\n\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()\n\n @pytest.mark.parametrize(\n \"variables\",\n [\n dict(x=\"x\", y=\"y\"),\n dict(x=\"x\"),\n dict(y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"x\", y=\"a\"),\n ]\n )\n def test_attach_basics(self, long_df, variables):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables=variables)\n p._attach(ax)\n assert p.ax is ax\n\n def test_attach_disallowed(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=\"numeric\")\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=[\"datetime\", \"numeric\"])\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=\"categorical\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=[\"numeric\", \"categorical\"])\n\n def test_attach_log_scale(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p._attach(ax, log_scale=2)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"y\": \"y\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"linear\"\n assert ax.yaxis.get_scale() == \"log\"\n assert not p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"log\"\n assert p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=(True, False))\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=(False, 2))\n assert ax.xaxis.get_scale() == \"linear\"\n assert ax.yaxis.get_scale() == \"log\"\n assert not p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n def test_attach_converters(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n p._attach(ax)\n assert ax.xaxis.converter is None\n assert \"Date\" in ax.yaxis.converter.__class__.__name__\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\", \"y\": \"y\"})\n p._attach(ax)\n assert \"CategoryConverter\" in ax.xaxis.converter.__class__.__name__\n assert ax.yaxis.converter is None\n\n def test_attach_facets(self, long_df):\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"col\": \"a\"})\n p._attach(g)\n assert p.ax is None\n assert p.facets == g\n\n def test_attach_shared_axes(self, long_df):\n\n g = FacetGrid(long_df)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", sharex=False)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", sharex=False, col_wrap=2)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharex=False)\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == len(g.axes.flat)\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharex=\"col\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharey=\"row\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == p.plot_data[\"row\"].nunique()\n assert p.converters[\"y\"].groupby(p.plot_data[\"row\"]).nunique().max() == 1\n\n def test_get_axes_single(self, long_df):\n\n ax = plt.figure().subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": \"a\"})\n p._attach(ax)\n assert p._get_axes({\"hue\": \"a\"}) is ax\n\n def test_get_axes_facets(self, long_df):\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"col\": \"a\"})\n p._attach(g)\n assert p._get_axes({\"col\": \"b\"}) is g.axes_dict[\"b\"]\n\n g = FacetGrid(long_df, col=\"a\", row=\"c\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"col\": \"a\", \"row\": \"c\"}\n )\n p._attach(g)\n assert p._get_axes({\"row\": 1, \"col\": \"b\"}) is g.axes_dict[(1, \"b\")]\n\n def test_comp_data(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n\n # We have disabled this check for now, while it remains part of\n # the internal API, because it will require updating a number of tests\n # with pytest.raises(AttributeError):\n # p.comp_data\n\n _, ax = plt.subplots()\n p._attach(ax)\n\n assert_array_equal(p.comp_data[\"x\"], p.plot_data[\"x\"])\n assert_array_equal(\n p.comp_data[\"y\"], ax.yaxis.convert_units(p.plot_data[\"y\"])\n )\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n\n _, ax = plt.subplots()\n p._attach(ax)\n\n assert_array_equal(\n p.comp_data[\"x\"], ax.xaxis.convert_units(p.plot_data[\"x\"])\n )\n\n def test_comp_data_log(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"z\", \"y\": \"y\"})\n _, ax = plt.subplots()\n p._attach(ax, log_scale=(True, False))\n\n assert_array_equal(\n p.comp_data[\"x\"], np.log10(p.plot_data[\"x\"])\n )\n assert_array_equal(p.comp_data[\"y\"], p.plot_data[\"y\"])\n\n def test_comp_data_category_order(self):\n\n s = (pd.Series([\"a\", \"b\", \"c\", \"a\"], dtype=\"category\")\n .cat.set_categories([\"b\", \"c\", \"a\"], ordered=True))\n\n p = VectorPlotter(variables={\"x\": s})\n _, ax = plt.subplots()\n p._attach(ax)\n assert_array_equal(\n p.comp_data[\"x\"],\n [2, 0, 1, 2],\n )\n\n @pytest.fixture(\n params=itertools.product(\n [None, np.nan, PD_NA],\n [\"numeric\", \"category\", \"datetime\"]\n )\n )\n @pytest.mark.parametrize(\n \"NA,var_type\",\n )\n def comp_data_missing_fixture(self, request):\n\n # This fixture holds the logic for parameterizing\n # the following test (test_comp_data_missing)\n\n NA, var_type = request.param\n\n if NA is None:\n pytest.skip(\"No pandas.NA available\")\n\n comp_data = [0, 1, np.nan, 2, np.nan, 1]\n if var_type == \"numeric\":\n orig_data = [0, 1, NA, 2, np.inf, 1]\n elif var_type == \"category\":\n orig_data = [\"a\", \"b\", NA, \"c\", NA, \"b\"]\n elif var_type == \"datetime\":\n # Use 1-based numbers to avoid issue on matplotlib<3.2\n # Could simplify the test a bit when we roll off that version\n comp_data = [1, 2, np.nan, 3, np.nan, 2]\n numbers = [1, 2, 3, 2]\n\n orig_data = mpl.dates.num2date(numbers)\n orig_data.insert(2, NA)\n orig_data.insert(4, np.inf)\n\n return orig_data, comp_data\n\n def test_comp_data_missing(self, comp_data_missing_fixture):\n\n orig_data, comp_data = comp_data_missing_fixture\n p = VectorPlotter(variables={\"x\": orig_data})\n ax = plt.figure().subplots()\n p._attach(ax)\n assert_array_equal(p.comp_data[\"x\"], comp_data)\n\n def test_comp_data_duplicate_index(self):\n\n x = pd.Series([1, 2, 3, 4, 5], [1, 1, 1, 2, 2])\n p = VectorPlotter(variables={\"x\": x})\n ax = plt.figure().subplots()\n p._attach(ax)\n assert_array_equal(p.comp_data[\"x\"], x)\n\n def test_var_order(self, long_df):\n\n order = [\"c\", \"b\", \"a\"]\n for var in [\"hue\", \"size\", \"style\"]:\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", var: \"a\"})\n\n mapper = getattr(p, f\"map_{var}\")\n mapper(order=order)\n\n assert p.var_levels[var] == order\n\n def test_scale_native(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n with pytest.raises(NotImplementedError):\n p.scale_native(\"x\")\n\n def test_scale_numeric(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"y\": \"y\"})\n with pytest.raises(NotImplementedError):\n p.scale_numeric(\"y\")\n\n def test_scale_datetime(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"t\"})\n with pytest.raises(NotImplementedError):\n p.scale_datetime(\"x\")\n\n def test_scale_categorical(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p.scale_categorical(\"y\")\n assert p.variables[\"y\"] is None\n assert p.var_types[\"y\"] == \"categorical\"\n assert (p.plot_data[\"y\"] == \"\").all()\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"s\"})\n p.scale_categorical(\"x\")\n assert p.var_types[\"x\"] == \"categorical\"\n assert hasattr(p.plot_data[\"x\"], \"str\")\n assert not p._var_ordered[\"x\"]\n assert p.plot_data[\"x\"].is_monotonic_increasing\n assert_array_equal(p.var_levels[\"x\"], p.plot_data[\"x\"].unique())\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n p.scale_categorical(\"x\")\n assert not p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], categorical_order(long_df[\"a\"]))\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a_cat\"})\n p.scale_categorical(\"x\")\n assert p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], categorical_order(long_df[\"a_cat\"]))\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n order = np.roll(long_df[\"a\"].unique(), 1)\n p.scale_categorical(\"x\", order=order)\n assert p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], order)\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"s\"})\n p.scale_categorical(\"x\", formatter=lambda x: f\"{x:%}\")\n assert p.plot_data[\"x\"].str.endswith(\"%\").all()\n assert all(s.endswith(\"%\") for s in p.var_levels[\"x\"])\n\n\nclass TestCoreFunc:\n\n def test_unique_dashes(self):\n\n n = 24\n dashes = unique_dashes(n)\n\n assert len(dashes) == n\n assert len(set(dashes)) == n\n assert dashes[0] == \"\"\n for spec in dashes[1:]:\n assert isinstance(spec, tuple)\n assert not len(spec) % 2\n\n def test_unique_markers(self):\n\n n = 24\n markers = unique_markers(n)\n\n assert len(markers) == n\n assert len(set(markers)) == n\n for m in markers:\n assert mpl.markers.MarkerStyle(m).is_filled()\n\n def test_variable_type(self):\n\n s = pd.Series([1., 2., 3.])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s.astype(int)) == \"numeric\"\n assert variable_type(s.astype(object)) == \"numeric\"\n assert variable_type(s.to_numpy()) == \"numeric\"\n assert variable_type(s.to_list()) == \"numeric\"\n\n s = pd.Series([1, 2, 3, np.nan], dtype=object)\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([np.nan, np.nan])\n # s = pd.Series([pd.NA, pd.NA])\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([\"1\", \"2\", \"3\"])\n assert variable_type(s) == \"categorical\"\n assert variable_type(s.to_numpy()) == \"categorical\"\n assert variable_type(s.to_list()) == \"categorical\"\n\n s = pd.Series([True, False, False])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s, boolean_type=\"categorical\") == \"categorical\"\n s_cat = s.astype(\"category\")\n assert variable_type(s_cat, boolean_type=\"categorical\") == \"categorical\"\n assert variable_type(s_cat, boolean_type=\"numeric\") == \"categorical\"\n\n s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])\n assert variable_type(s) == \"datetime\"\n assert variable_type(s.astype(object)) == \"datetime\"\n assert variable_type(s.to_numpy()) == \"datetime\"\n assert variable_type(s.to_list()) == \"datetime\"\n\n def test_infer_orient(self):\n\n nums = pd.Series(np.arange(6))\n cats = pd.Series([\"a\", \"b\"] * 3)\n dates = pd.date_range(\"1999-09-22\", \"2006-05-14\", 6)\n\n assert infer_orient(cats, nums) == \"v\"\n assert infer_orient(nums, cats) == \"h\"\n\n assert infer_orient(cats, dates, require_numeric=False) == \"v\"\n assert infer_orient(dates, cats, require_numeric=False) == \"h\"\n\n assert infer_orient(nums, None) == \"h\"\n with pytest.warns(UserWarning, match=\"Vertical .+ `x`\"):\n assert infer_orient(nums, None, \"v\") == \"h\"\n\n assert infer_orient(None, nums) == \"v\"\n with pytest.warns(UserWarning, match=\"Horizontal .+ `y`\"):\n assert infer_orient(None, nums, \"h\") == \"v\"\n\n infer_orient(cats, None, require_numeric=False) == \"h\"\n with pytest.raises(TypeError, match=\"Horizontal .+ `x`\"):\n infer_orient(cats, None)\n\n infer_orient(cats, None, require_numeric=False) == \"v\"\n with pytest.raises(TypeError, match=\"Vertical .+ `y`\"):\n infer_orient(None, cats)\n\n assert infer_orient(nums, nums, \"vert\") == \"v\"\n assert infer_orient(nums, nums, \"hori\") == \"h\"\n\n assert infer_orient(cats, cats, \"h\", require_numeric=False) == \"h\"\n assert infer_orient(cats, cats, \"v\", require_numeric=False) == \"v\"\n assert infer_orient(cats, cats, require_numeric=False) == \"v\"\n\n with pytest.raises(TypeError, match=\"Vertical .+ `y`\"):\n infer_orient(cats, cats, \"v\")\n with pytest.raises(TypeError, match=\"Horizontal .+ `x`\"):\n infer_orient(cats, cats, \"h\")\n with pytest.raises(TypeError, match=\"Neither\"):\n infer_orient(cats, cats)\n\n with pytest.raises(ValueError, match=\"`orient` must start with\"):\n infer_orient(cats, nums, orient=\"bad value\")\n\n def test_categorical_order(self):\n\n x = [\"a\", \"c\", \"c\", \"b\", \"a\", \"d\"]\n y = [3, 2, 5, 1, 4]\n order = [\"a\", \"b\", \"c\", \"d\"]\n\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(x, order)\n assert out == order\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n out = categorical_order(np.array(x))\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(pd.Series(x))\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(y)\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(np.array(y))\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(pd.Series(y))\n assert out == [1, 2, 3, 4, 5]\n\n x = pd.Categorical(x, order)\n out = categorical_order(x)\n assert out == list(x.categories)\n\n x = pd.Series(x)\n out = categorical_order(x)\n assert out == list(x.cat.categories)\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n x = [\"a\", np.nan, \"c\", \"c\", \"b\", \"a\", \"d\"]\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n"},{"col":4,"comment":"null","endLoc":104,"header":"def test_sd_single_obs(self)","id":4210,"name":"test_sd_single_obs","nodeType":"Function","startLoc":96,"text":"def test_sd_single_obs(self):\n\n y = 1.5\n ori = \"x\"\n df = pd.DataFrame([{\"x\": \"a\", \"y\": y}])\n gb = self.get_groupby(df, ori)\n res = Est(\"mean\", \"sd\")(df, gb, ori, {})\n expected = df.assign(ymin=y, ymax=y)\n assert_frame_equal(res, expected)"},{"col":4,"comment":"null","endLoc":116,"header":"def test_median_pi(self, df)","id":4211,"name":"test_median_pi","nodeType":"Function","startLoc":106,"text":"def test_median_pi(self, df):\n\n ori = \"x\"\n df = df[[\"x\", \"y\"]]\n gb = self.get_groupby(df, ori)\n res = Est(\"median\", (\"pi\", 100))(df, gb, ori, {})\n\n grouped = df.groupby(\"x\", as_index=False)[\"y\"]\n est = grouped.median()\n expected = est.assign(ymin=grouped.min()[\"y\"], ymax=grouped.max()[\"y\"])\n assert_frame_equal(res, expected)"},{"className":"TestSemanticMapping","col":0,"comment":"null","endLoc":61,"id":4212,"nodeType":"Class","startLoc":53,"text":"class TestSemanticMapping:\n\n def test_call_lookup(self):\n\n m = SemanticMapping(VectorPlotter())\n lookup_table = dict(zip(\"abc\", (1, 2, 3)))\n m.lookup_table = lookup_table\n for key, val in lookup_table.items():\n assert m(key) == val"},{"col":4,"comment":"null","endLoc":61,"header":"def test_call_lookup(self)","id":4213,"name":"test_call_lookup","nodeType":"Function","startLoc":55,"text":"def test_call_lookup(self):\n\n m = SemanticMapping(VectorPlotter())\n lookup_table = dict(zip(\"abc\", (1, 2, 3)))\n m.lookup_table = lookup_table\n for key, val in lookup_table.items():\n assert m(key) == val"},{"col":4,"comment":"null","endLoc":125,"header":"def test_seed(self, df)","id":4214,"name":"test_seed","nodeType":"Function","startLoc":118,"text":"def test_seed(self, df):\n\n ori = \"x\"\n gb = self.get_groupby(df, ori)\n args = df, gb, ori, {}\n res1 = Est(\"mean\", \"ci\", seed=99)(*args)\n res2 = Est(\"mean\", \"ci\", seed=99)(*args)\n assert_frame_equal(res1, res2)"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":4215,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":4216,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"attributeType":"Generator","col":0,"comment":"null","endLoc":12,"id":4217,"name":"py_files","nodeType":"Attribute","startLoc":12,"text":"py_files"},{"attributeType":"Generator","col":0,"comment":"null","endLoc":13,"id":4218,"name":"ipynb_files","nodeType":"Attribute","startLoc":13,"text":"ipynb_files"},{"attributeType":"list","col":0,"comment":"null","endLoc":15,"id":4219,"name":"datasets","nodeType":"Attribute","startLoc":15,"text":"datasets"},{"attributeType":"null","col":4,"comment":"null","endLoc":17,"id":4220,"name":"fname","nodeType":"Attribute","startLoc":17,"text":"fname"},{"className":"TestText","col":0,"comment":"null","endLoc":129,"id":4221,"nodeType":"Class","startLoc":12,"text":"class TestText:\n\n def get_texts(self, ax):\n if ax.texts:\n return list(ax.texts)\n else:\n # Compatibility with matplotlib < 3.5 (I think)\n return [a for a in ax.artists if isinstance(a, MPLText)]\n\n def test_simple(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n\n p = Plot(x, y, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n x_, y_ = text.get_position()\n assert x_ == x[i]\n assert y_ == y[i]\n assert text.get_text() == s[i]\n assert text.get_horizontalalignment() == \"center\"\n assert text.get_verticalalignment() == \"center_baseline\"\n\n def test_set_properties(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n color = \"red\"\n alpha = .6\n fontsize = 6\n valign = \"bottom\"\n\n m = Text(color=color, alpha=alpha, fontsize=fontsize, valign=valign)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n assert text.get_text() == s[i]\n assert text.get_color() == to_rgba(m.color, m.alpha)\n assert text.get_fontsize() == m.fontsize\n assert text.get_verticalalignment() == m.valign\n\n def test_mapped_properties(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n color = list(\"aab\")\n fontsize = [1, 2, 4]\n\n p = Plot(x, y, color=color, fontsize=fontsize, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n texts = self.get_texts(ax)\n assert texts[0].get_color() == texts[1].get_color()\n assert texts[0].get_color() != texts[2].get_color()\n assert (\n texts[0].get_fontsize()\n < texts[1].get_fontsize()\n < texts[2].get_fontsize()\n )\n\n def test_mapped_alignment(self):\n\n x = [1, 2]\n p = Plot(x=x, y=x, halign=x, valign=x, text=x).add(Text()).plot()\n ax = p._figure.axes[0]\n t1, t2 = self.get_texts(ax)\n assert t1.get_horizontalalignment() == \"left\"\n assert t2.get_horizontalalignment() == \"right\"\n assert t1.get_verticalalignment() == \"top\"\n assert t2.get_verticalalignment() == \"bottom\"\n\n def test_identity_fontsize(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n fs = [5, 8, 12]\n p = Plot(x, y, text=s, fontsize=fs).add(Text()).scale(fontsize=None).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n assert text.get_fontsize() == fs[i]\n\n def test_offset_centered(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n p = Plot(x, y, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n assert_array_almost_equal(text.get_transform().get_matrix(), ax_trans)\n\n def test_offset_valign(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n m = Text(valign=\"bottom\", fontsize=5, offset=.1)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n expected_shift_matrix = np.zeros((3, 3))\n expected_shift_matrix[1, -1] = m.offset * ax.figure.dpi / 72\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n shift_matrix = text.get_transform().get_matrix() - ax_trans\n assert_array_almost_equal(shift_matrix, expected_shift_matrix)\n\n def test_offset_halign(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n m = Text(halign=\"right\", fontsize=10, offset=.5)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n expected_shift_matrix = np.zeros((3, 3))\n expected_shift_matrix[0, -1] = -m.offset * ax.figure.dpi / 72\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n shift_matrix = text.get_transform().get_matrix() - ax_trans\n assert_array_almost_equal(shift_matrix, expected_shift_matrix)"},{"col":4,"comment":"null","endLoc":19,"header":"def get_texts(self, ax)","id":4222,"name":"get_texts","nodeType":"Function","startLoc":14,"text":"def get_texts(self, ax):\n if ax.texts:\n return list(ax.texts)\n else:\n # Compatibility with matplotlib < 3.5 (I think)\n return [a for a in ax.artists if isinstance(a, MPLText)]"},{"attributeType":"TextIO","col":24,"comment":"null","endLoc":18,"id":4223,"name":"fid","nodeType":"Attribute","startLoc":18,"text":"fid"},{"col":4,"comment":"null","endLoc":34,"header":"def test_simple(self)","id":4224,"name":"test_simple","nodeType":"Function","startLoc":21,"text":"def test_simple(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n\n p = Plot(x, y, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n x_, y_ = text.get_position()\n assert x_ == x[i]\n assert y_ == y[i]\n assert text.get_text() == s[i]\n assert text.get_horizontalalignment() == \"center\"\n assert text.get_verticalalignment() == \"center_baseline\""},{"className":"TestHueMapping","col":0,"comment":"null","endLoc":326,"id":4225,"nodeType":"Class","startLoc":64,"text":"class TestHueMapping:\n\n def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n palette = \"Set2\"\n p = HueMapping.map(p_orig, palette=palette)\n assert p is p_orig\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.palette == palette\n\n def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.map_type is None\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.map_type == p.var_types[\"hue\"]\n\n def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n palette = \"muted\"\n hue_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_hue(palette=palette, order=hue_order)\n assert p is p_orig\n assert p._hue_map.palette == palette\n assert p._hue_map.levels == hue_order\n\n def test_hue_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, hue=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.palette is None\n assert m.cmap is None\n assert m.norm is None\n assert m.lookup_table is None\n\n def test_hue_map_categorical(self, wide_df, long_df):\n\n p = VectorPlotter(data=wide_df)\n m = HueMapping(p)\n assert m.levels == wide_df.columns.to_list()\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test named palette\n palette = \"Blues\"\n expected_colors = color_palette(palette, wide_df.shape[1])\n expected_lookup_table = dict(zip(wide_df.columns, expected_colors))\n m = HueMapping(p, palette=palette)\n assert m.palette == \"Blues\"\n assert m.lookup_table == expected_lookup_table\n\n # Test list palette\n palette = color_palette(\"Reds\", wide_df.shape[1])\n expected_lookup_table = dict(zip(wide_df.columns, palette))\n m = HueMapping(p, palette=palette)\n assert m.palette == palette\n assert m.lookup_table == expected_lookup_table\n\n # Test dict palette\n colors = color_palette(\"Set1\", 8)\n palette = dict(zip(wide_df.columns, colors))\n m = HueMapping(p, palette=palette)\n assert m.palette == palette\n assert m.lookup_table == palette\n\n # Test dict with missing keys\n palette = dict(zip(wide_df.columns[:-1], colors))\n with pytest.raises(ValueError):\n HueMapping(p, palette=palette)\n\n # Test list with wrong number of colors\n palette = colors[:-1]\n with pytest.warns(UserWarning):\n HueMapping(p, palette=palette)\n\n # Test hue order\n hue_order = [\"a\", \"c\", \"d\"]\n m = HueMapping(p, order=hue_order)\n assert m.levels == hue_order\n\n # Test long data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"a\"))\n m = HueMapping(p)\n assert m.levels == categorical_order(long_df[\"a\"])\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test default palette\n m = HueMapping(p)\n hue_levels = categorical_order(long_df[\"a\"])\n expected_colors = color_palette(n_colors=len(hue_levels))\n expected_lookup_table = dict(zip(hue_levels, expected_colors))\n assert m.lookup_table == expected_lookup_table\n\n # Test missing data\n m = HueMapping(p)\n assert m(np.nan) == (0, 0, 0, 0)\n\n # Test default palette with many levels\n x = y = np.arange(26)\n hue = pd.Series(list(\"abcdefghijklmnopqrstuvwxyz\"))\n p = VectorPlotter(variables=dict(x=x, y=y, hue=hue))\n m = HueMapping(p)\n expected_colors = color_palette(\"husl\", n_colors=len(hue))\n expected_lookup_table = dict(zip(hue, expected_colors))\n assert m.lookup_table == expected_lookup_table\n\n # Test binary data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"c\"))\n m = HueMapping(p)\n assert m.levels == [0, 1]\n assert m.map_type == \"categorical\"\n\n for val in [0, 1]:\n p = VectorPlotter(\n data=long_df[long_df[\"c\"] == val],\n variables=dict(x=\"x\", y=\"y\", hue=\"c\"),\n )\n m = HueMapping(p)\n assert m.levels == [val]\n assert m.map_type == \"categorical\"\n\n # Test Timestamp data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"t\"))\n m = HueMapping(p)\n assert m.levels == [pd.Timestamp(t) for t in long_df[\"t\"].unique()]\n assert m.map_type == \"datetime\"\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", hue=\"a_cat\"))\n m = HueMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n assert m.map_type == \"categorical\"\n\n # Test numeric data with category type\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s_cat\")\n )\n m = HueMapping(p)\n assert m.levels == categorical_order(long_df[\"s_cat\"])\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test categorical palette specified for numeric data\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s\")\n )\n palette = \"deep\"\n levels = categorical_order(long_df[\"s\"])\n expected_colors = color_palette(palette, n_colors=len(levels))\n expected_lookup_table = dict(zip(levels, expected_colors))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == expected_lookup_table\n assert m.map_type == \"categorical\"\n\n def test_hue_map_numeric(self, long_df):\n\n vals = np.concatenate([np.linspace(0, 1, 256), [-.1, 1.1, np.nan]])\n\n # Test default colormap\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s\")\n )\n hue_levels = list(np.sort(long_df[\"s\"].unique()))\n m = HueMapping(p)\n assert m.levels == hue_levels\n assert m.map_type == \"numeric\"\n assert m.cmap.name == \"seaborn_cubehelix\"\n\n # Test named colormap\n palette = \"Purples\"\n m = HueMapping(p, palette=palette)\n assert_array_equal(m.cmap(vals), get_colormap(palette)(vals))\n\n # Test colormap object\n palette = get_colormap(\"Greens\")\n m = HueMapping(p, palette=palette)\n assert_array_equal(m.cmap(vals), palette(vals))\n\n # Test cubehelix shorthand\n palette = \"ch:2,0,light=.2\"\n m = HueMapping(p, palette=palette)\n assert isinstance(m.cmap, mpl.colors.ListedColormap)\n\n # Test specified hue limits\n hue_norm = 1, 4\n m = HueMapping(p, norm=hue_norm)\n assert isinstance(m.norm, mpl.colors.Normalize)\n assert m.norm.vmin == hue_norm[0]\n assert m.norm.vmax == hue_norm[1]\n\n # Test Normalize object\n hue_norm = mpl.colors.PowerNorm(2, vmin=1, vmax=10)\n m = HueMapping(p, norm=hue_norm)\n assert m.norm is hue_norm\n\n # Test default colormap values\n hmin, hmax = p.plot_data[\"hue\"].min(), p.plot_data[\"hue\"].max()\n m = HueMapping(p)\n assert m.lookup_table[hmin] == pytest.approx(m.cmap(0.0))\n assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))\n\n # Test specified colormap values\n hue_norm = hmin - 1, hmax - 1\n m = HueMapping(p, norm=hue_norm)\n norm_min = (hmin - hue_norm[0]) / (hue_norm[1] - hue_norm[0])\n assert m.lookup_table[hmin] == pytest.approx(m.cmap(norm_min))\n assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))\n\n # Test list of colors\n hue_levels = list(np.sort(long_df[\"s\"].unique()))\n palette = color_palette(\"Blues\", len(hue_levels))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == dict(zip(hue_levels, palette))\n\n palette = color_palette(\"Blues\", len(hue_levels) + 1)\n with pytest.warns(UserWarning):\n HueMapping(p, palette=palette)\n\n # Test dictionary of colors\n palette = dict(zip(hue_levels, color_palette(\"Reds\")))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == palette\n\n palette.pop(hue_levels[0])\n with pytest.raises(ValueError):\n HueMapping(p, palette=palette)\n\n # Test invalid palette\n with pytest.raises(ValueError):\n HueMapping(p, palette=\"not a valid palette\")\n\n # Test bad norm argument\n with pytest.raises(ValueError):\n HueMapping(p, norm=\"not a norm\")\n\n def test_hue_map_without_hue_dataa(self, long_df):\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n with pytest.warns(UserWarning, match=\"Ignoring `palette`\"):\n HueMapping(p, palette=\"viridis\")"},{"col":4,"comment":"null","endLoc":76,"header":"def test_init_from_map(self, long_df)","id":4226,"name":"test_init_from_map","nodeType":"Function","startLoc":66,"text":"def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n palette = \"Set2\"\n p = HueMapping.map(p_orig, palette=palette)\n assert p is p_orig\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.palette == palette"},{"col":4,"comment":"null","endLoc":92,"header":"def test_plotter_default_init(self, long_df)","id":4227,"name":"test_plotter_default_init","nodeType":"Function","startLoc":78,"text":"def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.map_type is None\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n assert isinstance(p._hue_map, HueMapping)\n assert p._hue_map.map_type == p.var_types[\"hue\"]"},{"col":4,"comment":"null","endLoc":105,"header":"def test_plotter_reinit(self, long_df)","id":4228,"name":"test_plotter_reinit","nodeType":"Function","startLoc":94,"text":"def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n palette = \"muted\"\n hue_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_hue(palette=palette, order=hue_order)\n assert p is p_orig\n assert p._hue_map.palette == palette\n assert p._hue_map.levels == hue_order"},{"col":4,"comment":"null","endLoc":116,"header":"def test_hue_map_null(self, flat_series, null_series)","id":4229,"name":"test_hue_map_null","nodeType":"Function","startLoc":107,"text":"def test_hue_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, hue=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.palette is None\n assert m.cmap is None\n assert m.norm is None\n assert m.lookup_table is None"},{"col":4,"comment":"null","endLoc":238,"header":"def test_hue_map_categorical(self, wide_df, long_df)","id":4230,"name":"test_hue_map_categorical","nodeType":"Function","startLoc":118,"text":"def test_hue_map_categorical(self, wide_df, long_df):\n\n p = VectorPlotter(data=wide_df)\n m = HueMapping(p)\n assert m.levels == wide_df.columns.to_list()\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test named palette\n palette = \"Blues\"\n expected_colors = color_palette(palette, wide_df.shape[1])\n expected_lookup_table = dict(zip(wide_df.columns, expected_colors))\n m = HueMapping(p, palette=palette)\n assert m.palette == \"Blues\"\n assert m.lookup_table == expected_lookup_table\n\n # Test list palette\n palette = color_palette(\"Reds\", wide_df.shape[1])\n expected_lookup_table = dict(zip(wide_df.columns, palette))\n m = HueMapping(p, palette=palette)\n assert m.palette == palette\n assert m.lookup_table == expected_lookup_table\n\n # Test dict palette\n colors = color_palette(\"Set1\", 8)\n palette = dict(zip(wide_df.columns, colors))\n m = HueMapping(p, palette=palette)\n assert m.palette == palette\n assert m.lookup_table == palette\n\n # Test dict with missing keys\n palette = dict(zip(wide_df.columns[:-1], colors))\n with pytest.raises(ValueError):\n HueMapping(p, palette=palette)\n\n # Test list with wrong number of colors\n palette = colors[:-1]\n with pytest.warns(UserWarning):\n HueMapping(p, palette=palette)\n\n # Test hue order\n hue_order = [\"a\", \"c\", \"d\"]\n m = HueMapping(p, order=hue_order)\n assert m.levels == hue_order\n\n # Test long data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"a\"))\n m = HueMapping(p)\n assert m.levels == categorical_order(long_df[\"a\"])\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test default palette\n m = HueMapping(p)\n hue_levels = categorical_order(long_df[\"a\"])\n expected_colors = color_palette(n_colors=len(hue_levels))\n expected_lookup_table = dict(zip(hue_levels, expected_colors))\n assert m.lookup_table == expected_lookup_table\n\n # Test missing data\n m = HueMapping(p)\n assert m(np.nan) == (0, 0, 0, 0)\n\n # Test default palette with many levels\n x = y = np.arange(26)\n hue = pd.Series(list(\"abcdefghijklmnopqrstuvwxyz\"))\n p = VectorPlotter(variables=dict(x=x, y=y, hue=hue))\n m = HueMapping(p)\n expected_colors = color_palette(\"husl\", n_colors=len(hue))\n expected_lookup_table = dict(zip(hue, expected_colors))\n assert m.lookup_table == expected_lookup_table\n\n # Test binary data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"c\"))\n m = HueMapping(p)\n assert m.levels == [0, 1]\n assert m.map_type == \"categorical\"\n\n for val in [0, 1]:\n p = VectorPlotter(\n data=long_df[long_df[\"c\"] == val],\n variables=dict(x=\"x\", y=\"y\", hue=\"c\"),\n )\n m = HueMapping(p)\n assert m.levels == [val]\n assert m.map_type == \"categorical\"\n\n # Test Timestamp data\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"t\"))\n m = HueMapping(p)\n assert m.levels == [pd.Timestamp(t) for t in long_df[\"t\"].unique()]\n assert m.map_type == \"datetime\"\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", hue=\"a_cat\"))\n m = HueMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n assert m.map_type == \"categorical\"\n\n # Test numeric data with category type\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s_cat\")\n )\n m = HueMapping(p)\n assert m.levels == categorical_order(long_df[\"s_cat\"])\n assert m.map_type == \"categorical\"\n assert m.cmap is None\n\n # Test categorical palette specified for numeric data\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s\")\n )\n palette = \"deep\"\n levels = categorical_order(long_df[\"s\"])\n expected_colors = color_palette(palette, n_colors=len(levels))\n expected_lookup_table = dict(zip(levels, expected_colors))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == expected_lookup_table\n assert m.map_type == \"categorical\""},{"attributeType":"null","col":12,"comment":"null","endLoc":16,"id":4231,"name":"nb","nodeType":"Attribute","startLoc":16,"text":"nb"},{"attributeType":"TextIO","col":32,"comment":"null","endLoc":21,"id":4232,"name":"f","nodeType":"Attribute","startLoc":21,"text":"f"},{"attributeType":"null","col":4,"comment":"null","endLoc":21,"id":4233,"name":"p","nodeType":"Attribute","startLoc":21,"text":"p"},{"fileName":"test_plot.py","filePath":"tests/_core","id":4234,"nodeType":"File","text":"import io\nimport xml\nimport functools\nimport itertools\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport pytest\nfrom pandas.testing import assert_frame_equal, assert_series_equal\nfrom numpy.testing import assert_array_equal\n\nfrom seaborn._core.plot import Plot, Default\nfrom seaborn._core.scales import Nominal, Continuous\nfrom seaborn._core.rules import categorical_order\nfrom seaborn._core.moves import Move, Shift, Dodge\nfrom seaborn._stats.aggregation import Agg\nfrom seaborn._marks.base import Mark\nfrom seaborn._stats.base import Stat\nfrom seaborn.external.version import Version\n\nassert_vector_equal = functools.partial(\n # TODO do we care about int/float dtype consistency?\n # Eventually most variables become floats ... but does it matter when?\n # (Or rather, does it matter if it happens too early?)\n assert_series_equal, check_names=False, check_dtype=False,\n)\n\n\ndef assert_gridspec_shape(ax, nrows=1, ncols=1):\n\n gs = ax.get_gridspec()\n if Version(mpl.__version__) < Version(\"3.2\"):\n assert gs._nrows == nrows\n assert gs._ncols == ncols\n else:\n assert gs.nrows == nrows\n assert gs.ncols == ncols\n\n\nclass MockMark(Mark):\n\n _grouping_props = [\"color\"]\n\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.passed_keys = []\n self.passed_data = []\n self.passed_axes = []\n self.passed_scales = None\n self.passed_orient = None\n self.n_splits = 0\n\n def _plot(self, split_gen, scales, orient):\n\n for keys, data, ax in split_gen():\n self.n_splits += 1\n self.passed_keys.append(keys)\n self.passed_data.append(data)\n self.passed_axes.append(ax)\n\n self.passed_scales = scales\n self.passed_orient = orient\n\n def _legend_artist(self, variables, value, scales):\n\n a = mpl.lines.Line2D([], [])\n a.variables = variables\n a.value = value\n return a\n\n\nclass TestInit:\n\n def test_empty(self):\n\n p = Plot()\n assert p._data.source_data is None\n assert p._data.source_vars == {}\n\n def test_data_only(self, long_df):\n\n p = Plot(long_df)\n assert p._data.source_data is long_df\n assert p._data.source_vars == {}\n\n def test_df_and_named_variables(self, long_df):\n\n variables = {\"x\": \"a\", \"y\": \"z\"}\n p = Plot(long_df, **variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], long_df[col])\n assert p._data.source_data is long_df\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_df_and_mixed_variables(self, long_df):\n\n variables = {\"x\": \"a\", \"y\": long_df[\"z\"]}\n p = Plot(long_df, **variables)\n for var, col in variables.items():\n if isinstance(col, str):\n assert_vector_equal(p._data.frame[var], long_df[col])\n else:\n assert_vector_equal(p._data.frame[var], col)\n assert p._data.source_data is long_df\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_vector_variables_only(self, long_df):\n\n variables = {\"x\": long_df[\"a\"], \"y\": long_df[\"z\"]}\n p = Plot(**variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], col)\n assert p._data.source_data is None\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_vector_variables_no_index(self, long_df):\n\n variables = {\"x\": long_df[\"a\"].to_numpy(), \"y\": long_df[\"z\"].to_list()}\n p = Plot(**variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], pd.Series(col))\n assert p._data.names[var] is None\n assert p._data.source_data is None\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_data_only_named(self, long_df):\n\n p = Plot(data=long_df)\n assert p._data.source_data is long_df\n assert p._data.source_vars == {}\n\n def test_positional_and_named_data(self, long_df):\n\n err = \"`data` given by both name and position\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, data=long_df)\n\n @pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_positional_and_named_xy(self, long_df, var):\n\n err = f\"`{var}` given by both name and position\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, \"a\", \"b\", **{var: \"c\"})\n\n def test_positional_data_x_y(self, long_df):\n\n p = Plot(long_df, \"a\", \"b\")\n assert p._data.source_data is long_df\n assert list(p._data.source_vars) == [\"x\", \"y\"]\n\n def test_positional_x_y(self, long_df):\n\n p = Plot(long_df[\"a\"], long_df[\"b\"])\n assert p._data.source_data is None\n assert list(p._data.source_vars) == [\"x\", \"y\"]\n\n def test_positional_data_x(self, long_df):\n\n p = Plot(long_df, \"a\")\n assert p._data.source_data is long_df\n assert list(p._data.source_vars) == [\"x\"]\n\n def test_positional_x(self, long_df):\n\n p = Plot(long_df[\"a\"])\n assert p._data.source_data is None\n assert list(p._data.source_vars) == [\"x\"]\n\n def test_positional_too_many(self, long_df):\n\n err = r\"Plot\\(\\) accepts no more than 3 positional arguments \\(data, x, y\\)\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, \"x\", \"y\", \"z\")\n\n def test_unknown_keywords(self, long_df):\n\n err = r\"Plot\\(\\) got unexpected keyword argument\\(s\\): bad\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, bad=\"x\")\n\n\nclass TestLayerAddition:\n\n def test_without_data(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark()).plot()\n layer, = p._layers\n assert_frame_equal(p._data.frame, layer[\"data\"].frame, check_dtype=False)\n\n def test_with_new_variable_by_name(self, long_df):\n\n p = Plot(long_df, x=\"x\").add(MockMark(), y=\"y\").plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])\n\n def test_with_new_variable_by_vector(self, long_df):\n\n p = Plot(long_df, x=\"x\").add(MockMark(), y=long_df[\"y\"]).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])\n\n def test_with_late_data_definition(self, long_df):\n\n p = Plot().add(MockMark(), data=long_df, x=\"x\", y=\"y\").plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])\n\n def test_with_new_data_definition(self, long_df):\n\n long_df_sub = long_df.sample(frac=.5)\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark(), data=long_df_sub).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(\n layer[\"data\"].frame[var], long_df_sub[var].reindex(long_df.index)\n )\n\n def test_drop_variable(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark(), y=None).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\"]\n assert_vector_equal(layer[\"data\"].frame[\"x\"], long_df[\"x\"], check_dtype=False)\n\n @pytest.mark.xfail(reason=\"Need decision on default stat\")\n def test_stat_default(self):\n\n class MarkWithDefaultStat(Mark):\n default_stat = Stat\n\n p = Plot().add(MarkWithDefaultStat())\n layer, = p._layers\n assert layer[\"stat\"].__class__ is Stat\n\n def test_stat_nondefault(self):\n\n class MarkWithDefaultStat(Mark):\n default_stat = Stat\n\n class OtherMockStat(Stat):\n pass\n\n p = Plot().add(MarkWithDefaultStat(), OtherMockStat())\n layer, = p._layers\n assert layer[\"stat\"].__class__ is OtherMockStat\n\n @pytest.mark.parametrize(\n \"arg,expected\",\n [(\"x\", \"x\"), (\"y\", \"y\"), (\"v\", \"x\"), (\"h\", \"y\")],\n )\n def test_orient(self, arg, expected):\n\n class MockStatTrackOrient(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.orient_at_call = orient\n return data\n\n class MockMoveTrackOrient(Move):\n def __call__(self, data, groupby, orient, scales):\n self.orient_at_call = orient\n return data\n\n s = MockStatTrackOrient()\n m = MockMoveTrackOrient()\n Plot(x=[1, 2, 3], y=[1, 2, 3]).add(MockMark(), s, m, orient=arg).plot()\n\n assert s.orient_at_call == expected\n assert m.orient_at_call == expected\n\n def test_variable_list(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\")\n assert p._variables == [\"x\", \"y\"]\n\n p = Plot(long_df).add(MockMark(), x=\"x\", y=\"y\")\n assert p._variables == [\"x\", \"y\"]\n\n p = Plot(long_df, y=\"x\", color=\"a\").add(MockMark(), x=\"y\")\n assert p._variables == [\"y\", \"color\", \"x\"]\n\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(MockMark(), color=None)\n assert p._variables == [\"x\", \"y\", \"color\"]\n\n p = (\n Plot(long_df, x=\"x\", y=\"y\")\n .add(MockMark(), color=\"a\")\n .add(MockMark(), alpha=\"s\")\n )\n assert p._variables == [\"x\", \"y\", \"color\", \"alpha\"]\n\n p = Plot(long_df, y=\"x\").pair(x=[\"a\", \"b\"])\n assert p._variables == [\"y\", \"x0\", \"x1\"]\n\n def test_type_checks(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=\"mark must be a Mark instance\"):\n p.add(MockMark)\n\n class MockStat(Stat):\n pass\n\n class MockMove(Move):\n pass\n\n err = \"Transforms must have at most one Stat type\"\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockStat)\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockMove(), MockStat())\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockMark(), MockStat())\n\n\nclass TestScaling:\n\n def test_inference(self, long_df):\n\n for col, scale_type in zip(\"zat\", [\"Continuous\", \"Nominal\", \"Temporal\"]):\n p = Plot(long_df, x=col, y=col).add(MockMark()).plot()\n for var in \"xy\":\n assert p._scales[var].__class__.__name__ == scale_type\n\n def test_inference_from_layer_data(self):\n\n p = Plot().add(MockMark(), x=[\"a\", \"b\", \"c\"]).plot()\n assert p._scales[\"x\"](\"b\") == 1\n\n def test_inference_joins(self):\n\n p = (\n Plot(y=pd.Series([1, 2, 3, 4]))\n .add(MockMark(), x=pd.Series([1, 2]))\n .add(MockMark(), x=pd.Series([\"a\", \"b\"], index=[2, 3]))\n .plot()\n )\n assert p._scales[\"x\"](\"a\") == 2\n\n def test_inferred_categorical_converter(self):\n\n p = Plot(x=[\"b\", \"c\", \"a\"]).add(MockMark()).plot()\n ax = p._figure.axes[0]\n assert ax.xaxis.convert_units(\"c\") == 1\n\n def test_explicit_categorical_converter(self):\n\n p = Plot(y=[2, 1, 3]).scale(y=Nominal()).add(MockMark()).plot()\n ax = p._figure.axes[0]\n assert ax.yaxis.convert_units(\"3\") == 2\n\n @pytest.mark.xfail(reason=\"Temporal auto-conversion not implemented\")\n def test_categorical_as_datetime(self):\n\n dates = [\"1970-01-03\", \"1970-01-02\", \"1970-01-04\"]\n p = Plot(x=dates).scale(...).add(MockMark()).plot()\n p # TODO\n ...\n\n def test_faceted_log_scale(self):\n\n p = Plot(y=[1, 10]).facet(col=[\"a\", \"b\"]).scale(y=\"log\").plot()\n for ax in p._figure.axes:\n xfm = ax.yaxis.get_transform().transform\n assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])\n\n def test_paired_single_log_scale(self):\n\n x0, x1 = [1, 2, 3], [1, 10, 100]\n p = Plot().pair(x=[x0, x1]).scale(x1=\"log\").plot()\n ax_lin, ax_log = p._figure.axes\n xfm_lin = ax_lin.xaxis.get_transform().transform\n assert_array_equal(xfm_lin([1, 10, 100]), [1, 10, 100])\n xfm_log = ax_log.xaxis.get_transform().transform\n assert_array_equal(xfm_log([1, 10, 100]), [0, 1, 2])\n\n @pytest.mark.xfail(reason=\"Custom log scale needs log name for consistency\")\n def test_log_scale_name(self):\n\n p = Plot().scale(x=\"log\").plot()\n ax = p._figure.axes[0]\n assert ax.get_xscale() == \"log\"\n assert ax.get_yscale() == \"linear\"\n\n def test_mark_data_log_transform_is_inverted(self, long_df):\n\n col = \"z\"\n m = MockMark()\n Plot(long_df, x=col).scale(x=\"log\").add(m).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[col])\n\n def test_mark_data_log_transfrom_with_stat(self, long_df):\n\n class Mean(Stat):\n group_by_orient = True\n\n def __call__(self, data, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.agg(data, {other: \"mean\"})\n\n col = \"z\"\n grouper = \"a\"\n m = MockMark()\n s = Mean()\n\n Plot(long_df, x=grouper, y=col).scale(y=\"log\").add(m, s).plot()\n\n expected = (\n long_df[col]\n .pipe(np.log)\n .groupby(long_df[grouper], sort=False)\n .mean()\n .pipe(np.exp)\n .reset_index(drop=True)\n )\n assert_vector_equal(m.passed_data[0][\"y\"], expected)\n\n def test_mark_data_from_categorical(self, long_df):\n\n col = \"a\"\n m = MockMark()\n Plot(long_df, x=col).add(m).plot()\n\n levels = categorical_order(long_df[col])\n level_map = {x: float(i) for i, x in enumerate(levels)}\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[col].map(level_map))\n\n def test_mark_data_from_datetime(self, long_df):\n\n col = \"t\"\n m = MockMark()\n Plot(long_df, x=col).add(m).plot()\n\n expected = long_df[col].map(mpl.dates.date2num)\n if Version(mpl.__version__) < Version(\"3.3\"):\n expected = expected + mpl.dates.date2num(np.datetime64('0000-12-31'))\n\n assert_vector_equal(m.passed_data[0][\"x\"], expected)\n\n def test_computed_var_ticks(self, long_df):\n\n class Identity(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient]})\n\n tick_locs = [1, 2, 5]\n scale = Continuous().tick(at=tick_locs)\n p = Plot(long_df, \"x\").add(MockMark(), Identity()).scale(y=scale).plot()\n ax = p._figure.axes[0]\n assert_array_equal(ax.get_yticks(), tick_locs)\n\n def test_computed_var_transform(self, long_df):\n\n class Identity(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient]})\n\n p = Plot(long_df, \"x\").add(MockMark(), Identity()).scale(y=\"log\").plot()\n ax = p._figure.axes[0]\n xfm = ax.yaxis.get_transform().transform\n assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])\n\n def test_explicit_range_with_axis_scaling(self):\n\n x = [1, 2, 3]\n ymin = [10, 100, 1000]\n ymax = [20, 200, 2000]\n m = MockMark()\n Plot(x=x, ymin=ymin, ymax=ymax).add(m).scale(y=\"log\").plot()\n assert_vector_equal(m.passed_data[0][\"ymax\"], pd.Series(ymax, dtype=float))\n\n def test_derived_range_with_axis_scaling(self):\n\n class AddOne(Stat):\n def __call__(self, df, *args):\n return df.assign(ymax=df[\"y\"] + 1)\n\n x = y = [1, 10, 100]\n\n m = MockMark()\n Plot(x, y).add(m, AddOne()).scale(y=\"log\").plot()\n assert_vector_equal(m.passed_data[0][\"ymax\"], pd.Series([10., 100., 1000.]))\n\n def test_facet_categories(self):\n\n m = MockMark()\n p = Plot(x=[\"a\", \"b\", \"a\", \"c\"]).facet(col=[\"x\", \"x\", \"y\", \"y\"]).add(m).plot()\n ax1, ax2 = p._figure.axes\n assert len(ax1.get_xticks()) == 3\n assert len(ax2.get_xticks()) == 3\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [2, 3]))\n\n def test_facet_categories_unshared(self):\n\n m = MockMark()\n p = (\n Plot(x=[\"a\", \"b\", \"a\", \"c\"])\n .facet(col=[\"x\", \"x\", \"y\", \"y\"])\n .share(x=False)\n .add(m)\n .plot()\n )\n ax1, ax2 = p._figure.axes\n assert len(ax1.get_xticks()) == 2\n assert len(ax2.get_xticks()) == 2\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 1.], [2, 3]))\n\n def test_facet_categories_single_dim_shared(self):\n\n data = [\n (\"a\", 1, 1), (\"b\", 1, 1),\n (\"a\", 1, 2), (\"c\", 1, 2),\n (\"b\", 2, 1), (\"d\", 2, 1),\n (\"e\", 2, 2), (\"e\", 2, 1),\n ]\n df = pd.DataFrame(data, columns=[\"x\", \"row\", \"col\"]).assign(y=1)\n m = MockMark()\n p = (\n Plot(df, x=\"x\")\n .facet(row=\"row\", col=\"col\")\n .add(m)\n .share(x=\"row\")\n .plot()\n )\n\n axs = p._figure.axes\n for ax in axs:\n assert ax.get_xticks() == [0, 1, 2]\n\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [2, 3]))\n assert_vector_equal(m.passed_data[2][\"x\"], pd.Series([0., 1., 2.], [4, 5, 7]))\n assert_vector_equal(m.passed_data[3][\"x\"], pd.Series([2.], [6]))\n\n def test_pair_categories(self):\n\n data = [(\"a\", \"a\"), (\"b\", \"c\")]\n df = pd.DataFrame(data, columns=[\"x1\", \"x2\"]).assign(y=1)\n m = MockMark()\n p = Plot(df, y=\"y\").pair(x=[\"x1\", \"x2\"]).add(m).plot()\n\n ax1, ax2 = p._figure.axes\n assert ax1.get_xticks() == [0, 1]\n assert ax2.get_xticks() == [0, 1]\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 1.], [0, 1]))\n\n @pytest.mark.xfail(\n Version(mpl.__version__) < Version(\"3.4.0\"),\n reason=\"Sharing paired categorical axes requires matplotlib>3.4.0\"\n )\n def test_pair_categories_shared(self):\n\n data = [(\"a\", \"a\"), (\"b\", \"c\")]\n df = pd.DataFrame(data, columns=[\"x1\", \"x2\"]).assign(y=1)\n m = MockMark()\n p = Plot(df, y=\"y\").pair(x=[\"x1\", \"x2\"]).add(m).share(x=True).plot()\n\n for ax in p._figure.axes:\n assert ax.get_xticks() == [0, 1, 2]\n print(m.passed_data)\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [0, 1]))\n\n def test_identity_mapping_linewidth(self):\n\n m = MockMark()\n x = y = [1, 2, 3, 4, 5]\n lw = pd.Series([.5, .1, .1, .9, 3])\n Plot(x=x, y=y, linewidth=lw).scale(linewidth=None).add(m).plot()\n assert_vector_equal(m.passed_scales[\"linewidth\"](lw), lw)\n\n def test_pair_single_coordinate_stat_orient(self, long_df):\n\n class MockStat(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.orient = orient\n return data\n\n s = MockStat()\n Plot(long_df).pair(x=[\"x\", \"y\"]).add(MockMark(), s).plot()\n assert s.orient == \"x\"\n\n def test_inferred_nominal_passed_to_stat(self):\n\n class MockStat(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.scales = scales\n return data\n\n s = MockStat()\n y = [\"a\", \"a\", \"b\", \"c\"]\n Plot(y=y).add(MockMark(), s).plot()\n assert s.scales[\"y\"].__class__.__name__ == \"Nominal\"\n\n # TODO where should RGB consistency be enforced?\n @pytest.mark.xfail(\n reason=\"Correct output representation for color with identity scale undefined\"\n )\n def test_identity_mapping_color_strings(self):\n\n m = MockMark()\n x = y = [1, 2, 3]\n c = [\"C0\", \"C2\", \"C1\"]\n Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()\n expected = mpl.colors.to_rgba_array(c)[:, :3]\n assert_array_equal(m.passed_scales[\"color\"](c), expected)\n\n def test_identity_mapping_color_tuples(self):\n\n m = MockMark()\n x = y = [1, 2, 3]\n c = [(1, 0, 0), (0, 1, 0), (1, 0, 0)]\n Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()\n expected = mpl.colors.to_rgba_array(c)[:, :3]\n assert_array_equal(m.passed_scales[\"color\"](c), expected)\n\n @pytest.mark.xfail(\n reason=\"Need decision on what to do with scale defined for unused variable\"\n )\n def test_undefined_variable_raises(self):\n\n p = Plot(x=[1, 2, 3], color=[\"a\", \"b\", \"c\"]).scale(y=Continuous())\n err = r\"No data found for variable\\(s\\) with explicit scale: {'y'}\"\n with pytest.raises(RuntimeError, match=err):\n p.plot()\n\n\nclass TestPlotting:\n\n def test_matplotlib_object_creation(self):\n\n p = Plot().plot()\n assert isinstance(p._figure, mpl.figure.Figure)\n for sub in p._subplots:\n assert isinstance(sub[\"ax\"], mpl.axes.Axes)\n\n def test_empty(self):\n\n m = MockMark()\n Plot().plot()\n assert m.n_splits == 0\n\n def test_single_split_single_layer(self, long_df):\n\n m = MockMark()\n p = Plot(long_df, x=\"f\", y=\"z\").add(m).plot()\n assert m.n_splits == 1\n\n assert m.passed_keys[0] == {}\n assert m.passed_axes == [sub[\"ax\"] for sub in p._subplots]\n for col in p._data.frame:\n assert_series_equal(m.passed_data[0][col], p._data.frame[col])\n\n def test_single_split_multi_layer(self, long_df):\n\n vs = [{\"color\": \"a\", \"linewidth\": \"z\"}, {\"color\": \"b\", \"pattern\": \"c\"}]\n\n class NoGroupingMark(MockMark):\n _grouping_props = []\n\n ms = [NoGroupingMark(), NoGroupingMark()]\n Plot(long_df).add(ms[0], **vs[0]).add(ms[1], **vs[1]).plot()\n\n for m, v in zip(ms, vs):\n for var, col in v.items():\n assert_vector_equal(m.passed_data[0][var], long_df[col])\n\n def check_splits_single_var(\n self, data, mark, data_vars, split_var, split_col, split_keys\n ):\n\n assert mark.n_splits == len(split_keys)\n assert mark.passed_keys == [{split_var: key} for key in split_keys]\n\n for i, key in enumerate(split_keys):\n\n split_data = data[data[split_col] == key]\n for var, col in data_vars.items():\n assert_array_equal(mark.passed_data[i][var], split_data[col])\n\n def check_splits_multi_vars(\n self, data, mark, data_vars, split_vars, split_cols, split_keys\n ):\n\n assert mark.n_splits == np.prod([len(ks) for ks in split_keys])\n\n expected_keys = [\n dict(zip(split_vars, level_keys))\n for level_keys in itertools.product(*split_keys)\n ]\n assert mark.passed_keys == expected_keys\n\n for i, keys in enumerate(itertools.product(*split_keys)):\n\n use_rows = pd.Series(True, data.index)\n for var, col, key in zip(split_vars, split_cols, keys):\n use_rows &= data[col] == key\n split_data = data[use_rows]\n for var, col in data_vars.items():\n assert_array_equal(mark.passed_data[i][var], split_data[col])\n\n @pytest.mark.parametrize(\n \"split_var\", [\n \"color\", # explicitly declared on the Mark\n \"group\", # implicitly used for all Mark classes\n ])\n def test_one_grouping_variable(self, long_df, split_var):\n\n split_col = \"a\"\n data_vars = {\"x\": \"f\", \"y\": \"z\", split_var: split_col}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).add(m).plot()\n\n split_keys = categorical_order(long_df[split_col])\n sub, *_ = p._subplots\n assert m.passed_axes == [sub[\"ax\"] for _ in split_keys]\n self.check_splits_single_var(\n long_df, m, data_vars, split_var, split_col, split_keys\n )\n\n def test_two_grouping_variables(self, long_df):\n\n split_vars = [\"color\", \"group\"]\n split_cols = [\"a\", \"b\"]\n data_vars = {\"y\": \"z\", **{var: col for var, col in zip(split_vars, split_cols)}}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).add(m).plot()\n\n split_keys = [categorical_order(long_df[col]) for col in split_cols]\n sub, *_ = p._subplots\n assert m.passed_axes == [\n sub[\"ax\"] for _ in itertools.product(*split_keys)\n ]\n self.check_splits_multi_vars(\n long_df, m, data_vars, split_vars, split_cols, split_keys\n )\n\n def test_facets_no_subgroups(self, long_df):\n\n split_var = \"col\"\n split_col = \"b\"\n data_vars = {\"x\": \"f\", \"y\": \"z\"}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).facet(**{split_var: split_col}).add(m).plot()\n\n split_keys = categorical_order(long_df[split_col])\n assert m.passed_axes == list(p._figure.axes)\n self.check_splits_single_var(\n long_df, m, data_vars, split_var, split_col, split_keys\n )\n\n def test_facets_one_subgroup(self, long_df):\n\n facet_var, facet_col = fx = \"col\", \"a\"\n group_var, group_col = gx = \"group\", \"b\"\n split_vars, split_cols = zip(*[fx, gx])\n data_vars = {\"x\": \"f\", \"y\": \"z\", group_var: group_col}\n\n m = MockMark()\n p = (\n Plot(long_df, **data_vars)\n .facet(**{facet_var: facet_col})\n .add(m)\n .plot()\n )\n\n split_keys = [categorical_order(long_df[col]) for col in [facet_col, group_col]]\n assert m.passed_axes == [\n ax\n for ax in list(p._figure.axes)\n for _ in categorical_order(long_df[group_col])\n ]\n self.check_splits_multi_vars(\n long_df, m, data_vars, split_vars, split_cols, split_keys\n )\n\n def test_layer_specific_facet_disabling(self, long_df):\n\n axis_vars = {\"x\": \"y\", \"y\": \"z\"}\n row_var = \"a\"\n\n m = MockMark()\n p = Plot(long_df, **axis_vars).facet(row=row_var).add(m, row=None).plot()\n\n col_levels = categorical_order(long_df[row_var])\n assert len(p._figure.axes) == len(col_levels)\n\n for data in m.passed_data:\n for var, col in axis_vars.items():\n assert_vector_equal(data[var], long_df[col])\n\n def test_paired_variables(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n\n m = MockMark()\n Plot(long_df).pair(x, y).add(m).plot()\n\n var_product = itertools.product(x, y)\n\n for data, (x_i, y_i) in zip(m.passed_data, var_product):\n assert_vector_equal(data[\"x\"], long_df[x_i].astype(float))\n assert_vector_equal(data[\"y\"], long_df[y_i].astype(float))\n\n def test_paired_one_dimension(self, long_df):\n\n x = [\"y\", \"z\"]\n\n m = MockMark()\n Plot(long_df).pair(x).add(m).plot()\n\n for data, x_i in zip(m.passed_data, x):\n assert_vector_equal(data[\"x\"], long_df[x_i].astype(float))\n\n def test_paired_variables_one_subset(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n group = \"a\"\n\n long_df[\"x\"] = long_df[\"x\"].astype(float) # simplify vector comparison\n\n m = MockMark()\n Plot(long_df, group=group).pair(x, y).add(m).plot()\n\n groups = categorical_order(long_df[group])\n var_product = itertools.product(x, y, groups)\n\n for data, (x_i, y_i, g_i) in zip(m.passed_data, var_product):\n rows = long_df[group] == g_i\n assert_vector_equal(data[\"x\"], long_df.loc[rows, x_i])\n assert_vector_equal(data[\"y\"], long_df.loc[rows, y_i])\n\n def test_paired_and_faceted(self, long_df):\n\n x = [\"y\", \"z\"]\n y = \"f\"\n row = \"c\"\n\n m = MockMark()\n Plot(long_df, y=y).facet(row=row).pair(x).add(m).plot()\n\n facets = categorical_order(long_df[row])\n var_product = itertools.product(x, facets)\n\n for data, (x_i, f_i) in zip(m.passed_data, var_product):\n rows = long_df[row] == f_i\n assert_vector_equal(data[\"x\"], long_df.loc[rows, x_i])\n assert_vector_equal(data[\"y\"], long_df.loc[rows, y])\n\n def test_theme_default(self):\n\n p = Plot().plot()\n assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), \"#EAEAF2\")\n\n def test_theme_params(self):\n\n color = \".888\"\n p = Plot().theme({\"axes.facecolor\": color}).plot()\n assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), color)\n\n def test_theme_error(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=r\"theme\\(\\) takes 1 positional\"):\n p.theme(\"arg1\", \"arg2\")\n\n def test_stat(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg()).plot()\n\n expected = long_df.groupby(\"a\", sort=False)[\"z\"].mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], expected)\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated\n\n def test_move(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"z\", y=\"z\").add(m, Shift(x=1)).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"z\"] + 1)\n assert_vector_equal(m.passed_data[0][\"y\"], long_df[\"z\"])\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated\n\n def test_stat_and_move(self, long_df):\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg(), Shift(y=1)).plot()\n\n expected = long_df.groupby(\"a\", sort=False)[\"z\"].mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], expected + 1)\n\n def test_stat_log_scale(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg()).scale(y=\"log\").plot()\n\n x = long_df[\"a\"]\n y = np.log10(long_df[\"z\"])\n expected = y.groupby(x, sort=False).mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], 10 ** expected)\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated\n\n def test_move_log_scale(self, long_df):\n\n m = MockMark()\n Plot(\n long_df, x=\"z\", y=\"z\"\n ).scale(x=\"log\").add(m, Shift(x=-1)).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"z\"] / 10)\n\n def test_multi_move(self, long_df):\n\n m = MockMark()\n move_stack = [Shift(1), Shift(2)]\n Plot(long_df, x=\"x\", y=\"y\").add(m, *move_stack).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"x\"] + 3)\n\n def test_multi_move_with_pairing(self, long_df):\n m = MockMark()\n move_stack = [Shift(1), Shift(2)]\n Plot(long_df, x=\"x\").pair(y=[\"y\", \"z\"]).add(m, *move_stack).plot()\n for frame in m.passed_data:\n assert_vector_equal(frame[\"x\"], long_df[\"x\"] + 3)\n\n def test_move_with_range(self, long_df):\n\n x = [0, 0, 1, 1, 2, 2]\n group = [0, 1, 0, 1, 0, 1]\n ymin = np.arange(6)\n ymax = np.arange(6) * 2\n\n m = MockMark()\n Plot(x=x, group=group, ymin=ymin, ymax=ymax).add(m, Dodge()).plot()\n\n signs = [-1, +1]\n for i, df in m.passed_data[0].groupby(\"group\"):\n assert_array_equal(df[\"x\"], np.arange(3) + signs[i] * 0.2)\n\n def test_methods_clone(self, long_df):\n\n p1 = Plot(long_df, \"x\", \"y\")\n p2 = p1.add(MockMark()).facet(\"a\")\n\n assert p1 is not p2\n assert not p1._layers\n assert not p1._facet_spec\n\n def test_default_is_no_pyplot(self):\n\n p = Plot().plot()\n\n assert not plt.get_fignums()\n assert isinstance(p._figure, mpl.figure.Figure)\n\n def test_with_pyplot(self):\n\n p = Plot().plot(pyplot=True)\n\n assert len(plt.get_fignums()) == 1\n fig = plt.gcf()\n assert p._figure is fig\n\n def test_show(self):\n\n p = Plot()\n\n with warnings.catch_warnings(record=True) as msg:\n out = p.show(block=False)\n assert out is None\n assert not hasattr(p, \"_figure\")\n\n assert len(plt.get_fignums()) == 1\n fig = plt.gcf()\n\n gui_backend = (\n # From https://github.com/matplotlib/matplotlib/issues/20281\n fig.canvas.manager.show != mpl.backend_bases.FigureManagerBase.show\n )\n if not gui_backend:\n assert msg\n\n def test_png_repr(self):\n\n p = Plot()\n data, metadata = p._repr_png_()\n img = Image.open(io.BytesIO(data))\n\n assert not hasattr(p, \"_figure\")\n assert isinstance(data, bytes)\n assert img.format == \"PNG\"\n assert sorted(metadata) == [\"height\", \"width\"]\n # TODO test retina scaling\n\n def test_save(self):\n\n buf = io.BytesIO()\n\n p = Plot().save(buf)\n assert isinstance(p, Plot)\n img = Image.open(buf)\n assert img.format == \"PNG\"\n\n buf = io.StringIO()\n Plot().save(buf, format=\"svg\")\n tag = xml.etree.ElementTree.fromstring(buf.getvalue()).tag\n assert tag == \"{http://www.w3.org/2000/svg}svg\"\n\n def test_layout_size(self):\n\n size = (4, 2)\n p = Plot().layout(size=size).plot()\n assert tuple(p._figure.get_size_inches()) == size\n\n def test_on_axes(self):\n\n ax = mpl.figure.Figure().subplots()\n m = MockMark()\n p = Plot().on(ax).add(m).plot()\n assert m.passed_axes == [ax]\n assert p._figure is ax.figure\n\n @pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_figure(self, facet):\n\n f = mpl.figure.Figure()\n m = MockMark()\n p = Plot().on(f).add(m)\n if facet:\n p = p.facet([\"a\", \"b\"])\n p = p.plot()\n assert m.passed_axes == f.axes\n assert p._figure is f\n\n @pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"mpl<3.4 does not have SubFigure\",\n )\n @pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_subfigure(self, facet):\n\n sf1, sf2 = mpl.figure.Figure().subfigures(2)\n sf1.subplots()\n m = MockMark()\n p = Plot().on(sf2).add(m)\n if facet:\n p = p.facet([\"a\", \"b\"])\n p = p.plot()\n assert m.passed_axes == sf2.figure.axes[1:]\n assert p._figure is sf2.figure\n\n def test_on_type_check(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=\"The `Plot.on`.+\"):\n p.on([])\n\n def test_on_axes_with_subplots_error(self):\n\n ax = mpl.figure.Figure().subplots()\n\n p1 = Plot().facet([\"a\", \"b\"]).on(ax)\n with pytest.raises(RuntimeError, match=\"Cannot create multiple subplots\"):\n p1.plot()\n\n p2 = Plot().pair([[\"a\", \"b\"], [\"x\", \"y\"]]).on(ax)\n with pytest.raises(RuntimeError, match=\"Cannot create multiple subplots\"):\n p2.plot()\n\n def test_on_disables_layout_algo(self):\n\n f = mpl.figure.Figure()\n p = Plot().on(f).plot()\n assert not p._figure.get_tight_layout()\n\n def test_axis_labels_from_constructor(self, long_df):\n\n ax, = Plot(long_df, x=\"a\", y=\"b\").plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n ax, = Plot(x=long_df[\"a\"], y=long_df[\"b\"].to_numpy()).plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n\n def test_axis_labels_from_layer(self, long_df):\n\n m = MockMark()\n\n ax, = Plot(long_df).add(m, x=\"a\", y=\"b\").plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n p = Plot().add(m, x=long_df[\"a\"], y=long_df[\"b\"].to_list())\n ax, = p.plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n\n def test_axis_labels_are_first_name(self, long_df):\n\n m = MockMark()\n p = (\n Plot(long_df, x=long_df[\"z\"].to_list(), y=\"b\")\n .add(m, x=\"a\")\n .add(m, x=\"x\", y=\"y\")\n )\n ax, = p.plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n def test_limits(self, long_df):\n\n limit = (-2, 24)\n p = Plot(long_df, x=\"x\", y=\"y\").limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == limit\n\n limit = (np.datetime64(\"2005-01-01\"), np.datetime64(\"2008-01-01\"))\n p = Plot(long_df, x=\"d\", y=\"y\").limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == tuple(mpl.dates.date2num(limit))\n\n limit = (\"b\", \"c\")\n p = Plot(x=[\"a\", \"b\", \"c\", \"d\"], y=[1, 2, 3, 4]).limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == (0.5, 2.5)\n\n def test_labels_axis(self, long_df):\n\n label = \"Y axis\"\n p = Plot(long_df, x=\"x\", y=\"y\").label(y=label).plot()\n ax = p._figure.axes[0]\n assert ax.get_ylabel() == label\n\n label = str.capitalize\n p = Plot(long_df, x=\"x\", y=\"y\").label(y=label).plot()\n ax = p._figure.axes[0]\n assert ax.get_ylabel() == \"Y\"\n\n def test_labels_legend(self, long_df):\n\n m = MockMark()\n\n label = \"A\"\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(m).label(color=label).plot()\n assert p._figure.legends[0].get_title().get_text() == label\n\n func = str.capitalize\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(m).label(color=func).plot()\n assert p._figure.legends[0].get_title().get_text() == label\n\n def test_labels_facets(self):\n\n data = {\"a\": [\"b\", \"c\"], \"x\": [\"y\", \"z\"]}\n p = Plot(data).facet(\"a\", \"x\").label(col=str.capitalize, row=\"$x$\").plot()\n axs = np.reshape(p._figure.axes, (2, 2))\n for (i, j), ax in np.ndenumerate(axs):\n expected = f\"A {data['a'][j]} | $x$ {data['x'][i]}\"\n assert ax.get_title() == expected\n\n def test_title_single(self):\n\n label = \"A\"\n p = Plot().label(title=label).plot()\n assert p._figure.axes[0].get_title() == label\n\n def test_title_facet_function(self):\n\n titles = [\"a\", \"b\"]\n p = Plot().facet(titles).label(title=str.capitalize).plot()\n for i, ax in enumerate(p._figure.axes):\n assert ax.get_title() == titles[i].upper()\n\n cols, rows = [\"a\", \"b\"], [\"x\", \"y\"]\n p = Plot().facet(cols, rows).label(title=str.capitalize).plot()\n for i, ax in enumerate(p._figure.axes):\n expected = \" | \".join([cols[i % 2].upper(), rows[i // 2].upper()])\n assert ax.get_title() == expected\n\n\nclass TestFacetInterface:\n\n @pytest.fixture(scope=\"class\", params=[\"row\", \"col\"])\n def dim(self, request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=[\"reverse\", \"subset\", \"expand\"])\n def reorder(self, request):\n return {\n \"reverse\": lambda x: x[::-1],\n \"subset\": lambda x: x[:-1],\n \"expand\": lambda x: x + [\"z\"],\n }[request.param]\n\n def check_facet_results_1d(self, p, df, dim, key, order=None):\n\n p = p.plot()\n\n order = categorical_order(df[key], order)\n assert len(p._figure.axes) == len(order)\n\n other_dim = {\"row\": \"col\", \"col\": \"row\"}[dim]\n\n for subplot, level in zip(p._subplots, order):\n assert subplot[dim] == level\n assert subplot[other_dim] is None\n assert subplot[\"ax\"].get_title() == f\"{level}\"\n assert_gridspec_shape(subplot[\"ax\"], **{f\"n{dim}s\": len(order)})\n\n def test_1d(self, long_df, dim):\n\n key = \"a\"\n p = Plot(long_df).facet(**{dim: key})\n self.check_facet_results_1d(p, long_df, dim, key)\n\n def test_1d_as_vector(self, long_df, dim):\n\n key = \"a\"\n p = Plot(long_df).facet(**{dim: long_df[key]})\n self.check_facet_results_1d(p, long_df, dim, key)\n\n def test_1d_with_order(self, long_df, dim, reorder):\n\n key = \"a\"\n order = reorder(categorical_order(long_df[key]))\n p = Plot(long_df).facet(**{dim: key, \"order\": order})\n self.check_facet_results_1d(p, long_df, dim, key, order)\n\n def check_facet_results_2d(self, p, df, variables, order=None):\n\n p = p.plot()\n\n if order is None:\n order = {dim: categorical_order(df[key]) for dim, key in variables.items()}\n\n levels = itertools.product(*[order[dim] for dim in [\"row\", \"col\"]])\n assert len(p._subplots) == len(list(levels))\n\n for subplot, (row_level, col_level) in zip(p._subplots, levels):\n assert subplot[\"row\"] == row_level\n assert subplot[\"col\"] == col_level\n assert subplot[\"axes\"].get_title() == (\n f\"{col_level} | {row_level}\"\n )\n assert_gridspec_shape(\n subplot[\"axes\"], len(levels[\"row\"]), len(levels[\"col\"])\n )\n\n def test_2d(self, long_df):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n p = Plot(long_df).facet(**variables)\n self.check_facet_results_2d(p, long_df, variables)\n\n def test_2d_with_order(self, long_df, reorder):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n order = {\n dim: reorder(categorical_order(long_df[key]))\n for dim, key in variables.items()\n }\n\n p = Plot(long_df).facet(**variables, order=order)\n self.check_facet_results_2d(p, long_df, variables, order)\n\n @pytest.mark.parametrize(\"algo\", [\"tight\", \"constrained\"])\n def test_layout_algo(self, algo):\n\n if algo == \"constrained\" and Version(mpl.__version__) < Version(\"3.3.0\"):\n pytest.skip(\"constrained_layout requires matplotlib>=3.3\")\n\n p = Plot().facet([\"a\", \"b\"]).limit(x=(.1, .9))\n\n p1 = p.layout(engine=algo).plot()\n p2 = p.layout(engine=None).plot()\n\n # Force a draw (we probably need a method for this)\n p1.save(io.BytesIO())\n p2.save(io.BytesIO())\n\n bb11, bb12 = [ax.get_position() for ax in p1._figure.axes]\n bb21, bb22 = [ax.get_position() for ax in p2._figure.axes]\n\n sep1 = bb12.corners()[0, 0] - bb11.corners()[2, 0]\n sep2 = bb22.corners()[0, 0] - bb21.corners()[2, 0]\n assert sep1 < sep2\n\n def test_axis_sharing(self, long_df):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n\n p = Plot(long_df).facet(**variables)\n\n p1 = p.plot()\n root, *other = p1._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert all(shareset.joined(root, ax) for ax in other)\n\n p2 = p.share(x=False, y=False).plot()\n root, *other = p2._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n p3 = p.share(x=\"col\", y=\"row\").plot()\n shape = (\n len(categorical_order(long_df[variables[\"row\"]])),\n len(categorical_order(long_df[variables[\"col\"]])),\n )\n axes_matrix = np.reshape(p3._figure.axes, shape)\n\n for (shared, unshared), vectors in zip(\n [\"yx\", \"xy\"], [axes_matrix, axes_matrix.T]\n ):\n for root, *other in vectors:\n shareset = {\n axis: getattr(root, f\"get_shared_{axis}_axes\")() for axis in \"xy\"\n }\n assert all(shareset[shared].joined(root, ax) for ax in other)\n assert not any(shareset[unshared].joined(root, ax) for ax in other)\n\n def test_col_wrapping(self):\n\n cols = list(\"abcd\")\n wrap = 3\n p = Plot().facet(col=cols, wrap=wrap).plot()\n\n assert len(p._figure.axes) == 4\n assert_gridspec_shape(p._figure.axes[0], len(cols) // wrap + 1, wrap)\n\n # TODO test axis labels and titles\n\n def test_row_wrapping(self):\n\n rows = list(\"abcd\")\n wrap = 3\n p = Plot().facet(row=rows, wrap=wrap).plot()\n\n assert_gridspec_shape(p._figure.axes[0], wrap, len(rows) // wrap + 1)\n assert len(p._figure.axes) == 4\n\n # TODO test axis labels and titles\n\n\nclass TestPairInterface:\n\n def check_pair_grid(self, p, x, y):\n\n xys = itertools.product(y, x)\n\n for (y_i, x_j), subplot in zip(xys, p._subplots):\n\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == \"\" if x_j is None else x_j\n assert ax.get_ylabel() == \"\" if y_i is None else y_i\n assert_gridspec_shape(subplot[\"ax\"], len(y), len(x))\n\n @pytest.mark.parametrize(\"vector_type\", [list, pd.Index])\n def test_all_numeric(self, long_df, vector_type):\n\n x, y = [\"x\", \"y\", \"z\"], [\"s\", \"f\"]\n p = Plot(long_df).pair(vector_type(x), vector_type(y)).plot()\n self.check_pair_grid(p, x, y)\n\n def test_single_variable_key_raises(self, long_df):\n\n p = Plot(long_df)\n err = \"You must pass a sequence of variable keys to `y`\"\n with pytest.raises(TypeError, match=err):\n p.pair(x=[\"x\", \"y\"], y=\"z\")\n\n @pytest.mark.parametrize(\"dim\", [\"x\", \"y\"])\n def test_single_dimension(self, long_df, dim):\n\n variables = {\"x\": None, \"y\": None}\n variables[dim] = [\"x\", \"y\", \"z\"]\n p = Plot(long_df).pair(**variables).plot()\n variables = {k: [v] if v is None else v for k, v in variables.items()}\n self.check_pair_grid(p, **variables)\n\n def test_non_cross(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n\n p = Plot(long_df).pair(x, y, cross=False).plot()\n\n for i, subplot in enumerate(p._subplots):\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == x[i]\n assert ax.get_ylabel() == y[i]\n assert_gridspec_shape(ax, 1, len(x))\n\n root, *other = p._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n def test_list_of_vectors(self, long_df):\n\n x_vars = [\"x\", \"z\"]\n p = Plot(long_df, y=\"y\").pair(x=[long_df[x] for x in x_vars]).plot()\n assert len(p._figure.axes) == len(x_vars)\n for ax, x_i in zip(p._figure.axes, x_vars):\n assert ax.get_xlabel() == x_i\n\n def test_with_no_variables(self, long_df):\n\n p = Plot(long_df).pair().plot()\n assert len(p._figure.axes) == 1\n\n def test_with_facets(self, long_df):\n\n x = \"x\"\n y = [\"y\", \"z\"]\n col = \"a\"\n\n p = Plot(long_df, x=x).facet(col).pair(y=y).plot()\n\n facet_levels = categorical_order(long_df[col])\n dims = itertools.product(y, facet_levels)\n\n for (y_i, col_i), subplot in zip(dims, p._subplots):\n\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == x\n assert ax.get_ylabel() == y_i\n assert ax.get_title() == f\"{col_i}\"\n assert_gridspec_shape(ax, len(y), len(facet_levels))\n\n @pytest.mark.parametrize(\"variables\", [(\"rows\", \"y\"), (\"columns\", \"x\")])\n def test_error_on_facet_overlap(self, long_df, variables):\n\n facet_dim, pair_axis = variables\n p = Plot(long_df).facet(**{facet_dim[:3]: \"a\"}).pair(**{pair_axis: [\"x\", \"y\"]})\n expected = f\"Cannot facet the {facet_dim} while pairing on `{pair_axis}`.\"\n with pytest.raises(RuntimeError, match=expected):\n p.plot()\n\n @pytest.mark.parametrize(\"variables\", [(\"columns\", \"y\"), (\"rows\", \"x\")])\n def test_error_on_wrap_overlap(self, long_df, variables):\n\n facet_dim, pair_axis = variables\n p = (\n Plot(long_df)\n .facet(wrap=2, **{facet_dim[:3]: \"a\"})\n .pair(**{pair_axis: [\"x\", \"y\"]})\n )\n expected = f\"Cannot wrap the {facet_dim} while pairing on `{pair_axis}``.\"\n with pytest.raises(RuntimeError, match=expected):\n p.plot()\n\n def test_axis_sharing(self, long_df):\n\n p = Plot(long_df).pair(x=[\"a\", \"b\"], y=[\"y\", \"z\"])\n shape = 2, 2\n\n p1 = p.plot()\n axes_matrix = np.reshape(p1._figure.axes, shape)\n\n for root, *other in axes_matrix: # Test row-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert not any(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n for root, *other in axes_matrix.T: # Test col-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert all(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert not any(y_shareset.joined(root, ax) for ax in other)\n\n p2 = p.share(x=False, y=False).plot()\n root, *other = p2._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n def test_axis_sharing_with_facets(self, long_df):\n\n p = Plot(long_df, y=\"y\").pair(x=[\"a\", \"b\"]).facet(row=\"c\").plot()\n shape = 2, 2\n\n axes_matrix = np.reshape(p._figure.axes, shape)\n\n for root, *other in axes_matrix: # Test row-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert not any(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n for root, *other in axes_matrix.T: # Test col-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert all(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n def test_x_wrapping(self, long_df):\n\n x_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n p = Plot(long_df, y=\"y\").pair(x=x_vars, wrap=wrap).plot()\n\n assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)\n assert len(p._figure.axes) == len(x_vars)\n for ax, var in zip(p._figure.axes, x_vars):\n label = ax.xaxis.get_label()\n assert label.get_visible()\n assert label.get_text() == var\n\n def test_y_wrapping(self, long_df):\n\n y_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n p = Plot(long_df, x=\"x\").pair(y=y_vars, wrap=wrap).plot()\n\n n_row, n_col = wrap, len(y_vars) // wrap + 1\n assert_gridspec_shape(p._figure.axes[0], n_row, n_col)\n assert len(p._figure.axes) == len(y_vars)\n label_array = np.empty(n_row * n_col, object)\n label_array[:len(y_vars)] = y_vars\n label_array = label_array.reshape((n_row, n_col), order=\"F\")\n label_array = [y for y in label_array.flat if y is not None]\n for i, ax in enumerate(p._figure.axes):\n label = ax.yaxis.get_label()\n assert label.get_visible()\n assert label.get_text() == label_array[i]\n\n def test_non_cross_wrapping(self, long_df):\n\n x_vars = [\"a\", \"b\", \"c\", \"t\"]\n y_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n\n p = (\n Plot(long_df, x=\"x\")\n .pair(x=x_vars, y=y_vars, wrap=wrap, cross=False)\n .plot()\n )\n\n assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)\n assert len(p._figure.axes) == len(x_vars)\n\n def test_cross_mismatched_lengths(self, long_df):\n\n p = Plot(long_df)\n with pytest.raises(ValueError, match=\"Lengths of the `x` and `y`\"):\n p.pair(x=[\"a\", \"b\"], y=[\"x\", \"y\", \"z\"], cross=False)\n\n def test_orient_inference(self, long_df):\n\n orient_list = []\n\n class CaptureOrientMove(Move):\n def __call__(self, data, groupby, orient, scales):\n orient_list.append(orient)\n return data\n\n (\n Plot(long_df, x=\"x\")\n .pair(y=[\"b\", \"z\"])\n .add(MockMark(), CaptureOrientMove())\n .plot()\n )\n\n assert orient_list == [\"y\", \"x\"]\n\n def test_computed_coordinate_orient_inference(self, long_df):\n\n class MockComputeStat(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient] * 2})\n\n m = MockMark()\n Plot(long_df, y=\"y\").add(m, MockComputeStat()).plot()\n assert m.passed_orient == \"y\"\n\n def test_two_variables_single_order_error(self, long_df):\n\n p = Plot(long_df)\n err = \"When faceting on both col= and row=, passing `order`\"\n with pytest.raises(RuntimeError, match=err):\n p.facet(col=\"a\", row=\"b\", order=[\"a\", \"b\", \"c\"])\n\n def test_limits(self, long_df):\n\n limit = (-2, 24)\n p = Plot(long_df, y=\"y\").pair(x=[\"x\", \"z\"]).limit(x1=limit).plot()\n ax1 = p._figure.axes[1]\n assert ax1.get_xlim() == limit\n\n def test_labels(self, long_df):\n\n label = \"Z\"\n p = Plot(long_df, y=\"y\").pair(x=[\"x\", \"z\"]).label(x1=label).plot()\n ax1 = p._figure.axes[1]\n assert ax1.get_xlabel() == label\n\n\nclass TestLabelVisibility:\n\n def test_single_subplot(self, long_df):\n\n x, y = \"a\", \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n subplot, *_ = p._subplots\n ax = subplot[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n @pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"col\": \"b\"}, {}), ({}, {\"x\": [\"x\", \"y\", \"f\"]})]\n )\n def test_1d_column(self, long_df, facet_kws, pair_kws):\n\n x = None if \"x\" in pair_kws else \"a\"\n y = \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n first, *other = p._subplots\n\n ax = first[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in other:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert not ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n @pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"row\": \"b\"}, {}), ({}, {\"y\": [\"x\", \"y\", \"f\"]})]\n )\n def test_1d_row(self, long_df, facet_kws, pair_kws):\n\n x = \"z\"\n y = None if \"y\" in pair_kws else \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n first, *other = p._subplots\n\n ax = first[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in other:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n def test_1d_column_wrapped(self):\n\n p = Plot().facet(col=[\"a\", \"b\", \"c\", \"d\"], wrap=3).plot()\n subplots = list(p._subplots)\n\n for s in [subplots[0], subplots[-1]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in subplots[1:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[1:-1]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n ax = subplots[0][\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n def test_1d_row_wrapped(self):\n\n p = Plot().facet(row=[\"a\", \"b\", \"c\", \"d\"], wrap=3).plot()\n subplots = list(p._subplots)\n\n for s in subplots[:-1]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in subplots[-2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[:-2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n ax = subplots[-1][\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n def test_1d_column_wrapped_non_cross(self, long_df):\n\n p = (\n Plot(long_df)\n .pair(x=[\"a\", \"b\", \"c\"], y=[\"x\", \"y\", \"z\"], wrap=2, cross=False)\n .plot()\n )\n for s in p._subplots:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n def test_2d(self):\n\n p = Plot().facet(col=[\"a\", \"b\"], row=[\"x\", \"y\"]).plot()\n subplots = list(p._subplots)\n\n for s in subplots[:2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in [subplots[0], subplots[2]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in [subplots[1], subplots[3]]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n def test_2d_unshared(self):\n\n p = (\n Plot()\n .facet(col=[\"a\", \"b\"], row=[\"x\", \"y\"])\n .share(x=False, y=False)\n .plot()\n )\n subplots = list(p._subplots)\n\n for s in subplots[:2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in [subplots[0], subplots[2]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in [subplots[1], subplots[3]]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n\nclass TestLegend:\n\n @pytest.fixture\n def xy(self):\n return dict(x=[1, 2, 3, 4], y=[1, 2, 3, 4])\n\n def test_single_layer_single_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy).add(MockMark(), color=s).plot()\n e, = p._legend_contents\n\n labels = categorical_order(s)\n\n assert e[0] == (s.name, s.name)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [\"color\"]\n\n def test_single_layer_common_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n sem = dict(color=s, marker=s)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n e, = p._legend_contents\n\n labels = categorical_order(s)\n\n assert e[0] == (s.name, s.name)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == list(sem)\n\n def test_single_layer_common_unnamed_variable(self, xy):\n\n s = np.array([\"a\", \"b\", \"a\", \"c\"])\n sem = dict(color=s, marker=s)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n\n e, = p._legend_contents\n\n labels = list(np.unique(s)) # assumes sorted order\n\n assert e[0] == (\"\", id(s))\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == list(sem)\n\n def test_single_layer_multi_variable(self, xy):\n\n s1 = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s1\")\n s2 = pd.Series([\"m\", \"m\", \"p\", \"m\"], name=\"s2\")\n sem = dict(color=s1, marker=s2)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n e1, e2 = p._legend_contents\n\n variables = {v.name: k for k, v in sem.items()}\n\n for e, s in zip([e1, e2], [s1, s2]):\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [variables[s.name]]\n\n def test_multi_layer_single_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s).add(MockMark()).add(MockMark()).plot()\n e1, e2 = p._legend_contents\n\n labels = categorical_order(s)\n\n for e in [e1, e2]:\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [\"color\"]\n\n def test_multi_layer_multi_variable(self, xy):\n\n s1 = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s1\")\n s2 = pd.Series([\"m\", \"m\", \"p\", \"m\"], name=\"s2\")\n sem = dict(color=s1), dict(marker=s2)\n variables = {\"s1\": \"color\", \"s2\": \"marker\"}\n p = Plot(**xy).add(MockMark(), **sem[0]).add(MockMark(), **sem[1]).plot()\n e1, e2 = p._legend_contents\n\n for e, s in zip([e1, e2], [s1, s2]):\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [variables[s.name]]\n\n def test_multi_layer_different_artists(self, xy):\n\n class MockMark1(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.lines.Line2D([], [])\n\n class MockMark2(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.patches.Patch()\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s).add(MockMark1()).add(MockMark2()).plot()\n\n legend, = p._figure.legends\n\n names = categorical_order(s)\n labels = [t.get_text() for t in legend.get_texts()]\n assert labels == names\n\n if Version(mpl.__version__) >= Version(\"3.2\"):\n contents = legend.get_children()[0]\n assert len(contents.findobj(mpl.lines.Line2D)) == len(names)\n assert len(contents.findobj(mpl.patches.Patch)) == len(names)\n\n def test_three_layers(self, xy):\n\n class MockMarkLine(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.lines.Line2D([], [])\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s)\n for _ in range(3):\n p = p.add(MockMarkLine())\n p = p.plot()\n texts = p._figure.legends[0].get_texts()\n assert len(texts) == len(s.unique())\n\n def test_identity_scale_ignored(self, xy):\n\n s = pd.Series([\"r\", \"g\", \"b\", \"g\"])\n p = Plot(**xy).add(MockMark(), color=s).scale(color=None).plot()\n assert not p._legend_contents\n\n def test_suppression_in_add_method(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy).add(MockMark(), color=s, legend=False).plot()\n assert not p._legend_contents\n\n def test_anonymous_title(self, xy):\n\n p = Plot(**xy, color=[\"a\", \"b\", \"c\", \"d\"]).add(MockMark()).plot()\n legend, = p._figure.legends\n assert legend.get_title().get_text() == \"\"\n\n def test_legendless_mark(self, xy):\n\n class NoLegendMark(MockMark):\n def _legend_artist(self, variables, value, scales):\n return None\n\n p = Plot(**xy, color=[\"a\", \"b\", \"c\", \"d\"]).add(NoLegendMark()).plot()\n assert not p._figure.legends\n\n\nclass TestDefaultObject:\n\n def test_default_repr(self):\n\n assert repr(Default()) == \"\"\n"},{"attributeType":"null","col":21,"comment":"null","endLoc":22,"id":4235,"name":"fid","nodeType":"Attribute","startLoc":22,"text":"fid"},{"attributeType":"SupportsDunderLT | SupportsDunderGT","col":4,"comment":"null","endLoc":25,"id":4236,"name":"name","nodeType":"Attribute","startLoc":25,"text":"name"},{"col":4,"comment":"null","endLoc":52,"header":"def test_set_properties(self)","id":4237,"name":"test_set_properties","nodeType":"Function","startLoc":36,"text":"def test_set_properties(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n color = \"red\"\n alpha = .6\n fontsize = 6\n valign = \"bottom\"\n\n m = Text(color=color, alpha=alpha, fontsize=fontsize, valign=valign)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n assert text.get_text() == s[i]\n assert text.get_color() == to_rgba(m.color, m.alpha)\n assert text.get_fontsize() == m.fontsize\n assert text.get_verticalalignment() == m.valign"},{"col":0,"comment":"","endLoc":1,"header":"set_nb_kernels.py#","id":4238,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Recursively set the kernel name for all jupyter notebook files.\"\"\"\n\nif __name__ == \"__main__\":\n\n _, kernel_name = sys.argv\n\n nb_paths = glob(\"./**/*.ipynb\", recursive=True)\n for path in nb_paths:\n\n with open(path) as f:\n nb = nbformat.read(f, as_version=4)\n\n nb[\"metadata\"][\"kernelspec\"][\"name\"] = kernel_name\n nb[\"metadata\"][\"kernelspec\"][\"display_name\"] = kernel_name\n\n with open(path, \"w\") as f:\n nbformat.write(nb, f)"},{"id":4239,"name":"faq.rst","nodeType":"TextFile","path":"doc","text":".. currentmodule:: seaborn\n\nFrequently asked questions\n==========================\n\nThis is a collection of answers to questions that are commonly raised about seaborn.\n\nGetting started\n---------------\n\n.. _faq_cant_import:\n\nI've installed seaborn, why can't I import it?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*It looks like you successfully installed seaborn by doing* `pip install seaborn` *but it cannot be imported. You get an error like \"ModuleNotFoundError: No module named 'seaborn'\" when you try.*\n\nThis is probably not a `seaborn` problem, *per se*. If you have multiple Python environments on your computer, it is possible that you did `pip install` in one environment and tried to import the library in another. On a unix system, you could check whether the terminal commands `which pip`, `which python`, and (if applicable) `which jupyter` point to the same `bin/` directory. If not, you'll need to sort out the definition of your `$PATH` variable.\n\nTwo alternate patterns for installing with `pip` may also be more robust to this problem:\n\n- Invoke `pip` on the command line with `python -m pip install ` rather than `pip install `\n- Use `%pip install ` in a Jupyter notebook to install it in the same place as the kernel\n\n.. _faq_import_fails:\n\nI can't import seaborn, even though it's definitely installed!\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You've definitely installed seaborn in the right place, but importing it produces a long traceback and a confusing error message, perhaps something like* `ImportError: DLL load failed: The specified module could not be found`.\n\nSuch errors usually indicate a problem with the way Python libraries are using compiled resources. Because seaborn is pure Python, it won't directly encounter these problems, but its dependencies (numpy, scipy, matplotlib, and pandas) might. To fix the issue, you'll first need to read through the traceback and figure out which dependency was being imported at the time of the error. Then consult the installation documentation for the relevant package, which might have advice for getting an installation working on your specific system.\n\nThe most common culprit of these issues is scipy, which has many compiled components. Starting in seaborn version 0.12, scipy is an optional dependency, which should help to reduce the frequency of these issues.\n\n.. _faq_no_plots:\n\nWhy aren't my plots showing up?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You're calling seaborn functions — maybe in a terminal or IDE with an integrated IPython console — but not seeing any plots.)*\n\nIn matplotlib, there is a distinction between *creating* a figure and *showing* it, and in some cases it's necessary to explicitly call :func:`matplotlib.pyplot.show` at the point when you want to see the plot. Because that command blocks by default and is not always desired (for instance, you may be executing a script that saves files to disk) seaborn does not deviate from standard matplotlib practice here.\n\nYet most of the examples in the seaborn docs do not have this line, because there are multiple ways to avoid needing it. In a Jupyter notebook with the `\"inline\" `_ (default) or `\"widget\" `_ backends, :func:`matplotlib.pyplot.show` is automatically called after executing a cell, so any figures will appear in the cell's outputs. You can also activate a more interactive experience by executing `%matplotlib` in any Jupyter or IPython interface or by calling :func:`matplotlib.pyplot.ion` anywhere in Python. Both methods will configure matplotlib to show or update the figure after every plotting command.\n\n.. _faq_repl_output:\n\nWhy is something printed after every notebook cell?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You're using seaborn in a Jupyter notebook, and every cell prints something like or before showing the plot.*\n\nJupyter notebooks will show the result of the final statement in the cell as part of its output, and each of seaborn's plotting functions return a reference to the matplotlib or seaborn object that contain the plot. If this is bothersome, you can suppress this output in a few ways:\n\n- Always assign the result of the final statement to a variable (e.g. `ax = sns.histplot(...)`)\n- Add a semicolon to the end of the final statement (e.g. `sns.histplot(...);`)\n- End every cell with a function that has no return value (e.g. `plt.show()`, which isn't needed but also causes no problems)\n- Add `cell metadata tags `_, if you're converting the notebook to a different representation\n\n.. _faq_inline_dpi:\n\nWhy do the plots look fuzzy in a Jupyter notebook?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe default \"inline\" backend (defined by `IPython `_) uses an unusually low dpi (`\"dots per inch\" `_) for figure output. This is a space-saving measure: lower dpi figures take up less disk space. (Also, lower dpi inline graphics appear *physically* smaller because they are represented as `PNGs `_, which do not exactly have a concept of resolution.) So one faces an economy/quality tradeoff.\n\nYou can increase the DPI by resetting the rc parameters through the matplotlib API, using\n\n::\n\n plt.rcParams.update({\"figure.dpi\": 96})\n\nOr do it as you activate the seaborn theme::\n\n sns.set_theme(rc={\"figure.dpi\": 96})\n\nIf you have a high pixel-density monitor, you can make your plots sharper using \"retina mode\"::\n\n %config InlineBackend.figure_format = \"retina\"\n\nThis won't change the apparent size of your plots in a Jupyter interface, but they might appear very large in other contexts (i.e. on GitHub). And they will take up 4x the disk space. Alternatively, you can make SVG plots::\n\n %config InlineBackend.figure_format = \"svg\"\n\nThis will configure matplotlib to emit `vector graphics `_ with \"infinite resolution\". The downside is that file size will now scale with the number and complexity of the artists in your plot, and in some cases (e.g., a large scatterplot matrix) the load will impact browser responsiveness.\n\nTricky concepts\n---------------\n\n.. _faq_function_levels:\n\nWhat do \"figure-level\" and \"axes-level\" mean?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You've encountered the term \"figure-level\" or \"axes-level\", maybe in the seaborn docs, StackOverflow answer, or GitHub thread, but you don't understand what it means.*\n\nIn brief, all plotting functions in seaborn fall into one of two categories:\n\n- \"axes-level\" functions, which plot onto a single subplot that may or may not exist at the time the function is called\n- \"figure-level\" functions, which internally create a matplotlib figure, potentially including multiple subplots\n\nThis design is intended to satisfy two objectives:\n\n- seaborn should offer functions that are \"drop-in\" replacements for matplotlib methods\n- seaborn should be able to produce figures that show \"facets\" or marginal distributions on distinct subplots\n\nThe figure-level functions always combine one or more axes-level functions with an object that manages the layout. So, for example, :func:`relplot` is a figure-level function that combines either :func:`scatterplot` or :func:`lineplot` with a :class:`FacetGrid`. In contrast, :func:`jointplot` is a figure-level function that can combine multiple different axes-level functions — :func:`scatterplot` and :func:`histplot` by default — with a :class:`JointGrid`.\n\nIf all you're doing is creating a plot with a single seaborn function call, this is not something you need to worry too much about. But it becomes relevant when you want to customize at a level beyond what the API of each function offers. It is also the source of various other points of confusion, so it is an important distinction understand (at least broadly) and keep in mind.\n\nThis is explained in more detail in the :doc:`tutorial ` and in `this blog post `_.\n\n.. _faq_categorical_plots:\n\nWhat is a \"categorical plot\" or \"categorical function\"?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNext to the figure-level/axes-level distinction, this concept is probably the second biggest source of confusing behavior.\n\nSeveral :ref:`seaborn functions ` are referred to as \"categorical\" because they are designed to support a use-case where either the x or y variable in a plot is categorical (that is, the variable takes a finite number of potentially non-numeric values).\n\nAt the time these functions were written, matplotlib did not have any direct support for non-numeric data types. So seaborn internally builds a mapping from unique values in the data to 0-based integer indexes, which is what it passes to matplotlib. If your data are strings, that's great, and it more-or-less matches how `matplotlib now handles `_ string-typed data.\n\nBut a potential gotcha is that these functions *always do this*, even if both the x and y variables are numeric. This gives rise to a number of confusing behaviors, especially when mixing categorical and non-categorical plots (e.g., a combo bar-and-line plot).\n\nThe v0.12 release added a `native_scale` parameter to :func:`stripplot` and :func:`swarmplot`, which provides control over this behavior. It will be rolled out to other categorical functions in future releases. But the current behavior will almost certainly remain the default, so this is an important API wrinkle to understand.\n\nSpecifying data\n---------------\n\n.. _faq_data_format:\n\nHow does my data need to be organized?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo get the most out of seaborn, your data should have a \"long-form\" or \"tidy\" representation. In a dataframe, `this means that `_ each variable has its own column, each observation has its own row, and each value has its own cell. With long-form data, you can succinctly and exactly specify a visualization by assigning variables in the dataset (columns) to roles in the plot.\n\nData organization is a common stumbling block for beginners, in part because data are often not collected or stored in a long-form representation. Therefore, it is often necessary to `reshape `_ the data using pandas before plotting. Data reshaping can be a complex undertaking, requiring both a solid grasp of dataframe structure and knowledge of the pandas API. Investing some time in developing this skill can pay large dividends.\n\nBut while seaborn is *most* powerful when provided with long-form data, nearly every seaborn function will accept and plot \"wide-form\" data too. You can trigger this by passing an object to seaborn's `data=` parameter without specifying other plot variables (`x`, `y`, ...). You'll be limited when using wide-form data: each function can make only one kind of wide-form plot. In most cases, seaborn tries to match what matplotlib or pandas would do with a dataset of the same structure. Reshaping your data into long-form will give you substantially more flexibility, but it can be helpful to take a quick look at your data very early in the process, and seaborn tries to make this possible.\n\nUnderstanding how your data should be represented — and how to get it that way if it starts out messy — is very important for making efficient and complete use of seaborn, and it is elaborated on at length in the :doc:`user-guide `.\n\n.. _faq_pandas_requirement:\n\nDoes seaborn only work with pandas?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nGenerally speaking, no: seaborn is `quite flexible `_ about how your dataset needs to be represented.\n\nIn most cases, :ref:`long-form data ` represented by multiple vector-like types can be passed directly to `x`, `y`, or other plotting parameters. Or you can pass a dictionary of vector types to `data` rather than a DataFrame. And when plotting with wide-form data, you can use a 2D numpy array or even nested lists to plot in wide-form mode.\n\nThere are a couple older functions (namely, :func:`catplot` and :func:`lmplot`) that do require you to pass a :class:`pandas.DataFrame`. But at this point, they are the exception, and they will gain more flexibility over the next few release cycles.\n\nLayout problems\n---------------\n\n.. _faq_figure_size:\n\nHow do I change the figure size?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis is going to be more complicated than you might hope, in part because there are multiple ways to change the figure size in matplotlib, and in part because of the :ref:`figure-level/axes-level ` distinction in seaborn.\n\nIn matplotlib, you can usually set the default size for all figures through the `rc parameters `_, specifically `figure.figsize`. And you can set the size of an individual figure when you create it (e.g. `plt.subplots(figsize=(w, h))`). If you're using an axes-level seaborn function, both of these will work as expected.\n\nFigure-level functions both ignore the default figure size and :ref:`parameterize the figure size differently `. When calling a figure-level function, you can pass values to `height=` and `aspect=` to set (roughly) the size of each *subplot*. The advantage here is that the size of the figure automatically adapts when you add faceting variables. But it can be confusing.\n\nFortunately, there's a consistent way to set the exact figure size in a function-independent manner. Instead of setting the figure size when the figure is created, modify it after you plot by calling `obj.figure.set_size_inches(...)`, where `obj` is either a matplotlib axes (usually assigned to `ax`) or a seaborn `FacetGrid` (usually assigned to `g`).\n\nNote that :attr:`FacetGrid.figure` exists only on seaborn >= 0.11.2; before that you'll have to access :attr:`FacetGrid.fig`.\n\nAlso, if you're making pngs (or in a Jupyter notebook), you can — perhaps surprisingly — scale all your plots up or down by :ref:`changing the dpi `.\n\n.. _faq_plot_misplaced:\n\nWhy isn't seaborn drawing the plot where I tell it to?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You've explicitly created a matplotlib figure with one or more subplots and tried to draw a seaborn plot on it, but you end up with an extra figure and a blank subplot. Perhaps your code looks something like*\n\n::\n\n f, ax = plt.subplots()\n sns.catplot(..., ax=ax)\n\nThis is a :ref:`figure-level/axes-level ` gotcha. Figure-level functions always create their own figure, so you can't direct them towards an existing axes the way you can with axes-level functions. Most functions will warn you when this happens, suggest the appropriate axes-level function, and ignore the `ax=` parameter. A few older functions might put the plot where you want it (because they internally pass `ax` to their axes-level function) while still creating an extra figure. This latter behavior should be considered a bug, and it is not to be relied on.\n\nThe way things currently work, you can either set up the matplotlib figure yourself, or you can use a figure-level function, but you can't do both at the same time.\n\n.. _faq_categorical_line:\n\nWhy can't I draw a line over a bar/box/strip/violin plot?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You're trying to create a single plot using multiple seaborn functions, perhaps by drawing a lineplot or regplot over a barplot or violinplot. You expect the line to go through the mean value for each box (etc.), but it looks to be misalgined, or maybe it's all the way off to the side.*\n\nYou are trying to combine a :ref:`\"categorical plot\" ` with another plot type. If your `x` variable has numeric values, it seems like this should work. But recall: seaborn's categorical plots map unique values on the categorical axis to integer indexes. So if your data have unique `x` values of 1, 6, 20, 94, the corresponding plot elements will get drawn at 0, 1, 2, 3 (and the tick labels will be changed to represent the actual value).\n\nThe line or regression plot doesn't know that this has happened, so it will use the actual numeric values, and the plots won't line up at all.\n\nAs of now, there are two ways to work around this. In situations where you want to draw a line, you could use the (somewhat misleadingly named) :func:`pointplot` function, which is also a \"categorical\" function and will use the same rules for drawing the plot. If this doesn't solve the problem (for one, it's not as visually flexible as :func:`lineplot`, you could implement the mapping from actual values to integer indexes yourself and draw the plot that way::\n\n unique_xs = sorted(df[\"x\"].unique())\n sns.violinplot(data=df, x=\"x\", y=\"y\")\n sns.lineplot(data=df, x=df[\"x\"].map(unique_xs.index), y=\"y\")\n\nThis is something that will be easier in a planned future release, as it will become possible to make the categorical functions treat numeric data as numeric. (As of v0.12, it's possible only in :func:`stripplot` and :func:`swarmplot`, using `native_scale=True`).\n\nHow do I move the legend?\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*When applying a semantic mapping to a plot, seaborn will automatically create a legend and add it to the figure. But the automatic choice of legend position is not always ideal.*\n\nWith seaborn v0.11.2 or later, use the :func:`move_legend` function.\n\nOn older versions, a common pattern was to call `ax.legend(loc=...)` after plotting. While this appears to move the legend, it actually *replaces* it with a new one, using any labeled artists that happen to be attached to the axes. This does `not consistently work `_ across plot types. And it does not propagate the legend title or positioning tweaks that are used to format a multi-variable legend.\n\nThe :func:`move_legend` function is actually more powerful than its name suggests, and it can also be used to modify other `legend parameters `_ (font size, handle length, etc.) after plotting.\n\nOther customizations\n--------------------\n\n.. _faq_figure_customization:\n\nHow can I can I change something about the figure?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You want to make a very specific plot, and seaborn's defaults aren't doing it for you.*\n\nThere's basically a four-layer hierarchy to customizing a seaborn figure:\n\n1. Explicit seaborn function parameters\n2. Passed-through matplotlib keyword arguments\n3. Matplotlib axes methods\n4. Matplotlib artist methods\n\nFirst, read through the API docs for the relevant seaborn function. Each has a lot of parameters (probably too many), and you may be able to accomplish your desired customization using seaborn's own API.\n\nBut seaborn does delegate a lot of customization to matplotlib. Most functions have `**kwargs` in their signature, which will catch extra keyword arguments and pass them through to the underlying matplotlib function. For example, :func:`scatterplot` has a number of parameters, but you can also use any valid keyword argument for :meth:`matplotlib.axes.Axes.scatter`, which it calls internally.\n\nPassing through keyword arguments lets you customize the artists that represent data, but often you will want to customize other aspects of the figure, such as labels, ticks, and titles. You can do this by calling methods on the object that seaborn's plotting functions return. Depending on whether you're calling an :ref:`axes-level or figure-level function `, this may be a :class:`matplotlib.axes.Axes` object or a seaborn wrapper (such as :class:`seaborn.FacetGrid`). Both kinds of objects have numerous methods that you can call to customize nearly anything about the figure. The easiest thing is usually to call :meth:`matplotlib.axes.Axes.set` or :meth:`seaborn.FacetGrid.set`, which let you modify multiple attributes at once, e.g.::\n\n ax = sns.scatterplot(...)\n ax.set(\n xlabel=\"The x label\",\n ylabel=\"The y label\",\n title=\"The title\"\n xlim=(xmin, xmax),\n xticks=[...],\n xticklabels=[...],\n )\n\nFinally, the deepest customization may require you to reach \"into\" the matplotlib axes and tweak the artists that are stored on it. These will be in artist lists, such as `ax.lines`, `ax.collections`, `ax.patches`, etc.\n\n*Warning:* Neither matplotlib nor seaborn consider the specific artists produced by their plotting functions to be part of stable API. Because it's not possible to gracefully warn about upcoming changes to the artist types or the order in which they are stored, code that interacts with these attributes could break unexpectedly. With that said, seaborn does try hard to avoid making this kind of change.\n\n.. _faq_matplotlib_requirement:\n\nWait, I need to learn how to use matplotlib too?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIt really depends on how much customization you need. You can certainly perform a lot of exploratory data analysis while primarily or exclusively interacting with the seaborn API. But, if you're polishing a figure for a presentation or publication, you'll likely find yourself needing to understand at least a little bit about how matplotlib works. Matplotlib is extremely flexible, and it lets you control literally everything about a figure if you drill down far enough.\n\nSeaborn was originally designed with the idea that it would handle a specific set of well-defined operations through a very high-level API, while letting users \"drop down\" to matplotlib when they desired additional customization. This can be a pretty powerful combination, and it works reasonably well if you already know how to use matplotlib. But as seaborn as gained more features, it has become more feasible to learn seaborn *first*. In that situation, the need to switch APIs tends to be a bit more confusing / frustrating. This has motivated the development of seaborn's new :doc:`objects interface `, which aims to provide a more cohesive API for both high-level and low-level figure specification. Hopefully, it will alleviate the \"two-library problem\" as it matures.\n\nWith that said, the level of deep control that matplotlib affords really can't be beat, so if you care about doing very specific things, it really is worth learning.\n\n.. _faq_object_oriented:\n\nHow do I use seaborn with matplotlib's object-oriented interface?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You prefer to use matplotlib's explicit or* `\"object-oriented\" `_ *interface, because it makes your code easier to reason about and maintain. But the object-orient interface consists of methods on matplotlib objects, whereas seaborn offers you independent functions.*\n\nThis is another case where it will be helpful to keep the :ref:`figure-level/axes-level ` distinction in mind.\n\nAxes-level functions can be used like any matplotlib axes method, but instead of calling `ax.func(...)`, you call `func(..., ax=ax)`. They also return the axes object (which they may have created, if no figure was currently active in matplotlib's global state). You can use the methods on that object to further customize the plot even if you didn't start with :func:`matplotlib.pyplot.figure` or :func:`matplotlib.pyplot.subplots`::\n\n ax = sns.histplot(...)\n ax.set(...)\n\nFigure-level functions :ref:`can't be directed towards an existing figure `, but they do store the matplotlib objects on the :class:`FacetGrid` object that they return (which seaborn docs always assign to a variable named `g`).\n\nIf your figure-level function created only one subplot, you can access it directly::\n\n g = sns.displot(...)\n g.ax.set(...)\n\nFor multiple subplots, you can either use :attr:`FacetGrid.axes` (which is always a 2D array of axes) or :attr:`FacetGrid.axes_dict` (which maps the row/col keys to the corresponding matplotlib object)::\n\n g = sns.displot(..., col=...)\n for col, ax in g.axes_dict.items():\n ax.set(...)\n\nBut if you're batch-setting attributes on all subplots, use the :meth:`FacetGrid.set` method rather than iterating over the individual axes::\n\n g = sns.displot(...)\n g.set(...)\n\nTo access the underlying matplotlib *figure*, use :attr:`FacetGrid.figure` on seaborn >= 0.11.2 (or :attr:`FacetGrid.fig` on any other version).\n\n.. _faq_bar_annotations:\n\nCan I annotate bar plots with the bar values?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNothing like this is built into seaborn, but matplotlib v3.4.0 added a convenience function (:meth:`matplotlib.axes.Axes.bar_label`) that makes it relatively easy. Here are a couple of recipes; note that you'll need to use a different approach depending on whether your bars come from a :ref:`figure-level or axes-level function `::\n\n # Axes-level\n ax = sns.histplot(df, x=\"x_var\")\n for bars in ax.containers:\n ax.bar_label(bars)\n\n # Figure-level, one subplot\n g = sns.displot(df, x=\"x_var\")\n for bars in g.ax.containers:\n g.ax.bar_label(bars)\n\n # Figure-level, multiple subplots\n g = sns.displot(df, x=\"x_var\", col=\"col_var)\n for ax in g.axes.flat:\n for bars in ax.containers:\n ax.bar_label(bars)\n\n.. _faq_dar_mode:\n\nCan I use seaborn in dark mode?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere's no direct support for this in seaborn, but matplotlib has a `\"dark_background\" `_ style-sheet that you could use, e.g.::\n\n sns.set_theme(style=\"ticks\", rc=plt.style.library[\"dark_background\"])\n\nNote that \"dark_background\" changes the default color palette to \"Set2\", and that will override any palette you define in :func:`set_theme`. If you'd rather use a different color palette, you'll have to call :func:`sns.set_palette` separately. The default :doc:`seaborn palette ` (\"deep\") has poor contrast against a dark background, so you'd be better off using \"muted\", \"bright\", or \"pastel\".\n\nStatistical inquiries\n---------------------\n\n.. _faq_stat_results:\n\nCan I access the results of seaborn's statistical transformations?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBecause seaborn performs some statistical operations as it builds plots (aggregating, bootstrapping, fitting regression models), some users would like access to the statistics that it computes. This is not possible: it's explicitly considered out of scope for seaborn (a visualization library) to offer an API for interrogating statistical models.\n\nIf you simply want to be diligent and verify that seaborn is doing things correctly (or that it matches your own code), it's open-source, so feel free to read the code. Or, because it's Python, you can call into the private methods that calculate the stats (just don't do this in production code). But don't expect seaborn to offer features that are more at home in `scipy `_ or `statsmodels `_.\n\n.. _faq_standard_error:\n\nCan I show standard error instead of a confidence interval?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs of v0.12, this is possible in most places, using the new `errorbar` API (see the :doc:`tutorial ` for more details).\n\n.. _faq_kde_value:\n\nWhy does the y axis for a KDE plot go above 1?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n*You've estimated a probability distribution for your data using* :func:`kdeplot`, *but the y axis goes above 1. Aren't probabilities bounded by 1? Is this a bug?*\n\nThis is not a bug, but it is a common confusion (about kernel density plots and probability distributions more broadly). A continuous probability distribution is defined by a `probability density function `_, which :func:`kdeplot` estimates. The probability density function does **not** output *a probability*: a continuous random variable can take an infinite number of values, so the probability of observing any *specific* value is infinitely small. You can only talk meaningfully about the probability of observing a value that falls within some *range*. The probability of observing a value that falls within the complete range of possible values is 1. Likewise, the probability density function is normalized so that the area under it (that is, the integral of the function across its domain) equals 1. If the range of likely values is small, the curve will have to go above 1 to make this possible.\n\nCommon curiosities\n------------------\n\n.. _faq_import_convention:\n\nWhy is seaborn imported as `sns`?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis is an obscure reference to the `namesake `_ of the library, but you can also think of it as \"seaborn name space\".\n\n.. _faq_seaborn_sucks:\n\nWhy is ggplot so much better than seaborn?\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nGood question. Probably because you get to use the word \"geom\" a lot, and it's fun to say. \"Geom\". \"Geeeeeooom\".\n"},{"fileName":"test_rules.py","filePath":"tests/_core","id":4240,"nodeType":"File","text":"\nimport numpy as np\nimport pandas as pd\n\nimport pytest\n\nfrom seaborn._core.rules import (\n VarType,\n variable_type,\n categorical_order,\n)\n\n\ndef test_vartype_object():\n\n v = VarType(\"numeric\")\n assert v == \"numeric\"\n assert v != \"categorical\"\n with pytest.raises(AssertionError):\n v == \"number\"\n with pytest.raises(AssertionError):\n VarType(\"date\")\n\n\ndef test_variable_type():\n\n s = pd.Series([1., 2., 3.])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s.astype(int)) == \"numeric\"\n assert variable_type(s.astype(object)) == \"numeric\"\n assert variable_type(s.to_numpy()) == \"numeric\"\n assert variable_type(s.to_list()) == \"numeric\"\n\n s = pd.Series([1, 2, 3, np.nan], dtype=object)\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([np.nan, np.nan])\n # s = pd.Series([pd.NA, pd.NA])\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([\"1\", \"2\", \"3\"])\n assert variable_type(s) == \"categorical\"\n assert variable_type(s.to_numpy()) == \"categorical\"\n assert variable_type(s.to_list()) == \"categorical\"\n\n s = pd.Series([True, False, False])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s, boolean_type=\"categorical\") == \"categorical\"\n s_cat = s.astype(\"category\")\n assert variable_type(s_cat, boolean_type=\"categorical\") == \"categorical\"\n assert variable_type(s_cat, boolean_type=\"numeric\") == \"categorical\"\n\n s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])\n assert variable_type(s) == \"datetime\"\n assert variable_type(s.astype(object)) == \"datetime\"\n assert variable_type(s.to_numpy()) == \"datetime\"\n assert variable_type(s.to_list()) == \"datetime\"\n\n\ndef test_categorical_order():\n\n x = pd.Series([\"a\", \"c\", \"c\", \"b\", \"a\", \"d\"])\n y = pd.Series([3, 2, 5, 1, 4])\n order = [\"a\", \"b\", \"c\", \"d\"]\n\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(x, order)\n assert out == order\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n out = categorical_order(y)\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(pd.Series(y))\n assert out == [1, 2, 3, 4, 5]\n\n y_cat = pd.Series(pd.Categorical(y, y))\n out = categorical_order(y_cat)\n assert out == list(y)\n\n x = pd.Series(x).astype(\"category\")\n out = categorical_order(x)\n assert out == list(x.cat.categories)\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n x = pd.Series([\"a\", np.nan, \"c\", \"c\", \"b\", \"a\", \"d\"])\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n"},{"col":0,"comment":"null","endLoc":22,"header":"def test_vartype_object()","id":4241,"name":"test_vartype_object","nodeType":"Function","startLoc":14,"text":"def test_vartype_object():\n\n v = VarType(\"numeric\")\n assert v == \"numeric\"\n assert v != \"categorical\"\n with pytest.raises(AssertionError):\n v == \"number\"\n with pytest.raises(AssertionError):\n VarType(\"date\")"},{"col":4,"comment":"null","endLoc":70,"header":"def test_mapped_properties(self)","id":4242,"name":"test_mapped_properties","nodeType":"Function","startLoc":54,"text":"def test_mapped_properties(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n color = list(\"aab\")\n fontsize = [1, 2, 4]\n\n p = Plot(x, y, color=color, fontsize=fontsize, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n texts = self.get_texts(ax)\n assert texts[0].get_color() == texts[1].get_color()\n assert texts[0].get_color() != texts[2].get_color()\n assert (\n texts[0].get_fontsize()\n < texts[1].get_fontsize()\n < texts[2].get_fontsize()\n )"},{"col":0,"comment":"null","endLoc":57,"header":"def test_variable_type()","id":4243,"name":"test_variable_type","nodeType":"Function","startLoc":25,"text":"def test_variable_type():\n\n s = pd.Series([1., 2., 3.])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s.astype(int)) == \"numeric\"\n assert variable_type(s.astype(object)) == \"numeric\"\n assert variable_type(s.to_numpy()) == \"numeric\"\n assert variable_type(s.to_list()) == \"numeric\"\n\n s = pd.Series([1, 2, 3, np.nan], dtype=object)\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([np.nan, np.nan])\n # s = pd.Series([pd.NA, pd.NA])\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([\"1\", \"2\", \"3\"])\n assert variable_type(s) == \"categorical\"\n assert variable_type(s.to_numpy()) == \"categorical\"\n assert variable_type(s.to_list()) == \"categorical\"\n\n s = pd.Series([True, False, False])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s, boolean_type=\"categorical\") == \"categorical\"\n s_cat = s.astype(\"category\")\n assert variable_type(s_cat, boolean_type=\"categorical\") == \"categorical\"\n assert variable_type(s_cat, boolean_type=\"numeric\") == \"categorical\"\n\n s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])\n assert variable_type(s) == \"datetime\"\n assert variable_type(s.astype(object)) == \"datetime\"\n assert variable_type(s.to_numpy()) == \"datetime\"\n assert variable_type(s.to_list()) == \"datetime\""},{"className":"MockMark","col":0,"comment":"null","endLoc":75,"id":4244,"nodeType":"Class","startLoc":45,"text":"class MockMark(Mark):\n\n _grouping_props = [\"color\"]\n\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.passed_keys = []\n self.passed_data = []\n self.passed_axes = []\n self.passed_scales = None\n self.passed_orient = None\n self.n_splits = 0\n\n def _plot(self, split_gen, scales, orient):\n\n for keys, data, ax in split_gen():\n self.n_splits += 1\n self.passed_keys.append(keys)\n self.passed_data.append(data)\n self.passed_axes.append(ax)\n\n self.passed_scales = scales\n self.passed_orient = orient\n\n def _legend_artist(self, variables, value, scales):\n\n a = mpl.lines.Line2D([], [])\n a.variables = variables\n a.value = value\n return a"},{"col":4,"comment":"null","endLoc":57,"header":"def __init__(self, *args, **kwargs)","id":4245,"name":"__init__","nodeType":"Function","startLoc":49,"text":"def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.passed_keys = []\n self.passed_data = []\n self.passed_axes = []\n self.passed_scales = None\n self.passed_orient = None\n self.n_splits = 0"},{"col":0,"comment":"","endLoc":5,"header":"cache_datasets.py#","id":4246,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nCache test datasets before running tests / building docs.\n\nAvoids race conditions that would arise from parallelization.\n\"\"\"\n\npath = pathlib.Path(\".\")\n\npy_files = path.rglob(\"*.py\")\n\nipynb_files = path.rglob(\"*.ipynb\")\n\ndatasets = []\n\nfor fname in py_files:\n with open(fname) as fid:\n datasets += re.findall(r\"load_dataset\\(['\\\"](\\w+)['\\\"]\", fid.read())\n\nfor p in ipynb_files:\n with p.open() as fid:\n datasets += re.findall(r\"load_dataset\\(\\\\['\\\"](\\w+)\\\\['\\\"]\", fid.read())\n\nfor name in sorted(set(datasets)):\n print(f\"Caching {name}\")\n load_dataset(name)"},{"col":4,"comment":"null","endLoc":68,"header":"def _plot(self, split_gen, scales, orient)","id":4247,"name":"_plot","nodeType":"Function","startLoc":59,"text":"def _plot(self, split_gen, scales, orient):\n\n for keys, data, ax in split_gen():\n self.n_splits += 1\n self.passed_keys.append(keys)\n self.passed_data.append(data)\n self.passed_axes.append(ax)\n\n self.passed_scales = scales\n self.passed_orient = orient"},{"col":0,"comment":"null","endLoc":94,"header":"def test_categorical_order()","id":4248,"name":"test_categorical_order","nodeType":"Function","startLoc":60,"text":"def test_categorical_order():\n\n x = pd.Series([\"a\", \"c\", \"c\", \"b\", \"a\", \"d\"])\n y = pd.Series([3, 2, 5, 1, 4])\n order = [\"a\", \"b\", \"c\", \"d\"]\n\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(x, order)\n assert out == order\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n out = categorical_order(y)\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(pd.Series(y))\n assert out == [1, 2, 3, 4, 5]\n\n y_cat = pd.Series(pd.Categorical(y, y))\n out = categorical_order(y_cat)\n assert out == list(y)\n\n x = pd.Series(x).astype(\"category\")\n out = categorical_order(x)\n assert out == list(x.cat.categories)\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n x = pd.Series([\"a\", np.nan, \"c\", \"c\", \"b\", \"a\", \"d\"])\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]"},{"col":4,"comment":"null","endLoc":81,"header":"def test_mapped_alignment(self)","id":4249,"name":"test_mapped_alignment","nodeType":"Function","startLoc":72,"text":"def test_mapped_alignment(self):\n\n x = [1, 2]\n p = Plot(x=x, y=x, halign=x, valign=x, text=x).add(Text()).plot()\n ax = p._figure.axes[0]\n t1, t2 = self.get_texts(ax)\n assert t1.get_horizontalalignment() == \"left\"\n assert t2.get_horizontalalignment() == \"right\"\n assert t1.get_verticalalignment() == \"top\"\n assert t2.get_verticalalignment() == \"bottom\""},{"col":4,"comment":"null","endLoc":91,"header":"def test_identity_fontsize(self)","id":4250,"name":"test_identity_fontsize","nodeType":"Function","startLoc":83,"text":"def test_identity_fontsize(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n fs = [5, 8, 12]\n p = Plot(x, y, text=s, fontsize=fs).add(Text()).scale(fontsize=None).plot()\n ax = p._figure.axes[0]\n for i, text in enumerate(self.get_texts(ax)):\n assert text.get_fontsize() == fs[i]"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":4251,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":4252,"name":"pd","nodeType":"Attribute","startLoc":3,"text":"pd"},{"fileName":"pairgrid_dotplot.py","filePath":"examples","id":4253,"nodeType":"File","text":"\"\"\"\nDot plot with several variables\n===============================\n\n_thumb: .3, .3\n\"\"\"\nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\n\n# Load the dataset\ncrashes = sns.load_dataset(\"car_crashes\")\n\n# Make the PairGrid\ng = sns.PairGrid(crashes.sort_values(\"total\", ascending=False),\n x_vars=crashes.columns[:-3], y_vars=[\"abbrev\"],\n height=10, aspect=.25)\n\n# Draw a dot plot using the stripplot function\ng.map(sns.stripplot, size=10, orient=\"h\", jitter=False,\n palette=\"flare_r\", linewidth=1, edgecolor=\"w\")\n\n# Use the same x axis limits on all columns and add better labels\ng.set(xlim=(0, 25), xlabel=\"Crashes\", ylabel=\"\")\n\n# Use semantically meaningful titles for the columns\ntitles = [\"Total crashes\", \"Speeding crashes\", \"Alcohol crashes\",\n \"Not distracted crashes\", \"No previous crashes\"]\n\nfor ax, title in zip(g.axes.flat, titles):\n\n # Set a different title for each axes\n ax.set(title=title)\n\n # Make the grid horizontal instead of vertical\n ax.xaxis.grid(False)\n ax.yaxis.grid(True)\n\nsns.despine(left=True, bottom=True)\n"},{"col":4,"comment":"null","endLoc":101,"header":"def test_offset_centered(self)","id":4254,"name":"test_offset_centered","nodeType":"Function","startLoc":93,"text":"def test_offset_centered(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n p = Plot(x, y, text=s).add(Text()).plot()\n ax = p._figure.axes[0]\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n assert_array_almost_equal(text.get_transform().get_matrix(), ax_trans)"},{"attributeType":"null","col":18,"comment":"null","endLoc":7,"id":4255,"name":"sns","nodeType":"Attribute","startLoc":7,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":4256,"name":"crashes","nodeType":"Attribute","startLoc":11,"text":"crashes"},{"col":4,"comment":"null","endLoc":75,"header":"def _legend_artist(self, variables, value, scales)","id":4257,"name":"_legend_artist","nodeType":"Function","startLoc":70,"text":"def _legend_artist(self, variables, value, scales):\n\n a = mpl.lines.Line2D([], [])\n a.variables = variables\n a.value = value\n return a"},{"attributeType":"list","col":4,"comment":"null","endLoc":47,"id":4258,"name":"_grouping_props","nodeType":"Attribute","startLoc":47,"text":"_grouping_props"},{"attributeType":"int","col":8,"comment":"null","endLoc":57,"id":4259,"name":"n_splits","nodeType":"Attribute","startLoc":57,"text":"self.n_splits"},{"col":4,"comment":"null","endLoc":115,"header":"def test_offset_valign(self)","id":4260,"name":"test_offset_valign","nodeType":"Function","startLoc":103,"text":"def test_offset_valign(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n m = Text(valign=\"bottom\", fontsize=5, offset=.1)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n expected_shift_matrix = np.zeros((3, 3))\n expected_shift_matrix[1, -1] = m.offset * ax.figure.dpi / 72\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n shift_matrix = text.get_transform().get_matrix() - ax_trans\n assert_array_almost_equal(shift_matrix, expected_shift_matrix)"},{"attributeType":"list","col":8,"comment":"null","endLoc":53,"id":4261,"name":"passed_data","nodeType":"Attribute","startLoc":53,"text":"self.passed_data"},{"attributeType":"None","col":8,"comment":"null","endLoc":56,"id":4262,"name":"passed_orient","nodeType":"Attribute","startLoc":56,"text":"self.passed_orient"},{"attributeType":"None","col":8,"comment":"null","endLoc":55,"id":4263,"name":"passed_scales","nodeType":"Attribute","startLoc":55,"text":"self.passed_scales"},{"attributeType":"list","col":8,"comment":"null","endLoc":54,"id":4264,"name":"passed_axes","nodeType":"Attribute","startLoc":54,"text":"self.passed_axes"},{"attributeType":"list","col":8,"comment":"null","endLoc":52,"id":4265,"name":"passed_keys","nodeType":"Attribute","startLoc":52,"text":"self.passed_keys"},{"className":"TestInit","col":0,"comment":"null","endLoc":185,"id":4266,"nodeType":"Class","startLoc":78,"text":"class TestInit:\n\n def test_empty(self):\n\n p = Plot()\n assert p._data.source_data is None\n assert p._data.source_vars == {}\n\n def test_data_only(self, long_df):\n\n p = Plot(long_df)\n assert p._data.source_data is long_df\n assert p._data.source_vars == {}\n\n def test_df_and_named_variables(self, long_df):\n\n variables = {\"x\": \"a\", \"y\": \"z\"}\n p = Plot(long_df, **variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], long_df[col])\n assert p._data.source_data is long_df\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_df_and_mixed_variables(self, long_df):\n\n variables = {\"x\": \"a\", \"y\": long_df[\"z\"]}\n p = Plot(long_df, **variables)\n for var, col in variables.items():\n if isinstance(col, str):\n assert_vector_equal(p._data.frame[var], long_df[col])\n else:\n assert_vector_equal(p._data.frame[var], col)\n assert p._data.source_data is long_df\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_vector_variables_only(self, long_df):\n\n variables = {\"x\": long_df[\"a\"], \"y\": long_df[\"z\"]}\n p = Plot(**variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], col)\n assert p._data.source_data is None\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_vector_variables_no_index(self, long_df):\n\n variables = {\"x\": long_df[\"a\"].to_numpy(), \"y\": long_df[\"z\"].to_list()}\n p = Plot(**variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], pd.Series(col))\n assert p._data.names[var] is None\n assert p._data.source_data is None\n assert p._data.source_vars.keys() == variables.keys()\n\n def test_data_only_named(self, long_df):\n\n p = Plot(data=long_df)\n assert p._data.source_data is long_df\n assert p._data.source_vars == {}\n\n def test_positional_and_named_data(self, long_df):\n\n err = \"`data` given by both name and position\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, data=long_df)\n\n @pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_positional_and_named_xy(self, long_df, var):\n\n err = f\"`{var}` given by both name and position\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, \"a\", \"b\", **{var: \"c\"})\n\n def test_positional_data_x_y(self, long_df):\n\n p = Plot(long_df, \"a\", \"b\")\n assert p._data.source_data is long_df\n assert list(p._data.source_vars) == [\"x\", \"y\"]\n\n def test_positional_x_y(self, long_df):\n\n p = Plot(long_df[\"a\"], long_df[\"b\"])\n assert p._data.source_data is None\n assert list(p._data.source_vars) == [\"x\", \"y\"]\n\n def test_positional_data_x(self, long_df):\n\n p = Plot(long_df, \"a\")\n assert p._data.source_data is long_df\n assert list(p._data.source_vars) == [\"x\"]\n\n def test_positional_x(self, long_df):\n\n p = Plot(long_df[\"a\"])\n assert p._data.source_data is None\n assert list(p._data.source_vars) == [\"x\"]\n\n def test_positional_too_many(self, long_df):\n\n err = r\"Plot\\(\\) accepts no more than 3 positional arguments \\(data, x, y\\)\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, \"x\", \"y\", \"z\")\n\n def test_unknown_keywords(self, long_df):\n\n err = r\"Plot\\(\\) got unexpected keyword argument\\(s\\): bad\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, bad=\"x\")"},{"col":4,"comment":"null","endLoc":84,"header":"def test_empty(self)","id":4267,"name":"test_empty","nodeType":"Function","startLoc":80,"text":"def test_empty(self):\n\n p = Plot()\n assert p._data.source_data is None\n assert p._data.source_vars == {}"},{"col":4,"comment":"null","endLoc":129,"header":"def test_offset_halign(self)","id":4268,"name":"test_offset_halign","nodeType":"Function","startLoc":117,"text":"def test_offset_halign(self):\n\n x = y = [1, 2, 3]\n s = list(\"abc\")\n m = Text(halign=\"right\", fontsize=10, offset=.5)\n p = Plot(x, y, text=s).add(m).plot()\n ax = p._figure.axes[0]\n expected_shift_matrix = np.zeros((3, 3))\n expected_shift_matrix[0, -1] = -m.offset * ax.figure.dpi / 72\n ax_trans = ax.transData.get_matrix()\n for text in self.get_texts(ax):\n shift_matrix = text.get_transform().get_matrix() - ax_trans\n assert_array_almost_equal(shift_matrix, expected_shift_matrix)"},{"col":4,"comment":"null","endLoc":90,"header":"def test_data_only(self, long_df)","id":4269,"name":"test_data_only","nodeType":"Function","startLoc":86,"text":"def test_data_only(self, long_df):\n\n p = Plot(long_df)\n assert p._data.source_data is long_df\n assert p._data.source_vars == {}"},{"col":4,"comment":"null","endLoc":99,"header":"def test_df_and_named_variables(self, long_df)","id":4270,"name":"test_df_and_named_variables","nodeType":"Function","startLoc":92,"text":"def test_df_and_named_variables(self, long_df):\n\n variables = {\"x\": \"a\", \"y\": \"z\"}\n p = Plot(long_df, **variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], long_df[col])\n assert p._data.source_data is long_df\n assert p._data.source_vars.keys() == variables.keys()"},{"attributeType":"PairGrid","col":0,"comment":"null","endLoc":14,"id":4271,"name":"g","nodeType":"Attribute","startLoc":14,"text":"g"},{"attributeType":"null","col":16,"comment":"null","endLoc":2,"id":4272,"name":"np","nodeType":"Attribute","startLoc":2,"text":"np"},{"attributeType":"null","col":36,"comment":"null","endLoc":4,"id":4273,"name":"MPLText","nodeType":"Attribute","startLoc":4,"text":"MPLText"},{"id":4274,"name":"objects.Lines.ipynb","nodeType":"TextFile","path":"doc/_docstrings","text":"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"2923956c-f141-4ecb-ab08-e819099f0fa9\",\n \"metadata\": {\n \"tags\": [\n \"hide\"\n ]\n },\n \"outputs\": [],\n \"source\": [\n \"import seaborn.objects as so\\n\",\n \"from seaborn import load_dataset\\n\",\n \"seaice = load_dataset(\\\"seaice\\\")\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"09694cb8-4867-49fc-80a6-a4551e50b77e\",\n \"metadata\": {},\n \"source\": [\n \"Like :class:`Line`, the mark draws a connecting line between sorted observations:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"acd5788f-e62b-497c-a109-f0bc02b8cae9\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"so.Plot(seaice, \\\"Date\\\", \\\"Extent\\\").add(so.Lines())\"\n ]\n },\n {\n \"cell_type\": \"raw\",\n \"id\": \"8f982f2d-1119-4842-9860-80b415fd24fe\",\n \"metadata\": {},\n \"source\": [\n \"Compared to :class:`Line`, this mark offers fewer settable properties, but it can have better performance when drawing a large number of lines:\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"d4411136-1787-47ca-91f4-4ecba541e575\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"(\\n\",\n \" so.Plot(\\n\",\n \" x=seaice[\\\"Date\\\"].dt.day_of_year,\\n\",\n \" y=seaice[\\\"Extent\\\"],\\n\",\n \" color=seaice[\\\"Date\\\"].dt.year\\n\",\n \" )\\n\",\n \" .facet(seaice[\\\"Date\\\"].dt.year.round(-1))\\n\",\n \" .add(so.Lines(linewidth=.5, color=\\\"#bbca\\\"), col=None)\\n\",\n \" .add(so.Lines(linewidth=1))\\n\",\n \" .scale(color=\\\"ch:rot=-.2,light=.7\\\")\\n\",\n \" .layout(size=(8, 4))\\n\",\n \" .label(title=\\\"{}s\\\".format)\\n\",\n \")\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"aaab3914-77d7-4d09-bdbe-f057a2fe28cf\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"py310\",\n \"language\": \"python\",\n \"name\": \"py310\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.10.0\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"},{"attributeType":"list","col":0,"comment":"null","endLoc":26,"id":4275,"name":"titles","nodeType":"Attribute","startLoc":26,"text":"titles"},{"attributeType":"null","col":4,"comment":"null","endLoc":29,"id":4276,"name":"ax","nodeType":"Attribute","startLoc":29,"text":"ax"},{"fileName":"gallery_generator.py","filePath":"doc/sphinxext","id":4277,"nodeType":"File","text":"\"\"\"\nSphinx plugin to run example scripts and create a gallery page.\n\nLightly modified from the mpld3 project.\n\n\"\"\"\nimport os\nimport os.path as op\nimport re\nimport glob\nimport token\nimport tokenize\nimport shutil\nimport warnings\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt # noqa: E402\n\n\n# Python 3 has no execfile\ndef execfile(filename, globals=None, locals=None):\n with open(filename, \"rb\") as fp:\n exec(compile(fp.read(), filename, 'exec'), globals, locals)\n\n\nRST_TEMPLATE = \"\"\"\n\n.. currentmodule:: seaborn\n\n.. _{sphinx_tag}:\n\n{docstring}\n\n.. image:: {img_file}\n\n**seaborn components used:** {components}\n\n.. literalinclude:: {fname}\n :lines: {end_line}-\n\n\"\"\"\n\n\nINDEX_TEMPLATE = \"\"\"\n:html_theme.sidebar_secondary.remove:\n\n.. raw:: html\n\n \n\n.. _{sphinx_tag}:\n\nExample gallery\n===============\n\n{toctree}\n\n{contents}\n\n.. raw:: html\n\n
\n\"\"\"\n\n\ndef create_thumbnail(infile, thumbfile,\n width=275, height=275,\n cx=0.5, cy=0.5, border=4):\n baseout, extout = op.splitext(thumbfile)\n\n im = matplotlib.image.imread(infile)\n rows, cols = im.shape[:2]\n x0 = int(cx * cols - .5 * width)\n y0 = int(cy * rows - .5 * height)\n xslice = slice(x0, x0 + width)\n yslice = slice(y0, y0 + height)\n thumb = im[yslice, xslice]\n thumb[:border, :, :3] = thumb[-border:, :, :3] = 0\n thumb[:, :border, :3] = thumb[:, -border:, :3] = 0\n\n dpi = 100\n fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi)\n\n ax = fig.add_axes([0, 0, 1, 1], aspect='auto',\n frameon=False, xticks=[], yticks=[])\n if all(thumb.shape):\n ax.imshow(thumb, aspect='auto', resample=True,\n interpolation='bilinear')\n else:\n warnings.warn(\n f\"Bad thumbnail crop. {thumbfile} will be empty.\"\n )\n fig.savefig(thumbfile, dpi=dpi)\n return fig\n\n\ndef indent(s, N=4):\n \"\"\"indent a string\"\"\"\n return s.replace('\\n', '\\n' + N * ' ')\n\n\nclass ExampleGenerator:\n \"\"\"Tools for generating an example page from a file\"\"\"\n def __init__(self, filename, target_dir):\n self.filename = filename\n self.target_dir = target_dir\n self.thumbloc = .5, .5\n self.extract_docstring()\n with open(filename) as fid:\n self.filetext = fid.read()\n\n outfilename = op.join(target_dir, self.rstfilename)\n\n # Only actually run it if the output RST file doesn't\n # exist or it was modified less recently than the example\n file_mtime = op.getmtime(filename)\n if not op.exists(outfilename) or op.getmtime(outfilename) < file_mtime:\n self.exec_file()\n else:\n print(f\"skipping {self.filename}\")\n\n @property\n def dirname(self):\n return op.split(self.filename)[0]\n\n @property\n def fname(self):\n return op.split(self.filename)[1]\n\n @property\n def modulename(self):\n return op.splitext(self.fname)[0]\n\n @property\n def pyfilename(self):\n return self.modulename + '.py'\n\n @property\n def rstfilename(self):\n return self.modulename + \".rst\"\n\n @property\n def htmlfilename(self):\n return self.modulename + '.html'\n\n @property\n def pngfilename(self):\n pngfile = self.modulename + '.png'\n return \"_images/\" + pngfile\n\n @property\n def thumbfilename(self):\n pngfile = self.modulename + '_thumb.png'\n return pngfile\n\n @property\n def sphinxtag(self):\n return self.modulename\n\n @property\n def pagetitle(self):\n return self.docstring.strip().split('\\n')[0].strip()\n\n @property\n def plotfunc(self):\n match = re.search(r\"sns\\.(.+plot)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+map)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+Grid)\\(\", self.filetext)\n if match:\n return match.group(1)\n return \"\"\n\n @property\n def components(self):\n\n objects = re.findall(r\"sns\\.(\\w+)\\(\", self.filetext)\n\n refs = []\n for obj in objects:\n if obj[0].isupper():\n refs.append(f\":class:`{obj}`\")\n else:\n refs.append(f\":func:`{obj}`\")\n return \", \".join(refs)\n\n def extract_docstring(self):\n \"\"\" Extract a module-level docstring\n \"\"\"\n lines = open(self.filename).readlines()\n start_row = 0\n if lines[0].startswith('#!'):\n lines.pop(0)\n start_row = 1\n\n docstring = ''\n first_par = ''\n line_iter = lines.__iter__()\n tokens = tokenize.generate_tokens(lambda: next(line_iter))\n for tok_type, tok_content, _, (erow, _), _ in tokens:\n tok_type = token.tok_name[tok_type]\n if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):\n continue\n elif tok_type == 'STRING':\n docstring = eval(tok_content)\n # If the docstring is formatted with several paragraphs,\n # extract the first one:\n paragraphs = '\\n'.join(line.rstrip()\n for line in docstring.split('\\n')\n ).split('\\n\\n')\n if len(paragraphs) > 0:\n first_par = paragraphs[0]\n break\n\n thumbloc = None\n for i, line in enumerate(docstring.split(\"\\n\")):\n m = re.match(r\"^_thumb: (\\.\\d+),\\s*(\\.\\d+)\", line)\n if m:\n thumbloc = float(m.group(1)), float(m.group(2))\n break\n if thumbloc is not None:\n self.thumbloc = thumbloc\n docstring = \"\\n\".join([l for l in docstring.split(\"\\n\")\n if not l.startswith(\"_thumb\")])\n\n self.docstring = docstring\n self.short_desc = first_par\n self.end_line = erow + 1 + start_row\n\n def exec_file(self):\n print(f\"running {self.filename}\")\n\n plt.close('all')\n my_globals = {'pl': plt,\n 'plt': plt}\n execfile(self.filename, my_globals)\n\n fig = plt.gcf()\n fig.canvas.draw()\n pngfile = op.join(self.target_dir, self.pngfilename)\n thumbfile = op.join(\"example_thumbs\", self.thumbfilename)\n self.html = f\"\"\n fig.savefig(pngfile, dpi=75, bbox_inches=\"tight\")\n\n cx, cy = self.thumbloc\n create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy)\n\n def toctree_entry(self):\n return f\" ./{op.splitext(self.htmlfilename)[0]}\\n\\n\"\n\n def contents_entry(self):\n return (\".. raw:: html\\n\\n\"\n \" \\n\\n\"\n \"\\n\\n\"\n \"\".format(self.htmlfilename,\n self.thumbfilename,\n self.plotfunc))\n\n\ndef main(app):\n static_dir = op.join(app.builder.srcdir, '_static')\n target_dir = op.join(app.builder.srcdir, 'examples')\n image_dir = op.join(app.builder.srcdir, 'examples/_images')\n thumb_dir = op.join(app.builder.srcdir, \"example_thumbs\")\n source_dir = op.abspath(op.join(app.builder.srcdir, '..', 'examples'))\n if not op.exists(static_dir):\n os.makedirs(static_dir)\n\n if not op.exists(target_dir):\n os.makedirs(target_dir)\n\n if not op.exists(image_dir):\n os.makedirs(image_dir)\n\n if not op.exists(thumb_dir):\n os.makedirs(thumb_dir)\n\n if not op.exists(source_dir):\n os.makedirs(source_dir)\n\n banner_data = []\n\n toctree = (\"\\n\\n\"\n \".. toctree::\\n\"\n \" :hidden:\\n\\n\")\n contents = \"\\n\\n\"\n\n # Write individual example files\n for filename in sorted(glob.glob(op.join(source_dir, \"*.py\"))):\n\n ex = ExampleGenerator(filename, target_dir)\n\n banner_data.append({\"title\": ex.pagetitle,\n \"url\": op.join('examples', ex.htmlfilename),\n \"thumb\": op.join(ex.thumbfilename)})\n shutil.copyfile(filename, op.join(target_dir, ex.pyfilename))\n output = RST_TEMPLATE.format(sphinx_tag=ex.sphinxtag,\n docstring=ex.docstring,\n end_line=ex.end_line,\n components=ex.components,\n fname=ex.pyfilename,\n img_file=ex.pngfilename)\n with open(op.join(target_dir, ex.rstfilename), 'w') as f:\n f.write(output)\n\n toctree += ex.toctree_entry()\n contents += ex.contents_entry()\n\n if len(banner_data) < 10:\n banner_data = (4 * banner_data)[:10]\n\n # write index file\n index_file = op.join(target_dir, 'index.rst')\n with open(index_file, 'w') as index:\n index.write(INDEX_TEMPLATE.format(sphinx_tag=\"example_gallery\",\n toctree=toctree,\n contents=contents))\n\n\ndef setup(app):\n app.connect('builder-inited', main)\n"},{"className":"ExampleGenerator","col":0,"comment":"Tools for generating an example page from a file","endLoc":329,"id":4278,"nodeType":"Class","startLoc":164,"text":"class ExampleGenerator:\n \"\"\"Tools for generating an example page from a file\"\"\"\n def __init__(self, filename, target_dir):\n self.filename = filename\n self.target_dir = target_dir\n self.thumbloc = .5, .5\n self.extract_docstring()\n with open(filename) as fid:\n self.filetext = fid.read()\n\n outfilename = op.join(target_dir, self.rstfilename)\n\n # Only actually run it if the output RST file doesn't\n # exist or it was modified less recently than the example\n file_mtime = op.getmtime(filename)\n if not op.exists(outfilename) or op.getmtime(outfilename) < file_mtime:\n self.exec_file()\n else:\n print(f\"skipping {self.filename}\")\n\n @property\n def dirname(self):\n return op.split(self.filename)[0]\n\n @property\n def fname(self):\n return op.split(self.filename)[1]\n\n @property\n def modulename(self):\n return op.splitext(self.fname)[0]\n\n @property\n def pyfilename(self):\n return self.modulename + '.py'\n\n @property\n def rstfilename(self):\n return self.modulename + \".rst\"\n\n @property\n def htmlfilename(self):\n return self.modulename + '.html'\n\n @property\n def pngfilename(self):\n pngfile = self.modulename + '.png'\n return \"_images/\" + pngfile\n\n @property\n def thumbfilename(self):\n pngfile = self.modulename + '_thumb.png'\n return pngfile\n\n @property\n def sphinxtag(self):\n return self.modulename\n\n @property\n def pagetitle(self):\n return self.docstring.strip().split('\\n')[0].strip()\n\n @property\n def plotfunc(self):\n match = re.search(r\"sns\\.(.+plot)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+map)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+Grid)\\(\", self.filetext)\n if match:\n return match.group(1)\n return \"\"\n\n @property\n def components(self):\n\n objects = re.findall(r\"sns\\.(\\w+)\\(\", self.filetext)\n\n refs = []\n for obj in objects:\n if obj[0].isupper():\n refs.append(f\":class:`{obj}`\")\n else:\n refs.append(f\":func:`{obj}`\")\n return \", \".join(refs)\n\n def extract_docstring(self):\n \"\"\" Extract a module-level docstring\n \"\"\"\n lines = open(self.filename).readlines()\n start_row = 0\n if lines[0].startswith('#!'):\n lines.pop(0)\n start_row = 1\n\n docstring = ''\n first_par = ''\n line_iter = lines.__iter__()\n tokens = tokenize.generate_tokens(lambda: next(line_iter))\n for tok_type, tok_content, _, (erow, _), _ in tokens:\n tok_type = token.tok_name[tok_type]\n if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):\n continue\n elif tok_type == 'STRING':\n docstring = eval(tok_content)\n # If the docstring is formatted with several paragraphs,\n # extract the first one:\n paragraphs = '\\n'.join(line.rstrip()\n for line in docstring.split('\\n')\n ).split('\\n\\n')\n if len(paragraphs) > 0:\n first_par = paragraphs[0]\n break\n\n thumbloc = None\n for i, line in enumerate(docstring.split(\"\\n\")):\n m = re.match(r\"^_thumb: (\\.\\d+),\\s*(\\.\\d+)\", line)\n if m:\n thumbloc = float(m.group(1)), float(m.group(2))\n break\n if thumbloc is not None:\n self.thumbloc = thumbloc\n docstring = \"\\n\".join([l for l in docstring.split(\"\\n\")\n if not l.startswith(\"_thumb\")])\n\n self.docstring = docstring\n self.short_desc = first_par\n self.end_line = erow + 1 + start_row\n\n def exec_file(self):\n print(f\"running {self.filename}\")\n\n plt.close('all')\n my_globals = {'pl': plt,\n 'plt': plt}\n execfile(self.filename, my_globals)\n\n fig = plt.gcf()\n fig.canvas.draw()\n pngfile = op.join(self.target_dir, self.pngfilename)\n thumbfile = op.join(\"example_thumbs\", self.thumbfilename)\n self.html = f\"\"\n fig.savefig(pngfile, dpi=75, bbox_inches=\"tight\")\n\n cx, cy = self.thumbloc\n create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy)\n\n def toctree_entry(self):\n return f\" ./{op.splitext(self.htmlfilename)[0]}\\n\\n\"\n\n def contents_entry(self):\n return (\".. raw:: html\\n\\n\"\n \" \\n\\n\"\n \"\\n\\n\"\n \"\".format(self.htmlfilename,\n self.thumbfilename,\n self.plotfunc))"},{"col":4,"comment":"null","endLoc":182,"header":"def __init__(self, filename, target_dir)","id":4279,"name":"__init__","nodeType":"Function","startLoc":166,"text":"def __init__(self, filename, target_dir):\n self.filename = filename\n self.target_dir = target_dir\n self.thumbloc = .5, .5\n self.extract_docstring()\n with open(filename) as fid:\n self.filetext = fid.read()\n\n outfilename = op.join(target_dir, self.rstfilename)\n\n # Only actually run it if the output RST file doesn't\n # exist or it was modified less recently than the example\n file_mtime = op.getmtime(filename)\n if not op.exists(outfilename) or op.getmtime(outfilename) < file_mtime:\n self.exec_file()\n else:\n print(f\"skipping {self.filename}\")"},{"col":4,"comment":" Extract a module-level docstring\n ","endLoc":293,"header":"def extract_docstring(self)","id":4280,"name":"extract_docstring","nodeType":"Function","startLoc":252,"text":"def extract_docstring(self):\n \"\"\" Extract a module-level docstring\n \"\"\"\n lines = open(self.filename).readlines()\n start_row = 0\n if lines[0].startswith('#!'):\n lines.pop(0)\n start_row = 1\n\n docstring = ''\n first_par = ''\n line_iter = lines.__iter__()\n tokens = tokenize.generate_tokens(lambda: next(line_iter))\n for tok_type, tok_content, _, (erow, _), _ in tokens:\n tok_type = token.tok_name[tok_type]\n if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):\n continue\n elif tok_type == 'STRING':\n docstring = eval(tok_content)\n # If the docstring is formatted with several paragraphs,\n # extract the first one:\n paragraphs = '\\n'.join(line.rstrip()\n for line in docstring.split('\\n')\n ).split('\\n\\n')\n if len(paragraphs) > 0:\n first_par = paragraphs[0]\n break\n\n thumbloc = None\n for i, line in enumerate(docstring.split(\"\\n\")):\n m = re.match(r\"^_thumb: (\\.\\d+),\\s*(\\.\\d+)\", line)\n if m:\n thumbloc = float(m.group(1)), float(m.group(2))\n break\n if thumbloc is not None:\n self.thumbloc = thumbloc\n docstring = \"\\n\".join([l for l in docstring.split(\"\\n\")\n if not l.startswith(\"_thumb\")])\n\n self.docstring = docstring\n self.short_desc = first_par\n self.end_line = erow + 1 + start_row"},{"col":42,"endLoc":264,"id":4282,"nodeType":"Lambda","startLoc":264,"text":"lambda: next(line_iter)"},{"fileName":"test_regression.py","filePath":"tests","id":4284,"nodeType":"File","text":"import warnings\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nimport pytest\nimport numpy.testing as npt\ntry:\n import pandas.testing as pdt\nexcept ImportError:\n import pandas.util.testing as pdt\n\ntry:\n import statsmodels.regression.linear_model as smlm\n _no_statsmodels = False\nexcept ImportError:\n _no_statsmodels = True\n\nfrom seaborn import regression as lm\nfrom seaborn.external.version import Version\nfrom seaborn.palettes import color_palette\n\nrs = np.random.RandomState(0)\n\n\nclass TestLinearPlotter:\n\n rs = np.random.RandomState(77)\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n d=rs.randint(-2, 3, 60),\n y=rs.gamma(4, size=60),\n s=np.tile(list(\"abcdefghij\"), 6)))\n df[\"z\"] = df.y + rs.randn(60)\n df[\"y_na\"] = df.y.copy()\n df.loc[[10, 20, 30], 'y_na'] = np.nan\n\n def test_establish_variables_from_frame(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y=\"y\")\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_establish_variables_from_series(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None, x=self.df.x, y=self.df.y)\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n assert p.data is None\n\n def test_establish_variables_from_array(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None,\n x=self.df.x.values,\n y=self.df.y.values)\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n assert p.data is None\n\n def test_establish_variables_from_lists(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None,\n x=self.df.x.values.tolist(),\n y=self.df.y.values.tolist())\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n assert p.data is None\n\n def test_establish_variables_from_mix(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y=self.df.y)\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_establish_variables_from_bad(self):\n\n p = lm._LinearPlotter()\n with pytest.raises(ValueError):\n p.establish_variables(None, x=\"x\", y=self.df.y)\n\n def test_dropna(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y_na=\"y_na\")\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y_na, self.df.y_na)\n\n p.dropna(\"x\", \"y_na\")\n mask = self.df.y_na.notnull()\n pdt.assert_series_equal(p.x, self.df.x[mask])\n pdt.assert_series_equal(p.y_na, self.df.y_na[mask])\n\n\nclass TestRegressionPlotter:\n\n rs = np.random.RandomState(49)\n\n grid = np.linspace(-3, 3, 30)\n n_boot = 100\n bins_numeric = 3\n bins_given = [-1, 0, 1]\n\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n d=rs.randint(-2, 3, 60),\n y=rs.gamma(4, size=60),\n s=np.tile(list(range(6)), 10)))\n df[\"z\"] = df.y + rs.randn(60)\n df[\"y_na\"] = df.y.copy()\n\n bw_err = rs.randn(6)[df.s.values] * 2\n df.y += bw_err\n\n p = 1 / (1 + np.exp(-(df.x * 2 + rs.randn(60))))\n df[\"c\"] = [rs.binomial(1, p_i) for p_i in p]\n df.loc[[10, 20, 30], 'y_na'] = np.nan\n\n def test_variables_from_frame(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, units=\"s\")\n\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_series_equal(p.units, self.df.s)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_variables_from_series(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y, units=self.df.s)\n\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n npt.assert_array_equal(p.units, self.df.s)\n assert p.data is None\n\n def test_variables_from_mix(self):\n\n p = lm._RegressionPlotter(\"x\", self.df.y + 1, data=self.df)\n\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y + 1)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_variables_must_be_1d(self):\n\n array_2d = np.random.randn(20, 2)\n array_1d = np.random.randn(20)\n with pytest.raises(ValueError):\n lm._RegressionPlotter(array_2d, array_1d)\n with pytest.raises(ValueError):\n lm._RegressionPlotter(array_1d, array_2d)\n\n def test_dropna(self):\n\n p = lm._RegressionPlotter(\"x\", \"y_na\", data=self.df)\n assert len(p.x) == pd.notnull(self.df.y_na).sum()\n\n p = lm._RegressionPlotter(\"x\", \"y_na\", data=self.df, dropna=False)\n assert len(p.x) == len(self.df.y_na)\n\n @pytest.mark.parametrize(\"x,y\",\n [([1.5], [2]),\n (np.array([1.5]), np.array([2])),\n (pd.Series(1.5), pd.Series(2))])\n def test_singleton(self, x, y):\n p = lm._RegressionPlotter(x, y)\n assert not p.fit_reg\n\n def test_ci(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95)\n assert p.ci == 95\n assert p.x_ci == 95\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95, x_ci=68)\n assert p.ci == 95\n assert p.x_ci == 68\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95, x_ci=\"sd\")\n assert p.ci == 95\n assert p.x_ci == \"sd\"\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_fast_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fit with the \"fast\" function, which just does linear algebra\n yhat_fast, _ = p.fit_fast(self.grid)\n\n # Fit using the statsmodels function with an OLS model\n yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)\n\n # Compare the vector of y_hat values\n npt.assert_array_almost_equal(yhat_fast, yhat_smod)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_poly(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fit an first-order polynomial\n yhat_poly, _ = p.fit_poly(self.grid, 1)\n\n # Fit using the statsmodels function with an OLS model\n yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)\n\n # Compare the vector of y_hat values\n npt.assert_array_almost_equal(yhat_poly, yhat_smod)\n\n def test_regress_logx(self):\n\n x = np.arange(1, 10)\n y = np.arange(1, 10)\n grid = np.linspace(1, 10, 100)\n p = lm._RegressionPlotter(x, y, n_boot=self.n_boot)\n\n yhat_lin, _ = p.fit_fast(grid)\n yhat_log, _ = p.fit_logx(grid)\n\n assert yhat_lin[0] > yhat_log[0]\n assert yhat_log[20] > yhat_lin[20]\n assert yhat_lin[90] > yhat_log[90]\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_n_boot(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fast (linear algebra) version\n _, boots_fast = p.fit_fast(self.grid)\n npt.assert_equal(boots_fast.shape, (self.n_boot, self.grid.size))\n\n # Slower (np.polyfit) version\n _, boots_poly = p.fit_poly(self.grid, 1)\n npt.assert_equal(boots_poly.shape, (self.n_boot, self.grid.size))\n\n # Slowest (statsmodels) version\n _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)\n npt.assert_equal(boots_smod.shape, (self.n_boot, self.grid.size))\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_without_bootstrap(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, ci=None)\n\n # Fast (linear algebra) version\n _, boots_fast = p.fit_fast(self.grid)\n assert boots_fast is None\n\n # Slower (np.polyfit) version\n _, boots_poly = p.fit_poly(self.grid, 1)\n assert boots_poly is None\n\n # Slowest (statsmodels) version\n _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)\n assert boots_smod is None\n\n def test_regress_bootstrap_seed(self):\n\n seed = 200\n p1 = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, seed=seed)\n p2 = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, seed=seed)\n\n _, boots1 = p1.fit_fast(self.grid)\n _, boots2 = p2.fit_fast(self.grid)\n npt.assert_array_equal(boots1, boots2)\n\n def test_numeric_bins(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_numeric)\n npt.assert_equal(len(bins), self.bins_numeric)\n npt.assert_array_equal(np.unique(x_binned), bins)\n\n def test_provided_bins(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_given)\n npt.assert_array_equal(np.unique(x_binned), self.bins_given)\n\n def test_bin_results(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_given)\n assert self.df.x[x_binned == 0].min() > self.df.x[x_binned == -1].max()\n assert self.df.x[x_binned == 1].min() > self.df.x[x_binned == 0].max()\n\n def test_scatter_data(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.d)\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, x_jitter=.1)\n x, y = p.scatter_data\n assert (x != self.df.d).any()\n npt.assert_array_less(np.abs(self.df.d - x), np.repeat(.1, len(x)))\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, y_jitter=.05)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.d)\n npt.assert_array_less(np.abs(self.df.y - y), np.repeat(.1, len(y)))\n\n def test_estimate_data(self):\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, x_estimator=np.mean)\n\n x, y, ci = p.estimate_data\n\n npt.assert_array_equal(x, np.sort(np.unique(self.df.d)))\n npt.assert_array_almost_equal(y, self.df.groupby(\"d\").y.mean())\n npt.assert_array_less(np.array(ci)[:, 0], y)\n npt.assert_array_less(y, np.array(ci)[:, 1])\n\n def test_estimate_cis(self):\n\n seed = 123\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=95, seed=seed)\n _, _, ci_big = p.estimate_data\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=50, seed=seed)\n _, _, ci_wee = p.estimate_data\n npt.assert_array_less(np.diff(ci_wee), np.diff(ci_big))\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=None)\n _, _, ci_nil = p.estimate_data\n npt.assert_array_equal(ci_nil, [None] * len(ci_nil))\n\n def test_estimate_units(self):\n\n # Seed the RNG locally\n seed = 345\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n units=\"s\", seed=seed, x_bins=3)\n _, _, ci_big = p.estimate_data\n ci_big = np.diff(ci_big, axis=1)\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, seed=seed, x_bins=3)\n _, _, ci_wee = p.estimate_data\n ci_wee = np.diff(ci_wee, axis=1)\n\n npt.assert_array_less(ci_wee, ci_big)\n\n def test_partial(self):\n\n x = self.rs.randn(100)\n y = x + self.rs.randn(100)\n z = x + self.rs.randn(100)\n\n p = lm._RegressionPlotter(y, z)\n _, r_orig = np.corrcoef(p.x, p.y)[0]\n\n p = lm._RegressionPlotter(y, z, y_partial=x)\n _, r_semipartial = np.corrcoef(p.x, p.y)[0]\n assert r_semipartial < r_orig\n\n p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)\n _, r_partial = np.corrcoef(p.x, p.y)[0]\n assert r_partial < r_orig\n\n x = pd.Series(x)\n y = pd.Series(y)\n p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)\n _, r_partial = np.corrcoef(p.x, p.y)[0]\n assert r_partial < r_orig\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"c\", data=self.df,\n logistic=True, n_boot=self.n_boot)\n _, yhat, _ = p.fit_regression(x_range=(-3, 3))\n npt.assert_array_less(yhat, 1)\n npt.assert_array_less(0, yhat)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_perfect_separation(self):\n\n y = self.df.x > self.df.x.mean()\n p = lm._RegressionPlotter(\"x\", y, data=self.df,\n logistic=True, n_boot=10)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n _, yhat, _ = p.fit_regression(x_range=(-3, 3))\n assert np.isnan(yhat).all()\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_robust_regression(self):\n\n p_ols = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot)\n _, ols_yhat, _ = p_ols.fit_regression(x_range=(-3, 3))\n\n p_robust = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n robust=True, n_boot=self.n_boot)\n _, robust_yhat, _ = p_robust.fit_regression(x_range=(-3, 3))\n\n assert len(ols_yhat) == len(robust_yhat)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_lowess_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, lowess=True)\n grid, yhat, err_bands = p.fit_regression(x_range=(-3, 3))\n\n assert len(grid) == len(yhat)\n assert err_bands is None\n\n def test_regression_options(self):\n\n with pytest.raises(ValueError):\n lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n lowess=True, order=2)\n\n with pytest.raises(ValueError):\n lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n lowess=True, logistic=True)\n\n def test_regression_limits(self):\n\n f, ax = plt.subplots()\n ax.scatter(self.df.x, self.df.y)\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df)\n grid, _, _ = p.fit_regression(ax)\n xlim = ax.get_xlim()\n assert grid.min() == xlim[0]\n assert grid.max() == xlim[1]\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, truncate=True)\n grid, _, _ = p.fit_regression()\n assert grid.min() == self.df.x.min()\n assert grid.max() == self.df.x.max()\n\n\nclass TestRegressionPlots:\n\n rs = np.random.RandomState(56)\n df = pd.DataFrame(dict(x=rs.randn(90),\n y=rs.randn(90) + 5,\n z=rs.randint(0, 1, 90),\n g=np.repeat(list(\"abc\"), 30),\n h=np.tile(list(\"xy\"), 45),\n u=np.tile(np.arange(6), 15)))\n bw_err = rs.randn(6)[df.u.values]\n df.y += bw_err\n\n def test_regplot_basic(self):\n\n f, ax = plt.subplots()\n lm.regplot(x=\"x\", y=\"y\", data=self.df)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n def test_regplot_selective(self):\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, scatter=False, ax=ax)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 1\n ax.clear()\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, fit_reg=False)\n assert len(ax.lines) == 0\n assert len(ax.collections) == 1\n ax.clear()\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, ci=None)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 1\n ax.clear()\n\n def test_regplot_scatter_kws_alpha(self):\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha is None\n assert ax.collections[0]._facecolors[0, 3] == 0.5\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha == 0.8\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color, 'alpha': 0.4})\n assert ax.collections[0]._alpha == 0.4\n\n f, ax = plt.subplots()\n color = 'r'\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha == 0.8\n\n f, ax = plt.subplots()\n alpha = .3\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n x_bins=5, fit_reg=False,\n scatter_kws={\"alpha\": alpha})\n for line in ax.lines:\n assert line.get_alpha() == alpha\n\n def test_regplot_binned(self):\n\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, x_bins=5)\n assert len(ax.lines) == 6\n assert len(ax.collections) == 2\n\n def test_lmplot_no_data(self):\n\n with pytest.raises(TypeError):\n # keyword argument `data` is required\n lm.lmplot(x=\"x\", y=\"y\")\n\n def test_lmplot_basic(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df)\n ax = g.axes[0, 0]\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n def test_lmplot_hue(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\")\n ax = g.axes[0, 0]\n\n assert len(ax.lines) == 2\n assert len(ax.collections) == 4\n\n def test_lmplot_markers(self):\n\n g1 = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", markers=\"s\")\n assert g1.hue_kws == {\"marker\": [\"s\", \"s\"]}\n\n g2 = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", markers=[\"o\", \"s\"])\n assert g2.hue_kws == {\"marker\": [\"o\", \"s\"]}\n\n with pytest.raises(ValueError):\n lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\",\n markers=[\"o\", \"s\", \"d\"])\n\n def test_lmplot_marker_linewidths(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\",\n fit_reg=False, markers=[\"o\", \"+\"])\n c = g.axes[0, 0].collections\n assert c[1].get_linewidths()[0] == mpl.rcParams[\"lines.linewidth\"]\n\n def test_lmplot_facets(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, row=\"g\", col=\"h\")\n assert g.axes.shape == (3, 2)\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, col=\"u\", col_wrap=4)\n assert g.axes.shape == (6,)\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", col=\"u\")\n assert g.axes.shape == (1, 6)\n\n def test_lmplot_hue_col_nolegend(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, col=\"h\", hue=\"h\")\n assert g._legend is None\n\n def test_lmplot_scatter_kws(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", hue=\"h\", data=self.df, ci=None)\n red_scatter, blue_scatter = g.axes[0, 0].collections\n\n red, blue = color_palette(n_colors=2)\n npt.assert_array_equal(red, red_scatter.get_facecolors()[0, :3])\n npt.assert_array_equal(blue, blue_scatter.get_facecolors()[0, :3])\n\n @pytest.mark.skipif(Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"MPL bug #15967\")\n @pytest.mark.parametrize(\"sharex\", [True, False])\n def test_lmplot_facet_truncate(self, sharex):\n\n g = lm.lmplot(\n data=self.df, x=\"x\", y=\"y\", hue=\"g\", col=\"h\",\n truncate=False, facet_kws=dict(sharex=sharex),\n )\n\n for ax in g.axes.flat:\n for line in ax.lines:\n xdata = line.get_xdata()\n assert ax.get_xlim() == tuple(xdata[[0, -1]])\n\n def test_lmplot_sharey(self):\n\n df = pd.DataFrame(dict(\n x=[0, 1, 2, 0, 1, 2],\n y=[1, -1, 0, -100, 200, 0],\n z=[\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"],\n ))\n\n with pytest.warns(UserWarning):\n g = lm.lmplot(data=df, x=\"x\", y=\"y\", col=\"z\", sharey=False)\n ax1, ax2 = g.axes.flat\n assert ax1.get_ylim()[0] > ax2.get_ylim()[0]\n assert ax1.get_ylim()[1] < ax2.get_ylim()[1]\n\n def test_lmplot_facet_kws(self):\n\n xlim = -4, 20\n g = lm.lmplot(\n data=self.df, x=\"x\", y=\"y\", col=\"h\", facet_kws={\"xlim\": xlim}\n )\n for ax in g.axes.flat:\n assert ax.get_xlim() == xlim\n\n def test_residplot(self):\n\n x, y = self.df.x, self.df.y\n ax = lm.residplot(x=x, y=y)\n\n resid = y - np.polyval(np.polyfit(x, y, 1), x)\n x_plot, y_plot = ax.collections[0].get_offsets().T\n\n npt.assert_array_equal(x, x_plot)\n npt.assert_array_almost_equal(resid, y_plot)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_residplot_lowess(self):\n\n ax = lm.residplot(x=\"x\", y=\"y\", data=self.df, lowess=True)\n assert len(ax.lines) == 2\n\n x, y = ax.lines[1].get_xydata().T\n npt.assert_array_equal(x, np.sort(self.df.x))\n\n def test_three_point_colors(self):\n\n x, y = np.random.randn(2, 3)\n ax = lm.regplot(x=x, y=y, color=(1, 0, 0))\n color = ax.collections[0].get_facecolors()\n npt.assert_almost_equal(color[0, :3],\n (1, 0, 0))\n\n def test_regplot_xlim(self):\n\n f, ax = plt.subplots()\n x, y1, y2 = np.random.randn(3, 50)\n lm.regplot(x=x, y=y1, truncate=False)\n lm.regplot(x=x, y=y2, truncate=False)\n line1, line2 = ax.lines\n assert np.array_equal(line1.get_xdata(), line2.get_xdata())\n"},{"className":"TestLinearPlotter","col":0,"comment":"null","endLoc":99,"id":4285,"nodeType":"Class","startLoc":28,"text":"class TestLinearPlotter:\n\n rs = np.random.RandomState(77)\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n d=rs.randint(-2, 3, 60),\n y=rs.gamma(4, size=60),\n s=np.tile(list(\"abcdefghij\"), 6)))\n df[\"z\"] = df.y + rs.randn(60)\n df[\"y_na\"] = df.y.copy()\n df.loc[[10, 20, 30], 'y_na'] = np.nan\n\n def test_establish_variables_from_frame(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y=\"y\")\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_establish_variables_from_series(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None, x=self.df.x, y=self.df.y)\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n assert p.data is None\n\n def test_establish_variables_from_array(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None,\n x=self.df.x.values,\n y=self.df.y.values)\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n assert p.data is None\n\n def test_establish_variables_from_lists(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None,\n x=self.df.x.values.tolist(),\n y=self.df.y.values.tolist())\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n assert p.data is None\n\n def test_establish_variables_from_mix(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y=self.df.y)\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_establish_variables_from_bad(self):\n\n p = lm._LinearPlotter()\n with pytest.raises(ValueError):\n p.establish_variables(None, x=\"x\", y=self.df.y)\n\n def test_dropna(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y_na=\"y_na\")\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y_na, self.df.y_na)\n\n p.dropna(\"x\", \"y_na\")\n mask = self.df.y_na.notnull()\n pdt.assert_series_equal(p.x, self.df.x[mask])\n pdt.assert_series_equal(p.y_na, self.df.y_na[mask])"},{"col":4,"comment":"null","endLoc":45,"header":"def test_establish_variables_from_frame(self)","id":4286,"name":"test_establish_variables_from_frame","nodeType":"Function","startLoc":39,"text":"def test_establish_variables_from_frame(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y=\"y\")\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_frame_equal(p.data, self.df)"},{"col":4,"comment":"null","endLoc":53,"header":"def test_establish_variables_from_series(self)","id":4292,"name":"test_establish_variables_from_series","nodeType":"Function","startLoc":47,"text":"def test_establish_variables_from_series(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None, x=self.df.x, y=self.df.y)\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n assert p.data is None"},{"col":4,"comment":"null","endLoc":311,"header":"def exec_file(self)","id":4293,"name":"exec_file","nodeType":"Function","startLoc":295,"text":"def exec_file(self):\n print(f\"running {self.filename}\")\n\n plt.close('all')\n my_globals = {'pl': plt,\n 'plt': plt}\n execfile(self.filename, my_globals)\n\n fig = plt.gcf()\n fig.canvas.draw()\n pngfile = op.join(self.target_dir, self.pngfilename)\n thumbfile = op.join(\"example_thumbs\", self.thumbfilename)\n self.html = f\"\"\n fig.savefig(pngfile, dpi=75, bbox_inches=\"tight\")\n\n cx, cy = self.thumbloc\n create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy)"},{"col":0,"comment":"null","endLoc":24,"header":"def execfile(filename, globals=None, locals=None)","id":4294,"name":"execfile","nodeType":"Function","startLoc":22,"text":"def execfile(filename, globals=None, locals=None):\n with open(filename, \"rb\") as fp:\n exec(compile(fp.read(), filename, 'exec'), globals, locals)"},{"col":4,"comment":"null","endLoc":63,"header":"def test_establish_variables_from_array(self)","id":4295,"name":"test_establish_variables_from_array","nodeType":"Function","startLoc":55,"text":"def test_establish_variables_from_array(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None,\n x=self.df.x.values,\n y=self.df.y.values)\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n assert p.data is None"},{"col":4,"comment":"null","endLoc":73,"header":"def test_establish_variables_from_lists(self)","id":4296,"name":"test_establish_variables_from_lists","nodeType":"Function","startLoc":65,"text":"def test_establish_variables_from_lists(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(None,\n x=self.df.x.values.tolist(),\n y=self.df.y.values.tolist())\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n assert p.data is None"},{"col":4,"comment":"null","endLoc":81,"header":"def test_establish_variables_from_mix(self)","id":4297,"name":"test_establish_variables_from_mix","nodeType":"Function","startLoc":75,"text":"def test_establish_variables_from_mix(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y=self.df.y)\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_frame_equal(p.data, self.df)"},{"col":4,"comment":"null","endLoc":87,"header":"def test_establish_variables_from_bad(self)","id":4298,"name":"test_establish_variables_from_bad","nodeType":"Function","startLoc":83,"text":"def test_establish_variables_from_bad(self):\n\n p = lm._LinearPlotter()\n with pytest.raises(ValueError):\n p.establish_variables(None, x=\"x\", y=self.df.y)"},{"col":4,"comment":"null","endLoc":99,"header":"def test_dropna(self)","id":4299,"name":"test_dropna","nodeType":"Function","startLoc":89,"text":"def test_dropna(self):\n\n p = lm._LinearPlotter()\n p.establish_variables(self.df, x=\"x\", y_na=\"y_na\")\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y_na, self.df.y_na)\n\n p.dropna(\"x\", \"y_na\")\n mask = self.df.y_na.notnull()\n pdt.assert_series_equal(p.x, self.df.x[mask])\n pdt.assert_series_equal(p.y_na, self.df.y_na[mask])"},{"attributeType":"null","col":4,"comment":"null","endLoc":30,"id":4300,"name":"rs","nodeType":"Attribute","startLoc":30,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":31,"id":4301,"name":"df","nodeType":"Attribute","startLoc":31,"text":"df"},{"className":"TestRegressionPlotter","col":0,"comment":"null","endLoc":455,"id":4302,"nodeType":"Class","startLoc":102,"text":"class TestRegressionPlotter:\n\n rs = np.random.RandomState(49)\n\n grid = np.linspace(-3, 3, 30)\n n_boot = 100\n bins_numeric = 3\n bins_given = [-1, 0, 1]\n\n df = pd.DataFrame(dict(x=rs.normal(size=60),\n d=rs.randint(-2, 3, 60),\n y=rs.gamma(4, size=60),\n s=np.tile(list(range(6)), 10)))\n df[\"z\"] = df.y + rs.randn(60)\n df[\"y_na\"] = df.y.copy()\n\n bw_err = rs.randn(6)[df.s.values] * 2\n df.y += bw_err\n\n p = 1 / (1 + np.exp(-(df.x * 2 + rs.randn(60))))\n df[\"c\"] = [rs.binomial(1, p_i) for p_i in p]\n df.loc[[10, 20, 30], 'y_na'] = np.nan\n\n def test_variables_from_frame(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, units=\"s\")\n\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_series_equal(p.units, self.df.s)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_variables_from_series(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y, units=self.df.s)\n\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n npt.assert_array_equal(p.units, self.df.s)\n assert p.data is None\n\n def test_variables_from_mix(self):\n\n p = lm._RegressionPlotter(\"x\", self.df.y + 1, data=self.df)\n\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y + 1)\n pdt.assert_frame_equal(p.data, self.df)\n\n def test_variables_must_be_1d(self):\n\n array_2d = np.random.randn(20, 2)\n array_1d = np.random.randn(20)\n with pytest.raises(ValueError):\n lm._RegressionPlotter(array_2d, array_1d)\n with pytest.raises(ValueError):\n lm._RegressionPlotter(array_1d, array_2d)\n\n def test_dropna(self):\n\n p = lm._RegressionPlotter(\"x\", \"y_na\", data=self.df)\n assert len(p.x) == pd.notnull(self.df.y_na).sum()\n\n p = lm._RegressionPlotter(\"x\", \"y_na\", data=self.df, dropna=False)\n assert len(p.x) == len(self.df.y_na)\n\n @pytest.mark.parametrize(\"x,y\",\n [([1.5], [2]),\n (np.array([1.5]), np.array([2])),\n (pd.Series(1.5), pd.Series(2))])\n def test_singleton(self, x, y):\n p = lm._RegressionPlotter(x, y)\n assert not p.fit_reg\n\n def test_ci(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95)\n assert p.ci == 95\n assert p.x_ci == 95\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95, x_ci=68)\n assert p.ci == 95\n assert p.x_ci == 68\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95, x_ci=\"sd\")\n assert p.ci == 95\n assert p.x_ci == \"sd\"\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_fast_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fit with the \"fast\" function, which just does linear algebra\n yhat_fast, _ = p.fit_fast(self.grid)\n\n # Fit using the statsmodels function with an OLS model\n yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)\n\n # Compare the vector of y_hat values\n npt.assert_array_almost_equal(yhat_fast, yhat_smod)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_poly(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fit an first-order polynomial\n yhat_poly, _ = p.fit_poly(self.grid, 1)\n\n # Fit using the statsmodels function with an OLS model\n yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)\n\n # Compare the vector of y_hat values\n npt.assert_array_almost_equal(yhat_poly, yhat_smod)\n\n def test_regress_logx(self):\n\n x = np.arange(1, 10)\n y = np.arange(1, 10)\n grid = np.linspace(1, 10, 100)\n p = lm._RegressionPlotter(x, y, n_boot=self.n_boot)\n\n yhat_lin, _ = p.fit_fast(grid)\n yhat_log, _ = p.fit_logx(grid)\n\n assert yhat_lin[0] > yhat_log[0]\n assert yhat_log[20] > yhat_lin[20]\n assert yhat_lin[90] > yhat_log[90]\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_n_boot(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fast (linear algebra) version\n _, boots_fast = p.fit_fast(self.grid)\n npt.assert_equal(boots_fast.shape, (self.n_boot, self.grid.size))\n\n # Slower (np.polyfit) version\n _, boots_poly = p.fit_poly(self.grid, 1)\n npt.assert_equal(boots_poly.shape, (self.n_boot, self.grid.size))\n\n # Slowest (statsmodels) version\n _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)\n npt.assert_equal(boots_smod.shape, (self.n_boot, self.grid.size))\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_without_bootstrap(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, ci=None)\n\n # Fast (linear algebra) version\n _, boots_fast = p.fit_fast(self.grid)\n assert boots_fast is None\n\n # Slower (np.polyfit) version\n _, boots_poly = p.fit_poly(self.grid, 1)\n assert boots_poly is None\n\n # Slowest (statsmodels) version\n _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)\n assert boots_smod is None\n\n def test_regress_bootstrap_seed(self):\n\n seed = 200\n p1 = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, seed=seed)\n p2 = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, seed=seed)\n\n _, boots1 = p1.fit_fast(self.grid)\n _, boots2 = p2.fit_fast(self.grid)\n npt.assert_array_equal(boots1, boots2)\n\n def test_numeric_bins(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_numeric)\n npt.assert_equal(len(bins), self.bins_numeric)\n npt.assert_array_equal(np.unique(x_binned), bins)\n\n def test_provided_bins(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_given)\n npt.assert_array_equal(np.unique(x_binned), self.bins_given)\n\n def test_bin_results(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_given)\n assert self.df.x[x_binned == 0].min() > self.df.x[x_binned == -1].max()\n assert self.df.x[x_binned == 1].min() > self.df.x[x_binned == 0].max()\n\n def test_scatter_data(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.d)\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, x_jitter=.1)\n x, y = p.scatter_data\n assert (x != self.df.d).any()\n npt.assert_array_less(np.abs(self.df.d - x), np.repeat(.1, len(x)))\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, y_jitter=.05)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.d)\n npt.assert_array_less(np.abs(self.df.y - y), np.repeat(.1, len(y)))\n\n def test_estimate_data(self):\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, x_estimator=np.mean)\n\n x, y, ci = p.estimate_data\n\n npt.assert_array_equal(x, np.sort(np.unique(self.df.d)))\n npt.assert_array_almost_equal(y, self.df.groupby(\"d\").y.mean())\n npt.assert_array_less(np.array(ci)[:, 0], y)\n npt.assert_array_less(y, np.array(ci)[:, 1])\n\n def test_estimate_cis(self):\n\n seed = 123\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=95, seed=seed)\n _, _, ci_big = p.estimate_data\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=50, seed=seed)\n _, _, ci_wee = p.estimate_data\n npt.assert_array_less(np.diff(ci_wee), np.diff(ci_big))\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=None)\n _, _, ci_nil = p.estimate_data\n npt.assert_array_equal(ci_nil, [None] * len(ci_nil))\n\n def test_estimate_units(self):\n\n # Seed the RNG locally\n seed = 345\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n units=\"s\", seed=seed, x_bins=3)\n _, _, ci_big = p.estimate_data\n ci_big = np.diff(ci_big, axis=1)\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, seed=seed, x_bins=3)\n _, _, ci_wee = p.estimate_data\n ci_wee = np.diff(ci_wee, axis=1)\n\n npt.assert_array_less(ci_wee, ci_big)\n\n def test_partial(self):\n\n x = self.rs.randn(100)\n y = x + self.rs.randn(100)\n z = x + self.rs.randn(100)\n\n p = lm._RegressionPlotter(y, z)\n _, r_orig = np.corrcoef(p.x, p.y)[0]\n\n p = lm._RegressionPlotter(y, z, y_partial=x)\n _, r_semipartial = np.corrcoef(p.x, p.y)[0]\n assert r_semipartial < r_orig\n\n p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)\n _, r_partial = np.corrcoef(p.x, p.y)[0]\n assert r_partial < r_orig\n\n x = pd.Series(x)\n y = pd.Series(y)\n p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)\n _, r_partial = np.corrcoef(p.x, p.y)[0]\n assert r_partial < r_orig\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"c\", data=self.df,\n logistic=True, n_boot=self.n_boot)\n _, yhat, _ = p.fit_regression(x_range=(-3, 3))\n npt.assert_array_less(yhat, 1)\n npt.assert_array_less(0, yhat)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_perfect_separation(self):\n\n y = self.df.x > self.df.x.mean()\n p = lm._RegressionPlotter(\"x\", y, data=self.df,\n logistic=True, n_boot=10)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n _, yhat, _ = p.fit_regression(x_range=(-3, 3))\n assert np.isnan(yhat).all()\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_robust_regression(self):\n\n p_ols = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot)\n _, ols_yhat, _ = p_ols.fit_regression(x_range=(-3, 3))\n\n p_robust = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n robust=True, n_boot=self.n_boot)\n _, robust_yhat, _ = p_robust.fit_regression(x_range=(-3, 3))\n\n assert len(ols_yhat) == len(robust_yhat)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_lowess_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, lowess=True)\n grid, yhat, err_bands = p.fit_regression(x_range=(-3, 3))\n\n assert len(grid) == len(yhat)\n assert err_bands is None\n\n def test_regression_options(self):\n\n with pytest.raises(ValueError):\n lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n lowess=True, order=2)\n\n with pytest.raises(ValueError):\n lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n lowess=True, logistic=True)\n\n def test_regression_limits(self):\n\n f, ax = plt.subplots()\n ax.scatter(self.df.x, self.df.y)\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df)\n grid, _, _ = p.fit_regression(ax)\n xlim = ax.get_xlim()\n assert grid.min() == xlim[0]\n assert grid.max() == xlim[1]\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, truncate=True)\n grid, _, _ = p.fit_regression()\n assert grid.min() == self.df.x.min()\n assert grid.max() == self.df.x.max()"},{"col":4,"comment":"null","endLoc":132,"header":"def test_variables_from_frame(self)","id":4303,"name":"test_variables_from_frame","nodeType":"Function","startLoc":125,"text":"def test_variables_from_frame(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, units=\"s\")\n\n pdt.assert_series_equal(p.x, self.df.x)\n pdt.assert_series_equal(p.y, self.df.y)\n pdt.assert_series_equal(p.units, self.df.s)\n pdt.assert_frame_equal(p.data, self.df)"},{"col":4,"comment":"null","endLoc":111,"header":"def test_df_and_mixed_variables(self, long_df)","id":4304,"name":"test_df_and_mixed_variables","nodeType":"Function","startLoc":101,"text":"def test_df_and_mixed_variables(self, long_df):\n\n variables = {\"x\": \"a\", \"y\": long_df[\"z\"]}\n p = Plot(long_df, **variables)\n for var, col in variables.items():\n if isinstance(col, str):\n assert_vector_equal(p._data.frame[var], long_df[col])\n else:\n assert_vector_equal(p._data.frame[var], col)\n assert p._data.source_data is long_df\n assert p._data.source_vars.keys() == variables.keys()"},{"col":4,"comment":"null","endLoc":141,"header":"def test_variables_from_series(self)","id":4305,"name":"test_variables_from_series","nodeType":"Function","startLoc":134,"text":"def test_variables_from_series(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y, units=self.df.s)\n\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y)\n npt.assert_array_equal(p.units, self.df.s)\n assert p.data is None"},{"col":4,"comment":"null","endLoc":149,"header":"def test_variables_from_mix(self)","id":4306,"name":"test_variables_from_mix","nodeType":"Function","startLoc":143,"text":"def test_variables_from_mix(self):\n\n p = lm._RegressionPlotter(\"x\", self.df.y + 1, data=self.df)\n\n npt.assert_array_equal(p.x, self.df.x)\n npt.assert_array_equal(p.y, self.df.y + 1)\n pdt.assert_frame_equal(p.data, self.df)"},{"col":4,"comment":"null","endLoc":158,"header":"def test_variables_must_be_1d(self)","id":4307,"name":"test_variables_must_be_1d","nodeType":"Function","startLoc":151,"text":"def test_variables_must_be_1d(self):\n\n array_2d = np.random.randn(20, 2)\n array_1d = np.random.randn(20)\n with pytest.raises(ValueError):\n lm._RegressionPlotter(array_2d, array_1d)\n with pytest.raises(ValueError):\n lm._RegressionPlotter(array_1d, array_2d)"},{"col":4,"comment":"null","endLoc":166,"header":"def test_dropna(self)","id":4308,"name":"test_dropna","nodeType":"Function","startLoc":160,"text":"def test_dropna(self):\n\n p = lm._RegressionPlotter(\"x\", \"y_na\", data=self.df)\n assert len(p.x) == pd.notnull(self.df.y_na).sum()\n\n p = lm._RegressionPlotter(\"x\", \"y_na\", data=self.df, dropna=False)\n assert len(p.x) == len(self.df.y_na)"},{"col":4,"comment":"null","endLoc":174,"header":"@pytest.mark.parametrize(\"x,y\",\n [([1.5], [2]),\n (np.array([1.5]), np.array([2])),\n (pd.Series(1.5), pd.Series(2))])\n def test_singleton(self, x, y)","id":4309,"name":"test_singleton","nodeType":"Function","startLoc":168,"text":"@pytest.mark.parametrize(\"x,y\",\n [([1.5], [2]),\n (np.array([1.5]), np.array([2])),\n (pd.Series(1.5), pd.Series(2))])\n def test_singleton(self, x, y):\n p = lm._RegressionPlotter(x, y)\n assert not p.fit_reg"},{"col":4,"comment":"null","endLoc":188,"header":"def test_ci(self)","id":4310,"name":"test_ci","nodeType":"Function","startLoc":176,"text":"def test_ci(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95)\n assert p.ci == 95\n assert p.x_ci == 95\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95, x_ci=68)\n assert p.ci == 95\n assert p.x_ci == 68\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, ci=95, x_ci=\"sd\")\n assert p.ci == 95\n assert p.x_ci == \"sd\""},{"col":4,"comment":"null","endLoc":120,"header":"def test_vector_variables_only(self, long_df)","id":4311,"name":"test_vector_variables_only","nodeType":"Function","startLoc":113,"text":"def test_vector_variables_only(self, long_df):\n\n variables = {\"x\": long_df[\"a\"], \"y\": long_df[\"z\"]}\n p = Plot(**variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], col)\n assert p._data.source_data is None\n assert p._data.source_vars.keys() == variables.keys()"},{"col":4,"comment":"null","endLoc":202,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_fast_regression(self)","id":4312,"name":"test_fast_regression","nodeType":"Function","startLoc":190,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_fast_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fit with the \"fast\" function, which just does linear algebra\n yhat_fast, _ = p.fit_fast(self.grid)\n\n # Fit using the statsmodels function with an OLS model\n yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)\n\n # Compare the vector of y_hat values\n npt.assert_array_almost_equal(yhat_fast, yhat_smod)"},{"col":4,"comment":"null","endLoc":130,"header":"def test_vector_variables_no_index(self, long_df)","id":4313,"name":"test_vector_variables_no_index","nodeType":"Function","startLoc":122,"text":"def test_vector_variables_no_index(self, long_df):\n\n variables = {\"x\": long_df[\"a\"].to_numpy(), \"y\": long_df[\"z\"].to_list()}\n p = Plot(**variables)\n for var, col in variables.items():\n assert_vector_equal(p._data.frame[var], pd.Series(col))\n assert p._data.names[var] is None\n assert p._data.source_data is None\n assert p._data.source_vars.keys() == variables.keys()"},{"col":4,"comment":"null","endLoc":216,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_poly(self)","id":4314,"name":"test_regress_poly","nodeType":"Function","startLoc":204,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_poly(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fit an first-order polynomial\n yhat_poly, _ = p.fit_poly(self.grid, 1)\n\n # Fit using the statsmodels function with an OLS model\n yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)\n\n # Compare the vector of y_hat values\n npt.assert_array_almost_equal(yhat_poly, yhat_smod)"},{"col":4,"comment":"null","endLoc":230,"header":"def test_regress_logx(self)","id":4315,"name":"test_regress_logx","nodeType":"Function","startLoc":218,"text":"def test_regress_logx(self):\n\n x = np.arange(1, 10)\n y = np.arange(1, 10)\n grid = np.linspace(1, 10, 100)\n p = lm._RegressionPlotter(x, y, n_boot=self.n_boot)\n\n yhat_lin, _ = p.fit_fast(grid)\n yhat_log, _ = p.fit_logx(grid)\n\n assert yhat_lin[0] > yhat_log[0]\n assert yhat_log[20] > yhat_lin[20]\n assert yhat_lin[90] > yhat_log[90]"},{"col":4,"comment":"null","endLoc":136,"header":"def test_data_only_named(self, long_df)","id":4316,"name":"test_data_only_named","nodeType":"Function","startLoc":132,"text":"def test_data_only_named(self, long_df):\n\n p = Plot(data=long_df)\n assert p._data.source_data is long_df\n assert p._data.source_vars == {}"},{"col":4,"comment":"null","endLoc":247,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_n_boot(self)","id":4317,"name":"test_regress_n_boot","nodeType":"Function","startLoc":232,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_n_boot(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, n_boot=self.n_boot)\n\n # Fast (linear algebra) version\n _, boots_fast = p.fit_fast(self.grid)\n npt.assert_equal(boots_fast.shape, (self.n_boot, self.grid.size))\n\n # Slower (np.polyfit) version\n _, boots_poly = p.fit_poly(self.grid, 1)\n npt.assert_equal(boots_poly.shape, (self.n_boot, self.grid.size))\n\n # Slowest (statsmodels) version\n _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)\n npt.assert_equal(boots_smod.shape, (self.n_boot, self.grid.size))"},{"col":4,"comment":"null","endLoc":142,"header":"def test_positional_and_named_data(self, long_df)","id":4318,"name":"test_positional_and_named_data","nodeType":"Function","startLoc":138,"text":"def test_positional_and_named_data(self, long_df):\n\n err = \"`data` given by both name and position\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, data=long_df)"},{"col":4,"comment":"null","endLoc":149,"header":"@pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_positional_and_named_xy(self, long_df, var)","id":4319,"name":"test_positional_and_named_xy","nodeType":"Function","startLoc":144,"text":"@pytest.mark.parametrize(\"var\", [\"x\", \"y\"])\n def test_positional_and_named_xy(self, long_df, var):\n\n err = f\"`{var}` given by both name and position\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, \"a\", \"b\", **{var: \"c\"})"},{"col":4,"comment":"null","endLoc":265,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_without_bootstrap(self)","id":4320,"name":"test_regress_without_bootstrap","nodeType":"Function","startLoc":249,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_regress_without_bootstrap(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, ci=None)\n\n # Fast (linear algebra) version\n _, boots_fast = p.fit_fast(self.grid)\n assert boots_fast is None\n\n # Slower (np.polyfit) version\n _, boots_poly = p.fit_poly(self.grid, 1)\n assert boots_poly is None\n\n # Slowest (statsmodels) version\n _, boots_smod = p.fit_statsmodels(self.grid, smlm.OLS)\n assert boots_smod is None"},{"col":4,"comment":"null","endLoc":155,"header":"def test_positional_data_x_y(self, long_df)","id":4321,"name":"test_positional_data_x_y","nodeType":"Function","startLoc":151,"text":"def test_positional_data_x_y(self, long_df):\n\n p = Plot(long_df, \"a\", \"b\")\n assert p._data.source_data is long_df\n assert list(p._data.source_vars) == [\"x\", \"y\"]"},{"col":4,"comment":"null","endLoc":277,"header":"def test_regress_bootstrap_seed(self)","id":4322,"name":"test_regress_bootstrap_seed","nodeType":"Function","startLoc":267,"text":"def test_regress_bootstrap_seed(self):\n\n seed = 200\n p1 = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, seed=seed)\n p2 = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot, seed=seed)\n\n _, boots1 = p1.fit_fast(self.grid)\n _, boots2 = p2.fit_fast(self.grid)\n npt.assert_array_equal(boots1, boots2)"},{"col":4,"comment":"null","endLoc":284,"header":"def test_numeric_bins(self)","id":4323,"name":"test_numeric_bins","nodeType":"Function","startLoc":279,"text":"def test_numeric_bins(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_numeric)\n npt.assert_equal(len(bins), self.bins_numeric)\n npt.assert_array_equal(np.unique(x_binned), bins)"},{"col":4,"comment":"null","endLoc":290,"header":"def test_provided_bins(self)","id":4324,"name":"test_provided_bins","nodeType":"Function","startLoc":286,"text":"def test_provided_bins(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_given)\n npt.assert_array_equal(np.unique(x_binned), self.bins_given)"},{"col":4,"comment":"null","endLoc":297,"header":"def test_bin_results(self)","id":4325,"name":"test_bin_results","nodeType":"Function","startLoc":292,"text":"def test_bin_results(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x_binned, bins = p.bin_predictor(self.bins_given)\n assert self.df.x[x_binned == 0].min() > self.df.x[x_binned == -1].max()\n assert self.df.x[x_binned == 1].min() > self.df.x[x_binned == 0].max()"},{"col":0,"comment":"null","endLoc":156,"header":"def create_thumbnail(infile, thumbfile,\n width=275, height=275,\n cx=0.5, cy=0.5, border=4)","id":4330,"name":"create_thumbnail","nodeType":"Function","startLoc":128,"text":"def create_thumbnail(infile, thumbfile,\n width=275, height=275,\n cx=0.5, cy=0.5, border=4):\n baseout, extout = op.splitext(thumbfile)\n\n im = matplotlib.image.imread(infile)\n rows, cols = im.shape[:2]\n x0 = int(cx * cols - .5 * width)\n y0 = int(cy * rows - .5 * height)\n xslice = slice(x0, x0 + width)\n yslice = slice(y0, y0 + height)\n thumb = im[yslice, xslice]\n thumb[:border, :, :3] = thumb[-border:, :, :3] = 0\n thumb[:, :border, :3] = thumb[:, -border:, :3] = 0\n\n dpi = 100\n fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi)\n\n ax = fig.add_axes([0, 0, 1, 1], aspect='auto',\n frameon=False, xticks=[], yticks=[])\n if all(thumb.shape):\n ax.imshow(thumb, aspect='auto', resample=True,\n interpolation='bilinear')\n else:\n warnings.warn(\n f\"Bad thumbnail crop. {thumbfile} will be empty.\"\n )\n fig.savefig(thumbfile, dpi=dpi)\n return fig"},{"col":4,"comment":"null","endLoc":320,"header":"def test_scatter_data(self)","id":4332,"name":"test_scatter_data","nodeType":"Function","startLoc":299,"text":"def test_scatter_data(self):\n\n p = lm._RegressionPlotter(self.df.x, self.df.y)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.d)\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, x_jitter=.1)\n x, y = p.scatter_data\n assert (x != self.df.d).any()\n npt.assert_array_less(np.abs(self.df.d - x), np.repeat(.1, len(x)))\n npt.assert_array_equal(y, self.df.y)\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, y_jitter=.05)\n x, y = p.scatter_data\n npt.assert_array_equal(x, self.df.d)\n npt.assert_array_less(np.abs(self.df.y - y), np.repeat(.1, len(y)))"},{"col":4,"comment":"null","endLoc":331,"header":"def test_estimate_data(self)","id":4333,"name":"test_estimate_data","nodeType":"Function","startLoc":322,"text":"def test_estimate_data(self):\n\n p = lm._RegressionPlotter(self.df.d, self.df.y, x_estimator=np.mean)\n\n x, y, ci = p.estimate_data\n\n npt.assert_array_equal(x, np.sort(np.unique(self.df.d)))\n npt.assert_array_almost_equal(y, self.df.groupby(\"d\").y.mean())\n npt.assert_array_less(np.array(ci)[:, 0], y)\n npt.assert_array_less(y, np.array(ci)[:, 1])"},{"col":4,"comment":"null","endLoc":349,"header":"def test_estimate_cis(self)","id":4335,"name":"test_estimate_cis","nodeType":"Function","startLoc":333,"text":"def test_estimate_cis(self):\n\n seed = 123\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=95, seed=seed)\n _, _, ci_big = p.estimate_data\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=50, seed=seed)\n _, _, ci_wee = p.estimate_data\n npt.assert_array_less(np.diff(ci_wee), np.diff(ci_big))\n\n p = lm._RegressionPlotter(self.df.d, self.df.y,\n x_estimator=np.mean, ci=None)\n _, _, ci_nil = p.estimate_data\n npt.assert_array_equal(ci_nil, [None] * len(ci_nil))"},{"col":4,"comment":"null","endLoc":161,"header":"def test_positional_x_y(self, long_df)","id":4336,"name":"test_positional_x_y","nodeType":"Function","startLoc":157,"text":"def test_positional_x_y(self, long_df):\n\n p = Plot(long_df[\"a\"], long_df[\"b\"])\n assert p._data.source_data is None\n assert list(p._data.source_vars) == [\"x\", \"y\"]"},{"col":4,"comment":"null","endLoc":365,"header":"def test_estimate_units(self)","id":4337,"name":"test_estimate_units","nodeType":"Function","startLoc":351,"text":"def test_estimate_units(self):\n\n # Seed the RNG locally\n seed = 345\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n units=\"s\", seed=seed, x_bins=3)\n _, _, ci_big = p.estimate_data\n ci_big = np.diff(ci_big, axis=1)\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, seed=seed, x_bins=3)\n _, _, ci_wee = p.estimate_data\n ci_wee = np.diff(ci_wee, axis=1)\n\n npt.assert_array_less(ci_wee, ci_big)"},{"col":4,"comment":"null","endLoc":388,"header":"def test_partial(self)","id":4338,"name":"test_partial","nodeType":"Function","startLoc":367,"text":"def test_partial(self):\n\n x = self.rs.randn(100)\n y = x + self.rs.randn(100)\n z = x + self.rs.randn(100)\n\n p = lm._RegressionPlotter(y, z)\n _, r_orig = np.corrcoef(p.x, p.y)[0]\n\n p = lm._RegressionPlotter(y, z, y_partial=x)\n _, r_semipartial = np.corrcoef(p.x, p.y)[0]\n assert r_semipartial < r_orig\n\n p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)\n _, r_partial = np.corrcoef(p.x, p.y)[0]\n assert r_partial < r_orig\n\n x = pd.Series(x)\n y = pd.Series(y)\n p = lm._RegressionPlotter(y, z, x_partial=x, y_partial=x)\n _, r_partial = np.corrcoef(p.x, p.y)[0]\n assert r_partial < r_orig"},{"col":4,"comment":"null","endLoc":397,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_regression(self)","id":4339,"name":"test_logistic_regression","nodeType":"Function","startLoc":390,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"c\", data=self.df,\n logistic=True, n_boot=self.n_boot)\n _, yhat, _ = p.fit_regression(x_range=(-3, 3))\n npt.assert_array_less(yhat, 1)\n npt.assert_array_less(0, yhat)"},{"col":4,"comment":"null","endLoc":167,"header":"def test_positional_data_x(self, long_df)","id":4340,"name":"test_positional_data_x","nodeType":"Function","startLoc":163,"text":"def test_positional_data_x(self, long_df):\n\n p = Plot(long_df, \"a\")\n assert p._data.source_data is long_df\n assert list(p._data.source_vars) == [\"x\"]"},{"col":4,"comment":"null","endLoc":173,"header":"def test_positional_x(self, long_df)","id":4341,"name":"test_positional_x","nodeType":"Function","startLoc":169,"text":"def test_positional_x(self, long_df):\n\n p = Plot(long_df[\"a\"])\n assert p._data.source_data is None\n assert list(p._data.source_vars) == [\"x\"]"},{"attributeType":"str","col":8,"comment":"null","endLoc":29,"id":4342,"name":"title","nodeType":"Attribute","startLoc":29,"text":"title"},{"col":0,"comment":"","endLoc":6,"header":"pairgrid_dotplot.py#","id":4343,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nDot plot with several variables\n===============================\n\n_thumb: .3, .3\n\"\"\"\n\nsns.set_theme(style=\"whitegrid\")\n\ncrashes = sns.load_dataset(\"car_crashes\")\n\ng = sns.PairGrid(crashes.sort_values(\"total\", ascending=False),\n x_vars=crashes.columns[:-3], y_vars=[\"abbrev\"],\n height=10, aspect=.25)\n\ng.map(sns.stripplot, size=10, orient=\"h\", jitter=False,\n palette=\"flare_r\", linewidth=1, edgecolor=\"w\")\n\ng.set(xlim=(0, 25), xlabel=\"Crashes\", ylabel=\"\")\n\ntitles = [\"Total crashes\", \"Speeding crashes\", \"Alcohol crashes\",\n \"Not distracted crashes\", \"No previous crashes\"]\n\nfor ax, title in zip(g.axes.flat, titles):\n\n # Set a different title for each axes\n ax.set(title=title)\n\n # Make the grid horizontal instead of vertical\n ax.xaxis.grid(False)\n ax.yaxis.grid(True)\n\nsns.despine(left=True, bottom=True)"},{"col":4,"comment":"null","endLoc":179,"header":"def test_positional_too_many(self, long_df)","id":4344,"name":"test_positional_too_many","nodeType":"Function","startLoc":175,"text":"def test_positional_too_many(self, long_df):\n\n err = r\"Plot\\(\\) accepts no more than 3 positional arguments \\(data, x, y\\)\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, \"x\", \"y\", \"z\")"},{"col":4,"comment":"null","endLoc":185,"header":"def test_unknown_keywords(self, long_df)","id":4345,"name":"test_unknown_keywords","nodeType":"Function","startLoc":181,"text":"def test_unknown_keywords(self, long_df):\n\n err = r\"Plot\\(\\) got unexpected keyword argument\\(s\\): bad\"\n with pytest.raises(TypeError, match=err):\n Plot(long_df, bad=\"x\")"},{"className":"TestLayerAddition","col":0,"comment":"null","endLoc":329,"id":4346,"nodeType":"Class","startLoc":188,"text":"class TestLayerAddition:\n\n def test_without_data(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark()).plot()\n layer, = p._layers\n assert_frame_equal(p._data.frame, layer[\"data\"].frame, check_dtype=False)\n\n def test_with_new_variable_by_name(self, long_df):\n\n p = Plot(long_df, x=\"x\").add(MockMark(), y=\"y\").plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])\n\n def test_with_new_variable_by_vector(self, long_df):\n\n p = Plot(long_df, x=\"x\").add(MockMark(), y=long_df[\"y\"]).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])\n\n def test_with_late_data_definition(self, long_df):\n\n p = Plot().add(MockMark(), data=long_df, x=\"x\", y=\"y\").plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])\n\n def test_with_new_data_definition(self, long_df):\n\n long_df_sub = long_df.sample(frac=.5)\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark(), data=long_df_sub).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(\n layer[\"data\"].frame[var], long_df_sub[var].reindex(long_df.index)\n )\n\n def test_drop_variable(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark(), y=None).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\"]\n assert_vector_equal(layer[\"data\"].frame[\"x\"], long_df[\"x\"], check_dtype=False)\n\n @pytest.mark.xfail(reason=\"Need decision on default stat\")\n def test_stat_default(self):\n\n class MarkWithDefaultStat(Mark):\n default_stat = Stat\n\n p = Plot().add(MarkWithDefaultStat())\n layer, = p._layers\n assert layer[\"stat\"].__class__ is Stat\n\n def test_stat_nondefault(self):\n\n class MarkWithDefaultStat(Mark):\n default_stat = Stat\n\n class OtherMockStat(Stat):\n pass\n\n p = Plot().add(MarkWithDefaultStat(), OtherMockStat())\n layer, = p._layers\n assert layer[\"stat\"].__class__ is OtherMockStat\n\n @pytest.mark.parametrize(\n \"arg,expected\",\n [(\"x\", \"x\"), (\"y\", \"y\"), (\"v\", \"x\"), (\"h\", \"y\")],\n )\n def test_orient(self, arg, expected):\n\n class MockStatTrackOrient(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.orient_at_call = orient\n return data\n\n class MockMoveTrackOrient(Move):\n def __call__(self, data, groupby, orient, scales):\n self.orient_at_call = orient\n return data\n\n s = MockStatTrackOrient()\n m = MockMoveTrackOrient()\n Plot(x=[1, 2, 3], y=[1, 2, 3]).add(MockMark(), s, m, orient=arg).plot()\n\n assert s.orient_at_call == expected\n assert m.orient_at_call == expected\n\n def test_variable_list(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\")\n assert p._variables == [\"x\", \"y\"]\n\n p = Plot(long_df).add(MockMark(), x=\"x\", y=\"y\")\n assert p._variables == [\"x\", \"y\"]\n\n p = Plot(long_df, y=\"x\", color=\"a\").add(MockMark(), x=\"y\")\n assert p._variables == [\"y\", \"color\", \"x\"]\n\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(MockMark(), color=None)\n assert p._variables == [\"x\", \"y\", \"color\"]\n\n p = (\n Plot(long_df, x=\"x\", y=\"y\")\n .add(MockMark(), color=\"a\")\n .add(MockMark(), alpha=\"s\")\n )\n assert p._variables == [\"x\", \"y\", \"color\", \"alpha\"]\n\n p = Plot(long_df, y=\"x\").pair(x=[\"a\", \"b\"])\n assert p._variables == [\"y\", \"x0\", \"x1\"]\n\n def test_type_checks(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=\"mark must be a Mark instance\"):\n p.add(MockMark)\n\n class MockStat(Stat):\n pass\n\n class MockMove(Move):\n pass\n\n err = \"Transforms must have at most one Stat type\"\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockStat)\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockMove(), MockStat())\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockMark(), MockStat())"},{"col":4,"comment":"null","endLoc":194,"header":"def test_without_data(self, long_df)","id":4347,"name":"test_without_data","nodeType":"Function","startLoc":190,"text":"def test_without_data(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark()).plot()\n layer, = p._layers\n assert_frame_equal(p._data.frame, layer[\"data\"].frame, check_dtype=False)"},{"col":4,"comment":"null","endLoc":202,"header":"def test_with_new_variable_by_name(self, long_df)","id":4348,"name":"test_with_new_variable_by_name","nodeType":"Function","startLoc":196,"text":"def test_with_new_variable_by_name(self, long_df):\n\n p = Plot(long_df, x=\"x\").add(MockMark(), y=\"y\").plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])"},{"col":4,"comment":"null","endLoc":408,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_perfect_separation(self)","id":4349,"name":"test_logistic_perfect_separation","nodeType":"Function","startLoc":399,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_logistic_perfect_separation(self):\n\n y = self.df.x > self.df.x.mean()\n p = lm._RegressionPlotter(\"x\", y, data=self.df,\n logistic=True, n_boot=10)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n _, yhat, _ = p.fit_regression(x_range=(-3, 3))\n assert np.isnan(yhat).all()"},{"col":4,"comment":"null","endLoc":210,"header":"def test_with_new_variable_by_vector(self, long_df)","id":4350,"name":"test_with_new_variable_by_vector","nodeType":"Function","startLoc":204,"text":"def test_with_new_variable_by_vector(self, long_df):\n\n p = Plot(long_df, x=\"x\").add(MockMark(), y=long_df[\"y\"]).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])"},{"col":4,"comment":"null","endLoc":218,"header":"def test_with_late_data_definition(self, long_df)","id":4353,"name":"test_with_late_data_definition","nodeType":"Function","startLoc":212,"text":"def test_with_late_data_definition(self, long_df):\n\n p = Plot().add(MockMark(), data=long_df, x=\"x\", y=\"y\").plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(layer[\"data\"].frame[var], long_df[var])"},{"col":4,"comment":"null","endLoc":186,"header":"@property\n def dirname(self)","id":4354,"name":"dirname","nodeType":"Function","startLoc":184,"text":"@property\n def dirname(self):\n return op.split(self.filename)[0]"},{"col":4,"comment":"null","endLoc":190,"header":"@property\n def fname(self)","id":4355,"name":"fname","nodeType":"Function","startLoc":188,"text":"@property\n def fname(self):\n return op.split(self.filename)[1]"},{"col":4,"comment":"null","endLoc":230,"header":"def test_with_new_data_definition(self, long_df)","id":4356,"name":"test_with_new_data_definition","nodeType":"Function","startLoc":220,"text":"def test_with_new_data_definition(self, long_df):\n\n long_df_sub = long_df.sample(frac=.5)\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark(), data=long_df_sub).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\", \"y\"]\n for var in \"xy\":\n assert_vector_equal(\n layer[\"data\"].frame[var], long_df_sub[var].reindex(long_df.index)\n )"},{"col":4,"comment":"null","endLoc":194,"header":"@property\n def modulename(self)","id":4357,"name":"modulename","nodeType":"Function","startLoc":192,"text":"@property\n def modulename(self):\n return op.splitext(self.fname)[0]"},{"col":4,"comment":"null","endLoc":198,"header":"@property\n def pyfilename(self)","id":4358,"name":"pyfilename","nodeType":"Function","startLoc":196,"text":"@property\n def pyfilename(self):\n return self.modulename + '.py'"},{"col":4,"comment":"null","endLoc":202,"header":"@property\n def rstfilename(self)","id":4359,"name":"rstfilename","nodeType":"Function","startLoc":200,"text":"@property\n def rstfilename(self):\n return self.modulename + \".rst\""},{"col":4,"comment":"null","endLoc":206,"header":"@property\n def htmlfilename(self)","id":4360,"name":"htmlfilename","nodeType":"Function","startLoc":204,"text":"@property\n def htmlfilename(self):\n return self.modulename + '.html'"},{"col":4,"comment":"null","endLoc":211,"header":"@property\n def pngfilename(self)","id":4361,"name":"pngfilename","nodeType":"Function","startLoc":208,"text":"@property\n def pngfilename(self):\n pngfile = self.modulename + '.png'\n return \"_images/\" + pngfile"},{"col":4,"comment":"null","endLoc":216,"header":"@property\n def thumbfilename(self)","id":4362,"name":"thumbfilename","nodeType":"Function","startLoc":213,"text":"@property\n def thumbfilename(self):\n pngfile = self.modulename + '_thumb.png'\n return pngfile"},{"col":4,"comment":"null","endLoc":220,"header":"@property\n def sphinxtag(self)","id":4363,"name":"sphinxtag","nodeType":"Function","startLoc":218,"text":"@property\n def sphinxtag(self):\n return self.modulename"},{"col":4,"comment":"null","endLoc":224,"header":"@property\n def pagetitle(self)","id":4364,"name":"pagetitle","nodeType":"Function","startLoc":222,"text":"@property\n def pagetitle(self):\n return self.docstring.strip().split('\\n')[0].strip()"},{"col":4,"comment":"null","endLoc":237,"header":"@property\n def plotfunc(self)","id":4365,"name":"plotfunc","nodeType":"Function","startLoc":226,"text":"@property\n def plotfunc(self):\n match = re.search(r\"sns\\.(.+plot)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+map)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+Grid)\\(\", self.filetext)\n if match:\n return match.group(1)\n return \"\""},{"col":4,"comment":"null","endLoc":237,"header":"def test_drop_variable(self, long_df)","id":4368,"name":"test_drop_variable","nodeType":"Function","startLoc":232,"text":"def test_drop_variable(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\").add(MockMark(), y=None).plot()\n layer, = p._layers\n assert layer[\"data\"].frame.columns.to_list() == [\"x\"]\n assert_vector_equal(layer[\"data\"].frame[\"x\"], long_df[\"x\"], check_dtype=False)"},{"col":4,"comment":"null","endLoc":247,"header":"@pytest.mark.xfail(reason=\"Need decision on default stat\")\n def test_stat_default(self)","id":4369,"name":"test_stat_default","nodeType":"Function","startLoc":239,"text":"@pytest.mark.xfail(reason=\"Need decision on default stat\")\n def test_stat_default(self):\n\n class MarkWithDefaultStat(Mark):\n default_stat = Stat\n\n p = Plot().add(MarkWithDefaultStat())\n layer, = p._layers\n assert layer[\"stat\"].__class__ is Stat"},{"col":4,"comment":"null","endLoc":259,"header":"def test_stat_nondefault(self)","id":4370,"name":"test_stat_nondefault","nodeType":"Function","startLoc":249,"text":"def test_stat_nondefault(self):\n\n class MarkWithDefaultStat(Mark):\n default_stat = Stat\n\n class OtherMockStat(Stat):\n pass\n\n p = Plot().add(MarkWithDefaultStat(), OtherMockStat())\n layer, = p._layers\n assert layer[\"stat\"].__class__ is OtherMockStat"},{"col":4,"comment":"null","endLoc":282,"header":"@pytest.mark.parametrize(\n \"arg,expected\",\n [(\"x\", \"x\"), (\"y\", \"y\"), (\"v\", \"x\"), (\"h\", \"y\")],\n )\n def test_orient(self, arg, expected)","id":4371,"name":"test_orient","nodeType":"Function","startLoc":261,"text":"@pytest.mark.parametrize(\n \"arg,expected\",\n [(\"x\", \"x\"), (\"y\", \"y\"), (\"v\", \"x\"), (\"h\", \"y\")],\n )\n def test_orient(self, arg, expected):\n\n class MockStatTrackOrient(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.orient_at_call = orient\n return data\n\n class MockMoveTrackOrient(Move):\n def __call__(self, data, groupby, orient, scales):\n self.orient_at_call = orient\n return data\n\n s = MockStatTrackOrient()\n m = MockMoveTrackOrient()\n Plot(x=[1, 2, 3], y=[1, 2, 3]).add(MockMark(), s, m, orient=arg).plot()\n\n assert s.orient_at_call == expected\n assert m.orient_at_call == expected"},{"col":4,"comment":"null","endLoc":306,"header":"def test_variable_list(self, long_df)","id":4372,"name":"test_variable_list","nodeType":"Function","startLoc":284,"text":"def test_variable_list(self, long_df):\n\n p = Plot(long_df, x=\"x\", y=\"y\")\n assert p._variables == [\"x\", \"y\"]\n\n p = Plot(long_df).add(MockMark(), x=\"x\", y=\"y\")\n assert p._variables == [\"x\", \"y\"]\n\n p = Plot(long_df, y=\"x\", color=\"a\").add(MockMark(), x=\"y\")\n assert p._variables == [\"y\", \"color\", \"x\"]\n\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(MockMark(), color=None)\n assert p._variables == [\"x\", \"y\", \"color\"]\n\n p = (\n Plot(long_df, x=\"x\", y=\"y\")\n .add(MockMark(), color=\"a\")\n .add(MockMark(), alpha=\"s\")\n )\n assert p._variables == [\"x\", \"y\", \"color\", \"alpha\"]\n\n p = Plot(long_df, y=\"x\").pair(x=[\"a\", \"b\"])\n assert p._variables == [\"y\", \"x0\", \"x1\"]"},{"col":4,"comment":"null","endLoc":250,"header":"@property\n def components(self)","id":4373,"name":"components","nodeType":"Function","startLoc":239,"text":"@property\n def components(self):\n\n objects = re.findall(r\"sns\\.(\\w+)\\(\", self.filetext)\n\n refs = []\n for obj in objects:\n if obj[0].isupper():\n refs.append(f\":class:`{obj}`\")\n else:\n refs.append(f\":func:`{obj}`\")\n return \", \".join(refs)"},{"col":4,"comment":"null","endLoc":314,"header":"def toctree_entry(self)","id":4374,"name":"toctree_entry","nodeType":"Function","startLoc":313,"text":"def toctree_entry(self):\n return f\" ./{op.splitext(self.htmlfilename)[0]}\\n\\n\""},{"col":4,"comment":"null","endLoc":329,"header":"def contents_entry(self)","id":4375,"name":"contents_entry","nodeType":"Function","startLoc":316,"text":"def contents_entry(self):\n return (\".. raw:: html\\n\\n\"\n \" \\n\\n\"\n \"\\n\\n\"\n \"\".format(self.htmlfilename,\n self.thumbfilename,\n self.plotfunc))"},{"fileName":"docscrape.py","filePath":"seaborn/external","id":4376,"nodeType":"File","text":"\"\"\"Extract reference documentation from the NumPy source tree.\n\nCopyright (C) 2008 Stefan van der Walt , Pauli Virtanen \n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the\n distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nimport inspect\nimport textwrap\nimport re\nimport pydoc\nfrom warnings import warn\nfrom collections import namedtuple\nfrom collections.abc import Callable, Mapping\nimport copy\nimport sys\n\n\ndef strip_blank_lines(l):\n \"Remove leading and trailing blank lines from a list of lines\"\n while l and not l[0].strip():\n del l[0]\n while l and not l[-1].strip():\n del l[-1]\n return l\n\n\nclass Reader:\n \"\"\"A line-based string reader.\n\n \"\"\"\n def __init__(self, data):\n \"\"\"\n Parameters\n ----------\n data : str\n String with lines separated by '\\n'.\n\n \"\"\"\n if isinstance(data, list):\n self._str = data\n else:\n self._str = data.split('\\n') # store string as list of lines\n\n self.reset()\n\n def __getitem__(self, n):\n return self._str[n]\n\n def reset(self):\n self._l = 0 # current line nr\n\n def read(self):\n if not self.eof():\n out = self[self._l]\n self._l += 1\n return out\n else:\n return ''\n\n def seek_next_non_empty_line(self):\n for l in self[self._l:]:\n if l.strip():\n break\n else:\n self._l += 1\n\n def eof(self):\n return self._l >= len(self._str)\n\n def read_to_condition(self, condition_func):\n start = self._l\n for line in self[start:]:\n if condition_func(line):\n return self[start:self._l]\n self._l += 1\n if self.eof():\n return self[start:self._l+1]\n return []\n\n def read_to_next_empty_line(self):\n self.seek_next_non_empty_line()\n\n def is_empty(line):\n return not line.strip()\n\n return self.read_to_condition(is_empty)\n\n def read_to_next_unindented_line(self):\n def is_unindented(line):\n return (line.strip() and (len(line.lstrip()) == len(line)))\n return self.read_to_condition(is_unindented)\n\n def peek(self, n=0):\n if self._l + n < len(self._str):\n return self[self._l + n]\n else:\n return ''\n\n def is_empty(self):\n return not ''.join(self._str).strip()\n\n\nclass ParseError(Exception):\n def __str__(self):\n message = self.args[0]\n if hasattr(self, 'docstring'):\n message = f\"{message} in {self.docstring!r}\"\n return message\n\n\nParameter = namedtuple('Parameter', ['name', 'type', 'desc'])\n\n\nclass NumpyDocString(Mapping):\n \"\"\"Parses a numpydoc string to an abstract representation\n\n Instances define a mapping from section title to structured data.\n\n \"\"\"\n\n sections = {\n 'Signature': '',\n 'Summary': [''],\n 'Extended Summary': [],\n 'Parameters': [],\n 'Returns': [],\n 'Yields': [],\n 'Receives': [],\n 'Raises': [],\n 'Warns': [],\n 'Other Parameters': [],\n 'Attributes': [],\n 'Methods': [],\n 'See Also': [],\n 'Notes': [],\n 'Warnings': [],\n 'References': '',\n 'Examples': '',\n 'index': {}\n }\n\n def __init__(self, docstring, config={}):\n orig_docstring = docstring\n docstring = textwrap.dedent(docstring).split('\\n')\n\n self._doc = Reader(docstring)\n self._parsed_data = copy.deepcopy(self.sections)\n\n try:\n self._parse()\n except ParseError as e:\n e.docstring = orig_docstring\n raise\n\n def __getitem__(self, key):\n return self._parsed_data[key]\n\n def __setitem__(self, key, val):\n if key not in self._parsed_data:\n self._error_location(f\"Unknown section {key}\", error=False)\n else:\n self._parsed_data[key] = val\n\n def __iter__(self):\n return iter(self._parsed_data)\n\n def __len__(self):\n return len(self._parsed_data)\n\n def _is_at_section(self):\n self._doc.seek_next_non_empty_line()\n\n if self._doc.eof():\n return False\n\n l1 = self._doc.peek().strip() # e.g. Parameters\n\n if l1.startswith('.. index::'):\n return True\n\n l2 = self._doc.peek(1).strip() # ---------- or ==========\n return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))\n\n def _strip(self, doc):\n i = 0\n j = 0\n for i, line in enumerate(doc):\n if line.strip():\n break\n\n for j, line in enumerate(doc[::-1]):\n if line.strip():\n break\n\n return doc[i:len(doc)-j]\n\n def _read_to_next_section(self):\n section = self._doc.read_to_next_empty_line()\n\n while not self._is_at_section() and not self._doc.eof():\n if not self._doc.peek(-1).strip(): # previous line was empty\n section += ['']\n\n section += self._doc.read_to_next_empty_line()\n\n return section\n\n def _read_sections(self):\n while not self._doc.eof():\n data = self._read_to_next_section()\n name = data[0].strip()\n\n if name.startswith('..'): # index section\n yield name, data[1:]\n elif len(data) < 2:\n yield StopIteration\n else:\n yield name, self._strip(data[2:])\n\n def _parse_param_list(self, content, single_element_is_type=False):\n r = Reader(content)\n params = []\n while not r.eof():\n header = r.read().strip()\n if ' : ' in header:\n arg_name, arg_type = header.split(' : ')[:2]\n else:\n if single_element_is_type:\n arg_name, arg_type = '', header\n else:\n arg_name, arg_type = header, ''\n\n desc = r.read_to_next_unindented_line()\n desc = dedent_lines(desc)\n desc = strip_blank_lines(desc)\n\n params.append(Parameter(arg_name, arg_type, desc))\n\n return params\n\n # See also supports the following formats.\n #\n # \n # SPACE* COLON SPACE+ SPACE*\n # ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE*\n # ( COMMA SPACE+ )* SPACE* COLON SPACE+ SPACE*\n\n # is one of\n # \n # COLON COLON BACKTICK BACKTICK\n # where\n # is a legal function name, and\n # is any nonempty sequence of word characters.\n # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`\n # is a string describing the function.\n\n _role = r\":(?P\\w+):\"\n _funcbacktick = r\"`(?P(?:~\\w+\\.)?[a-zA-Z0-9_\\.-]+)`\"\n _funcplain = r\"(?P[a-zA-Z0-9_\\.-]+)\"\n _funcname = r\"(\" + _role + _funcbacktick + r\"|\" + _funcplain + r\")\"\n _funcnamenext = _funcname.replace('role', 'rolenext')\n _funcnamenext = _funcnamenext.replace('name', 'namenext')\n _description = r\"(?P\\s*:(\\s+(?P\\S+.*))?)?\\s*$\"\n _func_rgx = re.compile(r\"^\\s*\" + _funcname + r\"\\s*\")\n _line_rgx = re.compile(\n r\"^\\s*\" +\n r\"(?P\" + # group for all function names\n _funcname +\n r\"(?P([,]\\s+\" + _funcnamenext + r\")*)\" +\n r\")\" + # end of \"allfuncs\"\n r\"(?P[,\\.])?\" + # Some function lists have a trailing comma (or period) '\\s*'\n _description)\n\n # Empty elements are replaced with '..'\n empty_description = '..'\n\n def _parse_see_also(self, content):\n \"\"\"\n func_name : Descriptive text\n continued text\n another_func_name : Descriptive text\n func_name1, func_name2, :meth:`func_name`, func_name3\n\n \"\"\"\n\n items = []\n\n def parse_item_name(text):\n \"\"\"Match ':role:`name`' or 'name'.\"\"\"\n m = self._func_rgx.match(text)\n if not m:\n raise ParseError(f\"{text} is not a item name\")\n role = m.group('role')\n name = m.group('name') if role else m.group('name2')\n return name, role, m.end()\n\n rest = []\n for line in content:\n if not line.strip():\n continue\n\n line_match = self._line_rgx.match(line)\n description = None\n if line_match:\n description = line_match.group('desc')\n if line_match.group('trailing') and description:\n self._error_location(\n 'Unexpected comma or period after function list at index %d of '\n 'line \"%s\"' % (line_match.end('trailing'), line),\n error=False)\n if not description and line.startswith(' '):\n rest.append(line.strip())\n elif line_match:\n funcs = []\n text = line_match.group('allfuncs')\n while True:\n if not text.strip():\n break\n name, role, match_end = parse_item_name(text)\n funcs.append((name, role))\n text = text[match_end:].strip()\n if text and text[0] == ',':\n text = text[1:].strip()\n rest = list(filter(None, [description]))\n items.append((funcs, rest))\n else:\n raise ParseError(f\"{line} is not a item name\")\n return items\n\n def _parse_index(self, section, content):\n \"\"\"\n .. index: default\n :refguide: something, else, and more\n\n \"\"\"\n def strip_each_in(lst):\n return [s.strip() for s in lst]\n\n out = {}\n section = section.split('::')\n if len(section) > 1:\n out['default'] = strip_each_in(section[1].split(','))[0]\n for line in content:\n line = line.split(':')\n if len(line) > 2:\n out[line[1]] = strip_each_in(line[2].split(','))\n return out\n\n def _parse_summary(self):\n \"\"\"Grab signature (if given) and summary\"\"\"\n if self._is_at_section():\n return\n\n # If several signatures present, take the last one\n while True:\n summary = self._doc.read_to_next_empty_line()\n summary_str = \" \".join([s.strip() for s in summary]).strip()\n compiled = re.compile(r'^([\\w., ]+=)?\\s*[\\w\\.]+\\(.*\\)$')\n if compiled.match(summary_str):\n self['Signature'] = summary_str\n if not self._is_at_section():\n continue\n break\n\n if summary is not None:\n self['Summary'] = summary\n\n if not self._is_at_section():\n self['Extended Summary'] = self._read_to_next_section()\n\n def _parse(self):\n self._doc.reset()\n self._parse_summary()\n\n sections = list(self._read_sections())\n section_names = {section for section, content in sections}\n\n has_returns = 'Returns' in section_names\n has_yields = 'Yields' in section_names\n # We could do more tests, but we are not. Arbitrarily.\n if has_returns and has_yields:\n msg = 'Docstring contains both a Returns and Yields section.'\n raise ValueError(msg)\n if not has_yields and 'Receives' in section_names:\n msg = 'Docstring contains a Receives section but not Yields.'\n raise ValueError(msg)\n\n for (section, content) in sections:\n if not section.startswith('..'):\n section = (s.capitalize() for s in section.split(' '))\n section = ' '.join(section)\n if self.get(section):\n self._error_location(f\"The section {section} appears twice\")\n\n if section in ('Parameters', 'Other Parameters', 'Attributes',\n 'Methods'):\n self[section] = self._parse_param_list(content)\n elif section in ('Returns', 'Yields', 'Raises', 'Warns', 'Receives'):\n self[section] = self._parse_param_list(\n content, single_element_is_type=True)\n elif section.startswith('.. index::'):\n self['index'] = self._parse_index(section, content)\n elif section == 'See Also':\n self['See Also'] = self._parse_see_also(content)\n else:\n self[section] = content\n\n def _error_location(self, msg, error=True):\n if hasattr(self, '_obj'):\n # we know where the docs came from:\n try:\n filename = inspect.getsourcefile(self._obj)\n except TypeError:\n filename = None\n msg = msg + f\" in the docstring of {self._obj} in {filename}.\"\n if error:\n raise ValueError(msg)\n else:\n warn(msg)\n\n # string conversion routines\n\n def _str_header(self, name, symbol='-'):\n return [name, len(name)*symbol]\n\n def _str_indent(self, doc, indent=4):\n out = []\n for line in doc:\n out += [' '*indent + line]\n return out\n\n def _str_signature(self):\n if self['Signature']:\n return [self['Signature'].replace('*', r'\\*')] + ['']\n else:\n return ['']\n\n def _str_summary(self):\n if self['Summary']:\n return self['Summary'] + ['']\n else:\n return []\n\n def _str_extended_summary(self):\n if self['Extended Summary']:\n return self['Extended Summary'] + ['']\n else:\n return []\n\n def _str_param_list(self, name):\n out = []\n if self[name]:\n out += self._str_header(name)\n for param in self[name]:\n parts = []\n if param.name:\n parts.append(param.name)\n if param.type:\n parts.append(param.type)\n out += [' : '.join(parts)]\n if param.desc and ''.join(param.desc).strip():\n out += self._str_indent(param.desc)\n out += ['']\n return out\n\n def _str_section(self, name):\n out = []\n if self[name]:\n out += self._str_header(name)\n out += self[name]\n out += ['']\n return out\n\n def _str_see_also(self, func_role):\n if not self['See Also']:\n return []\n out = []\n out += self._str_header(\"See Also\")\n out += ['']\n last_had_desc = True\n for funcs, desc in self['See Also']:\n assert isinstance(funcs, list)\n links = []\n for func, role in funcs:\n if role:\n link = f':{role}:`{func}`'\n elif func_role:\n link = f':{func_role}:`{func}`'\n else:\n link = f\"`{func}`_\"\n links.append(link)\n link = ', '.join(links)\n out += [link]\n if desc:\n out += self._str_indent([' '.join(desc)])\n last_had_desc = True\n else:\n last_had_desc = False\n out += self._str_indent([self.empty_description])\n\n if last_had_desc:\n out += ['']\n out += ['']\n return out\n\n def _str_index(self):\n idx = self['index']\n out = []\n output_index = False\n default_index = idx.get('default', '')\n if default_index:\n output_index = True\n out += [f'.. index:: {default_index}']\n for section, references in idx.items():\n if section == 'default':\n continue\n output_index = True\n out += [f\" :{section}: {', '.join(references)}\"]\n if output_index:\n return out\n else:\n return ''\n\n def __str__(self, func_role=''):\n out = []\n out += self._str_signature()\n out += self._str_summary()\n out += self._str_extended_summary()\n for param_list in ('Parameters', 'Returns', 'Yields', 'Receives',\n 'Other Parameters', 'Raises', 'Warns'):\n out += self._str_param_list(param_list)\n out += self._str_section('Warnings')\n out += self._str_see_also(func_role)\n for s in ('Notes', 'References', 'Examples'):\n out += self._str_section(s)\n for param_list in ('Attributes', 'Methods'):\n out += self._str_param_list(param_list)\n out += self._str_index()\n return '\\n'.join(out)\n\n\ndef indent(str, indent=4):\n indent_str = ' '*indent\n if str is None:\n return indent_str\n lines = str.split('\\n')\n return '\\n'.join(indent_str + l for l in lines)\n\n\ndef dedent_lines(lines):\n \"\"\"Deindent a list of lines maximally\"\"\"\n return textwrap.dedent(\"\\n\".join(lines)).split(\"\\n\")\n\n\ndef header(text, style='-'):\n return text + '\\n' + style*len(text) + '\\n'\n\n\nclass FunctionDoc(NumpyDocString):\n def __init__(self, func, role='func', doc=None, config={}):\n self._f = func\n self._role = role # e.g. \"func\" or \"meth\"\n\n if doc is None:\n if func is None:\n raise ValueError(\"No function or docstring given\")\n doc = inspect.getdoc(func) or ''\n NumpyDocString.__init__(self, doc, config)\n\n if not self['Signature'] and func is not None:\n func, func_name = self.get_func()\n try:\n try:\n signature = str(inspect.signature(func))\n except (AttributeError, ValueError):\n # try to read signature, backward compat for older Python\n if sys.version_info[0] >= 3:\n argspec = inspect.getfullargspec(func)\n else:\n argspec = inspect.getargspec(func)\n signature = inspect.formatargspec(*argspec)\n signature = f'{func_name}{signature}'\n except TypeError:\n signature = f'{func_name}()'\n self['Signature'] = signature\n\n def get_func(self):\n func_name = getattr(self._f, '__name__', self.__class__.__name__)\n if inspect.isclass(self._f):\n func = getattr(self._f, '__call__', self._f.__init__)\n else:\n func = self._f\n return func, func_name\n\n def __str__(self):\n out = ''\n\n func, func_name = self.get_func()\n\n roles = {'func': 'function',\n 'meth': 'method'}\n\n if self._role:\n if self._role not in roles:\n print(f\"Warning: invalid role {self._role}\")\n out += f\".. {roles.get(self._role, '')}:: {func_name}\\n \\n\\n\"\n\n out += super().__str__(func_role=self._role)\n return out\n\n\nclass ClassDoc(NumpyDocString):\n\n extra_public_methods = ['__call__']\n\n def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,\n config={}):\n if not inspect.isclass(cls) and cls is not None:\n raise ValueError(f\"Expected a class or None, but got {cls!r}\")\n self._cls = cls\n\n if 'sphinx' in sys.modules:\n from sphinx.ext.autodoc import ALL\n else:\n ALL = object()\n\n self.show_inherited_members = config.get(\n 'show_inherited_class_members', True)\n\n if modulename and not modulename.endswith('.'):\n modulename += '.'\n self._mod = modulename\n\n if doc is None:\n if cls is None:\n raise ValueError(\"No class or documentation string given\")\n doc = pydoc.getdoc(cls)\n\n NumpyDocString.__init__(self, doc)\n\n _members = config.get('members', [])\n if _members is ALL:\n _members = None\n _exclude = config.get('exclude-members', [])\n\n if config.get('show_class_members', True) and _exclude is not ALL:\n def splitlines_x(s):\n if not s:\n return []\n else:\n return s.splitlines()\n for field, items in [('Methods', self.methods),\n ('Attributes', self.properties)]:\n if not self[field]:\n doc_list = []\n for name in sorted(items):\n if (name in _exclude or\n (_members and name not in _members)):\n continue\n try:\n doc_item = pydoc.getdoc(getattr(self._cls, name))\n doc_list.append(\n Parameter(name, '', splitlines_x(doc_item)))\n except AttributeError:\n pass # method doesn't exist\n self[field] = doc_list\n\n @property\n def methods(self):\n if self._cls is None:\n return []\n return [name for name, func in inspect.getmembers(self._cls)\n if ((not name.startswith('_')\n or name in self.extra_public_methods)\n and isinstance(func, Callable)\n and self._is_show_member(name))]\n\n @property\n def properties(self):\n if self._cls is None:\n return []\n return [name for name, func in inspect.getmembers(self._cls)\n if (not name.startswith('_') and\n (func is None or isinstance(func, property) or\n inspect.isdatadescriptor(func))\n and self._is_show_member(name))]\n\n def _is_show_member(self, name):\n if self.show_inherited_members:\n return True # show all class members\n if name not in self._cls.__dict__:\n return False # class member is inherited, we do not show it\n return True\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":4377,"name":"mpg","nodeType":"Attribute","startLoc":12,"text":"mpg"},{"attributeType":"null","col":8,"comment":"null","endLoc":167,"id":4378,"name":"filename","nodeType":"Attribute","startLoc":167,"text":"self.filename"},{"attributeType":"LiteralString | str","col":8,"comment":"null","endLoc":291,"id":4379,"name":"docstring","nodeType":"Attribute","startLoc":291,"text":"self.docstring"},{"attributeType":"null","col":8,"comment":"null","endLoc":168,"id":4380,"name":"target_dir","nodeType":"Attribute","startLoc":168,"text":"self.target_dir"},{"col":0,"comment":"","endLoc":7,"header":"scatter_bubbles.py#","id":4381,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nScatterplot with varying point sizes and hues\n==============================================\n\n_thumb: .45, .5\n\n\"\"\"\n\nsns.set_theme(style=\"white\")\n\nmpg = sns.load_dataset(\"mpg\")\n\nsns.relplot(x=\"horsepower\", y=\"mpg\", hue=\"origin\", size=\"weight\",\n sizes=(40, 400), alpha=.5, palette=\"muted\",\n height=6, data=mpg)"},{"className":"Reader","col":0,"comment":"A line-based string reader.\n\n ","endLoc":122,"id":4382,"nodeType":"Class","startLoc":49,"text":"class Reader:\n \"\"\"A line-based string reader.\n\n \"\"\"\n def __init__(self, data):\n \"\"\"\n Parameters\n ----------\n data : str\n String with lines separated by '\\n'.\n\n \"\"\"\n if isinstance(data, list):\n self._str = data\n else:\n self._str = data.split('\\n') # store string as list of lines\n\n self.reset()\n\n def __getitem__(self, n):\n return self._str[n]\n\n def reset(self):\n self._l = 0 # current line nr\n\n def read(self):\n if not self.eof():\n out = self[self._l]\n self._l += 1\n return out\n else:\n return ''\n\n def seek_next_non_empty_line(self):\n for l in self[self._l:]:\n if l.strip():\n break\n else:\n self._l += 1\n\n def eof(self):\n return self._l >= len(self._str)\n\n def read_to_condition(self, condition_func):\n start = self._l\n for line in self[start:]:\n if condition_func(line):\n return self[start:self._l]\n self._l += 1\n if self.eof():\n return self[start:self._l+1]\n return []\n\n def read_to_next_empty_line(self):\n self.seek_next_non_empty_line()\n\n def is_empty(line):\n return not line.strip()\n\n return self.read_to_condition(is_empty)\n\n def read_to_next_unindented_line(self):\n def is_unindented(line):\n return (line.strip() and (len(line.lstrip()) == len(line)))\n return self.read_to_condition(is_unindented)\n\n def peek(self, n=0):\n if self._l + n < len(self._str):\n return self[self._l + n]\n else:\n return ''\n\n def is_empty(self):\n return not ''.join(self._str).strip()"},{"col":4,"comment":"null","endLoc":69,"header":"def __getitem__(self, n)","id":4383,"name":"__getitem__","nodeType":"Function","startLoc":68,"text":"def __getitem__(self, n):\n return self._str[n]"},{"col":4,"comment":"null","endLoc":80,"header":"def read(self)","id":4384,"name":"read","nodeType":"Function","startLoc":74,"text":"def read(self):\n if not self.eof():\n out = self[self._l]\n self._l += 1\n return out\n else:\n return ''"},{"col":4,"comment":"null","endLoc":90,"header":"def eof(self)","id":4385,"name":"eof","nodeType":"Function","startLoc":89,"text":"def eof(self):\n return self._l >= len(self._str)"},{"col":4,"comment":"null","endLoc":87,"header":"def seek_next_non_empty_line(self)","id":4386,"name":"seek_next_non_empty_line","nodeType":"Function","startLoc":82,"text":"def seek_next_non_empty_line(self):\n for l in self[self._l:]:\n if l.strip():\n break\n else:\n self._l += 1"},{"attributeType":"str","col":8,"comment":"null","endLoc":307,"id":4387,"name":"html","nodeType":"Attribute","startLoc":307,"text":"self.html"},{"attributeType":"str","col":8,"comment":"null","endLoc":292,"id":4388,"name":"short_desc","nodeType":"Attribute","startLoc":292,"text":"self.short_desc"},{"attributeType":"str","col":12,"comment":"null","endLoc":172,"id":4389,"name":"filetext","nodeType":"Attribute","startLoc":172,"text":"self.filetext"},{"attributeType":"int","col":8,"comment":"null","endLoc":293,"id":4390,"name":"end_line","nodeType":"Attribute","startLoc":293,"text":"self.end_line"},{"attributeType":"(float, float)","col":8,"comment":"null","endLoc":169,"id":4391,"name":"thumbloc","nodeType":"Attribute","startLoc":169,"text":"self.thumbloc"},{"col":4,"comment":"null","endLoc":100,"header":"def read_to_condition(self, condition_func)","id":4392,"name":"read_to_condition","nodeType":"Function","startLoc":92,"text":"def read_to_condition(self, condition_func):\n start = self._l\n for line in self[start:]:\n if condition_func(line):\n return self[start:self._l]\n self._l += 1\n if self.eof():\n return self[start:self._l+1]\n return []"},{"col":4,"comment":"null","endLoc":108,"header":"def read_to_next_empty_line(self)","id":4393,"name":"read_to_next_empty_line","nodeType":"Function","startLoc":102,"text":"def read_to_next_empty_line(self):\n self.seek_next_non_empty_line()\n\n def is_empty(line):\n return not line.strip()\n\n return self.read_to_condition(is_empty)"},{"col":0,"comment":"indent a string","endLoc":161,"header":"def indent(s, N=4)","id":4394,"name":"indent","nodeType":"Function","startLoc":159,"text":"def indent(s, N=4):\n \"\"\"indent a string\"\"\"\n return s.replace('\\n', '\\n' + N * ' ')"},{"col":4,"comment":"null","endLoc":113,"header":"def read_to_next_unindented_line(self)","id":4395,"name":"read_to_next_unindented_line","nodeType":"Function","startLoc":110,"text":"def read_to_next_unindented_line(self):\n def is_unindented(line):\n return (line.strip() and (len(line.lstrip()) == len(line)))\n return self.read_to_condition(is_unindented)"},{"col":0,"comment":"null","endLoc":389,"header":"def main(app)","id":4396,"name":"main","nodeType":"Function","startLoc":332,"text":"def main(app):\n static_dir = op.join(app.builder.srcdir, '_static')\n target_dir = op.join(app.builder.srcdir, 'examples')\n image_dir = op.join(app.builder.srcdir, 'examples/_images')\n thumb_dir = op.join(app.builder.srcdir, \"example_thumbs\")\n source_dir = op.abspath(op.join(app.builder.srcdir, '..', 'examples'))\n if not op.exists(static_dir):\n os.makedirs(static_dir)\n\n if not op.exists(target_dir):\n os.makedirs(target_dir)\n\n if not op.exists(image_dir):\n os.makedirs(image_dir)\n\n if not op.exists(thumb_dir):\n os.makedirs(thumb_dir)\n\n if not op.exists(source_dir):\n os.makedirs(source_dir)\n\n banner_data = []\n\n toctree = (\"\\n\\n\"\n \".. toctree::\\n\"\n \" :hidden:\\n\\n\")\n contents = \"\\n\\n\"\n\n # Write individual example files\n for filename in sorted(glob.glob(op.join(source_dir, \"*.py\"))):\n\n ex = ExampleGenerator(filename, target_dir)\n\n banner_data.append({\"title\": ex.pagetitle,\n \"url\": op.join('examples', ex.htmlfilename),\n \"thumb\": op.join(ex.thumbfilename)})\n shutil.copyfile(filename, op.join(target_dir, ex.pyfilename))\n output = RST_TEMPLATE.format(sphinx_tag=ex.sphinxtag,\n docstring=ex.docstring,\n end_line=ex.end_line,\n components=ex.components,\n fname=ex.pyfilename,\n img_file=ex.pngfilename)\n with open(op.join(target_dir, ex.rstfilename), 'w') as f:\n f.write(output)\n\n toctree += ex.toctree_entry()\n contents += ex.contents_entry()\n\n if len(banner_data) < 10:\n banner_data = (4 * banner_data)[:10]\n\n # write index file\n index_file = op.join(target_dir, 'index.rst')\n with open(index_file, 'w') as index:\n index.write(INDEX_TEMPLATE.format(sphinx_tag=\"example_gallery\",\n toctree=toctree,\n contents=contents))"},{"col":4,"comment":"null","endLoc":119,"header":"def peek(self, n=0)","id":4397,"name":"peek","nodeType":"Function","startLoc":115,"text":"def peek(self, n=0):\n if self._l + n < len(self._str):\n return self[self._l + n]\n else:\n return ''"},{"col":4,"comment":"null","endLoc":122,"header":"def is_empty(self)","id":4398,"name":"is_empty","nodeType":"Function","startLoc":121,"text":"def is_empty(self):\n return not ''.join(self._str).strip()"},{"col":4,"comment":"null","endLoc":329,"header":"def test_type_checks(self)","id":4399,"name":"test_type_checks","nodeType":"Function","startLoc":308,"text":"def test_type_checks(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=\"mark must be a Mark instance\"):\n p.add(MockMark)\n\n class MockStat(Stat):\n pass\n\n class MockMove(Move):\n pass\n\n err = \"Transforms must have at most one Stat type\"\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockStat)\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockMove(), MockStat())\n\n with pytest.raises(TypeError, match=err):\n p.add(MockMark(), MockMark(), MockStat())"},{"attributeType":"int","col":8,"comment":"null","endLoc":72,"id":4400,"name":"_l","nodeType":"Attribute","startLoc":72,"text":"self._l"},{"attributeType":"list","col":12,"comment":"null","endLoc":64,"id":4401,"name":"_str","nodeType":"Attribute","startLoc":64,"text":"self._str"},{"className":"ParseError","col":0,"comment":"null","endLoc":130,"id":4402,"nodeType":"Class","startLoc":125,"text":"class ParseError(Exception):\n def __str__(self):\n message = self.args[0]\n if hasattr(self, 'docstring'):\n message = f\"{message} in {self.docstring!r}\"\n return message"},{"col":4,"comment":"null","endLoc":130,"header":"def __str__(self)","id":4403,"name":"__str__","nodeType":"Function","startLoc":126,"text":"def __str__(self):\n message = self.args[0]\n if hasattr(self, 'docstring'):\n message = f\"{message} in {self.docstring!r}\"\n return message"},{"className":"FunctionDoc","col":0,"comment":"null","endLoc":631,"id":4404,"nodeType":"Class","startLoc":581,"text":"class FunctionDoc(NumpyDocString):\n def __init__(self, func, role='func', doc=None, config={}):\n self._f = func\n self._role = role # e.g. \"func\" or \"meth\"\n\n if doc is None:\n if func is None:\n raise ValueError(\"No function or docstring given\")\n doc = inspect.getdoc(func) or ''\n NumpyDocString.__init__(self, doc, config)\n\n if not self['Signature'] and func is not None:\n func, func_name = self.get_func()\n try:\n try:\n signature = str(inspect.signature(func))\n except (AttributeError, ValueError):\n # try to read signature, backward compat for older Python\n if sys.version_info[0] >= 3:\n argspec = inspect.getfullargspec(func)\n else:\n argspec = inspect.getargspec(func)\n signature = inspect.formatargspec(*argspec)\n signature = f'{func_name}{signature}'\n except TypeError:\n signature = f'{func_name}()'\n self['Signature'] = signature\n\n def get_func(self):\n func_name = getattr(self._f, '__name__', self.__class__.__name__)\n if inspect.isclass(self._f):\n func = getattr(self._f, '__call__', self._f.__init__)\n else:\n func = self._f\n return func, func_name\n\n def __str__(self):\n out = ''\n\n func, func_name = self.get_func()\n\n roles = {'func': 'function',\n 'meth': 'method'}\n\n if self._role:\n if self._role not in roles:\n print(f\"Warning: invalid role {self._role}\")\n out += f\".. {roles.get(self._role, '')}:: {func_name}\\n \\n\\n\"\n\n out += super().__str__(func_role=self._role)\n return out"},{"col":4,"comment":"null","endLoc":607,"header":"def __init__(self, func, role='func', doc=None, config={})","id":4405,"name":"__init__","nodeType":"Function","startLoc":582,"text":"def __init__(self, func, role='func', doc=None, config={}):\n self._f = func\n self._role = role # e.g. \"func\" or \"meth\"\n\n if doc is None:\n if func is None:\n raise ValueError(\"No function or docstring given\")\n doc = inspect.getdoc(func) or ''\n NumpyDocString.__init__(self, doc, config)\n\n if not self['Signature'] and func is not None:\n func, func_name = self.get_func()\n try:\n try:\n signature = str(inspect.signature(func))\n except (AttributeError, ValueError):\n # try to read signature, backward compat for older Python\n if sys.version_info[0] >= 3:\n argspec = inspect.getfullargspec(func)\n else:\n argspec = inspect.getargspec(func)\n signature = inspect.formatargspec(*argspec)\n signature = f'{func_name}{signature}'\n except TypeError:\n signature = f'{func_name}()'\n self['Signature'] = signature"},{"className":"TestScaling","col":0,"comment":"null","endLoc":646,"id":4407,"nodeType":"Class","startLoc":332,"text":"class TestScaling:\n\n def test_inference(self, long_df):\n\n for col, scale_type in zip(\"zat\", [\"Continuous\", \"Nominal\", \"Temporal\"]):\n p = Plot(long_df, x=col, y=col).add(MockMark()).plot()\n for var in \"xy\":\n assert p._scales[var].__class__.__name__ == scale_type\n\n def test_inference_from_layer_data(self):\n\n p = Plot().add(MockMark(), x=[\"a\", \"b\", \"c\"]).plot()\n assert p._scales[\"x\"](\"b\") == 1\n\n def test_inference_joins(self):\n\n p = (\n Plot(y=pd.Series([1, 2, 3, 4]))\n .add(MockMark(), x=pd.Series([1, 2]))\n .add(MockMark(), x=pd.Series([\"a\", \"b\"], index=[2, 3]))\n .plot()\n )\n assert p._scales[\"x\"](\"a\") == 2\n\n def test_inferred_categorical_converter(self):\n\n p = Plot(x=[\"b\", \"c\", \"a\"]).add(MockMark()).plot()\n ax = p._figure.axes[0]\n assert ax.xaxis.convert_units(\"c\") == 1\n\n def test_explicit_categorical_converter(self):\n\n p = Plot(y=[2, 1, 3]).scale(y=Nominal()).add(MockMark()).plot()\n ax = p._figure.axes[0]\n assert ax.yaxis.convert_units(\"3\") == 2\n\n @pytest.mark.xfail(reason=\"Temporal auto-conversion not implemented\")\n def test_categorical_as_datetime(self):\n\n dates = [\"1970-01-03\", \"1970-01-02\", \"1970-01-04\"]\n p = Plot(x=dates).scale(...).add(MockMark()).plot()\n p # TODO\n ...\n\n def test_faceted_log_scale(self):\n\n p = Plot(y=[1, 10]).facet(col=[\"a\", \"b\"]).scale(y=\"log\").plot()\n for ax in p._figure.axes:\n xfm = ax.yaxis.get_transform().transform\n assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])\n\n def test_paired_single_log_scale(self):\n\n x0, x1 = [1, 2, 3], [1, 10, 100]\n p = Plot().pair(x=[x0, x1]).scale(x1=\"log\").plot()\n ax_lin, ax_log = p._figure.axes\n xfm_lin = ax_lin.xaxis.get_transform().transform\n assert_array_equal(xfm_lin([1, 10, 100]), [1, 10, 100])\n xfm_log = ax_log.xaxis.get_transform().transform\n assert_array_equal(xfm_log([1, 10, 100]), [0, 1, 2])\n\n @pytest.mark.xfail(reason=\"Custom log scale needs log name for consistency\")\n def test_log_scale_name(self):\n\n p = Plot().scale(x=\"log\").plot()\n ax = p._figure.axes[0]\n assert ax.get_xscale() == \"log\"\n assert ax.get_yscale() == \"linear\"\n\n def test_mark_data_log_transform_is_inverted(self, long_df):\n\n col = \"z\"\n m = MockMark()\n Plot(long_df, x=col).scale(x=\"log\").add(m).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[col])\n\n def test_mark_data_log_transfrom_with_stat(self, long_df):\n\n class Mean(Stat):\n group_by_orient = True\n\n def __call__(self, data, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.agg(data, {other: \"mean\"})\n\n col = \"z\"\n grouper = \"a\"\n m = MockMark()\n s = Mean()\n\n Plot(long_df, x=grouper, y=col).scale(y=\"log\").add(m, s).plot()\n\n expected = (\n long_df[col]\n .pipe(np.log)\n .groupby(long_df[grouper], sort=False)\n .mean()\n .pipe(np.exp)\n .reset_index(drop=True)\n )\n assert_vector_equal(m.passed_data[0][\"y\"], expected)\n\n def test_mark_data_from_categorical(self, long_df):\n\n col = \"a\"\n m = MockMark()\n Plot(long_df, x=col).add(m).plot()\n\n levels = categorical_order(long_df[col])\n level_map = {x: float(i) for i, x in enumerate(levels)}\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[col].map(level_map))\n\n def test_mark_data_from_datetime(self, long_df):\n\n col = \"t\"\n m = MockMark()\n Plot(long_df, x=col).add(m).plot()\n\n expected = long_df[col].map(mpl.dates.date2num)\n if Version(mpl.__version__) < Version(\"3.3\"):\n expected = expected + mpl.dates.date2num(np.datetime64('0000-12-31'))\n\n assert_vector_equal(m.passed_data[0][\"x\"], expected)\n\n def test_computed_var_ticks(self, long_df):\n\n class Identity(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient]})\n\n tick_locs = [1, 2, 5]\n scale = Continuous().tick(at=tick_locs)\n p = Plot(long_df, \"x\").add(MockMark(), Identity()).scale(y=scale).plot()\n ax = p._figure.axes[0]\n assert_array_equal(ax.get_yticks(), tick_locs)\n\n def test_computed_var_transform(self, long_df):\n\n class Identity(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient]})\n\n p = Plot(long_df, \"x\").add(MockMark(), Identity()).scale(y=\"log\").plot()\n ax = p._figure.axes[0]\n xfm = ax.yaxis.get_transform().transform\n assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])\n\n def test_explicit_range_with_axis_scaling(self):\n\n x = [1, 2, 3]\n ymin = [10, 100, 1000]\n ymax = [20, 200, 2000]\n m = MockMark()\n Plot(x=x, ymin=ymin, ymax=ymax).add(m).scale(y=\"log\").plot()\n assert_vector_equal(m.passed_data[0][\"ymax\"], pd.Series(ymax, dtype=float))\n\n def test_derived_range_with_axis_scaling(self):\n\n class AddOne(Stat):\n def __call__(self, df, *args):\n return df.assign(ymax=df[\"y\"] + 1)\n\n x = y = [1, 10, 100]\n\n m = MockMark()\n Plot(x, y).add(m, AddOne()).scale(y=\"log\").plot()\n assert_vector_equal(m.passed_data[0][\"ymax\"], pd.Series([10., 100., 1000.]))\n\n def test_facet_categories(self):\n\n m = MockMark()\n p = Plot(x=[\"a\", \"b\", \"a\", \"c\"]).facet(col=[\"x\", \"x\", \"y\", \"y\"]).add(m).plot()\n ax1, ax2 = p._figure.axes\n assert len(ax1.get_xticks()) == 3\n assert len(ax2.get_xticks()) == 3\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [2, 3]))\n\n def test_facet_categories_unshared(self):\n\n m = MockMark()\n p = (\n Plot(x=[\"a\", \"b\", \"a\", \"c\"])\n .facet(col=[\"x\", \"x\", \"y\", \"y\"])\n .share(x=False)\n .add(m)\n .plot()\n )\n ax1, ax2 = p._figure.axes\n assert len(ax1.get_xticks()) == 2\n assert len(ax2.get_xticks()) == 2\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 1.], [2, 3]))\n\n def test_facet_categories_single_dim_shared(self):\n\n data = [\n (\"a\", 1, 1), (\"b\", 1, 1),\n (\"a\", 1, 2), (\"c\", 1, 2),\n (\"b\", 2, 1), (\"d\", 2, 1),\n (\"e\", 2, 2), (\"e\", 2, 1),\n ]\n df = pd.DataFrame(data, columns=[\"x\", \"row\", \"col\"]).assign(y=1)\n m = MockMark()\n p = (\n Plot(df, x=\"x\")\n .facet(row=\"row\", col=\"col\")\n .add(m)\n .share(x=\"row\")\n .plot()\n )\n\n axs = p._figure.axes\n for ax in axs:\n assert ax.get_xticks() == [0, 1, 2]\n\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [2, 3]))\n assert_vector_equal(m.passed_data[2][\"x\"], pd.Series([0., 1., 2.], [4, 5, 7]))\n assert_vector_equal(m.passed_data[3][\"x\"], pd.Series([2.], [6]))\n\n def test_pair_categories(self):\n\n data = [(\"a\", \"a\"), (\"b\", \"c\")]\n df = pd.DataFrame(data, columns=[\"x1\", \"x2\"]).assign(y=1)\n m = MockMark()\n p = Plot(df, y=\"y\").pair(x=[\"x1\", \"x2\"]).add(m).plot()\n\n ax1, ax2 = p._figure.axes\n assert ax1.get_xticks() == [0, 1]\n assert ax2.get_xticks() == [0, 1]\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 1.], [0, 1]))\n\n @pytest.mark.xfail(\n Version(mpl.__version__) < Version(\"3.4.0\"),\n reason=\"Sharing paired categorical axes requires matplotlib>3.4.0\"\n )\n def test_pair_categories_shared(self):\n\n data = [(\"a\", \"a\"), (\"b\", \"c\")]\n df = pd.DataFrame(data, columns=[\"x1\", \"x2\"]).assign(y=1)\n m = MockMark()\n p = Plot(df, y=\"y\").pair(x=[\"x1\", \"x2\"]).add(m).share(x=True).plot()\n\n for ax in p._figure.axes:\n assert ax.get_xticks() == [0, 1, 2]\n print(m.passed_data)\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [0, 1]))\n\n def test_identity_mapping_linewidth(self):\n\n m = MockMark()\n x = y = [1, 2, 3, 4, 5]\n lw = pd.Series([.5, .1, .1, .9, 3])\n Plot(x=x, y=y, linewidth=lw).scale(linewidth=None).add(m).plot()\n assert_vector_equal(m.passed_scales[\"linewidth\"](lw), lw)\n\n def test_pair_single_coordinate_stat_orient(self, long_df):\n\n class MockStat(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.orient = orient\n return data\n\n s = MockStat()\n Plot(long_df).pair(x=[\"x\", \"y\"]).add(MockMark(), s).plot()\n assert s.orient == \"x\"\n\n def test_inferred_nominal_passed_to_stat(self):\n\n class MockStat(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.scales = scales\n return data\n\n s = MockStat()\n y = [\"a\", \"a\", \"b\", \"c\"]\n Plot(y=y).add(MockMark(), s).plot()\n assert s.scales[\"y\"].__class__.__name__ == \"Nominal\"\n\n # TODO where should RGB consistency be enforced?\n @pytest.mark.xfail(\n reason=\"Correct output representation for color with identity scale undefined\"\n )\n def test_identity_mapping_color_strings(self):\n\n m = MockMark()\n x = y = [1, 2, 3]\n c = [\"C0\", \"C2\", \"C1\"]\n Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()\n expected = mpl.colors.to_rgba_array(c)[:, :3]\n assert_array_equal(m.passed_scales[\"color\"](c), expected)\n\n def test_identity_mapping_color_tuples(self):\n\n m = MockMark()\n x = y = [1, 2, 3]\n c = [(1, 0, 0), (0, 1, 0), (1, 0, 0)]\n Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()\n expected = mpl.colors.to_rgba_array(c)[:, :3]\n assert_array_equal(m.passed_scales[\"color\"](c), expected)\n\n @pytest.mark.xfail(\n reason=\"Need decision on what to do with scale defined for unused variable\"\n )\n def test_undefined_variable_raises(self):\n\n p = Plot(x=[1, 2, 3], color=[\"a\", \"b\", \"c\"]).scale(y=Continuous())\n err = r\"No data found for variable\\(s\\) with explicit scale: {'y'}\"\n with pytest.raises(RuntimeError, match=err):\n p.plot()"},{"col":4,"comment":"null","endLoc":339,"header":"def test_inference(self, long_df)","id":4408,"name":"test_inference","nodeType":"Function","startLoc":334,"text":"def test_inference(self, long_df):\n\n for col, scale_type in zip(\"zat\", [\"Continuous\", \"Nominal\", \"Temporal\"]):\n p = Plot(long_df, x=col, y=col).add(MockMark()).plot()\n for var in \"xy\":\n assert p._scales[var].__class__.__name__ == scale_type"},{"col":4,"comment":"null","endLoc":421,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_robust_regression(self)","id":4409,"name":"test_robust_regression","nodeType":"Function","startLoc":410,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_robust_regression(self):\n\n p_ols = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n n_boot=self.n_boot)\n _, ols_yhat, _ = p_ols.fit_regression(x_range=(-3, 3))\n\n p_robust = lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n robust=True, n_boot=self.n_boot)\n _, robust_yhat, _ = p_robust.fit_regression(x_range=(-3, 3))\n\n assert len(ols_yhat) == len(robust_yhat)"},{"col":4,"comment":"null","endLoc":430,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_lowess_regression(self)","id":4410,"name":"test_lowess_regression","nodeType":"Function","startLoc":423,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_lowess_regression(self):\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, lowess=True)\n grid, yhat, err_bands = p.fit_regression(x_range=(-3, 3))\n\n assert len(grid) == len(yhat)\n assert err_bands is None"},{"col":4,"comment":"null","endLoc":440,"header":"def test_regression_options(self)","id":4411,"name":"test_regression_options","nodeType":"Function","startLoc":432,"text":"def test_regression_options(self):\n\n with pytest.raises(ValueError):\n lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n lowess=True, order=2)\n\n with pytest.raises(ValueError):\n lm._RegressionPlotter(\"x\", \"y\", data=self.df,\n lowess=True, logistic=True)"},{"col":4,"comment":"null","endLoc":455,"header":"def test_regression_limits(self)","id":4412,"name":"test_regression_limits","nodeType":"Function","startLoc":442,"text":"def test_regression_limits(self):\n\n f, ax = plt.subplots()\n ax.scatter(self.df.x, self.df.y)\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df)\n grid, _, _ = p.fit_regression(ax)\n xlim = ax.get_xlim()\n assert grid.min() == xlim[0]\n assert grid.max() == xlim[1]\n\n p = lm._RegressionPlotter(\"x\", \"y\", data=self.df, truncate=True)\n grid, _, _ = p.fit_regression()\n assert grid.min() == self.df.x.min()\n assert grid.max() == self.df.x.max()"},{"attributeType":"null","col":4,"comment":"null","endLoc":104,"id":4413,"name":"rs","nodeType":"Attribute","startLoc":104,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":106,"id":4414,"name":"grid","nodeType":"Attribute","startLoc":106,"text":"grid"},{"attributeType":"int","col":4,"comment":"null","endLoc":107,"id":4415,"name":"n_boot","nodeType":"Attribute","startLoc":107,"text":"n_boot"},{"attributeType":"int","col":4,"comment":"null","endLoc":108,"id":4416,"name":"bins_numeric","nodeType":"Attribute","startLoc":108,"text":"bins_numeric"},{"attributeType":"list","col":4,"comment":"null","endLoc":109,"id":4417,"name":"bins_given","nodeType":"Attribute","startLoc":109,"text":"bins_given"},{"attributeType":"null","col":4,"comment":"null","endLoc":111,"id":4418,"name":"df","nodeType":"Attribute","startLoc":111,"text":"df"},{"attributeType":"int","col":4,"comment":"null","endLoc":118,"id":4419,"name":"bw_err","nodeType":"Attribute","startLoc":118,"text":"bw_err"},{"attributeType":"float","col":4,"comment":"null","endLoc":121,"id":4420,"name":"p","nodeType":"Attribute","startLoc":121,"text":"p"},{"className":"TestRegressionPlots","col":0,"comment":"null","endLoc":684,"id":4421,"nodeType":"Class","startLoc":458,"text":"class TestRegressionPlots:\n\n rs = np.random.RandomState(56)\n df = pd.DataFrame(dict(x=rs.randn(90),\n y=rs.randn(90) + 5,\n z=rs.randint(0, 1, 90),\n g=np.repeat(list(\"abc\"), 30),\n h=np.tile(list(\"xy\"), 45),\n u=np.tile(np.arange(6), 15)))\n bw_err = rs.randn(6)[df.u.values]\n df.y += bw_err\n\n def test_regplot_basic(self):\n\n f, ax = plt.subplots()\n lm.regplot(x=\"x\", y=\"y\", data=self.df)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n def test_regplot_selective(self):\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, scatter=False, ax=ax)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 1\n ax.clear()\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, fit_reg=False)\n assert len(ax.lines) == 0\n assert len(ax.collections) == 1\n ax.clear()\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, ci=None)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 1\n ax.clear()\n\n def test_regplot_scatter_kws_alpha(self):\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha is None\n assert ax.collections[0]._facecolors[0, 3] == 0.5\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha == 0.8\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color, 'alpha': 0.4})\n assert ax.collections[0]._alpha == 0.4\n\n f, ax = plt.subplots()\n color = 'r'\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha == 0.8\n\n f, ax = plt.subplots()\n alpha = .3\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n x_bins=5, fit_reg=False,\n scatter_kws={\"alpha\": alpha})\n for line in ax.lines:\n assert line.get_alpha() == alpha\n\n def test_regplot_binned(self):\n\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, x_bins=5)\n assert len(ax.lines) == 6\n assert len(ax.collections) == 2\n\n def test_lmplot_no_data(self):\n\n with pytest.raises(TypeError):\n # keyword argument `data` is required\n lm.lmplot(x=\"x\", y=\"y\")\n\n def test_lmplot_basic(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df)\n ax = g.axes[0, 0]\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)\n\n def test_lmplot_hue(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\")\n ax = g.axes[0, 0]\n\n assert len(ax.lines) == 2\n assert len(ax.collections) == 4\n\n def test_lmplot_markers(self):\n\n g1 = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", markers=\"s\")\n assert g1.hue_kws == {\"marker\": [\"s\", \"s\"]}\n\n g2 = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", markers=[\"o\", \"s\"])\n assert g2.hue_kws == {\"marker\": [\"o\", \"s\"]}\n\n with pytest.raises(ValueError):\n lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\",\n markers=[\"o\", \"s\", \"d\"])\n\n def test_lmplot_marker_linewidths(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\",\n fit_reg=False, markers=[\"o\", \"+\"])\n c = g.axes[0, 0].collections\n assert c[1].get_linewidths()[0] == mpl.rcParams[\"lines.linewidth\"]\n\n def test_lmplot_facets(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, row=\"g\", col=\"h\")\n assert g.axes.shape == (3, 2)\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, col=\"u\", col_wrap=4)\n assert g.axes.shape == (6,)\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", col=\"u\")\n assert g.axes.shape == (1, 6)\n\n def test_lmplot_hue_col_nolegend(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, col=\"h\", hue=\"h\")\n assert g._legend is None\n\n def test_lmplot_scatter_kws(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", hue=\"h\", data=self.df, ci=None)\n red_scatter, blue_scatter = g.axes[0, 0].collections\n\n red, blue = color_palette(n_colors=2)\n npt.assert_array_equal(red, red_scatter.get_facecolors()[0, :3])\n npt.assert_array_equal(blue, blue_scatter.get_facecolors()[0, :3])\n\n @pytest.mark.skipif(Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"MPL bug #15967\")\n @pytest.mark.parametrize(\"sharex\", [True, False])\n def test_lmplot_facet_truncate(self, sharex):\n\n g = lm.lmplot(\n data=self.df, x=\"x\", y=\"y\", hue=\"g\", col=\"h\",\n truncate=False, facet_kws=dict(sharex=sharex),\n )\n\n for ax in g.axes.flat:\n for line in ax.lines:\n xdata = line.get_xdata()\n assert ax.get_xlim() == tuple(xdata[[0, -1]])\n\n def test_lmplot_sharey(self):\n\n df = pd.DataFrame(dict(\n x=[0, 1, 2, 0, 1, 2],\n y=[1, -1, 0, -100, 200, 0],\n z=[\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"],\n ))\n\n with pytest.warns(UserWarning):\n g = lm.lmplot(data=df, x=\"x\", y=\"y\", col=\"z\", sharey=False)\n ax1, ax2 = g.axes.flat\n assert ax1.get_ylim()[0] > ax2.get_ylim()[0]\n assert ax1.get_ylim()[1] < ax2.get_ylim()[1]\n\n def test_lmplot_facet_kws(self):\n\n xlim = -4, 20\n g = lm.lmplot(\n data=self.df, x=\"x\", y=\"y\", col=\"h\", facet_kws={\"xlim\": xlim}\n )\n for ax in g.axes.flat:\n assert ax.get_xlim() == xlim\n\n def test_residplot(self):\n\n x, y = self.df.x, self.df.y\n ax = lm.residplot(x=x, y=y)\n\n resid = y - np.polyval(np.polyfit(x, y, 1), x)\n x_plot, y_plot = ax.collections[0].get_offsets().T\n\n npt.assert_array_equal(x, x_plot)\n npt.assert_array_almost_equal(resid, y_plot)\n\n @pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_residplot_lowess(self):\n\n ax = lm.residplot(x=\"x\", y=\"y\", data=self.df, lowess=True)\n assert len(ax.lines) == 2\n\n x, y = ax.lines[1].get_xydata().T\n npt.assert_array_equal(x, np.sort(self.df.x))\n\n def test_three_point_colors(self):\n\n x, y = np.random.randn(2, 3)\n ax = lm.regplot(x=x, y=y, color=(1, 0, 0))\n color = ax.collections[0].get_facecolors()\n npt.assert_almost_equal(color[0, :3],\n (1, 0, 0))\n\n def test_regplot_xlim(self):\n\n f, ax = plt.subplots()\n x, y1, y2 = np.random.randn(3, 50)\n lm.regplot(x=x, y=y1, truncate=False)\n lm.regplot(x=x, y=y2, truncate=False)\n line1, line2 = ax.lines\n assert np.array_equal(line1.get_xdata(), line2.get_xdata())"},{"col":4,"comment":"null","endLoc":479,"header":"def test_regplot_basic(self)","id":4422,"name":"test_regplot_basic","nodeType":"Function","startLoc":470,"text":"def test_regplot_basic(self):\n\n f, ax = plt.subplots()\n lm.regplot(x=\"x\", y=\"y\", data=self.df)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)"},{"col":4,"comment":"null","endLoc":499,"header":"def test_regplot_selective(self)","id":4424,"name":"test_regplot_selective","nodeType":"Function","startLoc":481,"text":"def test_regplot_selective(self):\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, scatter=False, ax=ax)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 1\n ax.clear()\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, fit_reg=False)\n assert len(ax.lines) == 0\n assert len(ax.collections) == 1\n ax.clear()\n\n f, ax = plt.subplots()\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, ci=None)\n assert len(ax.lines) == 1\n assert len(ax.collections) == 1\n ax.clear()"},{"col":4,"comment":"null","endLoc":534,"header":"def test_regplot_scatter_kws_alpha(self)","id":4425,"name":"test_regplot_scatter_kws_alpha","nodeType":"Function","startLoc":501,"text":"def test_regplot_scatter_kws_alpha(self):\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha is None\n assert ax.collections[0]._facecolors[0, 3] == 0.5\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha == 0.8\n\n f, ax = plt.subplots()\n color = np.array([[0.3, 0.8, 0.5]])\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color, 'alpha': 0.4})\n assert ax.collections[0]._alpha == 0.4\n\n f, ax = plt.subplots()\n color = 'r'\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n scatter_kws={'color': color})\n assert ax.collections[0]._alpha == 0.8\n\n f, ax = plt.subplots()\n alpha = .3\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df,\n x_bins=5, fit_reg=False,\n scatter_kws={\"alpha\": alpha})\n for line in ax.lines:\n assert line.get_alpha() == alpha"},{"col":4,"comment":"null","endLoc":540,"header":"def test_regplot_binned(self)","id":4426,"name":"test_regplot_binned","nodeType":"Function","startLoc":536,"text":"def test_regplot_binned(self):\n\n ax = lm.regplot(x=\"x\", y=\"y\", data=self.df, x_bins=5)\n assert len(ax.lines) == 6\n assert len(ax.collections) == 2"},{"col":4,"comment":"null","endLoc":546,"header":"def test_lmplot_no_data(self)","id":4427,"name":"test_lmplot_no_data","nodeType":"Function","startLoc":542,"text":"def test_lmplot_no_data(self):\n\n with pytest.raises(TypeError):\n # keyword argument `data` is required\n lm.lmplot(x=\"x\", y=\"y\")"},{"col":4,"comment":"null","endLoc":557,"header":"def test_lmplot_basic(self)","id":4428,"name":"test_lmplot_basic","nodeType":"Function","startLoc":548,"text":"def test_lmplot_basic(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df)\n ax = g.axes[0, 0]\n assert len(ax.lines) == 1\n assert len(ax.collections) == 2\n\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.df.x)\n npt.assert_array_equal(y, self.df.y)"},{"col":4,"comment":"null","endLoc":565,"header":"def test_lmplot_hue(self)","id":4429,"name":"test_lmplot_hue","nodeType":"Function","startLoc":559,"text":"def test_lmplot_hue(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\")\n ax = g.axes[0, 0]\n\n assert len(ax.lines) == 2\n assert len(ax.collections) == 4"},{"col":4,"comment":"null","endLoc":577,"header":"def test_lmplot_markers(self)","id":4430,"name":"test_lmplot_markers","nodeType":"Function","startLoc":567,"text":"def test_lmplot_markers(self):\n\n g1 = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", markers=\"s\")\n assert g1.hue_kws == {\"marker\": [\"s\", \"s\"]}\n\n g2 = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", markers=[\"o\", \"s\"])\n assert g2.hue_kws == {\"marker\": [\"o\", \"s\"]}\n\n with pytest.raises(ValueError):\n lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\",\n markers=[\"o\", \"s\", \"d\"])"},{"col":4,"comment":"null","endLoc":584,"header":"def test_lmplot_marker_linewidths(self)","id":4431,"name":"test_lmplot_marker_linewidths","nodeType":"Function","startLoc":579,"text":"def test_lmplot_marker_linewidths(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\",\n fit_reg=False, markers=[\"o\", \"+\"])\n c = g.axes[0, 0].collections\n assert c[1].get_linewidths()[0] == mpl.rcParams[\"lines.linewidth\"]"},{"col":4,"comment":"null","endLoc":595,"header":"def test_lmplot_facets(self)","id":4432,"name":"test_lmplot_facets","nodeType":"Function","startLoc":586,"text":"def test_lmplot_facets(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, row=\"g\", col=\"h\")\n assert g.axes.shape == (3, 2)\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, col=\"u\", col_wrap=4)\n assert g.axes.shape == (6,)\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, hue=\"h\", col=\"u\")\n assert g.axes.shape == (1, 6)"},{"col":4,"comment":"null","endLoc":600,"header":"def test_lmplot_hue_col_nolegend(self)","id":4433,"name":"test_lmplot_hue_col_nolegend","nodeType":"Function","startLoc":597,"text":"def test_lmplot_hue_col_nolegend(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", data=self.df, col=\"h\", hue=\"h\")\n assert g._legend is None"},{"col":4,"comment":"null","endLoc":609,"header":"def test_lmplot_scatter_kws(self)","id":4434,"name":"test_lmplot_scatter_kws","nodeType":"Function","startLoc":602,"text":"def test_lmplot_scatter_kws(self):\n\n g = lm.lmplot(x=\"x\", y=\"y\", hue=\"h\", data=self.df, ci=None)\n red_scatter, blue_scatter = g.axes[0, 0].collections\n\n red, blue = color_palette(n_colors=2)\n npt.assert_array_equal(red, red_scatter.get_facecolors()[0, :3])\n npt.assert_array_equal(blue, blue_scatter.get_facecolors()[0, :3])"},{"col":4,"comment":"null","endLoc":624,"header":"@pytest.mark.skipif(Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"MPL bug #15967\")\n @pytest.mark.parametrize(\"sharex\", [True, False])\n def test_lmplot_facet_truncate(self, sharex)","id":4435,"name":"test_lmplot_facet_truncate","nodeType":"Function","startLoc":611,"text":"@pytest.mark.skipif(Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"MPL bug #15967\")\n @pytest.mark.parametrize(\"sharex\", [True, False])\n def test_lmplot_facet_truncate(self, sharex):\n\n g = lm.lmplot(\n data=self.df, x=\"x\", y=\"y\", hue=\"g\", col=\"h\",\n truncate=False, facet_kws=dict(sharex=sharex),\n )\n\n for ax in g.axes.flat:\n for line in ax.lines:\n xdata = line.get_xdata()\n assert ax.get_xlim() == tuple(xdata[[0, -1]])"},{"col":4,"comment":"null","endLoc":344,"header":"def test_inference_from_layer_data(self)","id":4436,"name":"test_inference_from_layer_data","nodeType":"Function","startLoc":341,"text":"def test_inference_from_layer_data(self):\n\n p = Plot().add(MockMark(), x=[\"a\", \"b\", \"c\"]).plot()\n assert p._scales[\"x\"](\"b\") == 1"},{"col":4,"comment":"null","endLoc":354,"header":"def test_inference_joins(self)","id":4437,"name":"test_inference_joins","nodeType":"Function","startLoc":346,"text":"def test_inference_joins(self):\n\n p = (\n Plot(y=pd.Series([1, 2, 3, 4]))\n .add(MockMark(), x=pd.Series([1, 2]))\n .add(MockMark(), x=pd.Series([\"a\", \"b\"], index=[2, 3]))\n .plot()\n )\n assert p._scales[\"x\"](\"a\") == 2"},{"col":4,"comment":"null","endLoc":320,"header":"def test_hue_map_numeric(self, long_df)","id":4438,"name":"test_hue_map_numeric","nodeType":"Function","startLoc":240,"text":"def test_hue_map_numeric(self, long_df):\n\n vals = np.concatenate([np.linspace(0, 1, 256), [-.1, 1.1, np.nan]])\n\n # Test default colormap\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"s\")\n )\n hue_levels = list(np.sort(long_df[\"s\"].unique()))\n m = HueMapping(p)\n assert m.levels == hue_levels\n assert m.map_type == \"numeric\"\n assert m.cmap.name == \"seaborn_cubehelix\"\n\n # Test named colormap\n palette = \"Purples\"\n m = HueMapping(p, palette=palette)\n assert_array_equal(m.cmap(vals), get_colormap(palette)(vals))\n\n # Test colormap object\n palette = get_colormap(\"Greens\")\n m = HueMapping(p, palette=palette)\n assert_array_equal(m.cmap(vals), palette(vals))\n\n # Test cubehelix shorthand\n palette = \"ch:2,0,light=.2\"\n m = HueMapping(p, palette=palette)\n assert isinstance(m.cmap, mpl.colors.ListedColormap)\n\n # Test specified hue limits\n hue_norm = 1, 4\n m = HueMapping(p, norm=hue_norm)\n assert isinstance(m.norm, mpl.colors.Normalize)\n assert m.norm.vmin == hue_norm[0]\n assert m.norm.vmax == hue_norm[1]\n\n # Test Normalize object\n hue_norm = mpl.colors.PowerNorm(2, vmin=1, vmax=10)\n m = HueMapping(p, norm=hue_norm)\n assert m.norm is hue_norm\n\n # Test default colormap values\n hmin, hmax = p.plot_data[\"hue\"].min(), p.plot_data[\"hue\"].max()\n m = HueMapping(p)\n assert m.lookup_table[hmin] == pytest.approx(m.cmap(0.0))\n assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))\n\n # Test specified colormap values\n hue_norm = hmin - 1, hmax - 1\n m = HueMapping(p, norm=hue_norm)\n norm_min = (hmin - hue_norm[0]) / (hue_norm[1] - hue_norm[0])\n assert m.lookup_table[hmin] == pytest.approx(m.cmap(norm_min))\n assert m.lookup_table[hmax] == pytest.approx(m.cmap(1.0))\n\n # Test list of colors\n hue_levels = list(np.sort(long_df[\"s\"].unique()))\n palette = color_palette(\"Blues\", len(hue_levels))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == dict(zip(hue_levels, palette))\n\n palette = color_palette(\"Blues\", len(hue_levels) + 1)\n with pytest.warns(UserWarning):\n HueMapping(p, palette=palette)\n\n # Test dictionary of colors\n palette = dict(zip(hue_levels, color_palette(\"Reds\")))\n m = HueMapping(p, palette=palette)\n assert m.lookup_table == palette\n\n palette.pop(hue_levels[0])\n with pytest.raises(ValueError):\n HueMapping(p, palette=palette)\n\n # Test invalid palette\n with pytest.raises(ValueError):\n HueMapping(p, palette=\"not a valid palette\")\n\n # Test bad norm argument\n with pytest.raises(ValueError):\n HueMapping(p, norm=\"not a norm\")"},{"col":4,"comment":"null","endLoc":360,"header":"def test_inferred_categorical_converter(self)","id":4439,"name":"test_inferred_categorical_converter","nodeType":"Function","startLoc":356,"text":"def test_inferred_categorical_converter(self):\n\n p = Plot(x=[\"b\", \"c\", \"a\"]).add(MockMark()).plot()\n ax = p._figure.axes[0]\n assert ax.xaxis.convert_units(\"c\") == 1"},{"col":0,"comment":"null","endLoc":393,"header":"def setup(app)","id":4440,"name":"setup","nodeType":"Function","startLoc":392,"text":"def setup(app):\n app.connect('builder-inited', main)"},{"attributeType":"null","col":18,"comment":"null","endLoc":8,"id":4441,"name":"op","nodeType":"Attribute","startLoc":8,"text":"op"},{"attributeType":"null","col":28,"comment":"null","endLoc":18,"id":4442,"name":"plt","nodeType":"Attribute","startLoc":18,"text":"plt"},{"attributeType":"str","col":0,"comment":"null","endLoc":27,"id":4443,"name":"RST_TEMPLATE","nodeType":"Attribute","startLoc":27,"text":"RST_TEMPLATE"},{"attributeType":"str","col":0,"comment":"null","endLoc":45,"id":4444,"name":"INDEX_TEMPLATE","nodeType":"Attribute","startLoc":45,"text":"INDEX_TEMPLATE"},{"col":0,"comment":"","endLoc":6,"header":"gallery_generator.py#","id":4445,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nSphinx plugin to run example scripts and create a gallery page.\n\nLightly modified from the mpld3 project.\n\n\"\"\"\n\nmatplotlib.use('Agg')\n\nRST_TEMPLATE = \"\"\"\n\n.. currentmodule:: seaborn\n\n.. _{sphinx_tag}:\n\n{docstring}\n\n.. image:: {img_file}\n\n**seaborn components used:** {components}\n\n.. literalinclude:: {fname}\n :lines: {end_line}-\n\n\"\"\"\n\nINDEX_TEMPLATE = \"\"\"\n:html_theme.sidebar_secondary.remove:\n\n.. raw:: html\n\n \n\n.. _{sphinx_tag}:\n\nExample gallery\n===============\n\n{toctree}\n\n{contents}\n\n.. raw:: html\n\n
\n\"\"\""},{"col":4,"comment":"null","endLoc":366,"header":"def test_explicit_categorical_converter(self)","id":4446,"name":"test_explicit_categorical_converter","nodeType":"Function","startLoc":362,"text":"def test_explicit_categorical_converter(self):\n\n p = Plot(y=[2, 1, 3]).scale(y=Nominal()).add(MockMark()).plot()\n ax = p._figure.axes[0]\n assert ax.yaxis.convert_units(\"3\") == 2"},{"col":4,"comment":"null","endLoc":374,"header":"@pytest.mark.xfail(reason=\"Temporal auto-conversion not implemented\")\n def test_categorical_as_datetime(self)","id":4447,"name":"test_categorical_as_datetime","nodeType":"Function","startLoc":368,"text":"@pytest.mark.xfail(reason=\"Temporal auto-conversion not implemented\")\n def test_categorical_as_datetime(self):\n\n dates = [\"1970-01-03\", \"1970-01-02\", \"1970-01-04\"]\n p = Plot(x=dates).scale(...).add(MockMark()).plot()\n p # TODO\n ..."},{"col":4,"comment":"null","endLoc":381,"header":"def test_faceted_log_scale(self)","id":4448,"name":"test_faceted_log_scale","nodeType":"Function","startLoc":376,"text":"def test_faceted_log_scale(self):\n\n p = Plot(y=[1, 10]).facet(col=[\"a\", \"b\"]).scale(y=\"log\").plot()\n for ax in p._figure.axes:\n xfm = ax.yaxis.get_transform().transform\n assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])"},{"col":4,"comment":"null","endLoc":391,"header":"def test_paired_single_log_scale(self)","id":4449,"name":"test_paired_single_log_scale","nodeType":"Function","startLoc":383,"text":"def test_paired_single_log_scale(self):\n\n x0, x1 = [1, 2, 3], [1, 10, 100]\n p = Plot().pair(x=[x0, x1]).scale(x1=\"log\").plot()\n ax_lin, ax_log = p._figure.axes\n xfm_lin = ax_lin.xaxis.get_transform().transform\n assert_array_equal(xfm_lin([1, 10, 100]), [1, 10, 100])\n xfm_log = ax_log.xaxis.get_transform().transform\n assert_array_equal(xfm_log([1, 10, 100]), [0, 1, 2])"},{"col":4,"comment":"null","endLoc":399,"header":"@pytest.mark.xfail(reason=\"Custom log scale needs log name for consistency\")\n def test_log_scale_name(self)","id":4450,"name":"test_log_scale_name","nodeType":"Function","startLoc":393,"text":"@pytest.mark.xfail(reason=\"Custom log scale needs log name for consistency\")\n def test_log_scale_name(self):\n\n p = Plot().scale(x=\"log\").plot()\n ax = p._figure.axes[0]\n assert ax.get_xscale() == \"log\"\n assert ax.get_yscale() == \"linear\""},{"fileName":"test_categorical.py","filePath":"tests","id":4451,"nodeType":"File","text":"import itertools\nfrom functools import partial\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import rgb2hex, same_color, to_rgb, to_rgba\n\nimport pytest\nfrom pytest import approx\nimport numpy.testing as npt\nfrom numpy.testing import (\n assert_array_equal,\n assert_array_less,\n)\n\nfrom seaborn import categorical as cat\nfrom seaborn import palettes\n\nfrom seaborn.external.version import Version\nfrom seaborn._oldcore import categorical_order\nfrom seaborn.categorical import (\n _CategoricalPlotterNew,\n Beeswarm,\n catplot,\n stripplot,\n swarmplot,\n)\nfrom seaborn.palettes import color_palette\nfrom seaborn.utils import _normal_quantile_func, _draw_figure\nfrom seaborn._compat import get_colormap\nfrom seaborn._testing import assert_plots_equal\n\n\nPLOT_FUNCS = [\n catplot,\n stripplot,\n swarmplot,\n]\n\n\nclass TestCategoricalPlotterNew:\n\n @pytest.mark.parametrize(\n \"func,kwargs\",\n itertools.product(\n PLOT_FUNCS,\n [\n {\"x\": \"x\", \"y\": \"a\"},\n {\"x\": \"a\", \"y\": \"y\"},\n {\"x\": \"y\"},\n {\"y\": \"x\"},\n ],\n ),\n )\n def test_axis_labels(self, long_df, func, kwargs):\n\n func(data=long_df, **kwargs)\n\n ax = plt.gca()\n for axis in \"xy\":\n val = kwargs.get(axis, \"\")\n label_func = getattr(ax, f\"get_{axis}label\")\n assert label_func() == val\n\n @pytest.mark.parametrize(\"func\", PLOT_FUNCS)\n def test_empty(self, func):\n\n func()\n ax = plt.gca()\n assert not ax.collections\n assert not ax.patches\n assert not ax.lines\n\n func(x=[], y=[])\n ax = plt.gca()\n assert not ax.collections\n assert not ax.patches\n assert not ax.lines\n\n def test_redundant_hue_backcompat(self, long_df):\n\n p = _CategoricalPlotterNew(\n data=long_df,\n variables={\"x\": \"s\", \"y\": \"y\"},\n )\n\n color = None\n palette = dict(zip(long_df[\"s\"].unique(), color_palette()))\n hue_order = None\n\n palette, _ = p._hue_backcompat(color, palette, hue_order, force_hue=True)\n\n assert p.variables[\"hue\"] == \"s\"\n assert_array_equal(p.plot_data[\"hue\"], p.plot_data[\"x\"])\n assert all(isinstance(k, str) for k in palette)\n\n\nclass CategoricalFixture:\n \"\"\"Test boxplot (also base class for things like violinplots).\"\"\"\n rs = np.random.RandomState(30)\n n_total = 60\n x = rs.randn(int(n_total / 3), 3)\n x_df = pd.DataFrame(x, columns=pd.Series(list(\"XYZ\"), name=\"big\"))\n y = pd.Series(rs.randn(n_total), name=\"y_data\")\n y_perm = y.reindex(rs.choice(y.index, y.size, replace=False))\n g = pd.Series(np.repeat(list(\"abc\"), int(n_total / 3)), name=\"small\")\n h = pd.Series(np.tile(list(\"mn\"), int(n_total / 2)), name=\"medium\")\n u = pd.Series(np.tile(list(\"jkh\"), int(n_total / 3)))\n df = pd.DataFrame(dict(y=y, g=g, h=h, u=u))\n x_df[\"W\"] = g\n\n def get_box_artists(self, ax):\n\n if Version(mpl.__version__) < Version(\"3.5.0b0\"):\n return ax.artists\n else:\n # Exclude labeled patches, which are for the legend\n return [p for p in ax.patches if not p.get_label()]\n\n\nclass TestCategoricalPlotter(CategoricalFixture):\n\n def test_wide_df_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test basic wide DataFrame\n p.establish_variables(data=self.x_df)\n\n # Check data attribute\n for x, y, in zip(p.plot_data, self.x_df[[\"X\", \"Y\", \"Z\"]].values.T):\n npt.assert_array_equal(x, y)\n\n # Check semantic attributes\n assert p.orient == \"v\"\n assert p.plot_hues is None\n assert p.group_label == \"big\"\n assert p.value_label is None\n\n # Test wide dataframe with forced horizontal orientation\n p.establish_variables(data=self.x_df, orient=\"horiz\")\n assert p.orient == \"h\"\n\n # Test exception by trying to hue-group with a wide dataframe\n with pytest.raises(ValueError):\n p.establish_variables(hue=\"d\", data=self.x_df)\n\n def test_1d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test basic vector data\n x_1d_array = self.x.ravel()\n p.establish_variables(data=x_1d_array)\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.n_total\n assert p.group_label is None\n assert p.value_label is None\n\n # Test basic vector data in list form\n x_1d_list = x_1d_array.tolist()\n p.establish_variables(data=x_1d_list)\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.n_total\n assert p.group_label is None\n assert p.value_label is None\n\n # Test an object array that looks 1D but isn't\n x_notreally_1d = np.array([self.x.ravel(),\n self.x.ravel()[:int(self.n_total / 2)]],\n dtype=object)\n p.establish_variables(data=x_notreally_1d)\n assert len(p.plot_data) == 2\n assert len(p.plot_data[0]) == self.n_total\n assert len(p.plot_data[1]) == self.n_total / 2\n assert p.group_label is None\n assert p.value_label is None\n\n def test_2d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n x = self.x[:, 0]\n\n # Test vector data that looks 2D but doesn't really have columns\n p.establish_variables(data=x[:, np.newaxis])\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.x.shape[0]\n assert p.group_label is None\n assert p.value_label is None\n\n # Test vector data that looks 2D but doesn't really have rows\n p.establish_variables(data=x[np.newaxis, :])\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.x.shape[0]\n assert p.group_label is None\n assert p.value_label is None\n\n def test_3d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test that passing actually 3D data raises\n x = np.zeros((5, 5, 5))\n with pytest.raises(ValueError):\n p.establish_variables(data=x)\n\n def test_list_of_array_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test 2D input in list form\n x_list = self.x.T.tolist()\n p.establish_variables(data=x_list)\n assert len(p.plot_data) == 3\n\n lengths = [len(v_i) for v_i in p.plot_data]\n assert lengths == [self.n_total / 3] * 3\n\n assert p.group_label is None\n assert p.value_label is None\n\n def test_wide_array_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test 2D input in array form\n p.establish_variables(data=self.x)\n assert np.shape(p.plot_data) == (3, self.n_total / 3)\n npt.assert_array_equal(p.plot_data, self.x.T)\n\n assert p.group_label is None\n assert p.value_label is None\n\n def test_single_long_direct_inputs(self):\n\n p = cat._CategoricalPlotter()\n\n # Test passing a series to the x variable\n p.establish_variables(x=self.y)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"h\"\n assert p.value_label == \"y_data\"\n assert p.group_label is None\n\n # Test passing a series to the y variable\n p.establish_variables(y=self.y)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.value_label == \"y_data\"\n assert p.group_label is None\n\n # Test passing an array to the y variable\n p.establish_variables(y=self.y.values)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.group_label is None\n assert p.value_label is None\n\n # Test array and series with non-default index\n x = pd.Series([1, 1, 1, 1], index=[0, 2, 4, 6])\n y = np.array([1, 2, 3, 4])\n p.establish_variables(x, y)\n assert len(p.plot_data[0]) == 4\n\n def test_single_long_indirect_inputs(self):\n\n p = cat._CategoricalPlotter()\n\n # Test referencing a DataFrame series in the x variable\n p.establish_variables(x=\"y\", data=self.df)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"h\"\n assert p.value_label == \"y\"\n assert p.group_label is None\n\n # Test referencing a DataFrame series in the y variable\n p.establish_variables(y=\"y\", data=self.df)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.value_label == \"y\"\n assert p.group_label is None\n\n def test_longform_groupby(self):\n\n p = cat._CategoricalPlotter()\n\n # Test a vertically oriented grouped and nested plot\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert len(p.plot_data) == 3\n assert len(p.plot_hues) == 3\n assert p.orient == \"v\"\n assert p.value_label == \"y\"\n assert p.group_label == \"g\"\n assert p.hue_title == \"h\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test a grouped and nested plot with direct array value data\n p.establish_variables(\"g\", self.y.values, \"h\", self.df)\n assert p.value_label is None\n assert p.group_label == \"g\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n # Test a grouped and nested plot with direct array hue data\n p.establish_variables(\"g\", \"y\", self.h.values, self.df)\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test categorical grouping data\n df = self.df.copy()\n df.g = df.g.astype(\"category\")\n\n # Test that horizontal orientation is automatically detected\n p.establish_variables(\"y\", \"g\", hue=\"h\", data=df)\n assert len(p.plot_data) == 3\n assert len(p.plot_hues) == 3\n assert p.orient == \"h\"\n assert p.value_label == \"y\"\n assert p.group_label == \"g\"\n assert p.hue_title == \"h\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test grouped data that matches on index\n p1 = cat._CategoricalPlotter()\n p1.establish_variables(self.g, self.y, hue=self.h)\n p2 = cat._CategoricalPlotter()\n p2.establish_variables(self.g, self.y.iloc[::-1], self.h)\n for i, (d1, d2) in enumerate(zip(p1.plot_data, p2.plot_data)):\n assert np.array_equal(d1.sort_index(), d2.sort_index())\n\n def test_input_validation(self):\n\n p = cat._CategoricalPlotter()\n\n kws = dict(x=\"g\", y=\"y\", hue=\"h\", units=\"u\", data=self.df)\n for var in [\"x\", \"y\", \"hue\", \"units\"]:\n input_kws = kws.copy()\n input_kws[var] = \"bad_input\"\n with pytest.raises(ValueError):\n p.establish_variables(**input_kws)\n\n def test_order(self):\n\n p = cat._CategoricalPlotter()\n\n # Test inferred order from a wide dataframe input\n p.establish_variables(data=self.x_df)\n assert p.group_names == [\"X\", \"Y\", \"Z\"]\n\n # Test specified order with a wide dataframe input\n p.establish_variables(data=self.x_df, order=[\"Y\", \"Z\", \"X\"])\n assert p.group_names == [\"Y\", \"Z\", \"X\"]\n\n for group, vals in zip([\"Y\", \"Z\", \"X\"], p.plot_data):\n npt.assert_array_equal(vals, self.x_df[group])\n\n with pytest.raises(ValueError):\n p.establish_variables(data=self.x, order=[1, 2, 0])\n\n # Test inferred order from a grouped longform input\n p.establish_variables(\"g\", \"y\", data=self.df)\n assert p.group_names == [\"a\", \"b\", \"c\"]\n\n # Test specified order from a grouped longform input\n p.establish_variables(\"g\", \"y\", data=self.df, order=[\"b\", \"a\", \"c\"])\n assert p.group_names == [\"b\", \"a\", \"c\"]\n\n for group, vals in zip([\"b\", \"a\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n # Test inferred order from a grouped input with categorical groups\n df = self.df.copy()\n df.g = df.g.astype(\"category\")\n df.g = df.g.cat.reorder_categories([\"c\", \"b\", \"a\"])\n p.establish_variables(\"g\", \"y\", data=df)\n assert p.group_names == [\"c\", \"b\", \"a\"]\n\n for group, vals in zip([\"c\", \"b\", \"a\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n df.g = (df.g.cat.add_categories(\"d\")\n .cat.reorder_categories([\"c\", \"b\", \"d\", \"a\"]))\n p.establish_variables(\"g\", \"y\", data=df)\n assert p.group_names == [\"c\", \"b\", \"d\", \"a\"]\n\n def test_hue_order(self):\n\n p = cat._CategoricalPlotter()\n\n # Test inferred hue order\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.hue_names == [\"m\", \"n\"]\n\n # Test specified hue order\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df,\n hue_order=[\"n\", \"m\"])\n assert p.hue_names == [\"n\", \"m\"]\n\n # Test inferred hue order from a categorical hue input\n df = self.df.copy()\n df.h = df.h.astype(\"category\")\n df.h = df.h.cat.reorder_categories([\"n\", \"m\"])\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=df)\n assert p.hue_names == [\"n\", \"m\"]\n\n df.h = (df.h.cat.add_categories(\"o\")\n .cat.reorder_categories([\"o\", \"m\", \"n\"]))\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=df)\n assert p.hue_names == [\"o\", \"m\", \"n\"]\n\n def test_plot_units(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.plot_units is None\n\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df, units=\"u\")\n for group, units in zip([\"a\", \"b\", \"c\"], p.plot_units):\n npt.assert_array_equal(units, self.u[self.g == group])\n\n def test_default_palettes(self):\n\n p = cat._CategoricalPlotter()\n\n # Test palette mapping the x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, None, 1)\n assert p.colors == palettes.color_palette(n_colors=3)\n\n # Test palette mapping the hue position\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(None, None, 1)\n assert p.colors == palettes.color_palette(n_colors=2)\n\n def test_default_palette_with_many_levels(self):\n\n with palettes.color_palette([\"blue\", \"red\"], 2):\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, None, 1)\n npt.assert_array_equal(p.colors,\n palettes.husl_palette(3, l=.7)) # noqa\n\n def test_specific_color(self):\n\n p = cat._CategoricalPlotter()\n\n # Test the same color for each x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(\"blue\", None, 1)\n blue_rgb = mpl.colors.colorConverter.to_rgb(\"blue\")\n assert p.colors == [blue_rgb] * 3\n\n # Test a color-based blend for the hue mapping\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(\"#ff0022\", None, 1)\n rgba_array = np.array(palettes.light_palette(\"#ff0022\", 2))\n npt.assert_array_almost_equal(p.colors,\n rgba_array[:, :3])\n\n def test_specific_palette(self):\n\n p = cat._CategoricalPlotter()\n\n # Test palette mapping the x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, \"dark\", 1)\n assert p.colors == palettes.color_palette(\"dark\", 3)\n\n # Test that non-None `color` and `hue` raises an error\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(None, \"muted\", 1)\n assert p.colors == palettes.color_palette(\"muted\", 2)\n\n # Test that specified palette overrides specified color\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(\"blue\", \"deep\", 1)\n assert p.colors == palettes.color_palette(\"deep\", 3)\n\n def test_dict_as_palette(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n pal = {\"m\": (0, 0, 1), \"n\": (1, 0, 0)}\n p.establish_colors(None, pal, 1)\n assert p.colors == [(0, 0, 1), (1, 0, 0)]\n\n def test_palette_desaturation(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors((0, 0, 1), None, .5)\n assert p.colors == [(.25, .25, .75)] * 3\n\n p.establish_colors(None, [(0, 0, 1), (1, 0, 0), \"w\"], .5)\n assert p.colors == [(.25, .25, .75), (.75, .25, .25), (1, 1, 1)]\n\n\nclass TestCategoricalStatPlotter(CategoricalFixture):\n\n def test_no_bootstrappig(self):\n\n p = cat._CategoricalStatPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.estimate_statistic(\"mean\", None, 100, None)\n npt.assert_array_equal(p.confint, np.array([]))\n\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.estimate_statistic(np.mean, None, 100, None)\n npt.assert_array_equal(p.confint, np.array([[], [], []]))\n\n def test_single_layer_stats(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n\n assert p.statistic.shape == (3,)\n assert p.confint.shape == (3, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby(g).mean())\n\n for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):\n sem = grp_y.std() / np.sqrt(len(grp_y))\n mean = grp_y.mean()\n half_ci = _normal_quantile_func(.975) * sem\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_single_layer_stats_with_units(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 90))\n y = pd.Series(np.random.RandomState(0).randn(270))\n u = pd.Series(np.repeat(np.tile(list(\"xyz\"), 30), 3))\n y[u == \"x\"] -= 3\n y[u == \"y\"] += 3\n\n p.establish_variables(g, y)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat1, ci1 = p.statistic, p.confint\n\n p.establish_variables(g, y, units=u)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat2, ci2 = p.statistic, p.confint\n\n npt.assert_array_equal(stat1, stat2)\n ci1_size = ci1[:, 1] - ci1[:, 0]\n ci2_size = ci2[:, 1] - ci2[:, 0]\n npt.assert_array_less(ci1_size, ci2_size)\n\n def test_single_layer_stats_with_missing_data(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, order=list(\"abdc\"))\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n\n assert p.statistic.shape == (4,)\n assert p.confint.shape == (4, 2)\n\n rows = g == \"b\"\n mean = y[rows].mean()\n sem = y[rows].std() / np.sqrt(rows.sum())\n half_ci = _normal_quantile_func(.975) * sem\n ci = mean - half_ci, mean + half_ci\n npt.assert_almost_equal(p.statistic[1], mean)\n npt.assert_array_almost_equal(p.confint[1], ci, 2)\n\n npt.assert_equal(p.statistic[2], np.nan)\n npt.assert_array_equal(p.confint[2], (np.nan, np.nan))\n\n def test_nested_stats(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 50000, None)\n\n assert p.statistic.shape == (3, 2)\n assert p.confint.shape == (3, 2, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby([g, h]).mean().unstack())\n\n for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):\n for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):\n sem = hue_y.std() / np.sqrt(len(hue_y))\n mean = hue_y.mean()\n half_ci = _normal_quantile_func(.975) * sem\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_bootstrap_seed(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 1000, 0)\n confint_1 = p.confint\n p.estimate_statistic(\"mean\", (\"ci\", 95), 1000, 0)\n confint_2 = p.confint\n\n npt.assert_array_equal(confint_1, confint_2)\n\n def test_nested_stats_with_units(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 90))\n h = pd.Series(np.tile(list(\"xy\"), 135))\n u = pd.Series(np.repeat(list(\"ijkijk\"), 45))\n y = pd.Series(np.random.RandomState(0).randn(270))\n y[u == \"i\"] -= 3\n y[u == \"k\"] += 3\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat1, ci1 = p.statistic, p.confint\n\n p.establish_variables(g, y, h, units=u)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat2, ci2 = p.statistic, p.confint\n\n npt.assert_array_equal(stat1, stat2)\n ci1_size = ci1[:, 0, 1] - ci1[:, 0, 0]\n ci2_size = ci2[:, 0, 1] - ci2[:, 0, 0]\n npt.assert_array_less(ci1_size, ci2_size)\n\n def test_nested_stats_with_missing_data(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n\n p.establish_variables(g, y, h,\n order=list(\"abdc\"),\n hue_order=list(\"zyx\"))\n p.estimate_statistic(\"mean\", (\"ci\", 95), 50000, None)\n\n assert p.statistic.shape == (4, 3)\n assert p.confint.shape == (4, 3, 2)\n\n rows = (g == \"b\") & (h == \"x\")\n mean = y[rows].mean()\n sem = y[rows].std() / np.sqrt(rows.sum())\n half_ci = _normal_quantile_func(.975) * sem\n ci = mean - half_ci, mean + half_ci\n npt.assert_almost_equal(p.statistic[1, 2], mean)\n npt.assert_array_almost_equal(p.confint[1, 2], ci, 2)\n\n npt.assert_array_equal(p.statistic[:, 0], [np.nan] * 4)\n npt.assert_array_equal(p.statistic[2], [np.nan] * 3)\n npt.assert_array_equal(p.confint[:, 0],\n np.zeros((4, 2)) * np.nan)\n npt.assert_array_equal(p.confint[2],\n np.zeros((3, 2)) * np.nan)\n\n def test_sd_error_bars(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y)\n p.estimate_statistic(np.mean, \"sd\", None, None)\n\n assert p.statistic.shape == (3,)\n assert p.confint.shape == (3, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby(g).mean())\n\n for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):\n mean = grp_y.mean()\n half_ci = np.std(grp_y)\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_nested_sd_error_bars(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(np.mean, \"sd\", None, None)\n\n assert p.statistic.shape == (3, 2)\n assert p.confint.shape == (3, 2, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby([g, h]).mean().unstack())\n\n for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):\n for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):\n mean = hue_y.mean()\n half_ci = np.std(hue_y)\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_draw_cis(self):\n\n p = cat._CategoricalStatPlotter()\n\n # Test vertical CIs\n p.orient = \"v\"\n\n f, ax = plt.subplots()\n at_group = [0, 1]\n confints = [(.5, 1.5), (.25, .8)]\n colors = [\".2\", \".3\"]\n p.draw_confints(ax, at_group, confints, colors)\n\n lines = ax.lines\n for line, at, ci, c in zip(lines, at_group, confints, colors):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, [at, at])\n npt.assert_array_equal(y, ci)\n assert line.get_color() == c\n\n plt.close(\"all\")\n\n # Test horizontal CIs\n p.orient = \"h\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors)\n\n lines = ax.lines\n for line, at, ci, c in zip(lines, at_group, confints, colors):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, ci)\n npt.assert_array_equal(y, [at, at])\n assert line.get_color() == c\n\n plt.close(\"all\")\n\n # Test vertical CIs with endcaps\n p.orient = \"v\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, capsize=0.3)\n capline = ax.lines[len(ax.lines) - 1]\n caplinestart = capline.get_xdata()[0]\n caplineend = capline.get_xdata()[1]\n caplinelength = abs(caplineend - caplinestart)\n assert caplinelength == approx(0.3)\n assert len(ax.lines) == 6\n\n plt.close(\"all\")\n\n # Test horizontal CIs with endcaps\n p.orient = \"h\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, capsize=0.3)\n capline = ax.lines[len(ax.lines) - 1]\n caplinestart = capline.get_ydata()[0]\n caplineend = capline.get_ydata()[1]\n caplinelength = abs(caplineend - caplinestart)\n assert caplinelength == approx(0.3)\n assert len(ax.lines) == 6\n\n # Test extra keyword arguments\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, lw=4)\n line = ax.lines[0]\n assert line.get_linewidth() == 4\n\n plt.close(\"all\")\n\n # Test errwidth is set appropriately\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, errwidth=2)\n capline = ax.lines[len(ax.lines) - 1]\n assert capline._linewidth == 2\n assert len(ax.lines) == 2\n\n plt.close(\"all\")\n\n\nclass TestBoxPlotter(CategoricalFixture):\n\n default_kws = dict(x=None, y=None, hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None,\n saturation=.75, width=.8, dodge=True,\n fliersize=5, linewidth=None)\n\n def test_nested_width(self):\n\n kws = self.default_kws.copy()\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .4 * .98\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .3 * .98\n\n kws = self.default_kws.copy()\n kws[\"dodge\"] = False\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .8\n\n def test_hue_offsets(self):\n\n p = cat._BoxPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.2, .2])\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.15, .15])\n\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"h\", \"y\", \"g\", data=self.df)\n npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])\n\n def test_axes_data(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n assert len(self.get_box_artists(ax)) == 3\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(self.get_box_artists(ax)) == 6\n\n plt.close(\"all\")\n\n def test_box_colors(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df, saturation=1)\n pal = palettes.color_palette(n_colors=3)\n assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],\n pal)\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, saturation=1)\n pal = palettes.color_palette(n_colors=2)\n assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],\n pal * 3)\n\n plt.close(\"all\")\n\n def test_draw_missing_boxes(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df,\n order=[\"a\", \"b\", \"c\", \"d\"])\n assert len(self.get_box_artists(ax)) == 3\n\n def test_missing_data(self):\n\n x = [\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"d\"]\n h = [\"x\", \"y\", \"x\", \"y\", \"x\", \"y\", \"x\", \"y\"]\n y = self.rs.randn(8)\n y[-2:] = np.nan\n\n ax = cat.boxplot(x=x, y=y)\n assert len(self.get_box_artists(ax)) == 3\n\n plt.close(\"all\")\n\n y[-1] = 0\n ax = cat.boxplot(x=x, y=y, hue=h)\n assert len(self.get_box_artists(ax)) == 7\n\n plt.close(\"all\")\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.boxplot(x=self.g, y=self.y, ax=ax1)\n cat.boxplot(x=self.g, y=self.y_perm, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.boxplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, ax=ax1)\n cat.boxplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n def test_boxplots(self):\n\n # Smoke test the high level boxplot options\n\n cat.boxplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", order=list(\"nabc\"), data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=list(\"omn\"), data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n def test_axes_annotation(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n assert ax.get_xlim() == (-.5, 2.5)\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],\n [\"m\", \"n\"])\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n assert ax.get_ylim() == (2.5, -.5)\n npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n\nclass TestViolinPlotter(CategoricalFixture):\n\n default_kws = dict(x=None, y=None, hue=None, data=None,\n order=None, hue_order=None,\n bw=\"scott\", cut=2, scale=\"area\", scale_hue=True,\n gridsize=100, width=.8, inner=\"box\", split=False,\n dodge=True, orient=None, linewidth=None,\n color=None, palette=None, saturation=.75)\n\n def test_split_error(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"h\", y=\"y\", hue=\"g\", data=self.df, split=True))\n\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)\n\n def test_no_observations(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n y[-1] = np.nan\n p.establish_variables(x, y)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[0]) == 20\n assert len(p.support[1]) == 0\n\n assert len(p.density[0]) == 20\n assert len(p.density[1]) == 1\n\n assert p.density[1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", True, 20)\n assert p.density[1].item() == 0\n\n x = [\"a\"] * 4 + [\"b\"] * 2\n y = self.rs.randn(6)\n h = [\"m\", \"n\"] * 2 + [\"m\"] * 2\n\n p.establish_variables(x, y, hue=h)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[1][0]) == 20\n assert len(p.support[1][1]) == 0\n\n assert len(p.density[1][0]) == 20\n assert len(p.density[1][1]) == 1\n\n assert p.density[1][1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", False, 20)\n assert p.density[1][1].item() == 0\n\n def test_single_observation(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n p.establish_variables(x, y)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[0]) == 20\n assert len(p.support[1]) == 1\n\n assert len(p.density[0]) == 20\n assert len(p.density[1]) == 1\n\n assert p.density[1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", True, 20)\n assert p.density[1].item() == .5\n\n x = [\"b\"] * 4 + [\"a\"] * 3\n y = self.rs.randn(7)\n h = ([\"m\", \"n\"] * 4)[:-1]\n\n p.establish_variables(x, y, hue=h)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[1][0]) == 20\n assert len(p.support[1][1]) == 1\n\n assert len(p.density[1][0]) == 20\n assert len(p.density[1][1]) == 1\n\n assert p.density[1][1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", False, 20)\n assert p.density[1][1].item() == .5\n\n def test_dwidth(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", data=self.df))\n\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .4\n\n kws.update(dict(width=.4))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .2\n\n kws.update(dict(hue=\"h\", width=.8))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .2\n\n kws.update(dict(split=True))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .4\n\n def test_scale_area(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"area\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]\n max_before = np.array([d.max() for d in density])\n p.scale_area(density, max_before, False)\n max_after = np.array([d.max() for d in density])\n assert max_after[0] == 1\n\n before_ratio = max_before[1] / max_before[0]\n after_ratio = max_after[1] / max_after[0]\n assert before_ratio == after_ratio\n\n # Test nested grouping scaling across all densities\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n max_before = np.array([[r.max() for r in row] for row in density])\n p.scale_area(density, max_before, False)\n max_after = np.array([[r.max() for r in row] for row in density])\n assert max_after[0, 0] == 1\n\n before_ratio = max_before[1, 1] / max_before[0, 0]\n after_ratio = max_after[1, 1] / max_after[0, 0]\n assert before_ratio == after_ratio\n\n # Test nested grouping scaling within hue\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n max_before = np.array([[r.max() for r in row] for row in density])\n p.scale_area(density, max_before, True)\n max_after = np.array([[r.max() for r in row] for row in density])\n assert max_after[0, 0] == 1\n assert max_after[1, 0] == 1\n\n before_ratio = max_before[1, 1] / max_before[1, 0]\n after_ratio = max_after[1, 1] / max_after[1, 0]\n assert before_ratio == after_ratio\n\n def test_scale_width(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"width\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]\n p.scale_width(density)\n max_after = np.array([d.max() for d in density])\n npt.assert_array_equal(max_after, [1, 1])\n\n # Test nested grouping\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n p.scale_width(density)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[1, 1], [1, 1]])\n\n def test_scale_count(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"count\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 20), self.rs.uniform(0, .2, 40)]\n counts = np.array([20, 40])\n p.scale_count(density, counts, False)\n max_after = np.array([d.max() for d in density])\n npt.assert_array_equal(max_after, [.5, 1])\n\n # Test nested grouping scaling across all densities\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],\n [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]\n\n counts = np.array([[5, 40], [100, 50]])\n p.scale_count(density, counts, False)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[.05, .4], [1, .5]])\n\n # Test nested grouping scaling within hue\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],\n [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]\n\n counts = np.array([[5, 40], [100, 50]])\n p.scale_count(density, counts, True)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[.125, 1], [1, .5]])\n\n def test_bad_scale(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"not_a_scale_type\"\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)\n\n def test_kde_fit(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n data = self.y\n data_std = data.std(ddof=1)\n\n # Test reference rule bandwidth\n kde, bw = p.fit_kde(data, \"scott\")\n assert kde.factor == kde.scotts_factor()\n assert bw == kde.scotts_factor() * data_std\n\n # Test numeric scale factor\n kde, bw = p.fit_kde(self.y, .2)\n assert kde.factor == .2\n assert bw == .2 * data_std\n\n def test_draw_to_density(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n # p.dwidth will be 1 for easier testing\n p.width = 2\n\n # Test vertical plots\n support = np.array([.2, .6])\n density = np.array([.1, .4])\n\n # Test full vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, False)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.99 * -.4, .99 * .4])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Test left vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, \"left\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.99 * -.4, 0])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Test right vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, \"right\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [0, .99 * .4])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Switch orientation to test horizontal plots\n p.orient = \"h\"\n support = np.array([.2, .5])\n density = np.array([.3, .7])\n\n # Test full horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, False)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [.99 * -.7, .99 * .7])\n plt.close(\"all\")\n\n # Test left horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, \"left\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [.99 * -.7, 0])\n plt.close(\"all\")\n\n # Test right horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, \"right\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [0, .99 * .7])\n plt.close(\"all\")\n\n def test_draw_single_observations(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n p.width = 2\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_single_observation(ax, 1, 1.5, 1)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [0, 2])\n npt.assert_array_equal(y, [1.5, 1.5])\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_single_observation(ax, 2, 2.2, .5)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [2.2, 2.2])\n npt.assert_array_equal(y, [1.5, 2.5])\n plt.close(\"all\")\n\n def test_draw_box_lines(self):\n\n # Test vertical plot\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_box_lines(ax, self.y, 0)\n assert len(ax.lines) == 2\n\n q25, q50, q75 = np.percentile(self.y, [25, 50, 75])\n _, y = ax.lines[1].get_xydata().T\n npt.assert_array_equal(y, [q25, q75])\n\n _, y = ax.collections[0].get_offsets().T\n assert y == q50\n\n plt.close(\"all\")\n\n # Test horizontal plot\n kws = self.default_kws.copy()\n kws.update(dict(x=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_box_lines(ax, self.y, 0)\n assert len(ax.lines) == 2\n\n q25, q50, q75 = np.percentile(self.y, [25, 50, 75])\n x, _ = ax.lines[1].get_xydata().T\n npt.assert_array_equal(x, [q25, q75])\n\n x, _ = ax.collections[0].get_offsets().T\n assert x == q50\n\n plt.close(\"all\")\n\n def test_draw_quartiles(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_quartiles(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(np.percentile(self.y, [25, 50, 75]), ax.lines):\n _, y = line.get_xydata().T\n npt.assert_array_equal(y, [val, val])\n\n def test_draw_points(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_points(ax, self.y, 0)\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, np.zeros_like(self.y))\n npt.assert_array_equal(y, self.y)\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_points(ax, self.y, 0)\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.y)\n npt.assert_array_equal(y, np.zeros_like(self.y))\n plt.close(\"all\")\n\n def test_draw_sticks(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(self.y, ax.lines):\n _, y = line.get_xydata().T\n npt.assert_array_equal(y, [val, val])\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(self.y, ax.lines):\n x, _ = line.get_xydata().T\n npt.assert_array_equal(x, [val, val])\n plt.close(\"all\")\n\n def test_validate_inner(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(inner=\"bad_inner\"))\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)\n\n def test_draw_violinplots(self):\n\n kws = self.default_kws.copy()\n\n # Test single vertical violin\n kws.update(dict(y=\"y\", data=self.df, inner=None,\n saturation=1, color=(1, 0, 0, 1)))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n npt.assert_array_equal(ax.collections[0].get_facecolors(),\n [(1, 0, 0, 1)])\n plt.close(\"all\")\n\n # Test single horizontal violin\n kws.update(dict(x=\"y\", y=None, color=(0, 1, 0, 1)))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n npt.assert_array_equal(ax.collections[0].get_facecolors(),\n [(0, 1, 0, 1)])\n plt.close(\"all\")\n\n # Test multiple vertical violins\n kws.update(dict(x=\"g\", y=\"y\", color=None,))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n for violin, color in zip(ax.collections, palettes.color_palette()):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n # Test multiple violins with hue nesting\n kws.update(dict(hue=\"h\"))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 6\n for violin, color in zip(ax.collections,\n palettes.color_palette(n_colors=2) * 3):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n # Test multiple split violins\n kws.update(dict(split=True, palette=\"muted\"))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 6\n for violin, color in zip(ax.collections,\n palettes.color_palette(\"muted\",\n n_colors=2) * 3):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n def test_draw_violinplots_no_observations(self):\n\n kws = self.default_kws.copy()\n kws[\"inner\"] = None\n\n # Test single layer of grouping\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n y[-1] = np.nan\n kws.update(x=x, y=y)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n assert len(ax.lines) == 0\n plt.close(\"all\")\n\n # Test nested hue grouping\n x = [\"a\"] * 4 + [\"b\"] * 2\n y = self.rs.randn(6)\n h = [\"m\", \"n\"] * 2 + [\"m\"] * 2\n kws.update(x=x, y=y, hue=h)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 0\n plt.close(\"all\")\n\n def test_draw_violinplots_single_observations(self):\n\n kws = self.default_kws.copy()\n kws[\"inner\"] = None\n\n # Test single layer of grouping\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n kws.update(x=x, y=y)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n # Test nested hue grouping\n x = [\"b\"] * 4 + [\"a\"] * 3\n y = self.rs.randn(7)\n h = ([\"m\", \"n\"] * 4)[:-1]\n kws.update(x=x, y=y, hue=h)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n # Test nested hue grouping with split\n kws[\"split\"] = True\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n def test_violinplots(self):\n\n # Smoke test the high level violinplot options\n\n cat.violinplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n order = list(\"nabc\")\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", order=order, data=self.df)\n plt.close(\"all\")\n\n order = list(\"omn\")\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=order, data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n for inner in [\"box\", \"quart\", \"point\", \"stick\", None]:\n cat.violinplot(x=\"g\", y=\"y\", data=self.df, inner=inner)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, inner=inner)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n inner=inner, split=True)\n plt.close(\"all\")\n\n def test_split_one_each(self, rng):\n\n x = np.repeat([0, 1], 5)\n y = rng.normal(0, 1, 10)\n ax = cat.violinplot(x=x, y=y, hue=x, split=True, inner=\"box\")\n assert len(ax.lines) == 4\n\n\n# ====================================================================================\n# ====================================================================================\n\n\nclass SharedAxesLevelTests:\n\n def test_color(self, long_df):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C0\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C1\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", color=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", color=\"C3\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C3\")\n\n def test_two_calls(self):\n\n ax = plt.figure().subplots()\n self.func(x=[\"a\", \"b\", \"c\"], y=[1, 2, 3], ax=ax)\n self.func(x=[\"e\", \"f\"], y=[4, 5], ax=ax)\n assert ax.get_xlim() == (-.5, 4.5)\n\n\nclass SharedScatterTests(SharedAxesLevelTests):\n \"\"\"Tests functionality common to stripplot and swarmplot.\"\"\"\n\n def get_last_color(self, ax):\n\n colors = ax.collections[-1].get_facecolors()\n unique_colors = np.unique(colors, axis=0)\n assert len(unique_colors) == 1\n return to_rgba(unique_colors.squeeze())\n\n # ------------------------------------------------------------------------------\n\n def test_color(self, long_df):\n\n super().test_color(long_df)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", facecolor=\"C4\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C4\")\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", fc=\"C5\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C5\")\n\n def test_supplied_color_array(self, long_df):\n\n cmap = get_colormap(\"Blues\")\n norm = mpl.colors.Normalize()\n colors = cmap(norm(long_df[\"y\"].to_numpy()))\n\n keys = [\"c\", \"facecolor\", \"facecolors\"]\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n keys.append(\"fc\")\n\n for key in keys:\n\n ax = plt.figure().subplots()\n self.func(x=long_df[\"y\"], **{key: colors})\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n ax = plt.figure().subplots()\n self.func(x=long_df[\"y\"], c=long_df[\"y\"], cmap=cmap)\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n @pytest.mark.parametrize(\n \"orient,data_type\",\n itertools.product([\"h\", \"v\"], [\"dataframe\", \"dict\"]),\n )\n def test_wide(self, wide_df, orient, data_type):\n\n if data_type == \"dict\":\n wide_df = {k: v.to_numpy() for k, v in wide_df.items()}\n\n ax = self.func(data=wide_df, orient=orient)\n _draw_figure(ax.figure)\n palette = color_palette()\n\n cat_idx = 0 if orient == \"v\" else 1\n val_idx = int(not cat_idx)\n\n axis_objs = ax.xaxis, ax.yaxis\n cat_axis = axis_objs[cat_idx]\n\n for i, label in enumerate(cat_axis.get_majorticklabels()):\n\n key = label.get_text()\n points = ax.collections[i]\n point_pos = points.get_offsets().T\n val_pos = point_pos[val_idx]\n cat_pos = point_pos[cat_idx]\n\n assert_array_equal(cat_pos.round(), i)\n assert_array_equal(val_pos, wide_df[key])\n\n for point_color in points.get_facecolors():\n assert tuple(point_color) == to_rgba(palette[i])\n\n @pytest.mark.parametrize(\"orient\", [\"h\", \"v\"])\n def test_flat(self, flat_series, orient):\n\n ax = self.func(data=flat_series, orient=orient)\n _draw_figure(ax.figure)\n\n cat_idx = [\"v\", \"h\"].index(orient)\n val_idx = int(not cat_idx)\n\n points = ax.collections[0]\n pos = points.get_offsets().T\n\n assert_array_equal(pos[cat_idx].round(), np.zeros(len(flat_series)))\n assert_array_equal(pos[val_idx], flat_series)\n\n @pytest.mark.parametrize(\n \"variables,orient\",\n [\n # Order matters for assigning to x/y\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": None}, None),\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": \"a\"}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": \"a\"}, None),\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": \"x\"}, None),\n ({\"cat\": \"s\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"s\", \"hue\": None}, \"h\"),\n ({\"cat\": \"a\", \"val\": \"b\", \"hue\": None}, None),\n ({\"val\": \"a\", \"cat\": \"b\", \"hue\": None}, \"h\"),\n ({\"cat\": \"a\", \"val\": \"t\", \"hue\": None}, None),\n ({\"val\": \"t\", \"cat\": \"a\", \"hue\": None}, None),\n ({\"cat\": \"d\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"d\", \"hue\": None}, None),\n ({\"cat\": \"a_cat\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"s_cat\", \"hue\": None}, None),\n ],\n )\n def test_positions(self, long_df, variables, orient):\n\n cat_var = variables[\"cat\"]\n val_var = variables[\"val\"]\n hue_var = variables[\"hue\"]\n var_names = list(variables.values())\n x_var, y_var, *_ = var_names\n\n ax = self.func(\n data=long_df, x=x_var, y=y_var, hue=hue_var, orient=orient,\n )\n\n _draw_figure(ax.figure)\n\n cat_idx = var_names.index(cat_var)\n val_idx = var_names.index(val_var)\n\n axis_objs = ax.xaxis, ax.yaxis\n cat_axis = axis_objs[cat_idx]\n val_axis = axis_objs[val_idx]\n\n cat_data = long_df[cat_var]\n cat_levels = categorical_order(cat_data)\n\n for i, label in enumerate(cat_levels):\n\n vals = long_df.loc[cat_data == label, val_var]\n\n points = ax.collections[i].get_offsets().T\n cat_pos = points[var_names.index(cat_var)]\n val_pos = points[var_names.index(val_var)]\n\n assert_array_equal(val_pos, val_axis.convert_units(vals))\n assert_array_equal(cat_pos.round(), i)\n assert 0 <= np.ptp(cat_pos) <= .8\n\n label = pd.Index([label]).astype(str)[0]\n assert cat_axis.get_majorticklabels()[i].get_text() == label\n\n @pytest.mark.parametrize(\n \"variables\",\n [\n # Order matters for assigning to x/y\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"},\n {\"val\": \"y\", \"cat\": \"a\", \"hue\": \"c\"},\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"f\"},\n ],\n )\n def test_positions_dodged(self, long_df, variables):\n\n cat_var = variables[\"cat\"]\n val_var = variables[\"val\"]\n hue_var = variables[\"hue\"]\n var_names = list(variables.values())\n x_var, y_var, *_ = var_names\n\n ax = self.func(\n data=long_df, x=x_var, y=y_var, hue=hue_var, dodge=True,\n )\n\n cat_vals = categorical_order(long_df[cat_var])\n hue_vals = categorical_order(long_df[hue_var])\n\n n_hue = len(hue_vals)\n offsets = np.linspace(0, .8, n_hue + 1)[:-1]\n offsets -= offsets.mean()\n nest_width = .8 / n_hue\n\n for i, cat_val in enumerate(cat_vals):\n for j, hue_val in enumerate(hue_vals):\n rows = (long_df[cat_var] == cat_val) & (long_df[hue_var] == hue_val)\n vals = long_df.loc[rows, val_var]\n\n points = ax.collections[n_hue * i + j].get_offsets().T\n cat_pos = points[var_names.index(cat_var)]\n val_pos = points[var_names.index(val_var)]\n\n if pd.api.types.is_datetime64_any_dtype(vals):\n vals = mpl.dates.date2num(vals)\n\n assert_array_equal(val_pos, vals)\n\n assert_array_equal(cat_pos.round(), i)\n assert_array_equal((cat_pos - (i + offsets[j])).round() / nest_width, 0)\n assert 0 <= np.ptp(cat_pos) <= nest_width\n\n @pytest.mark.parametrize(\"cat_var\", [\"a\", \"s\", \"d\"])\n def test_positions_unfixed(self, long_df, cat_var):\n\n long_df = long_df.sort_values(cat_var)\n\n kws = dict(size=.001)\n if \"stripplot\" in str(self.func): # can't use __name__ with partial\n kws[\"jitter\"] = False\n\n ax = self.func(data=long_df, x=cat_var, y=\"y\", native_scale=True, **kws)\n\n for i, (cat_level, cat_data) in enumerate(long_df.groupby(cat_var)):\n\n points = ax.collections[i].get_offsets().T\n cat_pos = points[0]\n val_pos = points[1]\n\n assert_array_equal(val_pos, cat_data[\"y\"])\n\n comp_level = np.squeeze(ax.xaxis.convert_units(cat_level)).item()\n assert_array_equal(cat_pos.round(), comp_level)\n\n @pytest.mark.parametrize(\n \"x_type,order\",\n [\n (str, None),\n (str, [\"a\", \"b\", \"c\"]),\n (str, [\"c\", \"a\"]),\n (str, [\"a\", \"b\", \"c\", \"d\"]),\n (int, None),\n (int, [3, 1, 2]),\n (int, [3, 1]),\n (int, [1, 2, 3, 4]),\n (int, [\"3\", \"1\", \"2\"]),\n ]\n )\n def test_order(self, x_type, order):\n\n if x_type is str:\n x = [\"b\", \"a\", \"c\"]\n else:\n x = [2, 1, 3]\n y = [1, 2, 3]\n\n ax = self.func(x=x, y=y, order=order)\n _draw_figure(ax.figure)\n\n if order is None:\n order = x\n if x_type is int:\n order = np.sort(order)\n\n assert len(ax.collections) == len(order)\n tick_labels = ax.xaxis.get_majorticklabels()\n\n assert ax.get_xlim()[1] == (len(order) - .5)\n\n for i, points in enumerate(ax.collections):\n cat = order[i]\n assert tick_labels[i].get_text() == str(cat)\n\n positions = points.get_offsets()\n if x_type(cat) in x:\n val = y[x.index(x_type(cat))]\n assert positions[0, 1] == val\n else:\n assert not positions.size\n\n @pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_categorical(self, long_df, hue_var):\n\n cat_var = \"b\"\n\n hue_levels = categorical_order(long_df[hue_var])\n cat_levels = categorical_order(long_df[cat_var])\n\n pal_name = \"muted\"\n palette = dict(zip(hue_levels, color_palette(pal_name)))\n ax = self.func(data=long_df, x=cat_var, y=\"y\", hue=hue_var, palette=pal_name)\n\n for i, level in enumerate(cat_levels):\n\n sub_df = long_df[long_df[cat_var] == level]\n point_hues = sub_df[hue_var]\n\n points = ax.collections[i]\n point_colors = points.get_facecolors()\n\n assert len(point_hues) == len(point_colors)\n\n for hue, color in zip(point_hues, point_colors):\n assert tuple(color) == to_rgba(palette[hue])\n\n @pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_dodged(self, long_df, hue_var):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=hue_var, dodge=True)\n colors = color_palette(n_colors=long_df[hue_var].nunique())\n collections = iter(ax.collections)\n\n # Slightly awkward logic to handle challenges of how the artists work.\n # e.g. there are empty scatter collections but the because facecolors\n # for the empty collections will return the default scatter color\n while colors:\n points = next(collections)\n if points.get_offsets().any():\n face_color = tuple(points.get_facecolors()[0])\n expected_color = to_rgba(colors.pop(0))\n assert face_color == expected_color\n\n @pytest.mark.parametrize(\n \"val_var,val_col,hue_col\",\n list(itertools.product([\"x\", \"y\"], [\"b\", \"y\", \"t\"], [None, \"a\"])),\n )\n def test_single(self, long_df, val_var, val_col, hue_col):\n\n var_kws = {val_var: val_col, \"hue\": hue_col}\n ax = self.func(data=long_df, **var_kws)\n _draw_figure(ax.figure)\n\n axis_vars = [\"x\", \"y\"]\n val_idx = axis_vars.index(val_var)\n cat_idx = int(not val_idx)\n cat_var = axis_vars[cat_idx]\n\n cat_axis = getattr(ax, f\"{cat_var}axis\")\n val_axis = getattr(ax, f\"{val_var}axis\")\n\n points = ax.collections[0]\n point_pos = points.get_offsets().T\n cat_pos = point_pos[cat_idx]\n val_pos = point_pos[val_idx]\n\n assert_array_equal(cat_pos.round(), 0)\n assert cat_pos.max() <= .4\n assert cat_pos.min() >= -.4\n\n num_vals = val_axis.convert_units(long_df[val_col])\n assert_array_equal(val_pos, num_vals)\n\n if hue_col is not None:\n palette = dict(zip(\n categorical_order(long_df[hue_col]), color_palette()\n ))\n\n facecolors = points.get_facecolors()\n for i, color in enumerate(facecolors):\n if hue_col is None:\n assert tuple(color) == to_rgba(\"C0\")\n else:\n hue_level = long_df.loc[i, hue_col]\n expected_color = palette[hue_level]\n assert tuple(color) == to_rgba(expected_color)\n\n ticklabels = cat_axis.get_majorticklabels()\n assert len(ticklabels) == 1\n assert not ticklabels[0].get_text()\n\n def test_attributes(self, long_df):\n\n kwargs = dict(\n size=2,\n linewidth=1,\n edgecolor=\"C2\",\n )\n\n ax = self.func(x=long_df[\"y\"], **kwargs)\n points, = ax.collections\n\n assert points.get_sizes().item() == kwargs[\"size\"] ** 2\n assert points.get_linewidths().item() == kwargs[\"linewidth\"]\n assert tuple(points.get_edgecolors().squeeze()) == to_rgba(kwargs[\"edgecolor\"])\n\n def test_three_points(self):\n\n x = np.arange(3)\n ax = self.func(x=x)\n for point_color in ax.collections[0].get_facecolor():\n assert tuple(point_color) == to_rgba(\"C0\")\n\n def test_legend_categorical(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"b\")\n legend_texts = [t.get_text() for t in ax.legend_.texts]\n expected = categorical_order(long_df[\"b\"])\n assert legend_texts == expected\n\n def test_legend_numeric(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"z\")\n vals = [float(t.get_text()) for t in ax.legend_.texts]\n assert (vals[1] - vals[0]) == pytest.approx(vals[2] - vals[1])\n\n def test_legend_disabled(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"b\", legend=False)\n assert ax.legend_ is None\n\n def test_palette_from_color_deprecation(self, long_df):\n\n color = (.9, .4, .5)\n hex_color = mpl.colors.to_hex(color)\n\n hue_var = \"a\"\n n_hue = long_df[hue_var].nunique()\n palette = color_palette(f\"dark:{hex_color}\", n_hue)\n\n with pytest.warns(FutureWarning, match=\"Setting a gradient palette\"):\n ax = self.func(data=long_df, x=\"z\", hue=hue_var, color=color)\n\n points = ax.collections[0]\n for point_color in points.get_facecolors():\n assert to_rgb(point_color) in palette\n\n def test_palette_with_hue_deprecation(self, long_df):\n palette = \"Blues\"\n with pytest.warns(FutureWarning, match=\"Passing `palette` without\"):\n ax = self.func(data=long_df, x=\"a\", y=long_df[\"y\"], palette=palette)\n strips = ax.collections\n colors = color_palette(palette, len(strips))\n for strip, color in zip(strips, colors):\n assert same_color(strip.get_facecolor()[0], color)\n\n def test_log_scale(self):\n\n x = [1, 10, 100, 1000]\n\n ax = plt.figure().subplots()\n ax.set_xscale(\"log\")\n self.func(x=x)\n vals = ax.collections[0].get_offsets()[:, 0]\n assert_array_equal(x, vals)\n\n y = [1, 2, 3, 4]\n\n ax = plt.figure().subplots()\n ax.set_xscale(\"log\")\n self.func(x=x, y=y, native_scale=True)\n for i, point in enumerate(ax.collections):\n val = point.get_offsets()[0, 0]\n assert val == pytest.approx(x[i])\n\n x = y = np.ones(100)\n\n # Following test fails on pinned (but not latest) matplotlib.\n # (Even though visual output is ok -- so it's not an actual bug).\n # I'm not exactly sure why, so this version check is approximate\n # and should be revisited on a version bump.\n if Version(mpl.__version__) < Version(\"3.1\"):\n pytest.xfail()\n\n ax = plt.figure().subplots()\n ax.set_yscale(\"log\")\n self.func(x=x, y=y, orient=\"h\", native_scale=True)\n cat_points = ax.collections[0].get_offsets().copy()[:, 1]\n assert np.ptp(np.log10(cat_points)) <= .8\n\n @pytest.mark.parametrize(\n \"kwargs\",\n [\n dict(data=\"wide\"),\n dict(data=\"wide\", orient=\"h\"),\n dict(data=\"long\", x=\"x\", color=\"C3\"),\n dict(data=\"long\", y=\"y\", hue=\"a\", jitter=False),\n dict(data=\"long\", x=\"a\", y=\"y\", hue=\"z\", edgecolor=\"w\", linewidth=.5),\n dict(data=\"long\", x=\"a_cat\", y=\"y\", hue=\"z\"),\n dict(data=\"long\", x=\"y\", y=\"s\", hue=\"c\", orient=\"h\", dodge=True),\n dict(data=\"long\", x=\"s\", y=\"y\", hue=\"c\", native_scale=True),\n ]\n )\n def test_vs_catplot(self, long_df, wide_df, kwargs):\n\n kwargs = kwargs.copy()\n if kwargs[\"data\"] == \"long\":\n kwargs[\"data\"] = long_df\n elif kwargs[\"data\"] == \"wide\":\n kwargs[\"data\"] = wide_df\n\n try:\n name = self.func.__name__[:-4]\n except AttributeError:\n name = self.func.func.__name__[:-4]\n if name == \"swarm\":\n kwargs.pop(\"jitter\", None)\n\n np.random.seed(0) # for jitter\n ax = self.func(**kwargs)\n\n np.random.seed(0)\n g = catplot(**kwargs, kind=name)\n\n assert_plots_equal(ax, g.ax)\n\n\nclass TestStripPlot(SharedScatterTests):\n\n func = staticmethod(stripplot)\n\n def test_jitter_unfixed(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n kws = dict(data=long_df, x=\"y\", orient=\"h\", native_scale=True)\n\n np.random.seed(0)\n stripplot(**kws, y=\"s\", ax=ax1)\n\n np.random.seed(0)\n stripplot(**kws, y=long_df[\"s\"] * 2, ax=ax2)\n\n p1 = ax1.collections[0].get_offsets()[1]\n p2 = ax2.collections[0].get_offsets()[1]\n\n assert p2.std() > p1.std()\n\n @pytest.mark.parametrize(\n \"orient,jitter\",\n itertools.product([\"v\", \"h\"], [True, .1]),\n )\n def test_jitter(self, long_df, orient, jitter):\n\n cat_var, val_var = \"a\", \"y\"\n if orient == \"v\":\n x_var, y_var = cat_var, val_var\n cat_idx, val_idx = 0, 1\n else:\n x_var, y_var = val_var, cat_var\n cat_idx, val_idx = 1, 0\n\n cat_vals = categorical_order(long_df[cat_var])\n\n ax = stripplot(\n data=long_df, x=x_var, y=y_var, jitter=jitter,\n )\n\n if jitter is True:\n jitter_range = .4\n else:\n jitter_range = 2 * jitter\n\n for i, level in enumerate(cat_vals):\n\n vals = long_df.loc[long_df[cat_var] == level, val_var]\n points = ax.collections[i].get_offsets().T\n cat_points = points[cat_idx]\n val_points = points[val_idx]\n\n assert_array_equal(val_points, vals)\n assert np.std(cat_points) > 0\n assert np.ptp(cat_points) <= jitter_range\n\n\nclass TestSwarmPlot(SharedScatterTests):\n\n func = staticmethod(partial(swarmplot, warn_thresh=1))\n\n\nclass TestBarPlotter(CategoricalFixture):\n\n default_kws = dict(\n data=None, x=None, y=None, hue=None, units=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=100, seed=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None,\n saturation=.75, width=0.8,\n errcolor=\".26\", errwidth=None,\n capsize=None, dodge=True\n )\n\n def test_nested_width(self):\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"h\")\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.8 / 2)\n ax.clear()\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"g\", width=.5)\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.5 / 3)\n ax.clear()\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"g\", dodge=False)\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.8)\n ax.clear()\n\n def test_draw_vertical_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data)\n assert len(ax.lines) == len(p.plot_data)\n\n for bar, color in zip(ax.patches, p.colors):\n assert bar.get_facecolor()[:-1] == color\n\n positions = np.arange(len(p.plot_data)) - p.width / 2\n for bar, pos, stat in zip(ax.patches, positions, p.statistic):\n assert bar.get_x() == pos\n assert bar.get_width() == p.width\n assert bar.get_y() == 0\n assert bar.get_height() == stat\n\n def test_draw_horizontal_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data)\n assert len(ax.lines) == len(p.plot_data)\n\n for bar, color in zip(ax.patches, p.colors):\n assert bar.get_facecolor()[:-1] == color\n\n positions = np.arange(len(p.plot_data)) - p.width / 2\n for bar, pos, stat in zip(ax.patches, positions, p.statistic):\n assert bar.get_y() == pos\n assert bar.get_height() == p.width\n assert bar.get_x() == 0\n assert bar.get_width() == stat\n\n def test_draw_nested_vertical_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n n_groups, n_hues = len(p.plot_data), len(p.hue_names)\n assert len(ax.patches) == n_groups * n_hues\n assert len(ax.lines) == n_groups * n_hues\n\n for bar in ax.patches[:n_groups]:\n assert bar.get_facecolor()[:-1] == p.colors[0]\n for bar in ax.patches[n_groups:]:\n assert bar.get_facecolor()[:-1] == p.colors[1]\n\n positions = np.arange(len(p.plot_data))\n for bar, pos in zip(ax.patches[:n_groups], positions):\n assert bar.get_x() == approx(pos - p.width / 2)\n assert bar.get_width() == approx(p.nested_width)\n\n for bar, stat in zip(ax.patches, p.statistic.T.flat):\n assert bar.get_y() == approx(0)\n assert bar.get_height() == approx(stat)\n\n def test_draw_nested_horizontal_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n n_groups, n_hues = len(p.plot_data), len(p.hue_names)\n assert len(ax.patches) == n_groups * n_hues\n assert len(ax.lines) == n_groups * n_hues\n\n for bar in ax.patches[:n_groups]:\n assert bar.get_facecolor()[:-1] == p.colors[0]\n for bar in ax.patches[n_groups:]:\n assert bar.get_facecolor()[:-1] == p.colors[1]\n\n positions = np.arange(len(p.plot_data))\n for bar, pos in zip(ax.patches[:n_groups], positions):\n assert bar.get_y() == approx(pos - p.width / 2)\n assert bar.get_height() == approx(p.nested_width)\n\n for bar, stat in zip(ax.patches, p.statistic.T.flat):\n assert bar.get_x() == approx(0)\n assert bar.get_width() == approx(stat)\n\n def test_draw_missing_bars(self):\n\n kws = self.default_kws.copy()\n\n order = list(\"abcd\")\n kws.update(x=\"g\", y=\"y\", order=order, data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(order)\n assert len(ax.lines) == len(order)\n\n plt.close(\"all\")\n\n hue_order = list(\"mno\")\n kws.update(x=\"g\", y=\"y\", hue=\"h\", hue_order=hue_order, data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data) * len(hue_order)\n assert len(ax.lines) == len(p.plot_data) * len(hue_order)\n\n plt.close(\"all\")\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.barplot(x=self.g, y=self.y, errorbar=\"sd\", ax=ax1)\n cat.barplot(x=self.g, y=self.y_perm, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.patches, ax2.patches):\n assert approx(p1.get_xy()) == p2.get_xy()\n assert approx(p1.get_height()) == p2.get_height()\n assert approx(p1.get_width()) == p2.get_width()\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.barplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax1)\n cat.barplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.patches, ax2.patches):\n assert approx(p1.get_xy()) == p2.get_xy()\n assert approx(p1.get_height()) == p2.get_height()\n assert approx(p1.get_width()) == p2.get_width()\n\n def test_barplot_colors(self):\n\n # Test unnested palette colors\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df,\n saturation=1, palette=\"muted\")\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n palette = palettes.color_palette(\"muted\", len(self.g.unique()))\n for patch, pal_color in zip(ax.patches, palette):\n assert patch.get_facecolor()[:-1] == pal_color\n\n plt.close(\"all\")\n\n # Test single color\n color = (.2, .2, .3, 1)\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df,\n saturation=1, color=color)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n for patch in ax.patches:\n assert patch.get_facecolor() == color\n\n plt.close(\"all\")\n\n # Test nested palette colors\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n saturation=1, palette=\"Set2\")\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n palette = palettes.color_palette(\"Set2\", len(self.h.unique()))\n for patch in ax.patches[:len(self.g.unique())]:\n assert patch.get_facecolor()[:-1] == palette[0]\n for patch in ax.patches[len(self.g.unique()):]:\n assert patch.get_facecolor()[:-1] == palette[1]\n\n plt.close(\"all\")\n\n def test_simple_barplots(self):\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df)\n assert len(ax.patches) == len(self.g.unique())\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique())\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n def test_errorbar(self, long_df):\n\n ax = cat.barplot(data=long_df, x=\"a\", y=\"y\", errorbar=(\"sd\", 2))\n order = categorical_order(long_df[\"a\"])\n\n for i, line in enumerate(ax.lines):\n sub_df = long_df.loc[long_df[\"a\"] == order[i], \"y\"]\n mean = sub_df.mean()\n sd = sub_df.std()\n expected = mean - 2 * sd, mean + 2 * sd\n assert_array_equal(line.get_ydata(), expected)\n\n\nclass TestPointPlotter(CategoricalFixture):\n\n default_kws = dict(\n x=None, y=None, hue=None, data=None,\n estimator=\"mean\", errorbar=(\"ci\", 95),\n n_boot=100, units=None, seed=None,\n order=None, hue_order=None,\n markers=\"o\", linestyles=\"-\", dodge=0,\n join=True, scale=1,\n orient=None, color=None, palette=None,\n )\n\n def test_different_defualt_colors(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", data=self.df))\n p = cat._PointPlotter(**kws)\n color = palettes.color_palette()[0]\n npt.assert_array_equal(p.colors, [color, color, color])\n\n def test_hue_offsets(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", hue=\"h\", data=self.df))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [0, 0])\n\n kws.update(dict(dodge=.5))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [-.25, .25])\n\n kws.update(dict(x=\"h\", hue=\"g\", dodge=0))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [0, 0, 0])\n\n kws.update(dict(dodge=.3))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [-.15, 0, .15])\n\n def test_draw_vertical_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(p.plot_data) + 1\n points = ax.collections[0]\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, np.arange(len(p.plot_data)))\n npt.assert_array_equal(y, p.statistic)\n\n for got_color, want_color in zip(points.get_facecolors(),\n p.colors):\n npt.assert_array_equal(got_color[:-1], want_color)\n\n def test_draw_horizontal_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(p.plot_data) + 1\n points = ax.collections[0]\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, p.statistic)\n npt.assert_array_equal(y, np.arange(len(p.plot_data)))\n\n for got_color, want_color in zip(points.get_facecolors(),\n p.colors):\n npt.assert_array_equal(got_color[:-1], want_color)\n\n def test_draw_vertical_nested_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 2\n assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)\n\n for points, numbers, color in zip(ax.collections,\n p.statistic.T,\n p.colors):\n\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, np.arange(len(p.plot_data)))\n npt.assert_array_equal(y, numbers)\n\n for got_color in points.get_facecolors():\n npt.assert_array_equal(got_color[:-1], color)\n\n def test_draw_horizontal_nested_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 2\n assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)\n\n for points, numbers, color in zip(ax.collections,\n p.statistic.T,\n p.colors):\n\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, numbers)\n npt.assert_array_equal(y, np.arange(len(p.plot_data)))\n\n for got_color in points.get_facecolors():\n npt.assert_array_equal(got_color[:-1], color)\n\n def test_draw_missing_points(self):\n\n kws = self.default_kws.copy()\n df = self.df.copy()\n\n kws.update(x=\"g\", y=\"y\", hue=\"h\", hue_order=[\"x\", \"y\"], data=df)\n p = cat._PointPlotter(**kws)\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n df.loc[df[\"h\"] == \"m\", \"y\"] = np.nan\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=df)\n p = cat._PointPlotter(**kws)\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.pointplot(x=self.g, y=self.y, errorbar=\"sd\", ax=ax1)\n cat.pointplot(x=self.g, y=self.y_perm, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.collections, ax2.collections):\n assert approx(p1.get_offsets()) == p2.get_offsets()\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.pointplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax1)\n cat.pointplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.collections, ax2.collections):\n assert approx(p1.get_offsets()) == p2.get_offsets()\n\n def test_pointplot_colors(self):\n\n # Test a single-color unnested plot\n color = (.2, .2, .3, 1)\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df, color=color)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line in ax.lines:\n assert line.get_color() == color[:-1]\n\n for got_color in ax.collections[0].get_facecolors():\n npt.assert_array_equal(rgb2hex(got_color), rgb2hex(color))\n\n plt.close(\"all\")\n\n # Test a multi-color unnested plot\n palette = palettes.color_palette(\"Set1\", 3)\n kws.update(x=\"g\", y=\"y\", data=self.df, palette=\"Set1\")\n p = cat._PointPlotter(**kws)\n\n assert not p.join\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line, pal_color in zip(ax.lines, palette):\n npt.assert_array_equal(line.get_color(), pal_color)\n\n for point_color, pal_color in zip(ax.collections[0].get_facecolors(),\n palette):\n npt.assert_array_equal(rgb2hex(point_color), rgb2hex(pal_color))\n\n plt.close(\"all\")\n\n # Test a multi-colored nested plot\n palette = palettes.color_palette(\"dark\", 2)\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df, palette=\"dark\")\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line in ax.lines[:(len(p.plot_data) + 1)]:\n assert line.get_color() == palette[0]\n for line in ax.lines[(len(p.plot_data) + 1):]:\n assert line.get_color() == palette[1]\n\n for i, pal_color in enumerate(palette):\n for point_color in ax.collections[i].get_facecolors():\n npt.assert_array_equal(point_color[:-1], pal_color)\n\n plt.close(\"all\")\n\n def test_simple_pointplots(self):\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df)\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(self.g.unique()) + 1\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(self.g.unique()) + 1\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(ax.collections) == len(self.h.unique())\n assert len(ax.lines) == (\n len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())\n )\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n assert len(ax.collections) == len(self.h.unique())\n assert len(ax.lines) == (\n len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())\n )\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n def test_errorbar(self, long_df):\n\n ax = cat.pointplot(\n data=long_df, x=\"a\", y=\"y\", errorbar=(\"sd\", 2), join=False\n )\n order = categorical_order(long_df[\"a\"])\n\n for i, line in enumerate(ax.lines):\n sub_df = long_df.loc[long_df[\"a\"] == order[i], \"y\"]\n mean = sub_df.mean()\n sd = sub_df.std()\n expected = mean - 2 * sd, mean + 2 * sd\n assert_array_equal(line.get_ydata(), expected)\n\n\nclass TestCountPlot(CategoricalFixture):\n\n def test_plot_elements(self):\n\n ax = cat.countplot(x=\"g\", data=self.df)\n assert len(ax.patches) == self.g.unique().size\n for p in ax.patches:\n assert p.get_y() == 0\n assert p.get_height() == self.g.size / self.g.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(y=\"g\", data=self.df)\n assert len(ax.patches) == self.g.unique().size\n for p in ax.patches:\n assert p.get_x() == 0\n assert p.get_width() == self.g.size / self.g.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(x=\"g\", hue=\"h\", data=self.df)\n assert len(ax.patches) == self.g.unique().size * self.h.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(y=\"g\", hue=\"h\", data=self.df)\n assert len(ax.patches) == self.g.unique().size * self.h.unique().size\n plt.close(\"all\")\n\n def test_input_error(self):\n\n with pytest.raises(ValueError):\n cat.countplot(x=\"g\", y=\"h\", data=self.df)\n\n\nclass TestCatPlot(CategoricalFixture):\n\n def test_facet_organization(self):\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df)\n assert g.axes.shape == (1, 1)\n\n g = cat.catplot(x=\"g\", y=\"y\", col=\"h\", data=self.df)\n assert g.axes.shape == (1, 2)\n\n g = cat.catplot(x=\"g\", y=\"y\", row=\"h\", data=self.df)\n assert g.axes.shape == (2, 1)\n\n g = cat.catplot(x=\"g\", y=\"y\", col=\"u\", row=\"h\", data=self.df)\n assert g.axes.shape == (2, 3)\n\n def test_plot_elements(self):\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"point\")\n assert len(g.ax.collections) == 1\n want_lines = self.g.unique().size + 1\n assert len(g.ax.lines) == want_lines\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"point\")\n want_collections = self.h.unique().size\n assert len(g.ax.collections) == want_collections\n want_lines = (self.g.unique().size + 1) * self.h.unique().size\n assert len(g.ax.lines) == want_lines\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"bar\")\n want_elements = self.g.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"bar\")\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == want_elements\n\n g = cat.catplot(x=\"g\", data=self.df, kind=\"count\")\n want_elements = self.g.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == 0\n\n g = cat.catplot(x=\"g\", hue=\"h\", data=self.df, kind=\"count\")\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == 0\n\n g = cat.catplot(y=\"y\", data=self.df, kind=\"box\")\n want_artists = 1\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"box\")\n want_artists = self.g.unique().size\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"box\")\n want_artists = self.g.unique().size * self.h.unique().size\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"violin\", inner=None)\n want_elements = self.g.unique().size\n assert len(g.ax.collections) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n kind=\"violin\", inner=None)\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.collections) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"strip\")\n want_elements = self.g.unique().size\n assert len(g.ax.collections) == want_elements\n for strip in g.ax.collections:\n assert same_color(strip.get_facecolors(), \"C0\")\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"strip\")\n want_elements = self.g.unique().size + self.h.unique().size\n assert len(g.ax.collections) == want_elements\n\n def test_bad_plot_kind_error(self):\n\n with pytest.raises(ValueError):\n cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"not_a_kind\")\n\n def test_count_x_and_y(self):\n\n with pytest.raises(ValueError):\n cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"count\")\n\n def test_plot_colors(self):\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df)\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"bar\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"bar\", color=\"purple\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"bar\", palette=\"Set2\", hue=\"h\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df)\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df)\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n def test_ax_kwarg_removal(self):\n\n f, ax = plt.subplots()\n with pytest.warns(UserWarning, match=\"catplot is a figure-level\"):\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, ax=ax)\n assert len(ax.collections) == 0\n assert len(g.ax.collections) > 0\n\n def test_share_xy(self):\n\n # Test default behavior works\n g = cat.catplot(x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=True)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n g = cat.catplot(x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=True)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n # Test unsharing workscol\n with pytest.warns(UserWarning):\n g = cat.catplot(\n x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, kind=\"bar\",\n )\n for ax in g.axes.flat:\n assert len(ax.patches) == 1\n\n with pytest.warns(UserWarning):\n g = cat.catplot(\n x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, kind=\"bar\",\n )\n for ax in g.axes.flat:\n assert len(ax.patches) == 1\n\n # Make sure no warning is raised if color is provided on unshared plot\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n g = cat.catplot(\n x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, color=\"b\"\n )\n for ax in g.axes.flat:\n assert ax.get_xlim() == (-.5, .5)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n g = cat.catplot(\n x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, color=\"r\"\n )\n for ax in g.axes.flat:\n assert ax.get_ylim() == (.5, -.5)\n\n # Make sure order is used if given, regardless of sharex value\n order = self.df.g.unique()\n g = cat.catplot(x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, order=order)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n g = cat.catplot(x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, order=order)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n @pytest.mark.parametrize(\"var\", [\"col\", \"row\"])\n def test_array_faceter(self, long_df, var):\n\n g1 = catplot(data=long_df, x=\"y\", **{var: \"a\"})\n g2 = catplot(data=long_df, x=\"y\", **{var: long_df[\"a\"].to_numpy()})\n\n for ax1, ax2 in zip(g1.axes.flat, g2.axes.flat):\n assert_plots_equal(ax1, ax2)\n\n\nclass TestBoxenPlotter(CategoricalFixture):\n\n default_kws = dict(x=None, y=None, hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None,\n saturation=.75, width=.8, dodge=True,\n k_depth='tukey', linewidth=None,\n scale='exponential', outlier_prop=0.007,\n trust_alpha=0.05, showfliers=True)\n\n def ispatch(self, c):\n\n return isinstance(c, mpl.collections.PatchCollection)\n\n def ispath(self, c):\n\n return isinstance(c, mpl.collections.PathCollection)\n\n def edge_calc(self, n, data):\n\n q = np.asanyarray([0.5 ** n, 1 - 0.5 ** n]) * 100\n q = list(np.unique(q))\n return np.percentile(data, q)\n\n def test_box_ends_finite(self):\n\n p = cat._LVPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", data=self.df)\n box_ends = []\n k_vals = []\n for s in p.plot_data:\n b, k = p._lv_box_ends(s)\n box_ends.append(b)\n k_vals.append(k)\n\n # Check that all the box ends are finite and are within\n # the bounds of the data\n b_e = map(lambda a: np.all(np.isfinite(a)), box_ends)\n assert np.sum(list(b_e)) == len(box_ends)\n\n def within(t):\n a, d = t\n return ((np.ravel(a) <= d.max())\n & (np.ravel(a) >= d.min())).all()\n\n b_w = map(within, zip(box_ends, p.plot_data))\n assert np.sum(list(b_w)) == len(box_ends)\n\n k_f = map(lambda k: (k > 0.) & np.isfinite(k), k_vals)\n assert np.sum(list(k_f)) == len(k_vals)\n\n def test_box_ends_correct_tukey(self):\n\n n = 100\n linear_data = np.arange(n)\n expected_k = max(int(np.log2(n)) - 3, 1)\n expected_edges = [self.edge_calc(i, linear_data)\n for i in range(expected_k + 1, 1, -1)]\n\n p = cat._LVPlotter(**self.default_kws)\n calc_edges, calc_k = p._lv_box_ends(linear_data)\n\n npt.assert_array_equal(expected_edges, calc_edges)\n assert expected_k == calc_k\n\n def test_box_ends_correct_proportion(self):\n\n n = 100\n linear_data = np.arange(n)\n expected_k = int(np.log2(n)) - int(np.log2(n * 0.007)) + 1\n expected_edges = [self.edge_calc(i, linear_data)\n for i in range(expected_k + 1, 1, -1)]\n\n kws = self.default_kws.copy()\n kws[\"k_depth\"] = \"proportion\"\n p = cat._LVPlotter(**kws)\n calc_edges, calc_k = p._lv_box_ends(linear_data)\n\n npt.assert_array_equal(expected_edges, calc_edges)\n assert expected_k == calc_k\n\n @pytest.mark.parametrize(\n \"n,exp_k\",\n [(491, 6), (492, 7), (983, 7), (984, 8), (1966, 8), (1967, 9)],\n )\n def test_box_ends_correct_trustworthy(self, n, exp_k):\n\n linear_data = np.arange(n)\n kws = self.default_kws.copy()\n kws[\"k_depth\"] = \"trustworthy\"\n p = cat._LVPlotter(**kws)\n _, calc_k = p._lv_box_ends(linear_data)\n\n assert exp_k == calc_k\n\n def test_outliers(self):\n\n n = 100\n outlier_data = np.append(np.arange(n - 1), 2 * n)\n expected_k = max(int(np.log2(n)) - 3, 1)\n expected_edges = [self.edge_calc(i, outlier_data)\n for i in range(expected_k + 1, 1, -1)]\n\n p = cat._LVPlotter(**self.default_kws)\n calc_edges, calc_k = p._lv_box_ends(outlier_data)\n\n npt.assert_array_equal(calc_edges, expected_edges)\n assert calc_k == expected_k\n\n out_calc = p._lv_outliers(outlier_data, calc_k)\n out_exp = p._lv_outliers(outlier_data, expected_k)\n\n npt.assert_equal(out_calc, out_exp)\n\n def test_showfliers(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df, k_depth=\"proportion\",\n showfliers=True)\n ax_collections = list(filter(self.ispath, ax.collections))\n for c in ax_collections:\n assert len(c.get_offsets()) == 2\n\n # Test that all data points are in the plot\n assert ax.get_ylim()[0] < self.df[\"y\"].min()\n assert ax.get_ylim()[1] > self.df[\"y\"].max()\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df, showfliers=False)\n assert len(list(filter(self.ispath, ax.collections))) == 0\n\n plt.close(\"all\")\n\n def test_invalid_depths(self):\n\n kws = self.default_kws.copy()\n\n # Make sure illegal depth raises\n kws[\"k_depth\"] = \"nosuchdepth\"\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n # Make sure illegal outlier_prop raises\n kws[\"k_depth\"] = \"proportion\"\n for p in (-13, 37):\n kws[\"outlier_prop\"] = p\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n kws[\"k_depth\"] = \"trustworthy\"\n for alpha in (-13, 37):\n kws[\"trust_alpha\"] = alpha\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n @pytest.mark.parametrize(\"power\", [1, 3, 7, 11, 13, 17])\n def test_valid_depths(self, power):\n\n x = np.random.standard_t(10, 2 ** power)\n\n valid_depths = [\"proportion\", \"tukey\", \"trustworthy\", \"full\"]\n kws = self.default_kws.copy()\n\n for depth in valid_depths + [4]:\n kws[\"k_depth\"] = depth\n box_ends, k = cat._LVPlotter(**kws)._lv_box_ends(x)\n\n if depth == \"full\":\n assert k == int(np.log2(len(x))) + 1\n\n def test_valid_scales(self):\n\n valid_scales = [\"linear\", \"exponential\", \"area\"]\n kws = self.default_kws.copy()\n\n for scale in valid_scales + [\"unknown_scale\"]:\n kws[\"scale\"] = scale\n if scale not in valid_scales:\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n else:\n cat._LVPlotter(**kws)\n\n def test_hue_offsets(self):\n\n p = cat._LVPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.2, .2])\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._LVPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.15, .15])\n\n p = cat._LVPlotter(**kws)\n p.establish_variables(\"h\", \"y\", \"g\", data=self.df)\n npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])\n\n def test_axes_data(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 3\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 6\n\n plt.close(\"all\")\n\n def test_box_colors(self):\n\n pal = palettes.color_palette()\n\n ax = cat.boxenplot(\n x=\"g\", y=\"y\", data=self.df, saturation=1, showfliers=False\n )\n ax.figure.canvas.draw()\n for i, box in enumerate(ax.collections):\n assert same_color(box.get_facecolor()[0], pal[i])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(\n x=\"g\", y=\"y\", hue=\"h\", data=self.df, saturation=1, showfliers=False\n )\n ax.figure.canvas.draw()\n for i, box in enumerate(ax.collections):\n assert same_color(box.get_facecolor()[0], pal[i % 2])\n\n plt.close(\"all\")\n\n def test_draw_missing_boxes(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df,\n order=[\"a\", \"b\", \"c\", \"d\"])\n\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 3\n plt.close(\"all\")\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.boxenplot(x=self.g, y=self.y, ax=ax1)\n cat.boxenplot(x=self.g, y=self.y_perm, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.boxenplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, ax=ax1)\n cat.boxenplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n def test_missing_data(self):\n\n x = [\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"d\"]\n h = [\"x\", \"y\", \"x\", \"y\", \"x\", \"y\", \"x\", \"y\"]\n y = self.rs.randn(8)\n y[-2:] = np.nan\n\n ax = cat.boxenplot(x=x, y=y)\n assert len(ax.lines) == 3\n\n plt.close(\"all\")\n\n y[-1] = 0\n ax = cat.boxenplot(x=x, y=y, hue=h)\n assert len(ax.lines) == 7\n\n plt.close(\"all\")\n\n def test_boxenplots(self):\n\n # Smoke test the high level boxenplot options\n\n cat.boxenplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n for scale in (\"linear\", \"area\", \"exponential\"):\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", scale=scale, data=self.df)\n plt.close(\"all\")\n\n for depth in (\"proportion\", \"tukey\", \"trustworthy\"):\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", k_depth=depth, data=self.df)\n plt.close(\"all\")\n\n order = list(\"nabc\")\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", order=order, data=self.df)\n plt.close(\"all\")\n\n order = list(\"omn\")\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=order, data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\",\n palette=\"Set2\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df,\n orient=\"h\", color=\"b\")\n plt.close(\"all\")\n\n def test_axes_annotation(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n assert ax.get_xlim() == (-.5, 2.5)\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],\n [\"m\", \"n\"])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n assert ax.get_ylim() == (2.5, -.5)\n npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n @pytest.mark.parametrize(\"size\", [\"large\", \"medium\", \"small\", 22, 12])\n def test_legend_titlesize(self, size):\n\n rc_ctx = {\"legend.title_fontsize\": size}\n exp = mpl.font_manager.FontProperties(size=size).get_size()\n\n with plt.rc_context(rc=rc_ctx):\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n obs = ax.get_legend().get_title().get_fontproperties().get_size()\n assert obs == exp\n\n plt.close(\"all\")\n\n @pytest.mark.skipif(\n Version(pd.__version__) < Version(\"1.2\"),\n reason=\"Test requires pandas>=1.2\")\n def test_Float64_input(self):\n data = pd.DataFrame(\n {\"x\": np.random.choice([\"a\", \"b\"], 20), \"y\": np.random.random(20)}\n )\n data['y'] = data['y'].astype(pd.Float64Dtype())\n _ = cat.boxenplot(x=\"x\", y=\"y\", data=data)\n\n plt.close(\"all\")\n\n def test_line_kws(self):\n line_kws = {'linewidth': 5, 'color': 'purple',\n 'linestyle': '-.'}\n\n ax = cat.boxenplot(data=self.df, y='y', line_kws=line_kws)\n\n median_line = ax.lines[0]\n\n assert median_line.get_linewidth() == line_kws['linewidth']\n assert median_line.get_linestyle() == line_kws['linestyle']\n assert median_line.get_color() == line_kws['color']\n\n plt.close(\"all\")\n\n def test_flier_kws(self):\n flier_kws = {\n 'marker': 'v',\n 'color': np.array([[1, 0, 0, 1]]),\n 's': 5,\n }\n\n ax = cat.boxenplot(data=self.df, y='y', x='g', flier_kws=flier_kws)\n\n outliers_scatter = ax.findobj(mpl.collections.PathCollection)[0]\n\n # The number of vertices for a triangle is 3, the length of Path\n # collection objects is defined as n + 1 vertices.\n assert len(outliers_scatter.get_paths()[0]) == 4\n assert len(outliers_scatter.get_paths()[-1]) == 4\n\n assert (outliers_scatter.get_facecolor() == flier_kws['color']).all()\n\n assert np.unique(outliers_scatter.get_sizes()) == flier_kws['s']\n\n plt.close(\"all\")\n\n def test_box_kws(self):\n\n box_kws = {'linewidth': 5, 'edgecolor': np.array([[0, 1, 0, 1]])}\n\n ax = cat.boxenplot(data=self.df, y='y', x='g',\n box_kws=box_kws)\n\n boxes = ax.findobj(mpl.collections.PatchCollection)[0]\n\n # The number of vertices for a triangle is 3, the length of Path\n # collection objects is defined as n + 1 vertices.\n assert len(boxes.get_paths()[0]) == 5\n assert len(boxes.get_paths()[-1]) == 5\n\n assert np.unique(boxes.get_linewidth() == box_kws['linewidth'])\n\n plt.close(\"all\")\n\n\nclass TestBeeswarm:\n\n def test_could_overlap(self):\n\n p = Beeswarm()\n neighbors = p.could_overlap(\n (1, 1, .5),\n [(0, 0, .5),\n (1, .1, .2),\n (.5, .5, .5)]\n )\n assert_array_equal(neighbors, [(.5, .5, .5)])\n\n def test_position_candidates(self):\n\n p = Beeswarm()\n xy_i = (0, 1, .5)\n neighbors = [(0, 1, .5), (0, 1.5, .5)]\n candidates = p.position_candidates(xy_i, neighbors)\n dx1 = 1.05\n dx2 = np.sqrt(1 - .5 ** 2) * 1.05\n assert_array_equal(\n candidates,\n [(0, 1, .5), (-dx1, 1, .5), (dx1, 1, .5), (dx2, 1, .5), (-dx2, 1, .5)]\n )\n\n def test_find_first_non_overlapping_candidate(self):\n\n p = Beeswarm()\n candidates = [(.5, 1, .5), (1, 1, .5), (1.5, 1, .5)]\n neighbors = np.array([(0, 1, .5)])\n\n first = p.first_non_overlapping_candidate(candidates, neighbors)\n assert_array_equal(first, (1, 1, .5))\n\n def test_beeswarm(self, long_df):\n\n p = Beeswarm()\n data = long_df[\"y\"]\n d = data.diff().mean() * 1.5\n x = np.zeros(data.size)\n y = np.sort(data)\n r = np.full_like(y, d)\n orig_xyr = np.c_[x, y, r]\n swarm = p.beeswarm(orig_xyr)[:, :2]\n dmat = np.sqrt(np.sum(np.square(swarm[:, np.newaxis] - swarm), axis=-1))\n triu = dmat[np.triu_indices_from(dmat, 1)]\n assert_array_less(d, triu)\n assert_array_equal(y, swarm[:, 1])\n\n def test_add_gutters(self):\n\n p = Beeswarm(width=1)\n\n points = np.zeros(10)\n assert_array_equal(points, p.add_gutters(points, 0))\n\n points = np.array([0, -1, .4, .8])\n msg = r\"50.0% of the points cannot be placed.+$\"\n with pytest.warns(UserWarning, match=msg):\n new_points = p.add_gutters(points, 0)\n assert_array_equal(new_points, np.array([0, -.5, .4, .5]))\n"},{"col":4,"comment":"null","endLoc":406,"header":"def test_mark_data_log_transform_is_inverted(self, long_df)","id":4452,"name":"test_mark_data_log_transform_is_inverted","nodeType":"Function","startLoc":401,"text":"def test_mark_data_log_transform_is_inverted(self, long_df):\n\n col = \"z\"\n m = MockMark()\n Plot(long_df, x=col).scale(x=\"log\").add(m).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[col])"},{"col":4,"comment":"null","endLoc":432,"header":"def test_mark_data_log_transfrom_with_stat(self, long_df)","id":4453,"name":"test_mark_data_log_transfrom_with_stat","nodeType":"Function","startLoc":408,"text":"def test_mark_data_log_transfrom_with_stat(self, long_df):\n\n class Mean(Stat):\n group_by_orient = True\n\n def __call__(self, data, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return groupby.agg(data, {other: \"mean\"})\n\n col = \"z\"\n grouper = \"a\"\n m = MockMark()\n s = Mean()\n\n Plot(long_df, x=grouper, y=col).scale(y=\"log\").add(m, s).plot()\n\n expected = (\n long_df[col]\n .pipe(np.log)\n .groupby(long_df[grouper], sort=False)\n .mean()\n .pipe(np.exp)\n .reset_index(drop=True)\n )\n assert_vector_equal(m.passed_data[0][\"y\"], expected)"},{"col":4,"comment":"null","endLoc":442,"header":"def test_mark_data_from_categorical(self, long_df)","id":4454,"name":"test_mark_data_from_categorical","nodeType":"Function","startLoc":434,"text":"def test_mark_data_from_categorical(self, long_df):\n\n col = \"a\"\n m = MockMark()\n Plot(long_df, x=col).add(m).plot()\n\n levels = categorical_order(long_df[col])\n level_map = {x: float(i) for i, x in enumerate(levels)}\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[col].map(level_map))"},{"className":"TestCategoricalPlotterNew","col":0,"comment":"null","endLoc":98,"id":4455,"nodeType":"Class","startLoc":44,"text":"class TestCategoricalPlotterNew:\n\n @pytest.mark.parametrize(\n \"func,kwargs\",\n itertools.product(\n PLOT_FUNCS,\n [\n {\"x\": \"x\", \"y\": \"a\"},\n {\"x\": \"a\", \"y\": \"y\"},\n {\"x\": \"y\"},\n {\"y\": \"x\"},\n ],\n ),\n )\n def test_axis_labels(self, long_df, func, kwargs):\n\n func(data=long_df, **kwargs)\n\n ax = plt.gca()\n for axis in \"xy\":\n val = kwargs.get(axis, \"\")\n label_func = getattr(ax, f\"get_{axis}label\")\n assert label_func() == val\n\n @pytest.mark.parametrize(\"func\", PLOT_FUNCS)\n def test_empty(self, func):\n\n func()\n ax = plt.gca()\n assert not ax.collections\n assert not ax.patches\n assert not ax.lines\n\n func(x=[], y=[])\n ax = plt.gca()\n assert not ax.collections\n assert not ax.patches\n assert not ax.lines\n\n def test_redundant_hue_backcompat(self, long_df):\n\n p = _CategoricalPlotterNew(\n data=long_df,\n variables={\"x\": \"s\", \"y\": \"y\"},\n )\n\n color = None\n palette = dict(zip(long_df[\"s\"].unique(), color_palette()))\n hue_order = None\n\n palette, _ = p._hue_backcompat(color, palette, hue_order, force_hue=True)\n\n assert p.variables[\"hue\"] == \"s\"\n assert_array_equal(p.plot_data[\"hue\"], p.plot_data[\"x\"])\n assert all(isinstance(k, str) for k in palette)"},{"col":4,"comment":"null","endLoc":66,"header":"@pytest.mark.parametrize(\n \"func,kwargs\",\n itertools.product(\n PLOT_FUNCS,\n [\n {\"x\": \"x\", \"y\": \"a\"},\n {\"x\": \"a\", \"y\": \"y\"},\n {\"x\": \"y\"},\n {\"y\": \"x\"},\n ],\n ),\n )\n def test_axis_labels(self, long_df, func, kwargs)","id":4456,"name":"test_axis_labels","nodeType":"Function","startLoc":46,"text":"@pytest.mark.parametrize(\n \"func,kwargs\",\n itertools.product(\n PLOT_FUNCS,\n [\n {\"x\": \"x\", \"y\": \"a\"},\n {\"x\": \"a\", \"y\": \"y\"},\n {\"x\": \"y\"},\n {\"y\": \"x\"},\n ],\n ),\n )\n def test_axis_labels(self, long_df, func, kwargs):\n\n func(data=long_df, **kwargs)\n\n ax = plt.gca()\n for axis in \"xy\":\n val = kwargs.get(axis, \"\")\n label_func = getattr(ax, f\"get_{axis}label\")\n assert label_func() == val"},{"attributeType":"null","col":17,"comment":"null","endLoc":9,"id":4457,"name":"pd","nodeType":"Attribute","startLoc":9,"text":"pd"},{"attributeType":"null","col":18,"comment":"null","endLoc":10,"id":4458,"name":"sns","nodeType":"Attribute","startLoc":10,"text":"sns"},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":4459,"name":"r","nodeType":"Attribute","startLoc":15,"text":"r"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":4460,"name":"df","nodeType":"Attribute","startLoc":16,"text":"df"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":4461,"name":"df","nodeType":"Attribute","startLoc":19,"text":"df"},{"attributeType":"FacetGrid","col":0,"comment":"null","endLoc":22,"id":4462,"name":"g","nodeType":"Attribute","startLoc":22,"text":"g"},{"col":0,"comment":"","endLoc":7,"header":"radial_facets.py#","id":4463,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nFacetGrid with custom projection\n================================\n\n_thumb: .33, .5\n\n\"\"\"\n\nsns.set_theme()\n\nr = np.linspace(0, 10, num=100)\n\ndf = pd.DataFrame({'r': r, 'slow': r, 'medium': 2 * r, 'fast': 4 * r})\n\ndf = pd.melt(df, id_vars=['r'], var_name='speed', value_name='theta')\n\ng = sns.FacetGrid(df, col=\"speed\", hue=\"speed\",\n subplot_kws=dict(projection='polar'), height=4.5,\n sharex=False, sharey=False, despine=False)\n\ng.map(sns.scatterplot, \"theta\", \"r\")"},{"col":4,"comment":"null","endLoc":638,"header":"def test_lmplot_sharey(self)","id":4464,"name":"test_lmplot_sharey","nodeType":"Function","startLoc":626,"text":"def test_lmplot_sharey(self):\n\n df = pd.DataFrame(dict(\n x=[0, 1, 2, 0, 1, 2],\n y=[1, -1, 0, -100, 200, 0],\n z=[\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"],\n ))\n\n with pytest.warns(UserWarning):\n g = lm.lmplot(data=df, x=\"x\", y=\"y\", col=\"z\", sharey=False)\n ax1, ax2 = g.axes.flat\n assert ax1.get_ylim()[0] > ax2.get_ylim()[0]\n assert ax1.get_ylim()[1] < ax2.get_ylim()[1]"},{"col":4,"comment":"null","endLoc":647,"header":"def test_lmplot_facet_kws(self)","id":4465,"name":"test_lmplot_facet_kws","nodeType":"Function","startLoc":640,"text":"def test_lmplot_facet_kws(self):\n\n xlim = -4, 20\n g = lm.lmplot(\n data=self.df, x=\"x\", y=\"y\", col=\"h\", facet_kws={\"xlim\": xlim}\n )\n for ax in g.axes.flat:\n assert ax.get_xlim() == xlim"},{"col":4,"comment":"null","endLoc":658,"header":"def test_residplot(self)","id":4466,"name":"test_residplot","nodeType":"Function","startLoc":649,"text":"def test_residplot(self):\n\n x, y = self.df.x, self.df.y\n ax = lm.residplot(x=x, y=y)\n\n resid = y - np.polyval(np.polyfit(x, y, 1), x)\n x_plot, y_plot = ax.collections[0].get_offsets().T\n\n npt.assert_array_equal(x, x_plot)\n npt.assert_array_almost_equal(resid, y_plot)"},{"col":4,"comment":"null","endLoc":667,"header":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_residplot_lowess(self)","id":4467,"name":"test_residplot_lowess","nodeType":"Function","startLoc":660,"text":"@pytest.mark.skipif(_no_statsmodels, reason=\"no statsmodels\")\n def test_residplot_lowess(self):\n\n ax = lm.residplot(x=\"x\", y=\"y\", data=self.df, lowess=True)\n assert len(ax.lines) == 2\n\n x, y = ax.lines[1].get_xydata().T\n npt.assert_array_equal(x, np.sort(self.df.x))"},{"col":4,"comment":"null","endLoc":454,"header":"def test_mark_data_from_datetime(self, long_df)","id":4468,"name":"test_mark_data_from_datetime","nodeType":"Function","startLoc":444,"text":"def test_mark_data_from_datetime(self, long_df):\n\n col = \"t\"\n m = MockMark()\n Plot(long_df, x=col).add(m).plot()\n\n expected = long_df[col].map(mpl.dates.date2num)\n if Version(mpl.__version__) < Version(\"3.3\"):\n expected = expected + mpl.dates.date2num(np.datetime64('0000-12-31'))\n\n assert_vector_equal(m.passed_data[0][\"x\"], expected)"},{"col":4,"comment":"null","endLoc":675,"header":"def test_three_point_colors(self)","id":4469,"name":"test_three_point_colors","nodeType":"Function","startLoc":669,"text":"def test_three_point_colors(self):\n\n x, y = np.random.randn(2, 3)\n ax = lm.regplot(x=x, y=y, color=(1, 0, 0))\n color = ax.collections[0].get_facecolors()\n npt.assert_almost_equal(color[0, :3],\n (1, 0, 0))"},{"col":4,"comment":"null","endLoc":684,"header":"def test_regplot_xlim(self)","id":4470,"name":"test_regplot_xlim","nodeType":"Function","startLoc":677,"text":"def test_regplot_xlim(self):\n\n f, ax = plt.subplots()\n x, y1, y2 = np.random.randn(3, 50)\n lm.regplot(x=x, y=y1, truncate=False)\n lm.regplot(x=x, y=y2, truncate=False)\n line1, line2 = ax.lines\n assert np.array_equal(line1.get_xdata(), line2.get_xdata())"},{"attributeType":"null","col":4,"comment":"null","endLoc":460,"id":4471,"name":"rs","nodeType":"Attribute","startLoc":460,"text":"rs"},{"attributeType":"null","col":4,"comment":"null","endLoc":461,"id":4472,"name":"df","nodeType":"Attribute","startLoc":461,"text":"df"},{"attributeType":"null","col":4,"comment":"null","endLoc":467,"id":4473,"name":"bw_err","nodeType":"Attribute","startLoc":467,"text":"bw_err"},{"attributeType":"null","col":16,"comment":"null","endLoc":3,"id":4474,"name":"np","nodeType":"Attribute","startLoc":3,"text":"np"},{"attributeType":"null","col":21,"comment":"null","endLoc":4,"id":4475,"name":"mpl","nodeType":"Attribute","startLoc":4,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":5,"id":4476,"name":"plt","nodeType":"Attribute","startLoc":5,"text":"plt"},{"attributeType":"null","col":17,"comment":"null","endLoc":6,"id":4477,"name":"pd","nodeType":"Attribute","startLoc":6,"text":"pd"},{"attributeType":"null","col":24,"comment":"null","endLoc":9,"id":4478,"name":"npt","nodeType":"Attribute","startLoc":9,"text":"npt"},{"attributeType":"null","col":29,"comment":"null","endLoc":11,"id":4479,"name":"pdt","nodeType":"Attribute","startLoc":11,"text":"pdt"},{"attributeType":"null","col":34,"comment":"null","endLoc":13,"id":4480,"name":"pdt","nodeType":"Attribute","startLoc":13,"text":"pdt"},{"attributeType":"null","col":50,"comment":"null","endLoc":16,"id":4481,"name":"smlm","nodeType":"Attribute","startLoc":16,"text":"smlm"},{"attributeType":"bool","col":4,"comment":"null","endLoc":17,"id":4482,"name":"_no_statsmodels","nodeType":"Attribute","startLoc":17,"text":"_no_statsmodels"},{"attributeType":"bool","col":4,"comment":"null","endLoc":19,"id":4483,"name":"_no_statsmodels","nodeType":"Attribute","startLoc":19,"text":"_no_statsmodels"},{"attributeType":"null","col":34,"comment":"null","endLoc":21,"id":4484,"name":"lm","nodeType":"Attribute","startLoc":21,"text":"lm"},{"attributeType":"null","col":0,"comment":"null","endLoc":25,"id":4485,"name":"rs","nodeType":"Attribute","startLoc":25,"text":"rs"},{"col":0,"comment":"","endLoc":1,"header":"test_regression.py#","id":4486,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n import pandas.testing as pdt\nexcept ImportError:\n import pandas.util.testing as pdt\n\ntry:\n import statsmodels.regression.linear_model as smlm\n _no_statsmodels = False\nexcept ImportError:\n _no_statsmodels = True\n\nrs = np.random.RandomState(0)"},{"col":4,"comment":"null","endLoc":467,"header":"def test_computed_var_ticks(self, long_df)","id":4487,"name":"test_computed_var_ticks","nodeType":"Function","startLoc":456,"text":"def test_computed_var_ticks(self, long_df):\n\n class Identity(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient]})\n\n tick_locs = [1, 2, 5]\n scale = Continuous().tick(at=tick_locs)\n p = Plot(long_df, \"x\").add(MockMark(), Identity()).scale(y=scale).plot()\n ax = p._figure.axes[0]\n assert_array_equal(ax.get_yticks(), tick_locs)"},{"col":4,"comment":"null","endLoc":479,"header":"def test_computed_var_transform(self, long_df)","id":4488,"name":"test_computed_var_transform","nodeType":"Function","startLoc":469,"text":"def test_computed_var_transform(self, long_df):\n\n class Identity(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient]})\n\n p = Plot(long_df, \"x\").add(MockMark(), Identity()).scale(y=\"log\").plot()\n ax = p._figure.axes[0]\n xfm = ax.yaxis.get_transform().transform\n assert_array_equal(xfm([1, 10, 100]), [0, 1, 2])"},{"col":4,"comment":"null","endLoc":615,"header":"def get_func(self)","id":4489,"name":"get_func","nodeType":"Function","startLoc":609,"text":"def get_func(self):\n func_name = getattr(self._f, '__name__', self.__class__.__name__)\n if inspect.isclass(self._f):\n func = getattr(self._f, '__call__', self._f.__init__)\n else:\n func = self._f\n return func, func_name"},{"col":4,"comment":"null","endLoc":488,"header":"def test_explicit_range_with_axis_scaling(self)","id":4491,"name":"test_explicit_range_with_axis_scaling","nodeType":"Function","startLoc":481,"text":"def test_explicit_range_with_axis_scaling(self):\n\n x = [1, 2, 3]\n ymin = [10, 100, 1000]\n ymax = [20, 200, 2000]\n m = MockMark()\n Plot(x=x, ymin=ymin, ymax=ymax).add(m).scale(y=\"log\").plot()\n assert_vector_equal(m.passed_data[0][\"ymax\"], pd.Series(ymax, dtype=float))"},{"col":4,"comment":"null","endLoc":500,"header":"def test_derived_range_with_axis_scaling(self)","id":4492,"name":"test_derived_range_with_axis_scaling","nodeType":"Function","startLoc":490,"text":"def test_derived_range_with_axis_scaling(self):\n\n class AddOne(Stat):\n def __call__(self, df, *args):\n return df.assign(ymax=df[\"y\"] + 1)\n\n x = y = [1, 10, 100]\n\n m = MockMark()\n Plot(x, y).add(m, AddOne()).scale(y=\"log\").plot()\n assert_vector_equal(m.passed_data[0][\"ymax\"], pd.Series([10., 100., 1000.]))"},{"col":4,"comment":"null","endLoc":510,"header":"def test_facet_categories(self)","id":4493,"name":"test_facet_categories","nodeType":"Function","startLoc":502,"text":"def test_facet_categories(self):\n\n m = MockMark()\n p = Plot(x=[\"a\", \"b\", \"a\", \"c\"]).facet(col=[\"x\", \"x\", \"y\", \"y\"]).add(m).plot()\n ax1, ax2 = p._figure.axes\n assert len(ax1.get_xticks()) == 3\n assert len(ax2.get_xticks()) == 3\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [2, 3]))"},{"col":4,"comment":"null","endLoc":526,"header":"def test_facet_categories_unshared(self)","id":4494,"name":"test_facet_categories_unshared","nodeType":"Function","startLoc":512,"text":"def test_facet_categories_unshared(self):\n\n m = MockMark()\n p = (\n Plot(x=[\"a\", \"b\", \"a\", \"c\"])\n .facet(col=[\"x\", \"x\", \"y\", \"y\"])\n .share(x=False)\n .add(m)\n .plot()\n )\n ax1, ax2 = p._figure.axes\n assert len(ax1.get_xticks()) == 2\n assert len(ax2.get_xticks()) == 2\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 1.], [2, 3]))"},{"col":4,"comment":"null","endLoc":553,"header":"def test_facet_categories_single_dim_shared(self)","id":4495,"name":"test_facet_categories_single_dim_shared","nodeType":"Function","startLoc":528,"text":"def test_facet_categories_single_dim_shared(self):\n\n data = [\n (\"a\", 1, 1), (\"b\", 1, 1),\n (\"a\", 1, 2), (\"c\", 1, 2),\n (\"b\", 2, 1), (\"d\", 2, 1),\n (\"e\", 2, 2), (\"e\", 2, 1),\n ]\n df = pd.DataFrame(data, columns=[\"x\", \"row\", \"col\"]).assign(y=1)\n m = MockMark()\n p = (\n Plot(df, x=\"x\")\n .facet(row=\"row\", col=\"col\")\n .add(m)\n .share(x=\"row\")\n .plot()\n )\n\n axs = p._figure.axes\n for ax in axs:\n assert ax.get_xticks() == [0, 1, 2]\n\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [2, 3]))\n assert_vector_equal(m.passed_data[2][\"x\"], pd.Series([0., 1., 2.], [4, 5, 7]))\n assert_vector_equal(m.passed_data[3][\"x\"], pd.Series([2.], [6]))"},{"col":4,"comment":"null","endLoc":566,"header":"def test_pair_categories(self)","id":4496,"name":"test_pair_categories","nodeType":"Function","startLoc":555,"text":"def test_pair_categories(self):\n\n data = [(\"a\", \"a\"), (\"b\", \"c\")]\n df = pd.DataFrame(data, columns=[\"x1\", \"x2\"]).assign(y=1)\n m = MockMark()\n p = Plot(df, y=\"y\").pair(x=[\"x1\", \"x2\"]).add(m).plot()\n\n ax1, ax2 = p._figure.axes\n assert ax1.get_xticks() == [0, 1]\n assert ax2.get_xticks() == [0, 1]\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 1.], [0, 1]))"},{"col":4,"comment":"null","endLoc":81,"header":"@pytest.mark.parametrize(\"func\", PLOT_FUNCS)\n def test_empty(self, func)","id":4497,"name":"test_empty","nodeType":"Function","startLoc":68,"text":"@pytest.mark.parametrize(\"func\", PLOT_FUNCS)\n def test_empty(self, func):\n\n func()\n ax = plt.gca()\n assert not ax.collections\n assert not ax.patches\n assert not ax.lines\n\n func(x=[], y=[])\n ax = plt.gca()\n assert not ax.collections\n assert not ax.patches\n assert not ax.lines"},{"col":4,"comment":"null","endLoc":98,"header":"def test_redundant_hue_backcompat(self, long_df)","id":4498,"name":"test_redundant_hue_backcompat","nodeType":"Function","startLoc":83,"text":"def test_redundant_hue_backcompat(self, long_df):\n\n p = _CategoricalPlotterNew(\n data=long_df,\n variables={\"x\": \"s\", \"y\": \"y\"},\n )\n\n color = None\n palette = dict(zip(long_df[\"s\"].unique(), color_palette()))\n hue_order = None\n\n palette, _ = p._hue_backcompat(color, palette, hue_order, force_hue=True)\n\n assert p.variables[\"hue\"] == \"s\"\n assert_array_equal(p.plot_data[\"hue\"], p.plot_data[\"x\"])\n assert all(isinstance(k, str) for k in palette)"},{"className":"CategoricalFixture","col":0,"comment":"Test boxplot (also base class for things like violinplots).","endLoc":121,"id":4499,"nodeType":"Class","startLoc":101,"text":"class CategoricalFixture:\n \"\"\"Test boxplot (also base class for things like violinplots).\"\"\"\n rs = np.random.RandomState(30)\n n_total = 60\n x = rs.randn(int(n_total / 3), 3)\n x_df = pd.DataFrame(x, columns=pd.Series(list(\"XYZ\"), name=\"big\"))\n y = pd.Series(rs.randn(n_total), name=\"y_data\")\n y_perm = y.reindex(rs.choice(y.index, y.size, replace=False))\n g = pd.Series(np.repeat(list(\"abc\"), int(n_total / 3)), name=\"small\")\n h = pd.Series(np.tile(list(\"mn\"), int(n_total / 2)), name=\"medium\")\n u = pd.Series(np.tile(list(\"jkh\"), int(n_total / 3)))\n df = pd.DataFrame(dict(y=y, g=g, h=h, u=u))\n x_df[\"W\"] = g\n\n def get_box_artists(self, ax):\n\n if Version(mpl.__version__) < Version(\"3.5.0b0\"):\n return ax.artists\n else:\n # Exclude labeled patches, which are for the legend\n return [p for p in ax.patches if not p.get_label()]"},{"col":4,"comment":"null","endLoc":121,"header":"def get_box_artists(self, ax)","id":4500,"name":"get_box_artists","nodeType":"Function","startLoc":115,"text":"def get_box_artists(self, ax):\n\n if Version(mpl.__version__) < Version(\"3.5.0b0\"):\n return ax.artists\n else:\n # Exclude labeled patches, which are for the legend\n return [p for p in ax.patches if not p.get_label()]"},{"col":4,"comment":"null","endLoc":583,"header":"@pytest.mark.xfail(\n Version(mpl.__version__) < Version(\"3.4.0\"),\n reason=\"Sharing paired categorical axes requires matplotlib>3.4.0\"\n )\n def test_pair_categories_shared(self)","id":4501,"name":"test_pair_categories_shared","nodeType":"Function","startLoc":568,"text":"@pytest.mark.xfail(\n Version(mpl.__version__) < Version(\"3.4.0\"),\n reason=\"Sharing paired categorical axes requires matplotlib>3.4.0\"\n )\n def test_pair_categories_shared(self):\n\n data = [(\"a\", \"a\"), (\"b\", \"c\")]\n df = pd.DataFrame(data, columns=[\"x1\", \"x2\"]).assign(y=1)\n m = MockMark()\n p = Plot(df, y=\"y\").pair(x=[\"x1\", \"x2\"]).add(m).share(x=True).plot()\n\n for ax in p._figure.axes:\n assert ax.get_xticks() == [0, 1, 2]\n print(m.passed_data)\n assert_vector_equal(m.passed_data[0][\"x\"], pd.Series([0., 1.], [0, 1]))\n assert_vector_equal(m.passed_data[1][\"x\"], pd.Series([0., 2.], [0, 1]))"},{"col":4,"comment":"null","endLoc":631,"header":"def __str__(self)","id":4505,"name":"__str__","nodeType":"Function","startLoc":617,"text":"def __str__(self):\n out = ''\n\n func, func_name = self.get_func()\n\n roles = {'func': 'function',\n 'meth': 'method'}\n\n if self._role:\n if self._role not in roles:\n print(f\"Warning: invalid role {self._role}\")\n out += f\".. {roles.get(self._role, '')}:: {func_name}\\n \\n\\n\"\n\n out += super().__str__(func_role=self._role)\n return out"},{"attributeType":"null","col":4,"comment":"null","endLoc":103,"id":4506,"name":"rs","nodeType":"Attribute","startLoc":103,"text":"rs"},{"attributeType":"int","col":4,"comment":"null","endLoc":104,"id":4507,"name":"n_total","nodeType":"Attribute","startLoc":104,"text":"n_total"},{"attributeType":"null","col":4,"comment":"null","endLoc":105,"id":4508,"name":"x","nodeType":"Attribute","startLoc":105,"text":"x"},{"attributeType":"null","col":4,"comment":"null","endLoc":106,"id":4509,"name":"x_df","nodeType":"Attribute","startLoc":106,"text":"x_df"},{"attributeType":"null","col":4,"comment":"null","endLoc":107,"id":4510,"name":"y","nodeType":"Attribute","startLoc":107,"text":"y"},{"attributeType":"null","col":4,"comment":"null","endLoc":108,"id":4511,"name":"y_perm","nodeType":"Attribute","startLoc":108,"text":"y_perm"},{"attributeType":"null","col":4,"comment":"null","endLoc":109,"id":4512,"name":"g","nodeType":"Attribute","startLoc":109,"text":"g"},{"attributeType":"null","col":4,"comment":"null","endLoc":110,"id":4513,"name":"h","nodeType":"Attribute","startLoc":110,"text":"h"},{"attributeType":"null","col":4,"comment":"null","endLoc":111,"id":4514,"name":"u","nodeType":"Attribute","startLoc":111,"text":"u"},{"attributeType":"null","col":4,"comment":"null","endLoc":112,"id":4515,"name":"df","nodeType":"Attribute","startLoc":112,"text":"df"},{"className":"TestCategoricalPlotter","col":0,"comment":"null","endLoc":513,"id":4516,"nodeType":"Class","startLoc":124,"text":"class TestCategoricalPlotter(CategoricalFixture):\n\n def test_wide_df_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test basic wide DataFrame\n p.establish_variables(data=self.x_df)\n\n # Check data attribute\n for x, y, in zip(p.plot_data, self.x_df[[\"X\", \"Y\", \"Z\"]].values.T):\n npt.assert_array_equal(x, y)\n\n # Check semantic attributes\n assert p.orient == \"v\"\n assert p.plot_hues is None\n assert p.group_label == \"big\"\n assert p.value_label is None\n\n # Test wide dataframe with forced horizontal orientation\n p.establish_variables(data=self.x_df, orient=\"horiz\")\n assert p.orient == \"h\"\n\n # Test exception by trying to hue-group with a wide dataframe\n with pytest.raises(ValueError):\n p.establish_variables(hue=\"d\", data=self.x_df)\n\n def test_1d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test basic vector data\n x_1d_array = self.x.ravel()\n p.establish_variables(data=x_1d_array)\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.n_total\n assert p.group_label is None\n assert p.value_label is None\n\n # Test basic vector data in list form\n x_1d_list = x_1d_array.tolist()\n p.establish_variables(data=x_1d_list)\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.n_total\n assert p.group_label is None\n assert p.value_label is None\n\n # Test an object array that looks 1D but isn't\n x_notreally_1d = np.array([self.x.ravel(),\n self.x.ravel()[:int(self.n_total / 2)]],\n dtype=object)\n p.establish_variables(data=x_notreally_1d)\n assert len(p.plot_data) == 2\n assert len(p.plot_data[0]) == self.n_total\n assert len(p.plot_data[1]) == self.n_total / 2\n assert p.group_label is None\n assert p.value_label is None\n\n def test_2d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n x = self.x[:, 0]\n\n # Test vector data that looks 2D but doesn't really have columns\n p.establish_variables(data=x[:, np.newaxis])\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.x.shape[0]\n assert p.group_label is None\n assert p.value_label is None\n\n # Test vector data that looks 2D but doesn't really have rows\n p.establish_variables(data=x[np.newaxis, :])\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.x.shape[0]\n assert p.group_label is None\n assert p.value_label is None\n\n def test_3d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test that passing actually 3D data raises\n x = np.zeros((5, 5, 5))\n with pytest.raises(ValueError):\n p.establish_variables(data=x)\n\n def test_list_of_array_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test 2D input in list form\n x_list = self.x.T.tolist()\n p.establish_variables(data=x_list)\n assert len(p.plot_data) == 3\n\n lengths = [len(v_i) for v_i in p.plot_data]\n assert lengths == [self.n_total / 3] * 3\n\n assert p.group_label is None\n assert p.value_label is None\n\n def test_wide_array_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test 2D input in array form\n p.establish_variables(data=self.x)\n assert np.shape(p.plot_data) == (3, self.n_total / 3)\n npt.assert_array_equal(p.plot_data, self.x.T)\n\n assert p.group_label is None\n assert p.value_label is None\n\n def test_single_long_direct_inputs(self):\n\n p = cat._CategoricalPlotter()\n\n # Test passing a series to the x variable\n p.establish_variables(x=self.y)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"h\"\n assert p.value_label == \"y_data\"\n assert p.group_label is None\n\n # Test passing a series to the y variable\n p.establish_variables(y=self.y)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.value_label == \"y_data\"\n assert p.group_label is None\n\n # Test passing an array to the y variable\n p.establish_variables(y=self.y.values)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.group_label is None\n assert p.value_label is None\n\n # Test array and series with non-default index\n x = pd.Series([1, 1, 1, 1], index=[0, 2, 4, 6])\n y = np.array([1, 2, 3, 4])\n p.establish_variables(x, y)\n assert len(p.plot_data[0]) == 4\n\n def test_single_long_indirect_inputs(self):\n\n p = cat._CategoricalPlotter()\n\n # Test referencing a DataFrame series in the x variable\n p.establish_variables(x=\"y\", data=self.df)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"h\"\n assert p.value_label == \"y\"\n assert p.group_label is None\n\n # Test referencing a DataFrame series in the y variable\n p.establish_variables(y=\"y\", data=self.df)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.value_label == \"y\"\n assert p.group_label is None\n\n def test_longform_groupby(self):\n\n p = cat._CategoricalPlotter()\n\n # Test a vertically oriented grouped and nested plot\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert len(p.plot_data) == 3\n assert len(p.plot_hues) == 3\n assert p.orient == \"v\"\n assert p.value_label == \"y\"\n assert p.group_label == \"g\"\n assert p.hue_title == \"h\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test a grouped and nested plot with direct array value data\n p.establish_variables(\"g\", self.y.values, \"h\", self.df)\n assert p.value_label is None\n assert p.group_label == \"g\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n # Test a grouped and nested plot with direct array hue data\n p.establish_variables(\"g\", \"y\", self.h.values, self.df)\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test categorical grouping data\n df = self.df.copy()\n df.g = df.g.astype(\"category\")\n\n # Test that horizontal orientation is automatically detected\n p.establish_variables(\"y\", \"g\", hue=\"h\", data=df)\n assert len(p.plot_data) == 3\n assert len(p.plot_hues) == 3\n assert p.orient == \"h\"\n assert p.value_label == \"y\"\n assert p.group_label == \"g\"\n assert p.hue_title == \"h\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test grouped data that matches on index\n p1 = cat._CategoricalPlotter()\n p1.establish_variables(self.g, self.y, hue=self.h)\n p2 = cat._CategoricalPlotter()\n p2.establish_variables(self.g, self.y.iloc[::-1], self.h)\n for i, (d1, d2) in enumerate(zip(p1.plot_data, p2.plot_data)):\n assert np.array_equal(d1.sort_index(), d2.sort_index())\n\n def test_input_validation(self):\n\n p = cat._CategoricalPlotter()\n\n kws = dict(x=\"g\", y=\"y\", hue=\"h\", units=\"u\", data=self.df)\n for var in [\"x\", \"y\", \"hue\", \"units\"]:\n input_kws = kws.copy()\n input_kws[var] = \"bad_input\"\n with pytest.raises(ValueError):\n p.establish_variables(**input_kws)\n\n def test_order(self):\n\n p = cat._CategoricalPlotter()\n\n # Test inferred order from a wide dataframe input\n p.establish_variables(data=self.x_df)\n assert p.group_names == [\"X\", \"Y\", \"Z\"]\n\n # Test specified order with a wide dataframe input\n p.establish_variables(data=self.x_df, order=[\"Y\", \"Z\", \"X\"])\n assert p.group_names == [\"Y\", \"Z\", \"X\"]\n\n for group, vals in zip([\"Y\", \"Z\", \"X\"], p.plot_data):\n npt.assert_array_equal(vals, self.x_df[group])\n\n with pytest.raises(ValueError):\n p.establish_variables(data=self.x, order=[1, 2, 0])\n\n # Test inferred order from a grouped longform input\n p.establish_variables(\"g\", \"y\", data=self.df)\n assert p.group_names == [\"a\", \"b\", \"c\"]\n\n # Test specified order from a grouped longform input\n p.establish_variables(\"g\", \"y\", data=self.df, order=[\"b\", \"a\", \"c\"])\n assert p.group_names == [\"b\", \"a\", \"c\"]\n\n for group, vals in zip([\"b\", \"a\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n # Test inferred order from a grouped input with categorical groups\n df = self.df.copy()\n df.g = df.g.astype(\"category\")\n df.g = df.g.cat.reorder_categories([\"c\", \"b\", \"a\"])\n p.establish_variables(\"g\", \"y\", data=df)\n assert p.group_names == [\"c\", \"b\", \"a\"]\n\n for group, vals in zip([\"c\", \"b\", \"a\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n df.g = (df.g.cat.add_categories(\"d\")\n .cat.reorder_categories([\"c\", \"b\", \"d\", \"a\"]))\n p.establish_variables(\"g\", \"y\", data=df)\n assert p.group_names == [\"c\", \"b\", \"d\", \"a\"]\n\n def test_hue_order(self):\n\n p = cat._CategoricalPlotter()\n\n # Test inferred hue order\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.hue_names == [\"m\", \"n\"]\n\n # Test specified hue order\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df,\n hue_order=[\"n\", \"m\"])\n assert p.hue_names == [\"n\", \"m\"]\n\n # Test inferred hue order from a categorical hue input\n df = self.df.copy()\n df.h = df.h.astype(\"category\")\n df.h = df.h.cat.reorder_categories([\"n\", \"m\"])\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=df)\n assert p.hue_names == [\"n\", \"m\"]\n\n df.h = (df.h.cat.add_categories(\"o\")\n .cat.reorder_categories([\"o\", \"m\", \"n\"]))\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=df)\n assert p.hue_names == [\"o\", \"m\", \"n\"]\n\n def test_plot_units(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.plot_units is None\n\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df, units=\"u\")\n for group, units in zip([\"a\", \"b\", \"c\"], p.plot_units):\n npt.assert_array_equal(units, self.u[self.g == group])\n\n def test_default_palettes(self):\n\n p = cat._CategoricalPlotter()\n\n # Test palette mapping the x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, None, 1)\n assert p.colors == palettes.color_palette(n_colors=3)\n\n # Test palette mapping the hue position\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(None, None, 1)\n assert p.colors == palettes.color_palette(n_colors=2)\n\n def test_default_palette_with_many_levels(self):\n\n with palettes.color_palette([\"blue\", \"red\"], 2):\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, None, 1)\n npt.assert_array_equal(p.colors,\n palettes.husl_palette(3, l=.7)) # noqa\n\n def test_specific_color(self):\n\n p = cat._CategoricalPlotter()\n\n # Test the same color for each x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(\"blue\", None, 1)\n blue_rgb = mpl.colors.colorConverter.to_rgb(\"blue\")\n assert p.colors == [blue_rgb] * 3\n\n # Test a color-based blend for the hue mapping\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(\"#ff0022\", None, 1)\n rgba_array = np.array(palettes.light_palette(\"#ff0022\", 2))\n npt.assert_array_almost_equal(p.colors,\n rgba_array[:, :3])\n\n def test_specific_palette(self):\n\n p = cat._CategoricalPlotter()\n\n # Test palette mapping the x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, \"dark\", 1)\n assert p.colors == palettes.color_palette(\"dark\", 3)\n\n # Test that non-None `color` and `hue` raises an error\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(None, \"muted\", 1)\n assert p.colors == palettes.color_palette(\"muted\", 2)\n\n # Test that specified palette overrides specified color\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(\"blue\", \"deep\", 1)\n assert p.colors == palettes.color_palette(\"deep\", 3)\n\n def test_dict_as_palette(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n pal = {\"m\": (0, 0, 1), \"n\": (1, 0, 0)}\n p.establish_colors(None, pal, 1)\n assert p.colors == [(0, 0, 1), (1, 0, 0)]\n\n def test_palette_desaturation(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors((0, 0, 1), None, .5)\n assert p.colors == [(.25, .25, .75)] * 3\n\n p.establish_colors(None, [(0, 0, 1), (1, 0, 0), \"w\"], .5)\n assert p.colors == [(.25, .25, .75), (.75, .25, .25), (1, 1, 1)]"},{"col":4,"comment":"null","endLoc":149,"header":"def test_wide_df_data(self)","id":4517,"name":"test_wide_df_data","nodeType":"Function","startLoc":126,"text":"def test_wide_df_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test basic wide DataFrame\n p.establish_variables(data=self.x_df)\n\n # Check data attribute\n for x, y, in zip(p.plot_data, self.x_df[[\"X\", \"Y\", \"Z\"]].values.T):\n npt.assert_array_equal(x, y)\n\n # Check semantic attributes\n assert p.orient == \"v\"\n assert p.plot_hues is None\n assert p.group_label == \"big\"\n assert p.value_label is None\n\n # Test wide dataframe with forced horizontal orientation\n p.establish_variables(data=self.x_df, orient=\"horiz\")\n assert p.orient == \"h\"\n\n # Test exception by trying to hue-group with a wide dataframe\n with pytest.raises(ValueError):\n p.establish_variables(hue=\"d\", data=self.x_df)"},{"col":4,"comment":"null","endLoc":591,"header":"def test_identity_mapping_linewidth(self)","id":4518,"name":"test_identity_mapping_linewidth","nodeType":"Function","startLoc":585,"text":"def test_identity_mapping_linewidth(self):\n\n m = MockMark()\n x = y = [1, 2, 3, 4, 5]\n lw = pd.Series([.5, .1, .1, .9, 3])\n Plot(x=x, y=y, linewidth=lw).scale(linewidth=None).add(m).plot()\n assert_vector_equal(m.passed_scales[\"linewidth\"](lw), lw)"},{"col":4,"comment":"null","endLoc":602,"header":"def test_pair_single_coordinate_stat_orient(self, long_df)","id":4519,"name":"test_pair_single_coordinate_stat_orient","nodeType":"Function","startLoc":593,"text":"def test_pair_single_coordinate_stat_orient(self, long_df):\n\n class MockStat(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.orient = orient\n return data\n\n s = MockStat()\n Plot(long_df).pair(x=[\"x\", \"y\"]).add(MockMark(), s).plot()\n assert s.orient == \"x\""},{"col":4,"comment":"null","endLoc":614,"header":"def test_inferred_nominal_passed_to_stat(self)","id":4520,"name":"test_inferred_nominal_passed_to_stat","nodeType":"Function","startLoc":604,"text":"def test_inferred_nominal_passed_to_stat(self):\n\n class MockStat(Stat):\n def __call__(self, data, groupby, orient, scales):\n self.scales = scales\n return data\n\n s = MockStat()\n y = [\"a\", \"a\", \"b\", \"c\"]\n Plot(y=y).add(MockMark(), s).plot()\n assert s.scales[\"y\"].__class__.__name__ == \"Nominal\""},{"col":4,"comment":"null","endLoc":627,"header":"@pytest.mark.xfail(\n reason=\"Correct output representation for color with identity scale undefined\"\n )\n def test_identity_mapping_color_strings(self)","id":4521,"name":"test_identity_mapping_color_strings","nodeType":"Function","startLoc":617,"text":"@pytest.mark.xfail(\n reason=\"Correct output representation for color with identity scale undefined\"\n )\n def test_identity_mapping_color_strings(self):\n\n m = MockMark()\n x = y = [1, 2, 3]\n c = [\"C0\", \"C2\", \"C1\"]\n Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()\n expected = mpl.colors.to_rgba_array(c)[:, :3]\n assert_array_equal(m.passed_scales[\"color\"](c), expected)"},{"col":4,"comment":"null","endLoc":636,"header":"def test_identity_mapping_color_tuples(self)","id":4522,"name":"test_identity_mapping_color_tuples","nodeType":"Function","startLoc":629,"text":"def test_identity_mapping_color_tuples(self):\n\n m = MockMark()\n x = y = [1, 2, 3]\n c = [(1, 0, 0), (0, 1, 0), (1, 0, 0)]\n Plot(x=x, y=y, color=c).scale(color=None).add(m).plot()\n expected = mpl.colors.to_rgba_array(c)[:, :3]\n assert_array_equal(m.passed_scales[\"color\"](c), expected)"},{"col":4,"comment":"null","endLoc":646,"header":"@pytest.mark.xfail(\n reason=\"Need decision on what to do with scale defined for unused variable\"\n )\n def test_undefined_variable_raises(self)","id":4523,"name":"test_undefined_variable_raises","nodeType":"Function","startLoc":638,"text":"@pytest.mark.xfail(\n reason=\"Need decision on what to do with scale defined for unused variable\"\n )\n def test_undefined_variable_raises(self):\n\n p = Plot(x=[1, 2, 3], color=[\"a\", \"b\", \"c\"]).scale(y=Continuous())\n err = r\"No data found for variable\\(s\\) with explicit scale: {'y'}\"\n with pytest.raises(RuntimeError, match=err):\n p.plot()"},{"className":"TestPlotting","col":0,"comment":"null","endLoc":1212,"id":4524,"nodeType":"Class","startLoc":649,"text":"class TestPlotting:\n\n def test_matplotlib_object_creation(self):\n\n p = Plot().plot()\n assert isinstance(p._figure, mpl.figure.Figure)\n for sub in p._subplots:\n assert isinstance(sub[\"ax\"], mpl.axes.Axes)\n\n def test_empty(self):\n\n m = MockMark()\n Plot().plot()\n assert m.n_splits == 0\n\n def test_single_split_single_layer(self, long_df):\n\n m = MockMark()\n p = Plot(long_df, x=\"f\", y=\"z\").add(m).plot()\n assert m.n_splits == 1\n\n assert m.passed_keys[0] == {}\n assert m.passed_axes == [sub[\"ax\"] for sub in p._subplots]\n for col in p._data.frame:\n assert_series_equal(m.passed_data[0][col], p._data.frame[col])\n\n def test_single_split_multi_layer(self, long_df):\n\n vs = [{\"color\": \"a\", \"linewidth\": \"z\"}, {\"color\": \"b\", \"pattern\": \"c\"}]\n\n class NoGroupingMark(MockMark):\n _grouping_props = []\n\n ms = [NoGroupingMark(), NoGroupingMark()]\n Plot(long_df).add(ms[0], **vs[0]).add(ms[1], **vs[1]).plot()\n\n for m, v in zip(ms, vs):\n for var, col in v.items():\n assert_vector_equal(m.passed_data[0][var], long_df[col])\n\n def check_splits_single_var(\n self, data, mark, data_vars, split_var, split_col, split_keys\n ):\n\n assert mark.n_splits == len(split_keys)\n assert mark.passed_keys == [{split_var: key} for key in split_keys]\n\n for i, key in enumerate(split_keys):\n\n split_data = data[data[split_col] == key]\n for var, col in data_vars.items():\n assert_array_equal(mark.passed_data[i][var], split_data[col])\n\n def check_splits_multi_vars(\n self, data, mark, data_vars, split_vars, split_cols, split_keys\n ):\n\n assert mark.n_splits == np.prod([len(ks) for ks in split_keys])\n\n expected_keys = [\n dict(zip(split_vars, level_keys))\n for level_keys in itertools.product(*split_keys)\n ]\n assert mark.passed_keys == expected_keys\n\n for i, keys in enumerate(itertools.product(*split_keys)):\n\n use_rows = pd.Series(True, data.index)\n for var, col, key in zip(split_vars, split_cols, keys):\n use_rows &= data[col] == key\n split_data = data[use_rows]\n for var, col in data_vars.items():\n assert_array_equal(mark.passed_data[i][var], split_data[col])\n\n @pytest.mark.parametrize(\n \"split_var\", [\n \"color\", # explicitly declared on the Mark\n \"group\", # implicitly used for all Mark classes\n ])\n def test_one_grouping_variable(self, long_df, split_var):\n\n split_col = \"a\"\n data_vars = {\"x\": \"f\", \"y\": \"z\", split_var: split_col}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).add(m).plot()\n\n split_keys = categorical_order(long_df[split_col])\n sub, *_ = p._subplots\n assert m.passed_axes == [sub[\"ax\"] for _ in split_keys]\n self.check_splits_single_var(\n long_df, m, data_vars, split_var, split_col, split_keys\n )\n\n def test_two_grouping_variables(self, long_df):\n\n split_vars = [\"color\", \"group\"]\n split_cols = [\"a\", \"b\"]\n data_vars = {\"y\": \"z\", **{var: col for var, col in zip(split_vars, split_cols)}}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).add(m).plot()\n\n split_keys = [categorical_order(long_df[col]) for col in split_cols]\n sub, *_ = p._subplots\n assert m.passed_axes == [\n sub[\"ax\"] for _ in itertools.product(*split_keys)\n ]\n self.check_splits_multi_vars(\n long_df, m, data_vars, split_vars, split_cols, split_keys\n )\n\n def test_facets_no_subgroups(self, long_df):\n\n split_var = \"col\"\n split_col = \"b\"\n data_vars = {\"x\": \"f\", \"y\": \"z\"}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).facet(**{split_var: split_col}).add(m).plot()\n\n split_keys = categorical_order(long_df[split_col])\n assert m.passed_axes == list(p._figure.axes)\n self.check_splits_single_var(\n long_df, m, data_vars, split_var, split_col, split_keys\n )\n\n def test_facets_one_subgroup(self, long_df):\n\n facet_var, facet_col = fx = \"col\", \"a\"\n group_var, group_col = gx = \"group\", \"b\"\n split_vars, split_cols = zip(*[fx, gx])\n data_vars = {\"x\": \"f\", \"y\": \"z\", group_var: group_col}\n\n m = MockMark()\n p = (\n Plot(long_df, **data_vars)\n .facet(**{facet_var: facet_col})\n .add(m)\n .plot()\n )\n\n split_keys = [categorical_order(long_df[col]) for col in [facet_col, group_col]]\n assert m.passed_axes == [\n ax\n for ax in list(p._figure.axes)\n for _ in categorical_order(long_df[group_col])\n ]\n self.check_splits_multi_vars(\n long_df, m, data_vars, split_vars, split_cols, split_keys\n )\n\n def test_layer_specific_facet_disabling(self, long_df):\n\n axis_vars = {\"x\": \"y\", \"y\": \"z\"}\n row_var = \"a\"\n\n m = MockMark()\n p = Plot(long_df, **axis_vars).facet(row=row_var).add(m, row=None).plot()\n\n col_levels = categorical_order(long_df[row_var])\n assert len(p._figure.axes) == len(col_levels)\n\n for data in m.passed_data:\n for var, col in axis_vars.items():\n assert_vector_equal(data[var], long_df[col])\n\n def test_paired_variables(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n\n m = MockMark()\n Plot(long_df).pair(x, y).add(m).plot()\n\n var_product = itertools.product(x, y)\n\n for data, (x_i, y_i) in zip(m.passed_data, var_product):\n assert_vector_equal(data[\"x\"], long_df[x_i].astype(float))\n assert_vector_equal(data[\"y\"], long_df[y_i].astype(float))\n\n def test_paired_one_dimension(self, long_df):\n\n x = [\"y\", \"z\"]\n\n m = MockMark()\n Plot(long_df).pair(x).add(m).plot()\n\n for data, x_i in zip(m.passed_data, x):\n assert_vector_equal(data[\"x\"], long_df[x_i].astype(float))\n\n def test_paired_variables_one_subset(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n group = \"a\"\n\n long_df[\"x\"] = long_df[\"x\"].astype(float) # simplify vector comparison\n\n m = MockMark()\n Plot(long_df, group=group).pair(x, y).add(m).plot()\n\n groups = categorical_order(long_df[group])\n var_product = itertools.product(x, y, groups)\n\n for data, (x_i, y_i, g_i) in zip(m.passed_data, var_product):\n rows = long_df[group] == g_i\n assert_vector_equal(data[\"x\"], long_df.loc[rows, x_i])\n assert_vector_equal(data[\"y\"], long_df.loc[rows, y_i])\n\n def test_paired_and_faceted(self, long_df):\n\n x = [\"y\", \"z\"]\n y = \"f\"\n row = \"c\"\n\n m = MockMark()\n Plot(long_df, y=y).facet(row=row).pair(x).add(m).plot()\n\n facets = categorical_order(long_df[row])\n var_product = itertools.product(x, facets)\n\n for data, (x_i, f_i) in zip(m.passed_data, var_product):\n rows = long_df[row] == f_i\n assert_vector_equal(data[\"x\"], long_df.loc[rows, x_i])\n assert_vector_equal(data[\"y\"], long_df.loc[rows, y])\n\n def test_theme_default(self):\n\n p = Plot().plot()\n assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), \"#EAEAF2\")\n\n def test_theme_params(self):\n\n color = \".888\"\n p = Plot().theme({\"axes.facecolor\": color}).plot()\n assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), color)\n\n def test_theme_error(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=r\"theme\\(\\) takes 1 positional\"):\n p.theme(\"arg1\", \"arg2\")\n\n def test_stat(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg()).plot()\n\n expected = long_df.groupby(\"a\", sort=False)[\"z\"].mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], expected)\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated\n\n def test_move(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"z\", y=\"z\").add(m, Shift(x=1)).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"z\"] + 1)\n assert_vector_equal(m.passed_data[0][\"y\"], long_df[\"z\"])\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated\n\n def test_stat_and_move(self, long_df):\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg(), Shift(y=1)).plot()\n\n expected = long_df.groupby(\"a\", sort=False)[\"z\"].mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], expected + 1)\n\n def test_stat_log_scale(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg()).scale(y=\"log\").plot()\n\n x = long_df[\"a\"]\n y = np.log10(long_df[\"z\"])\n expected = y.groupby(x, sort=False).mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], 10 ** expected)\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated\n\n def test_move_log_scale(self, long_df):\n\n m = MockMark()\n Plot(\n long_df, x=\"z\", y=\"z\"\n ).scale(x=\"log\").add(m, Shift(x=-1)).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"z\"] / 10)\n\n def test_multi_move(self, long_df):\n\n m = MockMark()\n move_stack = [Shift(1), Shift(2)]\n Plot(long_df, x=\"x\", y=\"y\").add(m, *move_stack).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"x\"] + 3)\n\n def test_multi_move_with_pairing(self, long_df):\n m = MockMark()\n move_stack = [Shift(1), Shift(2)]\n Plot(long_df, x=\"x\").pair(y=[\"y\", \"z\"]).add(m, *move_stack).plot()\n for frame in m.passed_data:\n assert_vector_equal(frame[\"x\"], long_df[\"x\"] + 3)\n\n def test_move_with_range(self, long_df):\n\n x = [0, 0, 1, 1, 2, 2]\n group = [0, 1, 0, 1, 0, 1]\n ymin = np.arange(6)\n ymax = np.arange(6) * 2\n\n m = MockMark()\n Plot(x=x, group=group, ymin=ymin, ymax=ymax).add(m, Dodge()).plot()\n\n signs = [-1, +1]\n for i, df in m.passed_data[0].groupby(\"group\"):\n assert_array_equal(df[\"x\"], np.arange(3) + signs[i] * 0.2)\n\n def test_methods_clone(self, long_df):\n\n p1 = Plot(long_df, \"x\", \"y\")\n p2 = p1.add(MockMark()).facet(\"a\")\n\n assert p1 is not p2\n assert not p1._layers\n assert not p1._facet_spec\n\n def test_default_is_no_pyplot(self):\n\n p = Plot().plot()\n\n assert not plt.get_fignums()\n assert isinstance(p._figure, mpl.figure.Figure)\n\n def test_with_pyplot(self):\n\n p = Plot().plot(pyplot=True)\n\n assert len(plt.get_fignums()) == 1\n fig = plt.gcf()\n assert p._figure is fig\n\n def test_show(self):\n\n p = Plot()\n\n with warnings.catch_warnings(record=True) as msg:\n out = p.show(block=False)\n assert out is None\n assert not hasattr(p, \"_figure\")\n\n assert len(plt.get_fignums()) == 1\n fig = plt.gcf()\n\n gui_backend = (\n # From https://github.com/matplotlib/matplotlib/issues/20281\n fig.canvas.manager.show != mpl.backend_bases.FigureManagerBase.show\n )\n if not gui_backend:\n assert msg\n\n def test_png_repr(self):\n\n p = Plot()\n data, metadata = p._repr_png_()\n img = Image.open(io.BytesIO(data))\n\n assert not hasattr(p, \"_figure\")\n assert isinstance(data, bytes)\n assert img.format == \"PNG\"\n assert sorted(metadata) == [\"height\", \"width\"]\n # TODO test retina scaling\n\n def test_save(self):\n\n buf = io.BytesIO()\n\n p = Plot().save(buf)\n assert isinstance(p, Plot)\n img = Image.open(buf)\n assert img.format == \"PNG\"\n\n buf = io.StringIO()\n Plot().save(buf, format=\"svg\")\n tag = xml.etree.ElementTree.fromstring(buf.getvalue()).tag\n assert tag == \"{http://www.w3.org/2000/svg}svg\"\n\n def test_layout_size(self):\n\n size = (4, 2)\n p = Plot().layout(size=size).plot()\n assert tuple(p._figure.get_size_inches()) == size\n\n def test_on_axes(self):\n\n ax = mpl.figure.Figure().subplots()\n m = MockMark()\n p = Plot().on(ax).add(m).plot()\n assert m.passed_axes == [ax]\n assert p._figure is ax.figure\n\n @pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_figure(self, facet):\n\n f = mpl.figure.Figure()\n m = MockMark()\n p = Plot().on(f).add(m)\n if facet:\n p = p.facet([\"a\", \"b\"])\n p = p.plot()\n assert m.passed_axes == f.axes\n assert p._figure is f\n\n @pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"mpl<3.4 does not have SubFigure\",\n )\n @pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_subfigure(self, facet):\n\n sf1, sf2 = mpl.figure.Figure().subfigures(2)\n sf1.subplots()\n m = MockMark()\n p = Plot().on(sf2).add(m)\n if facet:\n p = p.facet([\"a\", \"b\"])\n p = p.plot()\n assert m.passed_axes == sf2.figure.axes[1:]\n assert p._figure is sf2.figure\n\n def test_on_type_check(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=\"The `Plot.on`.+\"):\n p.on([])\n\n def test_on_axes_with_subplots_error(self):\n\n ax = mpl.figure.Figure().subplots()\n\n p1 = Plot().facet([\"a\", \"b\"]).on(ax)\n with pytest.raises(RuntimeError, match=\"Cannot create multiple subplots\"):\n p1.plot()\n\n p2 = Plot().pair([[\"a\", \"b\"], [\"x\", \"y\"]]).on(ax)\n with pytest.raises(RuntimeError, match=\"Cannot create multiple subplots\"):\n p2.plot()\n\n def test_on_disables_layout_algo(self):\n\n f = mpl.figure.Figure()\n p = Plot().on(f).plot()\n assert not p._figure.get_tight_layout()\n\n def test_axis_labels_from_constructor(self, long_df):\n\n ax, = Plot(long_df, x=\"a\", y=\"b\").plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n ax, = Plot(x=long_df[\"a\"], y=long_df[\"b\"].to_numpy()).plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n\n def test_axis_labels_from_layer(self, long_df):\n\n m = MockMark()\n\n ax, = Plot(long_df).add(m, x=\"a\", y=\"b\").plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n p = Plot().add(m, x=long_df[\"a\"], y=long_df[\"b\"].to_list())\n ax, = p.plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n\n def test_axis_labels_are_first_name(self, long_df):\n\n m = MockMark()\n p = (\n Plot(long_df, x=long_df[\"z\"].to_list(), y=\"b\")\n .add(m, x=\"a\")\n .add(m, x=\"x\", y=\"y\")\n )\n ax, = p.plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n def test_limits(self, long_df):\n\n limit = (-2, 24)\n p = Plot(long_df, x=\"x\", y=\"y\").limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == limit\n\n limit = (np.datetime64(\"2005-01-01\"), np.datetime64(\"2008-01-01\"))\n p = Plot(long_df, x=\"d\", y=\"y\").limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == tuple(mpl.dates.date2num(limit))\n\n limit = (\"b\", \"c\")\n p = Plot(x=[\"a\", \"b\", \"c\", \"d\"], y=[1, 2, 3, 4]).limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == (0.5, 2.5)\n\n def test_labels_axis(self, long_df):\n\n label = \"Y axis\"\n p = Plot(long_df, x=\"x\", y=\"y\").label(y=label).plot()\n ax = p._figure.axes[0]\n assert ax.get_ylabel() == label\n\n label = str.capitalize\n p = Plot(long_df, x=\"x\", y=\"y\").label(y=label).plot()\n ax = p._figure.axes[0]\n assert ax.get_ylabel() == \"Y\"\n\n def test_labels_legend(self, long_df):\n\n m = MockMark()\n\n label = \"A\"\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(m).label(color=label).plot()\n assert p._figure.legends[0].get_title().get_text() == label\n\n func = str.capitalize\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(m).label(color=func).plot()\n assert p._figure.legends[0].get_title().get_text() == label\n\n def test_labels_facets(self):\n\n data = {\"a\": [\"b\", \"c\"], \"x\": [\"y\", \"z\"]}\n p = Plot(data).facet(\"a\", \"x\").label(col=str.capitalize, row=\"$x$\").plot()\n axs = np.reshape(p._figure.axes, (2, 2))\n for (i, j), ax in np.ndenumerate(axs):\n expected = f\"A {data['a'][j]} | $x$ {data['x'][i]}\"\n assert ax.get_title() == expected\n\n def test_title_single(self):\n\n label = \"A\"\n p = Plot().label(title=label).plot()\n assert p._figure.axes[0].get_title() == label\n\n def test_title_facet_function(self):\n\n titles = [\"a\", \"b\"]\n p = Plot().facet(titles).label(title=str.capitalize).plot()\n for i, ax in enumerate(p._figure.axes):\n assert ax.get_title() == titles[i].upper()\n\n cols, rows = [\"a\", \"b\"], [\"x\", \"y\"]\n p = Plot().facet(cols, rows).label(title=str.capitalize).plot()\n for i, ax in enumerate(p._figure.axes):\n expected = \" | \".join([cols[i % 2].upper(), rows[i // 2].upper()])\n assert ax.get_title() == expected"},{"col":4,"comment":"null","endLoc":656,"header":"def test_matplotlib_object_creation(self)","id":4525,"name":"test_matplotlib_object_creation","nodeType":"Function","startLoc":651,"text":"def test_matplotlib_object_creation(self):\n\n p = Plot().plot()\n assert isinstance(p._figure, mpl.figure.Figure)\n for sub in p._subplots:\n assert isinstance(sub[\"ax\"], mpl.axes.Axes)"},{"col":4,"comment":"null","endLoc":662,"header":"def test_empty(self)","id":4526,"name":"test_empty","nodeType":"Function","startLoc":658,"text":"def test_empty(self):\n\n m = MockMark()\n Plot().plot()\n assert m.n_splits == 0"},{"col":4,"comment":"null","endLoc":326,"header":"def test_hue_map_without_hue_dataa(self, long_df)","id":4527,"name":"test_hue_map_without_hue_dataa","nodeType":"Function","startLoc":322,"text":"def test_hue_map_without_hue_dataa(self, long_df):\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n with pytest.warns(UserWarning, match=\"Ignoring `palette`\"):\n HueMapping(p, palette=\"viridis\")"},{"col":4,"comment":"null","endLoc":673,"header":"def test_single_split_single_layer(self, long_df)","id":4528,"name":"test_single_split_single_layer","nodeType":"Function","startLoc":664,"text":"def test_single_split_single_layer(self, long_df):\n\n m = MockMark()\n p = Plot(long_df, x=\"f\", y=\"z\").add(m).plot()\n assert m.n_splits == 1\n\n assert m.passed_keys[0] == {}\n assert m.passed_axes == [sub[\"ax\"] for sub in p._subplots]\n for col in p._data.frame:\n assert_series_equal(m.passed_data[0][col], p._data.frame[col])"},{"col":4,"comment":"null","endLoc":180,"header":"def test_1d_input_data(self)","id":4529,"name":"test_1d_input_data","nodeType":"Function","startLoc":151,"text":"def test_1d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test basic vector data\n x_1d_array = self.x.ravel()\n p.establish_variables(data=x_1d_array)\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.n_total\n assert p.group_label is None\n assert p.value_label is None\n\n # Test basic vector data in list form\n x_1d_list = x_1d_array.tolist()\n p.establish_variables(data=x_1d_list)\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.n_total\n assert p.group_label is None\n assert p.value_label is None\n\n # Test an object array that looks 1D but isn't\n x_notreally_1d = np.array([self.x.ravel(),\n self.x.ravel()[:int(self.n_total / 2)]],\n dtype=object)\n p.establish_variables(data=x_notreally_1d)\n assert len(p.plot_data) == 2\n assert len(p.plot_data[0]) == self.n_total\n assert len(p.plot_data[1]) == self.n_total / 2\n assert p.group_label is None\n assert p.value_label is None"},{"col":4,"comment":"null","endLoc":687,"header":"def test_single_split_multi_layer(self, long_df)","id":4530,"name":"test_single_split_multi_layer","nodeType":"Function","startLoc":675,"text":"def test_single_split_multi_layer(self, long_df):\n\n vs = [{\"color\": \"a\", \"linewidth\": \"z\"}, {\"color\": \"b\", \"pattern\": \"c\"}]\n\n class NoGroupingMark(MockMark):\n _grouping_props = []\n\n ms = [NoGroupingMark(), NoGroupingMark()]\n Plot(long_df).add(ms[0], **vs[0]).add(ms[1], **vs[1]).plot()\n\n for m, v in zip(ms, vs):\n for var, col in v.items():\n assert_vector_equal(m.passed_data[0][var], long_df[col])"},{"className":"TestSizeMapping","col":0,"comment":"null","endLoc":476,"id":4531,"nodeType":"Class","startLoc":329,"text":"class TestSizeMapping:\n\n def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\")\n )\n sizes = 1, 6\n p = SizeMapping.map(p_orig, sizes=sizes)\n assert p is p_orig\n assert isinstance(p._size_map, SizeMapping)\n assert min(p._size_map.lookup_table.values()) == sizes[0]\n assert max(p._size_map.lookup_table.values()) == sizes[1]\n\n def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._size_map, SizeMapping)\n assert p._size_map.map_type is None\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n assert isinstance(p._size_map, SizeMapping)\n assert p._size_map.map_type == p.var_types[\"size\"]\n\n def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n sizes = [1, 4, 2]\n size_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_size(sizes=sizes, order=size_order)\n assert p is p_orig\n assert p._size_map.lookup_table == dict(zip(size_order, sizes))\n assert p._size_map.levels == size_order\n\n def test_size_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, size=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.norm is None\n assert m.lookup_table is None\n\n def test_map_size_numeric(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n )\n\n # Test default range of keys in the lookup table values\n m = SizeMapping(p)\n size_values = m.lookup_table.values()\n value_range = min(size_values), max(size_values)\n assert value_range == p._default_size_range\n\n # Test specified range of size values\n sizes = 1, 5\n m = SizeMapping(p, sizes=sizes)\n size_values = m.lookup_table.values()\n assert min(size_values), max(size_values) == sizes\n\n # Test size values with normalization range\n norm = 1, 10\n m = SizeMapping(p, sizes=sizes, norm=norm)\n normalize = mpl.colors.Normalize(*norm, clip=True)\n for key, val in m.lookup_table.items():\n assert val == sizes[0] + (sizes[1] - sizes[0]) * normalize(key)\n\n # Test size values with normalization object\n norm = mpl.colors.LogNorm(1, 10, clip=False)\n m = SizeMapping(p, sizes=sizes, norm=norm)\n assert m.norm.clip\n for key, val in m.lookup_table.items():\n assert val == sizes[0] + (sizes[1] - sizes[0]) * norm(key)\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=\"bad_sizes\")\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=(1, 2, 3))\n\n # Test bad norm argument\n with pytest.raises(ValueError):\n SizeMapping(p, norm=\"bad_norm\")\n\n def test_map_size_categorical(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n # Test specified size order\n levels = p.plot_data[\"size\"].unique()\n sizes = [1, 4, 6]\n order = [levels[1], levels[2], levels[0]]\n m = SizeMapping(p, sizes=sizes, order=order)\n assert m.lookup_table == dict(zip(order, sizes))\n\n # Test list of sizes\n order = categorical_order(p.plot_data[\"size\"])\n sizes = list(np.random.rand(len(levels)))\n m = SizeMapping(p, sizes=sizes)\n assert m.lookup_table == dict(zip(order, sizes))\n\n # Test dict of sizes\n sizes = dict(zip(levels, np.random.rand(len(levels))))\n m = SizeMapping(p, sizes=sizes)\n assert m.lookup_table == sizes\n\n # Test specified size range\n sizes = (2, 5)\n m = SizeMapping(p, sizes=sizes)\n values = np.linspace(*sizes, len(m.levels))[::-1]\n assert m.lookup_table == dict(zip(m.levels, values))\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", size=\"a_cat\"))\n m = SizeMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n assert m.map_type == \"categorical\"\n\n # Test sizes list with wrong length\n sizes = list(np.random.rand(len(levels) + 1))\n with pytest.warns(UserWarning):\n SizeMapping(p, sizes=sizes)\n\n # Test sizes dict with missing levels\n sizes = dict(zip(levels, np.random.rand(len(levels) - 1)))\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=sizes)\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=\"bad_size\")"},{"col":4,"comment":"null","endLoc":342,"header":"def test_init_from_map(self, long_df)","id":4532,"name":"test_init_from_map","nodeType":"Function","startLoc":331,"text":"def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\")\n )\n sizes = 1, 6\n p = SizeMapping.map(p_orig, sizes=sizes)\n assert p is p_orig\n assert isinstance(p._size_map, SizeMapping)\n assert min(p._size_map.lookup_table.values()) == sizes[0]\n assert max(p._size_map.lookup_table.values()) == sizes[1]"},{"attributeType":"str","col":8,"comment":"null","endLoc":584,"id":4533,"name":"_role","nodeType":"Attribute","startLoc":584,"text":"self._role"},{"attributeType":"null","col":8,"comment":"null","endLoc":583,"id":4534,"name":"_f","nodeType":"Attribute","startLoc":583,"text":"self._f"},{"className":"ClassDoc","col":0,"comment":"null","endLoc":715,"id":4535,"nodeType":"Class","startLoc":634,"text":"class ClassDoc(NumpyDocString):\n\n extra_public_methods = ['__call__']\n\n def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,\n config={}):\n if not inspect.isclass(cls) and cls is not None:\n raise ValueError(f\"Expected a class or None, but got {cls!r}\")\n self._cls = cls\n\n if 'sphinx' in sys.modules:\n from sphinx.ext.autodoc import ALL\n else:\n ALL = object()\n\n self.show_inherited_members = config.get(\n 'show_inherited_class_members', True)\n\n if modulename and not modulename.endswith('.'):\n modulename += '.'\n self._mod = modulename\n\n if doc is None:\n if cls is None:\n raise ValueError(\"No class or documentation string given\")\n doc = pydoc.getdoc(cls)\n\n NumpyDocString.__init__(self, doc)\n\n _members = config.get('members', [])\n if _members is ALL:\n _members = None\n _exclude = config.get('exclude-members', [])\n\n if config.get('show_class_members', True) and _exclude is not ALL:\n def splitlines_x(s):\n if not s:\n return []\n else:\n return s.splitlines()\n for field, items in [('Methods', self.methods),\n ('Attributes', self.properties)]:\n if not self[field]:\n doc_list = []\n for name in sorted(items):\n if (name in _exclude or\n (_members and name not in _members)):\n continue\n try:\n doc_item = pydoc.getdoc(getattr(self._cls, name))\n doc_list.append(\n Parameter(name, '', splitlines_x(doc_item)))\n except AttributeError:\n pass # method doesn't exist\n self[field] = doc_list\n\n @property\n def methods(self):\n if self._cls is None:\n return []\n return [name for name, func in inspect.getmembers(self._cls)\n if ((not name.startswith('_')\n or name in self.extra_public_methods)\n and isinstance(func, Callable)\n and self._is_show_member(name))]\n\n @property\n def properties(self):\n if self._cls is None:\n return []\n return [name for name, func in inspect.getmembers(self._cls)\n if (not name.startswith('_') and\n (func is None or isinstance(func, property) or\n inspect.isdatadescriptor(func))\n and self._is_show_member(name))]\n\n def _is_show_member(self, name):\n if self.show_inherited_members:\n return True # show all class members\n if name not in self._cls.__dict__:\n return False # class member is inherited, we do not show it\n return True"},{"col":4,"comment":"null","endLoc":688,"header":"def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,\n config={})","id":4536,"name":"__init__","nodeType":"Function","startLoc":638,"text":"def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,\n config={}):\n if not inspect.isclass(cls) and cls is not None:\n raise ValueError(f\"Expected a class or None, but got {cls!r}\")\n self._cls = cls\n\n if 'sphinx' in sys.modules:\n from sphinx.ext.autodoc import ALL\n else:\n ALL = object()\n\n self.show_inherited_members = config.get(\n 'show_inherited_class_members', True)\n\n if modulename and not modulename.endswith('.'):\n modulename += '.'\n self._mod = modulename\n\n if doc is None:\n if cls is None:\n raise ValueError(\"No class or documentation string given\")\n doc = pydoc.getdoc(cls)\n\n NumpyDocString.__init__(self, doc)\n\n _members = config.get('members', [])\n if _members is ALL:\n _members = None\n _exclude = config.get('exclude-members', [])\n\n if config.get('show_class_members', True) and _exclude is not ALL:\n def splitlines_x(s):\n if not s:\n return []\n else:\n return s.splitlines()\n for field, items in [('Methods', self.methods),\n ('Attributes', self.properties)]:\n if not self[field]:\n doc_list = []\n for name in sorted(items):\n if (name in _exclude or\n (_members and name not in _members)):\n continue\n try:\n doc_item = pydoc.getdoc(getattr(self._cls, name))\n doc_list.append(\n Parameter(name, '', splitlines_x(doc_item)))\n except AttributeError:\n pass # method doesn't exist\n self[field] = doc_list"},{"col":4,"comment":"null","endLoc":358,"header":"def test_plotter_default_init(self, long_df)","id":4537,"name":"test_plotter_default_init","nodeType":"Function","startLoc":344,"text":"def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._size_map, SizeMapping)\n assert p._size_map.map_type is None\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n assert isinstance(p._size_map, SizeMapping)\n assert p._size_map.map_type == p.var_types[\"size\"]"},{"col":4,"comment":"null","endLoc":200,"header":"def test_2d_input_data(self)","id":4538,"name":"test_2d_input_data","nodeType":"Function","startLoc":182,"text":"def test_2d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n x = self.x[:, 0]\n\n # Test vector data that looks 2D but doesn't really have columns\n p.establish_variables(data=x[:, np.newaxis])\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.x.shape[0]\n assert p.group_label is None\n assert p.value_label is None\n\n # Test vector data that looks 2D but doesn't really have rows\n p.establish_variables(data=x[np.newaxis, :])\n assert len(p.plot_data) == 1\n assert len(p.plot_data[0]) == self.x.shape[0]\n assert p.group_label is None\n assert p.value_label is None"},{"col":4,"comment":"null","endLoc":371,"header":"def test_plotter_reinit(self, long_df)","id":4539,"name":"test_plotter_reinit","nodeType":"Function","startLoc":360,"text":"def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n sizes = [1, 4, 2]\n size_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_size(sizes=sizes, order=size_order)\n assert p is p_orig\n assert p._size_map.lookup_table == dict(zip(size_order, sizes))\n assert p._size_map.levels == size_order"},{"col":4,"comment":"null","endLoc":700,"header":"def check_splits_single_var(\n self, data, mark, data_vars, split_var, split_col, split_keys\n )","id":4540,"name":"check_splits_single_var","nodeType":"Function","startLoc":689,"text":"def check_splits_single_var(\n self, data, mark, data_vars, split_var, split_col, split_keys\n ):\n\n assert mark.n_splits == len(split_keys)\n assert mark.passed_keys == [{split_var: key} for key in split_keys]\n\n for i, key in enumerate(split_keys):\n\n split_data = data[data[split_col] == key]\n for var, col in data_vars.items():\n assert_array_equal(mark.passed_data[i][var], split_data[col])"},{"col":4,"comment":"null","endLoc":209,"header":"def test_3d_input_data(self)","id":4541,"name":"test_3d_input_data","nodeType":"Function","startLoc":202,"text":"def test_3d_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test that passing actually 3D data raises\n x = np.zeros((5, 5, 5))\n with pytest.raises(ValueError):\n p.establish_variables(data=x)"},{"col":4,"comment":"null","endLoc":224,"header":"def test_list_of_array_input_data(self)","id":4542,"name":"test_list_of_array_input_data","nodeType":"Function","startLoc":211,"text":"def test_list_of_array_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test 2D input in list form\n x_list = self.x.T.tolist()\n p.establish_variables(data=x_list)\n assert len(p.plot_data) == 3\n\n lengths = [len(v_i) for v_i in p.plot_data]\n assert lengths == [self.n_total / 3] * 3\n\n assert p.group_label is None\n assert p.value_label is None"},{"col":4,"comment":"null","endLoc":721,"header":"def check_splits_multi_vars(\n self, data, mark, data_vars, split_vars, split_cols, split_keys\n )","id":4543,"name":"check_splits_multi_vars","nodeType":"Function","startLoc":702,"text":"def check_splits_multi_vars(\n self, data, mark, data_vars, split_vars, split_cols, split_keys\n ):\n\n assert mark.n_splits == np.prod([len(ks) for ks in split_keys])\n\n expected_keys = [\n dict(zip(split_vars, level_keys))\n for level_keys in itertools.product(*split_keys)\n ]\n assert mark.passed_keys == expected_keys\n\n for i, keys in enumerate(itertools.product(*split_keys)):\n\n use_rows = pd.Series(True, data.index)\n for var, col, key in zip(split_vars, split_cols, keys):\n use_rows &= data[col] == key\n split_data = data[use_rows]\n for var, col in data_vars.items():\n assert_array_equal(mark.passed_data[i][var], split_data[col])"},{"col":4,"comment":"null","endLoc":236,"header":"def test_wide_array_input_data(self)","id":4544,"name":"test_wide_array_input_data","nodeType":"Function","startLoc":226,"text":"def test_wide_array_input_data(self):\n\n p = cat._CategoricalPlotter()\n\n # Test 2D input in array form\n p.establish_variables(data=self.x)\n assert np.shape(p.plot_data) == (3, self.n_total / 3)\n npt.assert_array_equal(p.plot_data, self.x.T)\n\n assert p.group_label is None\n assert p.value_label is None"},{"col":4,"comment":"null","endLoc":267,"header":"def test_single_long_direct_inputs(self)","id":4545,"name":"test_single_long_direct_inputs","nodeType":"Function","startLoc":238,"text":"def test_single_long_direct_inputs(self):\n\n p = cat._CategoricalPlotter()\n\n # Test passing a series to the x variable\n p.establish_variables(x=self.y)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"h\"\n assert p.value_label == \"y_data\"\n assert p.group_label is None\n\n # Test passing a series to the y variable\n p.establish_variables(y=self.y)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.value_label == \"y_data\"\n assert p.group_label is None\n\n # Test passing an array to the y variable\n p.establish_variables(y=self.y.values)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.group_label is None\n assert p.value_label is None\n\n # Test array and series with non-default index\n x = pd.Series([1, 1, 1, 1], index=[0, 2, 4, 6])\n y = np.array([1, 2, 3, 4])\n p.establish_variables(x, y)\n assert len(p.plot_data[0]) == 4"},{"col":4,"comment":"null","endLoc":285,"header":"def test_single_long_indirect_inputs(self)","id":4546,"name":"test_single_long_indirect_inputs","nodeType":"Function","startLoc":269,"text":"def test_single_long_indirect_inputs(self):\n\n p = cat._CategoricalPlotter()\n\n # Test referencing a DataFrame series in the x variable\n p.establish_variables(x=\"y\", data=self.df)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"h\"\n assert p.value_label == \"y\"\n assert p.group_label is None\n\n # Test referencing a DataFrame series in the y variable\n p.establish_variables(y=\"y\", data=self.df)\n npt.assert_equal(p.plot_data, [self.y])\n assert p.orient == \"v\"\n assert p.value_label == \"y\"\n assert p.group_label is None"},{"col":4,"comment":"null","endLoc":345,"header":"def test_longform_groupby(self)","id":4547,"name":"test_longform_groupby","nodeType":"Function","startLoc":287,"text":"def test_longform_groupby(self):\n\n p = cat._CategoricalPlotter()\n\n # Test a vertically oriented grouped and nested plot\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert len(p.plot_data) == 3\n assert len(p.plot_hues) == 3\n assert p.orient == \"v\"\n assert p.value_label == \"y\"\n assert p.group_label == \"g\"\n assert p.hue_title == \"h\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test a grouped and nested plot with direct array value data\n p.establish_variables(\"g\", self.y.values, \"h\", self.df)\n assert p.value_label is None\n assert p.group_label == \"g\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n # Test a grouped and nested plot with direct array hue data\n p.establish_variables(\"g\", \"y\", self.h.values, self.df)\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test categorical grouping data\n df = self.df.copy()\n df.g = df.g.astype(\"category\")\n\n # Test that horizontal orientation is automatically detected\n p.establish_variables(\"y\", \"g\", hue=\"h\", data=df)\n assert len(p.plot_data) == 3\n assert len(p.plot_hues) == 3\n assert p.orient == \"h\"\n assert p.value_label == \"y\"\n assert p.group_label == \"g\"\n assert p.hue_title == \"h\"\n\n for group, vals in zip([\"a\", \"b\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n for group, hues in zip([\"a\", \"b\", \"c\"], p.plot_hues):\n npt.assert_array_equal(hues, self.h[self.g == group])\n\n # Test grouped data that matches on index\n p1 = cat._CategoricalPlotter()\n p1.establish_variables(self.g, self.y, hue=self.h)\n p2 = cat._CategoricalPlotter()\n p2.establish_variables(self.g, self.y.iloc[::-1], self.h)\n for i, (d1, d2) in enumerate(zip(p1.plot_data, p2.plot_data)):\n assert np.array_equal(d1.sort_index(), d2.sort_index())"},{"col":4,"comment":"null","endLoc":380,"header":"def test_size_map_null(self, flat_series, null_series)","id":4548,"name":"test_size_map_null","nodeType":"Function","startLoc":373,"text":"def test_size_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, size=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.norm is None\n assert m.lookup_table is None"},{"col":4,"comment":"null","endLoc":425,"header":"def test_map_size_numeric(self, long_df)","id":4549,"name":"test_map_size_numeric","nodeType":"Function","startLoc":382,"text":"def test_map_size_numeric(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"s\"),\n )\n\n # Test default range of keys in the lookup table values\n m = SizeMapping(p)\n size_values = m.lookup_table.values()\n value_range = min(size_values), max(size_values)\n assert value_range == p._default_size_range\n\n # Test specified range of size values\n sizes = 1, 5\n m = SizeMapping(p, sizes=sizes)\n size_values = m.lookup_table.values()\n assert min(size_values), max(size_values) == sizes\n\n # Test size values with normalization range\n norm = 1, 10\n m = SizeMapping(p, sizes=sizes, norm=norm)\n normalize = mpl.colors.Normalize(*norm, clip=True)\n for key, val in m.lookup_table.items():\n assert val == sizes[0] + (sizes[1] - sizes[0]) * normalize(key)\n\n # Test size values with normalization object\n norm = mpl.colors.LogNorm(1, 10, clip=False)\n m = SizeMapping(p, sizes=sizes, norm=norm)\n assert m.norm.clip\n for key, val in m.lookup_table.items():\n assert val == sizes[0] + (sizes[1] - sizes[0]) * norm(key)\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=\"bad_sizes\")\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=(1, 2, 3))\n\n # Test bad norm argument\n with pytest.raises(ValueError):\n SizeMapping(p, norm=\"bad_norm\")"},{"col":4,"comment":"null","endLoc":476,"header":"def test_map_size_categorical(self, long_df)","id":4551,"name":"test_map_size_categorical","nodeType":"Function","startLoc":427,"text":"def test_map_size_categorical(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=\"a\"),\n )\n\n # Test specified size order\n levels = p.plot_data[\"size\"].unique()\n sizes = [1, 4, 6]\n order = [levels[1], levels[2], levels[0]]\n m = SizeMapping(p, sizes=sizes, order=order)\n assert m.lookup_table == dict(zip(order, sizes))\n\n # Test list of sizes\n order = categorical_order(p.plot_data[\"size\"])\n sizes = list(np.random.rand(len(levels)))\n m = SizeMapping(p, sizes=sizes)\n assert m.lookup_table == dict(zip(order, sizes))\n\n # Test dict of sizes\n sizes = dict(zip(levels, np.random.rand(len(levels))))\n m = SizeMapping(p, sizes=sizes)\n assert m.lookup_table == sizes\n\n # Test specified size range\n sizes = (2, 5)\n m = SizeMapping(p, sizes=sizes)\n values = np.linspace(*sizes, len(m.levels))[::-1]\n assert m.lookup_table == dict(zip(m.levels, values))\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", size=\"a_cat\"))\n m = SizeMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n assert m.map_type == \"categorical\"\n\n # Test sizes list with wrong length\n sizes = list(np.random.rand(len(levels) + 1))\n with pytest.warns(UserWarning):\n SizeMapping(p, sizes=sizes)\n\n # Test sizes dict with missing levels\n sizes = dict(zip(levels, np.random.rand(len(levels) - 1)))\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=sizes)\n\n # Test bad sizes argument\n with pytest.raises(ValueError):\n SizeMapping(p, sizes=\"bad_size\")"},{"col":4,"comment":"null","endLoc":698,"header":"@property\n def methods(self)","id":4552,"name":"methods","nodeType":"Function","startLoc":690,"text":"@property\n def methods(self):\n if self._cls is None:\n return []\n return [name for name, func in inspect.getmembers(self._cls)\n if ((not name.startswith('_')\n or name in self.extra_public_methods)\n and isinstance(func, Callable)\n and self._is_show_member(name))]"},{"col":4,"comment":"null","endLoc":715,"header":"def _is_show_member(self, name)","id":4556,"name":"_is_show_member","nodeType":"Function","startLoc":710,"text":"def _is_show_member(self, name):\n if self.show_inherited_members:\n return True # show all class members\n if name not in self._cls.__dict__:\n return False # class member is inherited, we do not show it\n return True"},{"col":4,"comment":"null","endLoc":708,"header":"@property\n def properties(self)","id":4557,"name":"properties","nodeType":"Function","startLoc":700,"text":"@property\n def properties(self):\n if self._cls is None:\n return []\n return [name for name, func in inspect.getmembers(self._cls)\n if (not name.startswith('_') and\n (func is None or isinstance(func, property) or\n inspect.isdatadescriptor(func))\n and self._is_show_member(name))]"},{"attributeType":"list","col":4,"comment":"null","endLoc":636,"id":4559,"name":"extra_public_methods","nodeType":"Attribute","startLoc":636,"text":"extra_public_methods"},{"attributeType":"bool","col":8,"comment":"null","endLoc":649,"id":4560,"name":"show_inherited_members","nodeType":"Attribute","startLoc":649,"text":"self.show_inherited_members"},{"attributeType":"None","col":8,"comment":"null","endLoc":642,"id":4561,"name":"_cls","nodeType":"Attribute","startLoc":642,"text":"self._cls"},{"attributeType":"str","col":8,"comment":"null","endLoc":654,"id":4562,"name":"_mod","nodeType":"Attribute","startLoc":654,"text":"self._mod"},{"col":0,"comment":"null","endLoc":569,"header":"def indent(str, indent=4)","id":4563,"name":"indent","nodeType":"Function","startLoc":564,"text":"def indent(str, indent=4):\n indent_str = ' '*indent\n if str is None:\n return indent_str\n lines = str.split('\\n')\n return '\\n'.join(indent_str + l for l in lines)"},{"col":0,"comment":"null","endLoc":578,"header":"def header(text, style='-')","id":4564,"name":"header","nodeType":"Function","startLoc":577,"text":"def header(text, style='-'):\n return text + '\\n' + style*len(text) + '\\n'"},{"attributeType":"Parameter","col":0,"comment":"null","endLoc":133,"id":4565,"name":"Parameter","nodeType":"Attribute","startLoc":133,"text":"Parameter"},{"col":0,"comment":"","endLoc":28,"header":"docscrape.py#","id":4566,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"Extract reference documentation from the NumPy source tree.\n\nCopyright (C) 2008 Stefan van der Walt , Pauli Virtanen \n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the\n distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n\nParameter = namedtuple('Parameter', ['name', 'type', 'desc'])"},{"col":4,"comment":"null","endLoc":356,"header":"def test_input_validation(self)","id":4567,"name":"test_input_validation","nodeType":"Function","startLoc":347,"text":"def test_input_validation(self):\n\n p = cat._CategoricalPlotter()\n\n kws = dict(x=\"g\", y=\"y\", hue=\"h\", units=\"u\", data=self.df)\n for var in [\"x\", \"y\", \"hue\", \"units\"]:\n input_kws = kws.copy()\n input_kws[var] = \"bad_input\"\n with pytest.raises(ValueError):\n p.establish_variables(**input_kws)"},{"col":4,"comment":"null","endLoc":400,"header":"def test_order(self)","id":4568,"name":"test_order","nodeType":"Function","startLoc":358,"text":"def test_order(self):\n\n p = cat._CategoricalPlotter()\n\n # Test inferred order from a wide dataframe input\n p.establish_variables(data=self.x_df)\n assert p.group_names == [\"X\", \"Y\", \"Z\"]\n\n # Test specified order with a wide dataframe input\n p.establish_variables(data=self.x_df, order=[\"Y\", \"Z\", \"X\"])\n assert p.group_names == [\"Y\", \"Z\", \"X\"]\n\n for group, vals in zip([\"Y\", \"Z\", \"X\"], p.plot_data):\n npt.assert_array_equal(vals, self.x_df[group])\n\n with pytest.raises(ValueError):\n p.establish_variables(data=self.x, order=[1, 2, 0])\n\n # Test inferred order from a grouped longform input\n p.establish_variables(\"g\", \"y\", data=self.df)\n assert p.group_names == [\"a\", \"b\", \"c\"]\n\n # Test specified order from a grouped longform input\n p.establish_variables(\"g\", \"y\", data=self.df, order=[\"b\", \"a\", \"c\"])\n assert p.group_names == [\"b\", \"a\", \"c\"]\n\n for group, vals in zip([\"b\", \"a\", \"c\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n # Test inferred order from a grouped input with categorical groups\n df = self.df.copy()\n df.g = df.g.astype(\"category\")\n df.g = df.g.cat.reorder_categories([\"c\", \"b\", \"a\"])\n p.establish_variables(\"g\", \"y\", data=df)\n assert p.group_names == [\"c\", \"b\", \"a\"]\n\n for group, vals in zip([\"c\", \"b\", \"a\"], p.plot_data):\n npt.assert_array_equal(vals, self.y[self.g == group])\n\n df.g = (df.g.cat.add_categories(\"d\")\n .cat.reorder_categories([\"c\", \"b\", \"d\", \"a\"]))\n p.establish_variables(\"g\", \"y\", data=df)\n assert p.group_names == [\"c\", \"b\", \"d\", \"a\"]"},{"className":"TestStyleMapping","col":0,"comment":"null","endLoc":602,"id":4569,"nodeType":"Class","startLoc":479,"text":"class TestStyleMapping:\n\n def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\")\n )\n markers = [\"s\", \"p\", \"h\"]\n p = StyleMapping.map(p_orig, markers=markers)\n assert p is p_orig\n assert isinstance(p._style_map, StyleMapping)\n assert p._style_map(p._style_map.levels, \"marker\") == markers\n\n def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._style_map, StyleMapping)\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n assert isinstance(p._style_map, StyleMapping)\n\n def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n markers = [\"s\", \"p\", \"h\"]\n style_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_style(markers=markers, order=style_order)\n assert p is p_orig\n assert p._style_map.levels == style_order\n assert p._style_map(style_order, \"marker\") == markers\n\n def test_style_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, style=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.lookup_table is None\n\n def test_map_style(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n\n # Test defaults\n m = StyleMapping(p, markers=True, dashes=True)\n\n n = len(m.levels)\n for key, dashes in zip(m.levels, unique_dashes(n)):\n assert m(key, \"dashes\") == dashes\n\n actual_marker_paths = {\n k: mpl.markers.MarkerStyle(m(k, \"marker\")).get_path()\n for k in m.levels\n }\n expected_marker_paths = {\n k: mpl.markers.MarkerStyle(m).get_path()\n for k, m in zip(m.levels, unique_markers(n))\n }\n assert actual_marker_paths == expected_marker_paths\n\n # Test lists\n markers, dashes = [\"o\", \"s\", \"d\"], [(1, 0), (1, 1), (2, 1, 3, 1)]\n m = StyleMapping(p, markers=markers, dashes=dashes)\n for key, mark, dash in zip(m.levels, markers, dashes):\n assert m(key, \"marker\") == mark\n assert m(key, \"dashes\") == dash\n\n # Test dicts\n markers = dict(zip(p.plot_data[\"style\"].unique(), markers))\n dashes = dict(zip(p.plot_data[\"style\"].unique(), dashes))\n m = StyleMapping(p, markers=markers, dashes=dashes)\n for key in m.levels:\n assert m(key, \"marker\") == markers[key]\n assert m(key, \"dashes\") == dashes[key]\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", style=\"a_cat\"))\n m = StyleMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n\n # Test style order with defaults\n order = p.plot_data[\"style\"].unique()[[1, 2, 0]]\n m = StyleMapping(p, markers=True, dashes=True, order=order)\n n = len(order)\n for key, mark, dash in zip(order, unique_markers(n), unique_dashes(n)):\n assert m(key, \"dashes\") == dash\n assert m(key, \"marker\") == mark\n obj = mpl.markers.MarkerStyle(mark)\n path = obj.get_path().transformed(obj.get_transform())\n assert_array_equal(m(key, \"path\").vertices, path.vertices)\n\n # Test too many levels with style lists\n with pytest.warns(UserWarning):\n StyleMapping(p, markers=[\"o\", \"s\"], dashes=False)\n\n with pytest.warns(UserWarning):\n StyleMapping(p, markers=False, dashes=[(2, 1)])\n\n # Test missing keys with style dicts\n markers, dashes = {\"a\": \"o\", \"b\": \"s\"}, False\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n markers, dashes = False, {\"a\": (1, 0), \"b\": (2, 1)}\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n # Test mixture of filled and unfilled markers\n markers, dashes = [\"o\", \"x\", \"s\"], None\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)"},{"col":4,"comment":"null","endLoc":491,"header":"def test_init_from_map(self, long_df)","id":4570,"name":"test_init_from_map","nodeType":"Function","startLoc":481,"text":"def test_init_from_map(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\")\n )\n markers = [\"s\", \"p\", \"h\"]\n p = StyleMapping.map(p_orig, markers=markers)\n assert p is p_orig\n assert isinstance(p._style_map, StyleMapping)\n assert p._style_map(p._style_map.levels, \"marker\") == markers"},{"col":4,"comment":"null","endLoc":505,"header":"def test_plotter_default_init(self, long_df)","id":4571,"name":"test_plotter_default_init","nodeType":"Function","startLoc":493,"text":"def test_plotter_default_init(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n assert isinstance(p._style_map, StyleMapping)\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n assert isinstance(p._style_map, StyleMapping)"},{"col":4,"comment":"null","endLoc":425,"header":"def test_hue_order(self)","id":4572,"name":"test_hue_order","nodeType":"Function","startLoc":402,"text":"def test_hue_order(self):\n\n p = cat._CategoricalPlotter()\n\n # Test inferred hue order\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.hue_names == [\"m\", \"n\"]\n\n # Test specified hue order\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df,\n hue_order=[\"n\", \"m\"])\n assert p.hue_names == [\"n\", \"m\"]\n\n # Test inferred hue order from a categorical hue input\n df = self.df.copy()\n df.h = df.h.astype(\"category\")\n df.h = df.h.cat.reorder_categories([\"n\", \"m\"])\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=df)\n assert p.hue_names == [\"n\", \"m\"]\n\n df.h = (df.h.cat.add_categories(\"o\")\n .cat.reorder_categories([\"o\", \"m\", \"n\"]))\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=df)\n assert p.hue_names == [\"o\", \"m\", \"n\"]"},{"col":4,"comment":"null","endLoc":518,"header":"def test_plotter_reinit(self, long_df)","id":4573,"name":"test_plotter_reinit","nodeType":"Function","startLoc":507,"text":"def test_plotter_reinit(self, long_df):\n\n p_orig = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n markers = [\"s\", \"p\", \"h\"]\n style_order = [\"b\", \"a\", \"c\"]\n p = p_orig.map_style(markers=markers, order=style_order)\n assert p is p_orig\n assert p._style_map.levels == style_order\n assert p._style_map(style_order, \"marker\") == markers"},{"col":4,"comment":"null","endLoc":435,"header":"def test_plot_units(self)","id":4574,"name":"test_plot_units","nodeType":"Function","startLoc":427,"text":"def test_plot_units(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.plot_units is None\n\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df, units=\"u\")\n for group, units in zip([\"a\", \"b\", \"c\"], p.plot_units):\n npt.assert_array_equal(units, self.u[self.g == group])"},{"col":4,"comment":"null","endLoc":526,"header":"def test_style_map_null(self, flat_series, null_series)","id":4575,"name":"test_style_map_null","nodeType":"Function","startLoc":520,"text":"def test_style_map_null(self, flat_series, null_series):\n\n p = VectorPlotter(variables=dict(x=flat_series, style=null_series))\n m = HueMapping(p)\n assert m.levels is None\n assert m.map_type is None\n assert m.lookup_table is None"},{"col":4,"comment":"null","endLoc":602,"header":"def test_map_style(self, long_df)","id":4576,"name":"test_map_style","nodeType":"Function","startLoc":528,"text":"def test_map_style(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", style=\"a\"),\n )\n\n # Test defaults\n m = StyleMapping(p, markers=True, dashes=True)\n\n n = len(m.levels)\n for key, dashes in zip(m.levels, unique_dashes(n)):\n assert m(key, \"dashes\") == dashes\n\n actual_marker_paths = {\n k: mpl.markers.MarkerStyle(m(k, \"marker\")).get_path()\n for k in m.levels\n }\n expected_marker_paths = {\n k: mpl.markers.MarkerStyle(m).get_path()\n for k, m in zip(m.levels, unique_markers(n))\n }\n assert actual_marker_paths == expected_marker_paths\n\n # Test lists\n markers, dashes = [\"o\", \"s\", \"d\"], [(1, 0), (1, 1), (2, 1, 3, 1)]\n m = StyleMapping(p, markers=markers, dashes=dashes)\n for key, mark, dash in zip(m.levels, markers, dashes):\n assert m(key, \"marker\") == mark\n assert m(key, \"dashes\") == dash\n\n # Test dicts\n markers = dict(zip(p.plot_data[\"style\"].unique(), markers))\n dashes = dict(zip(p.plot_data[\"style\"].unique(), dashes))\n m = StyleMapping(p, markers=markers, dashes=dashes)\n for key in m.levels:\n assert m(key, \"marker\") == markers[key]\n assert m(key, \"dashes\") == dashes[key]\n\n # Test explicit categories\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", style=\"a_cat\"))\n m = StyleMapping(p)\n assert m.levels == long_df[\"a_cat\"].cat.categories.to_list()\n\n # Test style order with defaults\n order = p.plot_data[\"style\"].unique()[[1, 2, 0]]\n m = StyleMapping(p, markers=True, dashes=True, order=order)\n n = len(order)\n for key, mark, dash in zip(order, unique_markers(n), unique_dashes(n)):\n assert m(key, \"dashes\") == dash\n assert m(key, \"marker\") == mark\n obj = mpl.markers.MarkerStyle(mark)\n path = obj.get_path().transformed(obj.get_transform())\n assert_array_equal(m(key, \"path\").vertices, path.vertices)\n\n # Test too many levels with style lists\n with pytest.warns(UserWarning):\n StyleMapping(p, markers=[\"o\", \"s\"], dashes=False)\n\n with pytest.warns(UserWarning):\n StyleMapping(p, markers=False, dashes=[(2, 1)])\n\n # Test missing keys with style dicts\n markers, dashes = {\"a\": \"o\", \"b\": \"s\"}, False\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n markers, dashes = False, {\"a\": (1, 0), \"b\": (2, 1)}\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)\n\n # Test mixture of filled and unfilled markers\n markers, dashes = [\"o\", \"x\", \"s\"], None\n with pytest.raises(ValueError):\n StyleMapping(p, markers=markers, dashes=dashes)"},{"col":4,"comment":"null","endLoc":449,"header":"def test_default_palettes(self)","id":4577,"name":"test_default_palettes","nodeType":"Function","startLoc":437,"text":"def test_default_palettes(self):\n\n p = cat._CategoricalPlotter()\n\n # Test palette mapping the x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, None, 1)\n assert p.colors == palettes.color_palette(n_colors=3)\n\n # Test palette mapping the hue position\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(None, None, 1)\n assert p.colors == palettes.color_palette(n_colors=2)"},{"col":4,"comment":"null","endLoc":458,"header":"def test_default_palette_with_many_levels(self)","id":4578,"name":"test_default_palette_with_many_levels","nodeType":"Function","startLoc":451,"text":"def test_default_palette_with_many_levels(self):\n\n with palettes.color_palette([\"blue\", \"red\"], 2):\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, None, 1)\n npt.assert_array_equal(p.colors,\n palettes.husl_palette(3, l=.7)) # noqa"},{"col":4,"comment":"null","endLoc":475,"header":"def test_specific_color(self)","id":4579,"name":"test_specific_color","nodeType":"Function","startLoc":460,"text":"def test_specific_color(self):\n\n p = cat._CategoricalPlotter()\n\n # Test the same color for each x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(\"blue\", None, 1)\n blue_rgb = mpl.colors.colorConverter.to_rgb(\"blue\")\n assert p.colors == [blue_rgb] * 3\n\n # Test a color-based blend for the hue mapping\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(\"#ff0022\", None, 1)\n rgba_array = np.array(palettes.light_palette(\"#ff0022\", 2))\n npt.assert_array_almost_equal(p.colors,\n rgba_array[:, :3])"},{"col":4,"comment":"null","endLoc":495,"header":"def test_specific_palette(self)","id":4580,"name":"test_specific_palette","nodeType":"Function","startLoc":477,"text":"def test_specific_palette(self):\n\n p = cat._CategoricalPlotter()\n\n # Test palette mapping the x position\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(None, \"dark\", 1)\n assert p.colors == palettes.color_palette(\"dark\", 3)\n\n # Test that non-None `color` and `hue` raises an error\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.establish_colors(None, \"muted\", 1)\n assert p.colors == palettes.color_palette(\"muted\", 2)\n\n # Test that specified palette overrides specified color\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors(\"blue\", \"deep\", 1)\n assert p.colors == palettes.color_palette(\"deep\", 3)"},{"col":4,"comment":"null","endLoc":503,"header":"def test_dict_as_palette(self)","id":4581,"name":"test_dict_as_palette","nodeType":"Function","startLoc":497,"text":"def test_dict_as_palette(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n pal = {\"m\": (0, 0, 1), \"n\": (1, 0, 0)}\n p.establish_colors(None, pal, 1)\n assert p.colors == [(0, 0, 1), (1, 0, 0)]"},{"col":4,"comment":"null","endLoc":513,"header":"def test_palette_desaturation(self)","id":4582,"name":"test_palette_desaturation","nodeType":"Function","startLoc":505,"text":"def test_palette_desaturation(self):\n\n p = cat._CategoricalPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.establish_colors((0, 0, 1), None, .5)\n assert p.colors == [(.25, .25, .75)] * 3\n\n p.establish_colors(None, [(0, 0, 1), (1, 0, 0), \"w\"], .5)\n assert p.colors == [(.25, .25, .75), (.75, .25, .25), (1, 1, 1)]"},{"className":"TestCategoricalStatPlotter","col":0,"comment":"null","endLoc":819,"id":4583,"nodeType":"Class","startLoc":516,"text":"class TestCategoricalStatPlotter(CategoricalFixture):\n\n def test_no_bootstrappig(self):\n\n p = cat._CategoricalStatPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.estimate_statistic(\"mean\", None, 100, None)\n npt.assert_array_equal(p.confint, np.array([]))\n\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.estimate_statistic(np.mean, None, 100, None)\n npt.assert_array_equal(p.confint, np.array([[], [], []]))\n\n def test_single_layer_stats(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n\n assert p.statistic.shape == (3,)\n assert p.confint.shape == (3, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby(g).mean())\n\n for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):\n sem = grp_y.std() / np.sqrt(len(grp_y))\n mean = grp_y.mean()\n half_ci = _normal_quantile_func(.975) * sem\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_single_layer_stats_with_units(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 90))\n y = pd.Series(np.random.RandomState(0).randn(270))\n u = pd.Series(np.repeat(np.tile(list(\"xyz\"), 30), 3))\n y[u == \"x\"] -= 3\n y[u == \"y\"] += 3\n\n p.establish_variables(g, y)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat1, ci1 = p.statistic, p.confint\n\n p.establish_variables(g, y, units=u)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat2, ci2 = p.statistic, p.confint\n\n npt.assert_array_equal(stat1, stat2)\n ci1_size = ci1[:, 1] - ci1[:, 0]\n ci2_size = ci2[:, 1] - ci2[:, 0]\n npt.assert_array_less(ci1_size, ci2_size)\n\n def test_single_layer_stats_with_missing_data(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, order=list(\"abdc\"))\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n\n assert p.statistic.shape == (4,)\n assert p.confint.shape == (4, 2)\n\n rows = g == \"b\"\n mean = y[rows].mean()\n sem = y[rows].std() / np.sqrt(rows.sum())\n half_ci = _normal_quantile_func(.975) * sem\n ci = mean - half_ci, mean + half_ci\n npt.assert_almost_equal(p.statistic[1], mean)\n npt.assert_array_almost_equal(p.confint[1], ci, 2)\n\n npt.assert_equal(p.statistic[2], np.nan)\n npt.assert_array_equal(p.confint[2], (np.nan, np.nan))\n\n def test_nested_stats(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 50000, None)\n\n assert p.statistic.shape == (3, 2)\n assert p.confint.shape == (3, 2, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby([g, h]).mean().unstack())\n\n for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):\n for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):\n sem = hue_y.std() / np.sqrt(len(hue_y))\n mean = hue_y.mean()\n half_ci = _normal_quantile_func(.975) * sem\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_bootstrap_seed(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 1000, 0)\n confint_1 = p.confint\n p.estimate_statistic(\"mean\", (\"ci\", 95), 1000, 0)\n confint_2 = p.confint\n\n npt.assert_array_equal(confint_1, confint_2)\n\n def test_nested_stats_with_units(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 90))\n h = pd.Series(np.tile(list(\"xy\"), 135))\n u = pd.Series(np.repeat(list(\"ijkijk\"), 45))\n y = pd.Series(np.random.RandomState(0).randn(270))\n y[u == \"i\"] -= 3\n y[u == \"k\"] += 3\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat1, ci1 = p.statistic, p.confint\n\n p.establish_variables(g, y, h, units=u)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat2, ci2 = p.statistic, p.confint\n\n npt.assert_array_equal(stat1, stat2)\n ci1_size = ci1[:, 0, 1] - ci1[:, 0, 0]\n ci2_size = ci2[:, 0, 1] - ci2[:, 0, 0]\n npt.assert_array_less(ci1_size, ci2_size)\n\n def test_nested_stats_with_missing_data(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n\n p.establish_variables(g, y, h,\n order=list(\"abdc\"),\n hue_order=list(\"zyx\"))\n p.estimate_statistic(\"mean\", (\"ci\", 95), 50000, None)\n\n assert p.statistic.shape == (4, 3)\n assert p.confint.shape == (4, 3, 2)\n\n rows = (g == \"b\") & (h == \"x\")\n mean = y[rows].mean()\n sem = y[rows].std() / np.sqrt(rows.sum())\n half_ci = _normal_quantile_func(.975) * sem\n ci = mean - half_ci, mean + half_ci\n npt.assert_almost_equal(p.statistic[1, 2], mean)\n npt.assert_array_almost_equal(p.confint[1, 2], ci, 2)\n\n npt.assert_array_equal(p.statistic[:, 0], [np.nan] * 4)\n npt.assert_array_equal(p.statistic[2], [np.nan] * 3)\n npt.assert_array_equal(p.confint[:, 0],\n np.zeros((4, 2)) * np.nan)\n npt.assert_array_equal(p.confint[2],\n np.zeros((3, 2)) * np.nan)\n\n def test_sd_error_bars(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y)\n p.estimate_statistic(np.mean, \"sd\", None, None)\n\n assert p.statistic.shape == (3,)\n assert p.confint.shape == (3, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby(g).mean())\n\n for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):\n mean = grp_y.mean()\n half_ci = np.std(grp_y)\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_nested_sd_error_bars(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(np.mean, \"sd\", None, None)\n\n assert p.statistic.shape == (3, 2)\n assert p.confint.shape == (3, 2, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby([g, h]).mean().unstack())\n\n for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):\n for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):\n mean = hue_y.mean()\n half_ci = np.std(hue_y)\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)\n\n def test_draw_cis(self):\n\n p = cat._CategoricalStatPlotter()\n\n # Test vertical CIs\n p.orient = \"v\"\n\n f, ax = plt.subplots()\n at_group = [0, 1]\n confints = [(.5, 1.5), (.25, .8)]\n colors = [\".2\", \".3\"]\n p.draw_confints(ax, at_group, confints, colors)\n\n lines = ax.lines\n for line, at, ci, c in zip(lines, at_group, confints, colors):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, [at, at])\n npt.assert_array_equal(y, ci)\n assert line.get_color() == c\n\n plt.close(\"all\")\n\n # Test horizontal CIs\n p.orient = \"h\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors)\n\n lines = ax.lines\n for line, at, ci, c in zip(lines, at_group, confints, colors):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, ci)\n npt.assert_array_equal(y, [at, at])\n assert line.get_color() == c\n\n plt.close(\"all\")\n\n # Test vertical CIs with endcaps\n p.orient = \"v\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, capsize=0.3)\n capline = ax.lines[len(ax.lines) - 1]\n caplinestart = capline.get_xdata()[0]\n caplineend = capline.get_xdata()[1]\n caplinelength = abs(caplineend - caplinestart)\n assert caplinelength == approx(0.3)\n assert len(ax.lines) == 6\n\n plt.close(\"all\")\n\n # Test horizontal CIs with endcaps\n p.orient = \"h\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, capsize=0.3)\n capline = ax.lines[len(ax.lines) - 1]\n caplinestart = capline.get_ydata()[0]\n caplineend = capline.get_ydata()[1]\n caplinelength = abs(caplineend - caplinestart)\n assert caplinelength == approx(0.3)\n assert len(ax.lines) == 6\n\n # Test extra keyword arguments\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, lw=4)\n line = ax.lines[0]\n assert line.get_linewidth() == 4\n\n plt.close(\"all\")\n\n # Test errwidth is set appropriately\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, errwidth=2)\n capline = ax.lines[len(ax.lines) - 1]\n assert capline._linewidth == 2\n assert len(ax.lines) == 2\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":527,"header":"def test_no_bootstrappig(self)","id":4584,"name":"test_no_bootstrappig","nodeType":"Function","startLoc":518,"text":"def test_no_bootstrappig(self):\n\n p = cat._CategoricalStatPlotter()\n p.establish_variables(\"g\", \"y\", data=self.df)\n p.estimate_statistic(\"mean\", None, 100, None)\n npt.assert_array_equal(p.confint, np.array([]))\n\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n p.estimate_statistic(np.mean, None, 100, None)\n npt.assert_array_equal(p.confint, np.array([[], [], []]))"},{"col":4,"comment":"null","endLoc":741,"header":"@pytest.mark.parametrize(\n \"split_var\", [\n \"color\", # explicitly declared on the Mark\n \"group\", # implicitly used for all Mark classes\n ])\n def test_one_grouping_variable(self, long_df, split_var)","id":4585,"name":"test_one_grouping_variable","nodeType":"Function","startLoc":723,"text":"@pytest.mark.parametrize(\n \"split_var\", [\n \"color\", # explicitly declared on the Mark\n \"group\", # implicitly used for all Mark classes\n ])\n def test_one_grouping_variable(self, long_df, split_var):\n\n split_col = \"a\"\n data_vars = {\"x\": \"f\", \"y\": \"z\", split_var: split_col}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).add(m).plot()\n\n split_keys = categorical_order(long_df[split_col])\n sub, *_ = p._subplots\n assert m.passed_axes == [sub[\"ax\"] for _ in split_keys]\n self.check_splits_single_var(\n long_df, m, data_vars, split_var, split_col, split_keys\n )"},{"col":4,"comment":"null","endLoc":550,"header":"def test_single_layer_stats(self)","id":4586,"name":"test_single_layer_stats","nodeType":"Function","startLoc":529,"text":"def test_single_layer_stats(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n\n assert p.statistic.shape == (3,)\n assert p.confint.shape == (3, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby(g).mean())\n\n for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):\n sem = grp_y.std() / np.sqrt(len(grp_y))\n mean = grp_y.mean()\n half_ci = _normal_quantile_func(.975) * sem\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)"},{"col":4,"comment":"null","endLoc":759,"header":"def test_two_grouping_variables(self, long_df)","id":4587,"name":"test_two_grouping_variables","nodeType":"Function","startLoc":743,"text":"def test_two_grouping_variables(self, long_df):\n\n split_vars = [\"color\", \"group\"]\n split_cols = [\"a\", \"b\"]\n data_vars = {\"y\": \"z\", **{var: col for var, col in zip(split_vars, split_cols)}}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).add(m).plot()\n\n split_keys = [categorical_order(long_df[col]) for col in split_cols]\n sub, *_ = p._subplots\n assert m.passed_axes == [\n sub[\"ax\"] for _ in itertools.product(*split_keys)\n ]\n self.check_splits_multi_vars(\n long_df, m, data_vars, split_vars, split_cols, split_keys\n )"},{"col":4,"comment":"null","endLoc":573,"header":"def test_single_layer_stats_with_units(self)","id":4588,"name":"test_single_layer_stats_with_units","nodeType":"Function","startLoc":552,"text":"def test_single_layer_stats_with_units(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 90))\n y = pd.Series(np.random.RandomState(0).randn(270))\n u = pd.Series(np.repeat(np.tile(list(\"xyz\"), 30), 3))\n y[u == \"x\"] -= 3\n y[u == \"y\"] += 3\n\n p.establish_variables(g, y)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat1, ci1 = p.statistic, p.confint\n\n p.establish_variables(g, y, units=u)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat2, ci2 = p.statistic, p.confint\n\n npt.assert_array_equal(stat1, stat2)\n ci1_size = ci1[:, 1] - ci1[:, 0]\n ci2_size = ci2[:, 1] - ci2[:, 0]\n npt.assert_array_less(ci1_size, ci2_size)"},{"col":4,"comment":"null","endLoc":774,"header":"def test_facets_no_subgroups(self, long_df)","id":4589,"name":"test_facets_no_subgroups","nodeType":"Function","startLoc":761,"text":"def test_facets_no_subgroups(self, long_df):\n\n split_var = \"col\"\n split_col = \"b\"\n data_vars = {\"x\": \"f\", \"y\": \"z\"}\n\n m = MockMark()\n p = Plot(long_df, **data_vars).facet(**{split_var: split_col}).add(m).plot()\n\n split_keys = categorical_order(long_df[split_col])\n assert m.passed_axes == list(p._figure.axes)\n self.check_splits_single_var(\n long_df, m, data_vars, split_var, split_col, split_keys\n )"},{"col":4,"comment":"null","endLoc":597,"header":"def test_single_layer_stats_with_missing_data(self)","id":4590,"name":"test_single_layer_stats_with_missing_data","nodeType":"Function","startLoc":575,"text":"def test_single_layer_stats_with_missing_data(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, order=list(\"abdc\"))\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n\n assert p.statistic.shape == (4,)\n assert p.confint.shape == (4, 2)\n\n rows = g == \"b\"\n mean = y[rows].mean()\n sem = y[rows].std() / np.sqrt(rows.sum())\n half_ci = _normal_quantile_func(.975) * sem\n ci = mean - half_ci, mean + half_ci\n npt.assert_almost_equal(p.statistic[1], mean)\n npt.assert_array_almost_equal(p.confint[1], ci, 2)\n\n npt.assert_equal(p.statistic[2], np.nan)\n npt.assert_array_equal(p.confint[2], (np.nan, np.nan))"},{"col":4,"comment":"null","endLoc":799,"header":"def test_facets_one_subgroup(self, long_df)","id":4591,"name":"test_facets_one_subgroup","nodeType":"Function","startLoc":776,"text":"def test_facets_one_subgroup(self, long_df):\n\n facet_var, facet_col = fx = \"col\", \"a\"\n group_var, group_col = gx = \"group\", \"b\"\n split_vars, split_cols = zip(*[fx, gx])\n data_vars = {\"x\": \"f\", \"y\": \"z\", group_var: group_col}\n\n m = MockMark()\n p = (\n Plot(long_df, **data_vars)\n .facet(**{facet_var: facet_col})\n .add(m)\n .plot()\n )\n\n split_keys = [categorical_order(long_df[col]) for col in [facet_col, group_col]]\n assert m.passed_axes == [\n ax\n for ax in list(p._figure.axes)\n for _ in categorical_order(long_df[group_col])\n ]\n self.check_splits_multi_vars(\n long_df, m, data_vars, split_vars, split_cols, split_keys\n )"},{"col":4,"comment":"null","endLoc":622,"header":"def test_nested_stats(self)","id":4592,"name":"test_nested_stats","nodeType":"Function","startLoc":599,"text":"def test_nested_stats(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 50000, None)\n\n assert p.statistic.shape == (3, 2)\n assert p.confint.shape == (3, 2, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby([g, h]).mean().unstack())\n\n for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):\n for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):\n sem = hue_y.std() / np.sqrt(len(hue_y))\n mean = hue_y.mean()\n half_ci = _normal_quantile_func(.975) * sem\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)"},{"col":4,"comment":"null","endLoc":814,"header":"def test_layer_specific_facet_disabling(self, long_df)","id":4593,"name":"test_layer_specific_facet_disabling","nodeType":"Function","startLoc":801,"text":"def test_layer_specific_facet_disabling(self, long_df):\n\n axis_vars = {\"x\": \"y\", \"y\": \"z\"}\n row_var = \"a\"\n\n m = MockMark()\n p = Plot(long_df, **axis_vars).facet(row=row_var).add(m, row=None).plot()\n\n col_levels = categorical_order(long_df[row_var])\n assert len(p._figure.axes) == len(col_levels)\n\n for data in m.passed_data:\n for var, col in axis_vars.items():\n assert_vector_equal(data[var], long_df[col])"},{"col":4,"comment":"null","endLoc":828,"header":"def test_paired_variables(self, long_df)","id":4594,"name":"test_paired_variables","nodeType":"Function","startLoc":816,"text":"def test_paired_variables(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n\n m = MockMark()\n Plot(long_df).pair(x, y).add(m).plot()\n\n var_product = itertools.product(x, y)\n\n for data, (x_i, y_i) in zip(m.passed_data, var_product):\n assert_vector_equal(data[\"x\"], long_df[x_i].astype(float))\n assert_vector_equal(data[\"y\"], long_df[y_i].astype(float))"},{"col":4,"comment":"null","endLoc":638,"header":"def test_bootstrap_seed(self)","id":4595,"name":"test_bootstrap_seed","nodeType":"Function","startLoc":624,"text":"def test_bootstrap_seed(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 1000, 0)\n confint_1 = p.confint\n p.estimate_statistic(\"mean\", (\"ci\", 95), 1000, 0)\n confint_2 = p.confint\n\n npt.assert_array_equal(confint_1, confint_2)"},{"col":4,"comment":"null","endLoc":662,"header":"def test_nested_stats_with_units(self)","id":4596,"name":"test_nested_stats_with_units","nodeType":"Function","startLoc":640,"text":"def test_nested_stats_with_units(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 90))\n h = pd.Series(np.tile(list(\"xy\"), 135))\n u = pd.Series(np.repeat(list(\"ijkijk\"), 45))\n y = pd.Series(np.random.RandomState(0).randn(270))\n y[u == \"i\"] -= 3\n y[u == \"k\"] += 3\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat1, ci1 = p.statistic, p.confint\n\n p.establish_variables(g, y, h, units=u)\n p.estimate_statistic(\"mean\", (\"ci\", 95), 10000, None)\n stat2, ci2 = p.statistic, p.confint\n\n npt.assert_array_equal(stat1, stat2)\n ci1_size = ci1[:, 0, 1] - ci1[:, 0, 0]\n ci2_size = ci2[:, 0, 1] - ci2[:, 0, 0]\n npt.assert_array_less(ci1_size, ci2_size)"},{"col":4,"comment":"null","endLoc":838,"header":"def test_paired_one_dimension(self, long_df)","id":4597,"name":"test_paired_one_dimension","nodeType":"Function","startLoc":830,"text":"def test_paired_one_dimension(self, long_df):\n\n x = [\"y\", \"z\"]\n\n m = MockMark()\n Plot(long_df).pair(x).add(m).plot()\n\n for data, x_i in zip(m.passed_data, x):\n assert_vector_equal(data[\"x\"], long_df[x_i].astype(float))"},{"col":4,"comment":"null","endLoc":857,"header":"def test_paired_variables_one_subset(self, long_df)","id":4598,"name":"test_paired_variables_one_subset","nodeType":"Function","startLoc":840,"text":"def test_paired_variables_one_subset(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n group = \"a\"\n\n long_df[\"x\"] = long_df[\"x\"].astype(float) # simplify vector comparison\n\n m = MockMark()\n Plot(long_df, group=group).pair(x, y).add(m).plot()\n\n groups = categorical_order(long_df[group])\n var_product = itertools.product(x, y, groups)\n\n for data, (x_i, y_i, g_i) in zip(m.passed_data, var_product):\n rows = long_df[group] == g_i\n assert_vector_equal(data[\"x\"], long_df.loc[rows, x_i])\n assert_vector_equal(data[\"y\"], long_df.loc[rows, y_i])"},{"col":4,"comment":"null","endLoc":693,"header":"def test_nested_stats_with_missing_data(self)","id":4599,"name":"test_nested_stats_with_missing_data","nodeType":"Function","startLoc":664,"text":"def test_nested_stats_with_missing_data(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n\n p.establish_variables(g, y, h,\n order=list(\"abdc\"),\n hue_order=list(\"zyx\"))\n p.estimate_statistic(\"mean\", (\"ci\", 95), 50000, None)\n\n assert p.statistic.shape == (4, 3)\n assert p.confint.shape == (4, 3, 2)\n\n rows = (g == \"b\") & (h == \"x\")\n mean = y[rows].mean()\n sem = y[rows].std() / np.sqrt(rows.sum())\n half_ci = _normal_quantile_func(.975) * sem\n ci = mean - half_ci, mean + half_ci\n npt.assert_almost_equal(p.statistic[1, 2], mean)\n npt.assert_array_almost_equal(p.confint[1, 2], ci, 2)\n\n npt.assert_array_equal(p.statistic[:, 0], [np.nan] * 4)\n npt.assert_array_equal(p.statistic[2], [np.nan] * 3)\n npt.assert_array_equal(p.confint[:, 0],\n np.zeros((4, 2)) * np.nan)\n npt.assert_array_equal(p.confint[2],\n np.zeros((3, 2)) * np.nan)"},{"className":"TestVectorPlotter","col":0,"comment":"null","endLoc":1407,"id":4600,"nodeType":"Class","startLoc":605,"text":"class TestVectorPlotter:\n\n def test_flat_variables(self, flat_data):\n\n p = VectorPlotter()\n p.assign_variables(data=flat_data)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_data)\n\n try:\n expected_x = flat_data.index\n expected_x_name = flat_data.index.name\n except AttributeError:\n expected_x = np.arange(len(flat_data))\n expected_x_name = None\n\n x = p.plot_data[\"x\"]\n assert_array_equal(x, expected_x)\n\n expected_y = flat_data\n expected_y_name = getattr(flat_data, \"name\", None)\n\n y = p.plot_data[\"y\"]\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] == expected_x_name\n assert p.variables[\"y\"] == expected_y_name\n\n def test_long_df(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(data=long_df, variables=long_variables)\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_df_with_index(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_df.set_index(\"a\"),\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_df_with_multiindex(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_df.set_index([\"a\", \"x\"]),\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_dict(self, long_dict, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_dict,\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], pd.Series(long_dict[val]))\n\n @pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_long_vectors(self, long_df, long_variables, vector_type):\n\n variables = {key: long_df[val] for key, val in long_variables.items()}\n if vector_type == \"numpy\":\n variables = {key: val.to_numpy() for key, val in variables.items()}\n elif vector_type == \"list\":\n variables = {key: val.to_list() for key, val in variables.items()}\n\n p = VectorPlotter()\n p.assign_variables(variables=variables)\n assert p.input_format == \"long\"\n\n assert list(p.variables) == list(long_variables)\n if vector_type == \"series\":\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])\n\n def test_long_undefined_variables(self, long_df):\n\n p = VectorPlotter()\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"not_in_df\"),\n )\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"x\", y=\"not_in_df\"),\n )\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"not_in_df\"),\n )\n\n @pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg):\n\n p = VectorPlotter()\n p.assign_variables(data=arg)\n assert not p.variables\n\n if not isinstance(arg, pd.DataFrame):\n p = VectorPlotter()\n p.assign_variables(variables=dict(x=arg, y=arg))\n assert not p.variables\n\n def test_units(self, repeated_df):\n\n p = VectorPlotter()\n p.assign_variables(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", units=\"u\"),\n )\n assert_array_equal(p.plot_data[\"units\"], repeated_df[\"u\"])\n\n @pytest.mark.parametrize(\"name\", [3, 4.5])\n def test_long_numeric_name(self, long_df, name):\n\n long_df[name] = long_df[\"x\"]\n p = VectorPlotter()\n p.assign_variables(data=long_df, variables={\"x\": name})\n assert_array_equal(p.plot_data[\"x\"], long_df[name])\n assert p.variables[\"x\"] == name\n\n def test_long_hierarchical_index(self, rng):\n\n cols = pd.MultiIndex.from_product([[\"a\"], [\"x\", \"y\"]])\n data = rng.uniform(size=(50, 2))\n df = pd.DataFrame(data, columns=cols)\n\n name = (\"a\", \"y\")\n var = \"y\"\n\n p = VectorPlotter()\n p.assign_variables(data=df, variables={var: name})\n assert_array_equal(p.plot_data[var], df[name])\n assert p.variables[var] == name\n\n def test_long_scalar_and_data(self, long_df):\n\n val = 22\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": val})\n assert (p.plot_data[\"y\"] == val).all()\n assert p.variables[\"y\"] is None\n\n def test_wide_semantic_error(self, wide_df):\n\n err = \"The following variable cannot be assigned with wide-form data: `hue`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=wide_df, variables={\"hue\": \"a\"})\n\n def test_long_unknown_error(self, long_df):\n\n err = \"Could not interpret value `what` for parameter `hue`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": \"what\"})\n\n def test_long_unmatched_size_error(self, long_df, flat_array):\n\n err = \"Length of ndarray vectors must match length of `data`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": flat_array})\n\n def test_wide_categorical_columns(self, wide_df):\n\n wide_df.columns = pd.CategoricalIndex(wide_df.columns)\n p = VectorPlotter(data=wide_df)\n assert_array_equal(p.plot_data[\"hue\"].unique(), [\"a\", \"b\", \"c\"])\n\n def test_iter_data_quantitites(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n out = p.iter_data(\"hue\")\n assert len(list(out)) == 1\n\n var = \"a\"\n n_subsets = len(long_df[var].unique())\n\n semantics = [\"hue\", \"size\", \"style\"]\n for semantic in semantics:\n\n p = VectorPlotter(\n data=long_df,\n variables={\"x\": \"x\", \"y\": \"y\", semantic: var},\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n var = \"a\"\n n_subsets = len(long_df[var].unique())\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var, style=var),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n # --\n\n out = p.iter_data(semantics, reverse=True)\n assert len(list(out)) == n_subsets\n\n # --\n\n var1, var2 = \"a\", \"s\"\n\n n_subsets = len(long_df[var1].unique())\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, style=var2),\n )\n out = p.iter_data([\"hue\"])\n assert len(list(out)) == n_subsets\n\n n_subsets = len(set(list(map(tuple, long_df[[var1, var2]].values))))\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, style=var2),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2, style=var1),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n # --\n\n var1, var2, var3 = \"a\", \"s\", \"b\"\n cols = [var1, var2, var3]\n n_subsets = len(set(list(map(tuple, long_df[cols].values))))\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2, style=var3),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n def test_iter_data_keys(self, long_df):\n\n semantics = [\"hue\", \"size\", \"style\"]\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert sub_vars == {}\n\n # --\n\n var = \"a\"\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert list(sub_vars) == [\"hue\"]\n assert sub_vars[\"hue\"] in long_df[var].values\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=var),\n )\n for sub_vars, _ in p.iter_data(\"size\"):\n assert list(sub_vars) == [\"size\"]\n assert sub_vars[\"size\"] in long_df[var].values\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var, style=var),\n )\n for sub_vars, _ in p.iter_data(semantics):\n assert list(sub_vars) == [\"hue\", \"style\"]\n assert sub_vars[\"hue\"] in long_df[var].values\n assert sub_vars[\"style\"] in long_df[var].values\n assert sub_vars[\"hue\"] == sub_vars[\"style\"]\n\n var1, var2 = \"a\", \"s\"\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2),\n )\n for sub_vars, _ in p.iter_data(semantics):\n assert list(sub_vars) == [\"hue\", \"size\"]\n assert sub_vars[\"hue\"] in long_df[var1].values\n assert sub_vars[\"size\"] in long_df[var2].values\n\n semantics = [\"hue\", \"col\", \"row\"]\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, col=var2),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert list(sub_vars) == [\"hue\", \"col\"]\n assert sub_vars[\"hue\"] in long_df[var1].values\n assert sub_vars[\"col\"] in long_df[var2].values\n\n def test_iter_data_values(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n\n p.sort = True\n _, sub_data = next(p.iter_data(\"hue\"))\n assert_frame_equal(sub_data, p.plot_data)\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n\n for sub_vars, sub_data in p.iter_data(\"hue\"):\n rows = p.plot_data[\"hue\"] == sub_vars[\"hue\"]\n assert_frame_equal(sub_data, p.plot_data[rows])\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"s\"),\n )\n for sub_vars, sub_data in p.iter_data([\"hue\", \"size\"]):\n rows = p.plot_data[\"hue\"] == sub_vars[\"hue\"]\n rows &= p.plot_data[\"size\"] == sub_vars[\"size\"]\n assert_frame_equal(sub_data, p.plot_data[rows])\n\n def test_iter_data_reverse(self, long_df):\n\n reversed_order = categorical_order(long_df[\"a\"])[::-1]\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n iterator = p.iter_data(\"hue\", reverse=True)\n for i, (sub_vars, _) in enumerate(iterator):\n assert sub_vars[\"hue\"] == reversed_order[i]\n\n def test_iter_data_dropna(self, missing_df):\n\n p = VectorPlotter(\n data=missing_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n for _, sub_df in p.iter_data(\"hue\"):\n assert not sub_df.isna().any().any()\n\n some_missing = False\n for _, sub_df in p.iter_data(\"hue\", dropna=False):\n some_missing |= sub_df.isna().any().any()\n assert some_missing\n\n def test_axis_labels(self, long_df):\n\n f, ax = plt.subplots()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"a\"))\n\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(y=\"a\"))\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"\"\n assert ax.get_ylabel() == \"a\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"a\"))\n\n p._add_axis_labels(ax, default_y=\"default\")\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"default\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(y=\"a\"))\n p._add_axis_labels(ax, default_x=\"default\", default_y=\"default\")\n assert ax.get_xlabel() == \"default\"\n assert ax.get_ylabel() == \"a\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"a\"))\n ax.set(xlabel=\"existing\", ylabel=\"also existing\")\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"existing\"\n assert ax.get_ylabel() == \"also existing\"\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p._add_axis_labels(ax1)\n p._add_axis_labels(ax2)\n\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n assert ax1.yaxis.label.get_visible()\n\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()\n\n @pytest.mark.parametrize(\n \"variables\",\n [\n dict(x=\"x\", y=\"y\"),\n dict(x=\"x\"),\n dict(y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"x\", y=\"a\"),\n ]\n )\n def test_attach_basics(self, long_df, variables):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables=variables)\n p._attach(ax)\n assert p.ax is ax\n\n def test_attach_disallowed(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=\"numeric\")\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=[\"datetime\", \"numeric\"])\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=\"categorical\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=[\"numeric\", \"categorical\"])\n\n def test_attach_log_scale(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p._attach(ax, log_scale=2)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"y\": \"y\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"linear\"\n assert ax.yaxis.get_scale() == \"log\"\n assert not p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"log\"\n assert p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=(True, False))\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=(False, 2))\n assert ax.xaxis.get_scale() == \"linear\"\n assert ax.yaxis.get_scale() == \"log\"\n assert not p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n def test_attach_converters(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n p._attach(ax)\n assert ax.xaxis.converter is None\n assert \"Date\" in ax.yaxis.converter.__class__.__name__\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\", \"y\": \"y\"})\n p._attach(ax)\n assert \"CategoryConverter\" in ax.xaxis.converter.__class__.__name__\n assert ax.yaxis.converter is None\n\n def test_attach_facets(self, long_df):\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"col\": \"a\"})\n p._attach(g)\n assert p.ax is None\n assert p.facets == g\n\n def test_attach_shared_axes(self, long_df):\n\n g = FacetGrid(long_df)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", sharex=False)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", sharex=False, col_wrap=2)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharex=False)\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == len(g.axes.flat)\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharex=\"col\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharey=\"row\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == p.plot_data[\"row\"].nunique()\n assert p.converters[\"y\"].groupby(p.plot_data[\"row\"]).nunique().max() == 1\n\n def test_get_axes_single(self, long_df):\n\n ax = plt.figure().subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": \"a\"})\n p._attach(ax)\n assert p._get_axes({\"hue\": \"a\"}) is ax\n\n def test_get_axes_facets(self, long_df):\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"col\": \"a\"})\n p._attach(g)\n assert p._get_axes({\"col\": \"b\"}) is g.axes_dict[\"b\"]\n\n g = FacetGrid(long_df, col=\"a\", row=\"c\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"col\": \"a\", \"row\": \"c\"}\n )\n p._attach(g)\n assert p._get_axes({\"row\": 1, \"col\": \"b\"}) is g.axes_dict[(1, \"b\")]\n\n def test_comp_data(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n\n # We have disabled this check for now, while it remains part of\n # the internal API, because it will require updating a number of tests\n # with pytest.raises(AttributeError):\n # p.comp_data\n\n _, ax = plt.subplots()\n p._attach(ax)\n\n assert_array_equal(p.comp_data[\"x\"], p.plot_data[\"x\"])\n assert_array_equal(\n p.comp_data[\"y\"], ax.yaxis.convert_units(p.plot_data[\"y\"])\n )\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n\n _, ax = plt.subplots()\n p._attach(ax)\n\n assert_array_equal(\n p.comp_data[\"x\"], ax.xaxis.convert_units(p.plot_data[\"x\"])\n )\n\n def test_comp_data_log(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"z\", \"y\": \"y\"})\n _, ax = plt.subplots()\n p._attach(ax, log_scale=(True, False))\n\n assert_array_equal(\n p.comp_data[\"x\"], np.log10(p.plot_data[\"x\"])\n )\n assert_array_equal(p.comp_data[\"y\"], p.plot_data[\"y\"])\n\n def test_comp_data_category_order(self):\n\n s = (pd.Series([\"a\", \"b\", \"c\", \"a\"], dtype=\"category\")\n .cat.set_categories([\"b\", \"c\", \"a\"], ordered=True))\n\n p = VectorPlotter(variables={\"x\": s})\n _, ax = plt.subplots()\n p._attach(ax)\n assert_array_equal(\n p.comp_data[\"x\"],\n [2, 0, 1, 2],\n )\n\n @pytest.fixture(\n params=itertools.product(\n [None, np.nan, PD_NA],\n [\"numeric\", \"category\", \"datetime\"]\n )\n )\n @pytest.mark.parametrize(\n \"NA,var_type\",\n )\n def comp_data_missing_fixture(self, request):\n\n # This fixture holds the logic for parameterizing\n # the following test (test_comp_data_missing)\n\n NA, var_type = request.param\n\n if NA is None:\n pytest.skip(\"No pandas.NA available\")\n\n comp_data = [0, 1, np.nan, 2, np.nan, 1]\n if var_type == \"numeric\":\n orig_data = [0, 1, NA, 2, np.inf, 1]\n elif var_type == \"category\":\n orig_data = [\"a\", \"b\", NA, \"c\", NA, \"b\"]\n elif var_type == \"datetime\":\n # Use 1-based numbers to avoid issue on matplotlib<3.2\n # Could simplify the test a bit when we roll off that version\n comp_data = [1, 2, np.nan, 3, np.nan, 2]\n numbers = [1, 2, 3, 2]\n\n orig_data = mpl.dates.num2date(numbers)\n orig_data.insert(2, NA)\n orig_data.insert(4, np.inf)\n\n return orig_data, comp_data\n\n def test_comp_data_missing(self, comp_data_missing_fixture):\n\n orig_data, comp_data = comp_data_missing_fixture\n p = VectorPlotter(variables={\"x\": orig_data})\n ax = plt.figure().subplots()\n p._attach(ax)\n assert_array_equal(p.comp_data[\"x\"], comp_data)\n\n def test_comp_data_duplicate_index(self):\n\n x = pd.Series([1, 2, 3, 4, 5], [1, 1, 1, 2, 2])\n p = VectorPlotter(variables={\"x\": x})\n ax = plt.figure().subplots()\n p._attach(ax)\n assert_array_equal(p.comp_data[\"x\"], x)\n\n def test_var_order(self, long_df):\n\n order = [\"c\", \"b\", \"a\"]\n for var in [\"hue\", \"size\", \"style\"]:\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", var: \"a\"})\n\n mapper = getattr(p, f\"map_{var}\")\n mapper(order=order)\n\n assert p.var_levels[var] == order\n\n def test_scale_native(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n with pytest.raises(NotImplementedError):\n p.scale_native(\"x\")\n\n def test_scale_numeric(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"y\": \"y\"})\n with pytest.raises(NotImplementedError):\n p.scale_numeric(\"y\")\n\n def test_scale_datetime(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"t\"})\n with pytest.raises(NotImplementedError):\n p.scale_datetime(\"x\")\n\n def test_scale_categorical(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p.scale_categorical(\"y\")\n assert p.variables[\"y\"] is None\n assert p.var_types[\"y\"] == \"categorical\"\n assert (p.plot_data[\"y\"] == \"\").all()\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"s\"})\n p.scale_categorical(\"x\")\n assert p.var_types[\"x\"] == \"categorical\"\n assert hasattr(p.plot_data[\"x\"], \"str\")\n assert not p._var_ordered[\"x\"]\n assert p.plot_data[\"x\"].is_monotonic_increasing\n assert_array_equal(p.var_levels[\"x\"], p.plot_data[\"x\"].unique())\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n p.scale_categorical(\"x\")\n assert not p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], categorical_order(long_df[\"a\"]))\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a_cat\"})\n p.scale_categorical(\"x\")\n assert p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], categorical_order(long_df[\"a_cat\"]))\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n order = np.roll(long_df[\"a\"].unique(), 1)\n p.scale_categorical(\"x\", order=order)\n assert p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], order)\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"s\"})\n p.scale_categorical(\"x\", formatter=lambda x: f\"{x:%}\")\n assert p.plot_data[\"x\"].str.endswith(\"%\").all()\n assert all(s.endswith(\"%\") for s in p.var_levels[\"x\"])"},{"col":4,"comment":"null","endLoc":632,"header":"def test_flat_variables(self, flat_data)","id":4601,"name":"test_flat_variables","nodeType":"Function","startLoc":607,"text":"def test_flat_variables(self, flat_data):\n\n p = VectorPlotter()\n p.assign_variables(data=flat_data)\n assert p.input_format == \"wide\"\n assert list(p.variables) == [\"x\", \"y\"]\n assert len(p.plot_data) == len(flat_data)\n\n try:\n expected_x = flat_data.index\n expected_x_name = flat_data.index.name\n except AttributeError:\n expected_x = np.arange(len(flat_data))\n expected_x_name = None\n\n x = p.plot_data[\"x\"]\n assert_array_equal(x, expected_x)\n\n expected_y = flat_data\n expected_y_name = getattr(flat_data, \"name\", None)\n\n y = p.plot_data[\"y\"]\n assert_array_equal(y, expected_y)\n\n assert p.variables[\"x\"] == expected_x_name\n assert p.variables[\"y\"] == expected_y_name"},{"col":4,"comment":"null","endLoc":642,"header":"def test_long_df(self, long_df, long_variables)","id":4602,"name":"test_long_df","nodeType":"Function","startLoc":634,"text":"def test_long_df(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(data=long_df, variables=long_variables)\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])"},{"col":4,"comment":"null","endLoc":655,"header":"def test_long_df_with_index(self, long_df, long_variables)","id":4603,"name":"test_long_df_with_index","nodeType":"Function","startLoc":644,"text":"def test_long_df_with_index(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_df.set_index(\"a\"),\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])"},{"col":4,"comment":"null","endLoc":668,"header":"def test_long_df_with_multiindex(self, long_df, long_variables)","id":4604,"name":"test_long_df_with_multiindex","nodeType":"Function","startLoc":657,"text":"def test_long_df_with_multiindex(self, long_df, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_df.set_index([\"a\", \"x\"]),\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])"},{"col":4,"comment":"null","endLoc":681,"header":"def test_long_dict(self, long_dict, long_variables)","id":4605,"name":"test_long_dict","nodeType":"Function","startLoc":670,"text":"def test_long_dict(self, long_dict, long_variables):\n\n p = VectorPlotter()\n p.assign_variables(\n data=long_dict,\n variables=long_variables,\n )\n assert p.input_format == \"long\"\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], pd.Series(long_dict[val]))"},{"col":4,"comment":"null","endLoc":704,"header":"@pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_long_vectors(self, long_df, long_variables, vector_type)","id":4606,"name":"test_long_vectors","nodeType":"Function","startLoc":683,"text":"@pytest.mark.parametrize(\n \"vector_type\",\n [\"series\", \"numpy\", \"list\"],\n )\n def test_long_vectors(self, long_df, long_variables, vector_type):\n\n variables = {key: long_df[val] for key, val in long_variables.items()}\n if vector_type == \"numpy\":\n variables = {key: val.to_numpy() for key, val in variables.items()}\n elif vector_type == \"list\":\n variables = {key: val.to_list() for key, val in variables.items()}\n\n p = VectorPlotter()\n p.assign_variables(variables=variables)\n assert p.input_format == \"long\"\n\n assert list(p.variables) == list(long_variables)\n if vector_type == \"series\":\n assert p.variables == long_variables\n\n for key, val in long_variables.items():\n assert_array_equal(p.plot_data[key], long_df[val])"},{"col":4,"comment":"null","endLoc":874,"header":"def test_paired_and_faceted(self, long_df)","id":4607,"name":"test_paired_and_faceted","nodeType":"Function","startLoc":859,"text":"def test_paired_and_faceted(self, long_df):\n\n x = [\"y\", \"z\"]\n y = \"f\"\n row = \"c\"\n\n m = MockMark()\n Plot(long_df, y=y).facet(row=row).pair(x).add(m).plot()\n\n facets = categorical_order(long_df[row])\n var_product = itertools.product(x, facets)\n\n for data, (x_i, f_i) in zip(m.passed_data, var_product):\n rows = long_df[row] == f_i\n assert_vector_equal(data[\"x\"], long_df.loc[rows, x_i])\n assert_vector_equal(data[\"y\"], long_df.loc[rows, y])"},{"col":4,"comment":"null","endLoc":715,"header":"def test_sd_error_bars(self)","id":4608,"name":"test_sd_error_bars","nodeType":"Function","startLoc":695,"text":"def test_sd_error_bars(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y)\n p.estimate_statistic(np.mean, \"sd\", None, None)\n\n assert p.statistic.shape == (3,)\n assert p.confint.shape == (3, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby(g).mean())\n\n for ci, (_, grp_y) in zip(p.confint, y.groupby(g)):\n mean = grp_y.mean()\n half_ci = np.std(grp_y)\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)"},{"col":4,"comment":"null","endLoc":739,"header":"def test_nested_sd_error_bars(self)","id":4609,"name":"test_nested_sd_error_bars","nodeType":"Function","startLoc":717,"text":"def test_nested_sd_error_bars(self):\n\n p = cat._CategoricalStatPlotter()\n\n g = pd.Series(np.repeat(list(\"abc\"), 100))\n h = pd.Series(np.tile(list(\"xy\"), 150))\n y = pd.Series(np.random.RandomState(0).randn(300))\n\n p.establish_variables(g, y, h)\n p.estimate_statistic(np.mean, \"sd\", None, None)\n\n assert p.statistic.shape == (3, 2)\n assert p.confint.shape == (3, 2, 2)\n\n npt.assert_array_almost_equal(p.statistic,\n y.groupby([g, h]).mean().unstack())\n\n for ci_g, (_, grp_y) in zip(p.confint, y.groupby(g)):\n for ci, hue_y in zip(ci_g, [grp_y.iloc[::2], grp_y.iloc[1::2]]):\n mean = hue_y.mean()\n half_ci = np.std(hue_y)\n ci_want = mean - half_ci, mean + half_ci\n npt.assert_array_almost_equal(ci_want, ci, 2)"},{"col":4,"comment":"null","endLoc":879,"header":"def test_theme_default(self)","id":4610,"name":"test_theme_default","nodeType":"Function","startLoc":876,"text":"def test_theme_default(self):\n\n p = Plot().plot()\n assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), \"#EAEAF2\")"},{"col":4,"comment":"null","endLoc":885,"header":"def test_theme_params(self)","id":4611,"name":"test_theme_params","nodeType":"Function","startLoc":881,"text":"def test_theme_params(self):\n\n color = \".888\"\n p = Plot().theme({\"axes.facecolor\": color}).plot()\n assert mpl.colors.same_color(p._figure.axes[0].get_facecolor(), color)"},{"col":4,"comment":"null","endLoc":891,"header":"def test_theme_error(self)","id":4612,"name":"test_theme_error","nodeType":"Function","startLoc":887,"text":"def test_theme_error(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=r\"theme\\(\\) takes 1 positional\"):\n p.theme(\"arg1\", \"arg2\")"},{"col":4,"comment":"null","endLoc":903,"header":"def test_stat(self, long_df)","id":4613,"name":"test_stat","nodeType":"Function","startLoc":893,"text":"def test_stat(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg()).plot()\n\n expected = long_df.groupby(\"a\", sort=False)[\"z\"].mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], expected)\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated"},{"col":4,"comment":"null","endLoc":723,"header":"def test_long_undefined_variables(self, long_df)","id":4614,"name":"test_long_undefined_variables","nodeType":"Function","startLoc":706,"text":"def test_long_undefined_variables(self, long_df):\n\n p = VectorPlotter()\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"not_in_df\"),\n )\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"x\", y=\"not_in_df\"),\n )\n\n with pytest.raises(ValueError):\n p.assign_variables(\n data=long_df, variables=dict(x=\"x\", y=\"y\", hue=\"not_in_df\"),\n )"},{"col":4,"comment":"null","endLoc":819,"header":"def test_draw_cis(self)","id":4615,"name":"test_draw_cis","nodeType":"Function","startLoc":741,"text":"def test_draw_cis(self):\n\n p = cat._CategoricalStatPlotter()\n\n # Test vertical CIs\n p.orient = \"v\"\n\n f, ax = plt.subplots()\n at_group = [0, 1]\n confints = [(.5, 1.5), (.25, .8)]\n colors = [\".2\", \".3\"]\n p.draw_confints(ax, at_group, confints, colors)\n\n lines = ax.lines\n for line, at, ci, c in zip(lines, at_group, confints, colors):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, [at, at])\n npt.assert_array_equal(y, ci)\n assert line.get_color() == c\n\n plt.close(\"all\")\n\n # Test horizontal CIs\n p.orient = \"h\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors)\n\n lines = ax.lines\n for line, at, ci, c in zip(lines, at_group, confints, colors):\n x, y = line.get_xydata().T\n npt.assert_array_equal(x, ci)\n npt.assert_array_equal(y, [at, at])\n assert line.get_color() == c\n\n plt.close(\"all\")\n\n # Test vertical CIs with endcaps\n p.orient = \"v\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, capsize=0.3)\n capline = ax.lines[len(ax.lines) - 1]\n caplinestart = capline.get_xdata()[0]\n caplineend = capline.get_xdata()[1]\n caplinelength = abs(caplineend - caplinestart)\n assert caplinelength == approx(0.3)\n assert len(ax.lines) == 6\n\n plt.close(\"all\")\n\n # Test horizontal CIs with endcaps\n p.orient = \"h\"\n\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, capsize=0.3)\n capline = ax.lines[len(ax.lines) - 1]\n caplinestart = capline.get_ydata()[0]\n caplineend = capline.get_ydata()[1]\n caplinelength = abs(caplineend - caplinestart)\n assert caplinelength == approx(0.3)\n assert len(ax.lines) == 6\n\n # Test extra keyword arguments\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, lw=4)\n line = ax.lines[0]\n assert line.get_linewidth() == 4\n\n plt.close(\"all\")\n\n # Test errwidth is set appropriately\n f, ax = plt.subplots()\n p.draw_confints(ax, at_group, confints, colors, errwidth=2)\n capline = ax.lines[len(ax.lines) - 1]\n assert capline._linewidth == 2\n assert len(ax.lines) == 2\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":914,"header":"def test_move(self, long_df)","id":4616,"name":"test_move","nodeType":"Function","startLoc":905,"text":"def test_move(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"z\", y=\"z\").add(m, Shift(x=1)).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"z\"] + 1)\n assert_vector_equal(m.passed_data[0][\"y\"], long_df[\"z\"])\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated"},{"col":4,"comment":"null","endLoc":737,"header":"@pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg)","id":4617,"name":"test_empty_data_input","nodeType":"Function","startLoc":725,"text":"@pytest.mark.parametrize(\n \"arg\", [[], np.array([]), pd.DataFrame()],\n )\n def test_empty_data_input(self, arg):\n\n p = VectorPlotter()\n p.assign_variables(data=arg)\n assert not p.variables\n\n if not isinstance(arg, pd.DataFrame):\n p = VectorPlotter()\n p.assign_variables(variables=dict(x=arg, y=arg))\n assert not p.variables"},{"col":4,"comment":"null","endLoc":922,"header":"def test_stat_and_move(self, long_df)","id":4618,"name":"test_stat_and_move","nodeType":"Function","startLoc":916,"text":"def test_stat_and_move(self, long_df):\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg(), Shift(y=1)).plot()\n\n expected = long_df.groupby(\"a\", sort=False)[\"z\"].mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], expected + 1)"},{"col":4,"comment":"null","endLoc":746,"header":"def test_units(self, repeated_df)","id":4619,"name":"test_units","nodeType":"Function","startLoc":739,"text":"def test_units(self, repeated_df):\n\n p = VectorPlotter()\n p.assign_variables(\n data=repeated_df,\n variables=dict(x=\"x\", y=\"y\", units=\"u\"),\n )\n assert_array_equal(p.plot_data[\"units\"], repeated_df[\"u\"])"},{"col":4,"comment":"null","endLoc":755,"header":"@pytest.mark.parametrize(\"name\", [3, 4.5])\n def test_long_numeric_name(self, long_df, name)","id":4620,"name":"test_long_numeric_name","nodeType":"Function","startLoc":748,"text":"@pytest.mark.parametrize(\"name\", [3, 4.5])\n def test_long_numeric_name(self, long_df, name):\n\n long_df[name] = long_df[\"x\"]\n p = VectorPlotter()\n p.assign_variables(data=long_df, variables={\"x\": name})\n assert_array_equal(p.plot_data[\"x\"], long_df[name])\n assert p.variables[\"x\"] == name"},{"col":4,"comment":"null","endLoc":769,"header":"def test_long_hierarchical_index(self, rng)","id":4621,"name":"test_long_hierarchical_index","nodeType":"Function","startLoc":757,"text":"def test_long_hierarchical_index(self, rng):\n\n cols = pd.MultiIndex.from_product([[\"a\"], [\"x\", \"y\"]])\n data = rng.uniform(size=(50, 2))\n df = pd.DataFrame(data, columns=cols)\n\n name = (\"a\", \"y\")\n var = \"y\"\n\n p = VectorPlotter()\n p.assign_variables(data=df, variables={var: name})\n assert_array_equal(p.plot_data[var], df[name])\n assert p.variables[var] == name"},{"col":4,"comment":"null","endLoc":936,"header":"def test_stat_log_scale(self, long_df)","id":4622,"name":"test_stat_log_scale","nodeType":"Function","startLoc":924,"text":"def test_stat_log_scale(self, long_df):\n\n orig_df = long_df.copy(deep=True)\n\n m = MockMark()\n Plot(long_df, x=\"a\", y=\"z\").add(m, Agg()).scale(y=\"log\").plot()\n\n x = long_df[\"a\"]\n y = np.log10(long_df[\"z\"])\n expected = y.groupby(x, sort=False).mean().reset_index(drop=True)\n assert_vector_equal(m.passed_data[0][\"y\"], 10 ** expected)\n\n assert_frame_equal(long_df, orig_df) # Test data was not mutated"},{"col":4,"comment":"null","endLoc":776,"header":"def test_long_scalar_and_data(self, long_df)","id":4623,"name":"test_long_scalar_and_data","nodeType":"Function","startLoc":771,"text":"def test_long_scalar_and_data(self, long_df):\n\n val = 22\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": val})\n assert (p.plot_data[\"y\"] == val).all()\n assert p.variables[\"y\"] is None"},{"col":4,"comment":"null","endLoc":782,"header":"def test_wide_semantic_error(self, wide_df)","id":4624,"name":"test_wide_semantic_error","nodeType":"Function","startLoc":778,"text":"def test_wide_semantic_error(self, wide_df):\n\n err = \"The following variable cannot be assigned with wide-form data: `hue`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=wide_df, variables={\"hue\": \"a\"})"},{"col":4,"comment":"null","endLoc":788,"header":"def test_long_unknown_error(self, long_df)","id":4625,"name":"test_long_unknown_error","nodeType":"Function","startLoc":784,"text":"def test_long_unknown_error(self, long_df):\n\n err = \"Could not interpret value `what` for parameter `hue`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": \"what\"})"},{"col":4,"comment":"null","endLoc":794,"header":"def test_long_unmatched_size_error(self, long_df, flat_array)","id":4626,"name":"test_long_unmatched_size_error","nodeType":"Function","startLoc":790,"text":"def test_long_unmatched_size_error(self, long_df, flat_array):\n\n err = \"Length of ndarray vectors must match length of `data`\"\n with pytest.raises(ValueError, match=err):\n VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": flat_array})"},{"col":4,"comment":"null","endLoc":800,"header":"def test_wide_categorical_columns(self, wide_df)","id":4627,"name":"test_wide_categorical_columns","nodeType":"Function","startLoc":796,"text":"def test_wide_categorical_columns(self, wide_df):\n\n wide_df.columns = pd.CategoricalIndex(wide_df.columns)\n p = VectorPlotter(data=wide_df)\n assert_array_equal(p.plot_data[\"hue\"].unique(), [\"a\", \"b\", \"c\"])"},{"col":4,"comment":"null","endLoc":879,"header":"def test_iter_data_quantitites(self, long_df)","id":4628,"name":"test_iter_data_quantitites","nodeType":"Function","startLoc":802,"text":"def test_iter_data_quantitites(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n out = p.iter_data(\"hue\")\n assert len(list(out)) == 1\n\n var = \"a\"\n n_subsets = len(long_df[var].unique())\n\n semantics = [\"hue\", \"size\", \"style\"]\n for semantic in semantics:\n\n p = VectorPlotter(\n data=long_df,\n variables={\"x\": \"x\", \"y\": \"y\", semantic: var},\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n var = \"a\"\n n_subsets = len(long_df[var].unique())\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var, style=var),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n # --\n\n out = p.iter_data(semantics, reverse=True)\n assert len(list(out)) == n_subsets\n\n # --\n\n var1, var2 = \"a\", \"s\"\n\n n_subsets = len(long_df[var1].unique())\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, style=var2),\n )\n out = p.iter_data([\"hue\"])\n assert len(list(out)) == n_subsets\n\n n_subsets = len(set(list(map(tuple, long_df[[var1, var2]].values))))\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, style=var2),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2, style=var1),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets\n\n # --\n\n var1, var2, var3 = \"a\", \"s\", \"b\"\n cols = [var1, var2, var3]\n n_subsets = len(set(list(map(tuple, long_df[cols].values))))\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2, style=var3),\n )\n out = p.iter_data(semantics)\n assert len(list(out)) == n_subsets"},{"col":4,"comment":"null","endLoc":944,"header":"def test_move_log_scale(self, long_df)","id":4629,"name":"test_move_log_scale","nodeType":"Function","startLoc":938,"text":"def test_move_log_scale(self, long_df):\n\n m = MockMark()\n Plot(\n long_df, x=\"z\", y=\"z\"\n ).scale(x=\"log\").add(m, Shift(x=-1)).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"z\"] / 10)"},{"col":4,"comment":"null","endLoc":951,"header":"def test_multi_move(self, long_df)","id":4630,"name":"test_multi_move","nodeType":"Function","startLoc":946,"text":"def test_multi_move(self, long_df):\n\n m = MockMark()\n move_stack = [Shift(1), Shift(2)]\n Plot(long_df, x=\"x\", y=\"y\").add(m, *move_stack).plot()\n assert_vector_equal(m.passed_data[0][\"x\"], long_df[\"x\"] + 3)"},{"col":4,"comment":"null","endLoc":958,"header":"def test_multi_move_with_pairing(self, long_df)","id":4631,"name":"test_multi_move_with_pairing","nodeType":"Function","startLoc":953,"text":"def test_multi_move_with_pairing(self, long_df):\n m = MockMark()\n move_stack = [Shift(1), Shift(2)]\n Plot(long_df, x=\"x\").pair(y=[\"y\", \"z\"]).add(m, *move_stack).plot()\n for frame in m.passed_data:\n assert_vector_equal(frame[\"x\"], long_df[\"x\"] + 3)"},{"col":4,"comment":"null","endLoc":972,"header":"def test_move_with_range(self, long_df)","id":4632,"name":"test_move_with_range","nodeType":"Function","startLoc":960,"text":"def test_move_with_range(self, long_df):\n\n x = [0, 0, 1, 1, 2, 2]\n group = [0, 1, 0, 1, 0, 1]\n ymin = np.arange(6)\n ymax = np.arange(6) * 2\n\n m = MockMark()\n Plot(x=x, group=group, ymin=ymin, ymax=ymax).add(m, Dodge()).plot()\n\n signs = [-1, +1]\n for i, df in m.passed_data[0].groupby(\"group\"):\n assert_array_equal(df[\"x\"], np.arange(3) + signs[i] * 0.2)"},{"className":"TestBoxPlotter","col":0,"comment":"null","endLoc":993,"id":4633,"nodeType":"Class","startLoc":822,"text":"class TestBoxPlotter(CategoricalFixture):\n\n default_kws = dict(x=None, y=None, hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None,\n saturation=.75, width=.8, dodge=True,\n fliersize=5, linewidth=None)\n\n def test_nested_width(self):\n\n kws = self.default_kws.copy()\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .4 * .98\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .3 * .98\n\n kws = self.default_kws.copy()\n kws[\"dodge\"] = False\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .8\n\n def test_hue_offsets(self):\n\n p = cat._BoxPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.2, .2])\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.15, .15])\n\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"h\", \"y\", \"g\", data=self.df)\n npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])\n\n def test_axes_data(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n assert len(self.get_box_artists(ax)) == 3\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(self.get_box_artists(ax)) == 6\n\n plt.close(\"all\")\n\n def test_box_colors(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df, saturation=1)\n pal = palettes.color_palette(n_colors=3)\n assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],\n pal)\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, saturation=1)\n pal = palettes.color_palette(n_colors=2)\n assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],\n pal * 3)\n\n plt.close(\"all\")\n\n def test_draw_missing_boxes(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df,\n order=[\"a\", \"b\", \"c\", \"d\"])\n assert len(self.get_box_artists(ax)) == 3\n\n def test_missing_data(self):\n\n x = [\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"d\"]\n h = [\"x\", \"y\", \"x\", \"y\", \"x\", \"y\", \"x\", \"y\"]\n y = self.rs.randn(8)\n y[-2:] = np.nan\n\n ax = cat.boxplot(x=x, y=y)\n assert len(self.get_box_artists(ax)) == 3\n\n plt.close(\"all\")\n\n y[-1] = 0\n ax = cat.boxplot(x=x, y=y, hue=h)\n assert len(self.get_box_artists(ax)) == 7\n\n plt.close(\"all\")\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.boxplot(x=self.g, y=self.y, ax=ax1)\n cat.boxplot(x=self.g, y=self.y_perm, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.boxplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, ax=ax1)\n cat.boxplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n def test_boxplots(self):\n\n # Smoke test the high level boxplot options\n\n cat.boxplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", order=list(\"nabc\"), data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=list(\"omn\"), data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n def test_axes_annotation(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n assert ax.get_xlim() == (-.5, 2.5)\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],\n [\"m\", \"n\"])\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n assert ax.get_ylim() == (2.5, -.5)\n npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":847,"header":"def test_nested_width(self)","id":4634,"name":"test_nested_width","nodeType":"Function","startLoc":830,"text":"def test_nested_width(self):\n\n kws = self.default_kws.copy()\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .4 * .98\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .3 * .98\n\n kws = self.default_kws.copy()\n kws[\"dodge\"] = False\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n assert p.nested_width == .8"},{"col":4,"comment":"null","endLoc":981,"header":"def test_methods_clone(self, long_df)","id":4635,"name":"test_methods_clone","nodeType":"Function","startLoc":974,"text":"def test_methods_clone(self, long_df):\n\n p1 = Plot(long_df, \"x\", \"y\")\n p2 = p1.add(MockMark()).facet(\"a\")\n\n assert p1 is not p2\n assert not p1._layers\n assert not p1._facet_spec"},{"col":4,"comment":"null","endLoc":988,"header":"def test_default_is_no_pyplot(self)","id":4636,"name":"test_default_is_no_pyplot","nodeType":"Function","startLoc":983,"text":"def test_default_is_no_pyplot(self):\n\n p = Plot().plot()\n\n assert not plt.get_fignums()\n assert isinstance(p._figure, mpl.figure.Figure)"},{"col":4,"comment":"null","endLoc":996,"header":"def test_with_pyplot(self)","id":4637,"name":"test_with_pyplot","nodeType":"Function","startLoc":990,"text":"def test_with_pyplot(self):\n\n p = Plot().plot(pyplot=True)\n\n assert len(plt.get_fignums()) == 1\n fig = plt.gcf()\n assert p._figure is fig"},{"col":4,"comment":"null","endLoc":1015,"header":"def test_show(self)","id":4638,"name":"test_show","nodeType":"Function","startLoc":998,"text":"def test_show(self):\n\n p = Plot()\n\n with warnings.catch_warnings(record=True) as msg:\n out = p.show(block=False)\n assert out is None\n assert not hasattr(p, \"_figure\")\n\n assert len(plt.get_fignums()) == 1\n fig = plt.gcf()\n\n gui_backend = (\n # From https://github.com/matplotlib/matplotlib/issues/20281\n fig.canvas.manager.show != mpl.backend_bases.FigureManagerBase.show\n )\n if not gui_backend:\n assert msg"},{"col":4,"comment":"null","endLoc":863,"header":"def test_hue_offsets(self)","id":4639,"name":"test_hue_offsets","nodeType":"Function","startLoc":849,"text":"def test_hue_offsets(self):\n\n p = cat._BoxPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.2, .2])\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.15, .15])\n\n p = cat._BoxPlotter(**kws)\n p.establish_variables(\"h\", \"y\", \"g\", data=self.df)\n npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])"},{"col":4,"comment":"null","endLoc":875,"header":"def test_axes_data(self)","id":4640,"name":"test_axes_data","nodeType":"Function","startLoc":865,"text":"def test_axes_data(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n assert len(self.get_box_artists(ax)) == 3\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(self.get_box_artists(ax)) == 6\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":891,"header":"def test_box_colors(self)","id":4641,"name":"test_box_colors","nodeType":"Function","startLoc":877,"text":"def test_box_colors(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df, saturation=1)\n pal = palettes.color_palette(n_colors=3)\n assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],\n pal)\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, saturation=1)\n pal = palettes.color_palette(n_colors=2)\n assert same_color([patch.get_facecolor() for patch in self.get_box_artists(ax)],\n pal * 3)\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":897,"header":"def test_draw_missing_boxes(self)","id":4642,"name":"test_draw_missing_boxes","nodeType":"Function","startLoc":893,"text":"def test_draw_missing_boxes(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df,\n order=[\"a\", \"b\", \"c\", \"d\"])\n assert len(self.get_box_artists(ax)) == 3"},{"col":4,"comment":"null","endLoc":915,"header":"def test_missing_data(self)","id":4643,"name":"test_missing_data","nodeType":"Function","startLoc":899,"text":"def test_missing_data(self):\n\n x = [\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"d\"]\n h = [\"x\", \"y\", \"x\", \"y\", \"x\", \"y\", \"x\", \"y\"]\n y = self.rs.randn(8)\n y[-2:] = np.nan\n\n ax = cat.boxplot(x=x, y=y)\n assert len(self.get_box_artists(ax)) == 3\n\n plt.close(\"all\")\n\n y[-1] = 0\n ax = cat.boxplot(x=x, y=y, hue=h)\n assert len(self.get_box_artists(ax)) == 7\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":932,"header":"def test_unaligned_index(self)","id":4644,"name":"test_unaligned_index","nodeType":"Function","startLoc":917,"text":"def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.boxplot(x=self.g, y=self.y, ax=ax1)\n cat.boxplot(x=self.g, y=self.y_perm, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.boxplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, ax=ax1)\n cat.boxplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())"},{"col":4,"comment":"null","endLoc":960,"header":"def test_boxplots(self)","id":4645,"name":"test_boxplots","nodeType":"Function","startLoc":934,"text":"def test_boxplots(self):\n\n # Smoke test the high level boxplot options\n\n cat.boxplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", order=list(\"nabc\"), data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=list(\"omn\"), data=self.df)\n plt.close(\"all\")\n\n cat.boxplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":993,"header":"def test_axes_annotation(self)","id":4646,"name":"test_axes_annotation","nodeType":"Function","startLoc":962,"text":"def test_axes_annotation(self):\n\n ax = cat.boxplot(x=\"g\", y=\"y\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n assert ax.get_xlim() == (-.5, 2.5)\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],\n [\"m\", \"n\"])\n\n plt.close(\"all\")\n\n ax = cat.boxplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n assert ax.get_ylim() == (2.5, -.5)\n npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":824,"id":4647,"name":"default_kws","nodeType":"Attribute","startLoc":824,"text":"default_kws"},{"className":"TestViolinPlotter","col":0,"comment":"null","endLoc":1602,"id":4648,"nodeType":"Class","startLoc":996,"text":"class TestViolinPlotter(CategoricalFixture):\n\n default_kws = dict(x=None, y=None, hue=None, data=None,\n order=None, hue_order=None,\n bw=\"scott\", cut=2, scale=\"area\", scale_hue=True,\n gridsize=100, width=.8, inner=\"box\", split=False,\n dodge=True, orient=None, linewidth=None,\n color=None, palette=None, saturation=.75)\n\n def test_split_error(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"h\", y=\"y\", hue=\"g\", data=self.df, split=True))\n\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)\n\n def test_no_observations(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n y[-1] = np.nan\n p.establish_variables(x, y)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[0]) == 20\n assert len(p.support[1]) == 0\n\n assert len(p.density[0]) == 20\n assert len(p.density[1]) == 1\n\n assert p.density[1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", True, 20)\n assert p.density[1].item() == 0\n\n x = [\"a\"] * 4 + [\"b\"] * 2\n y = self.rs.randn(6)\n h = [\"m\", \"n\"] * 2 + [\"m\"] * 2\n\n p.establish_variables(x, y, hue=h)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[1][0]) == 20\n assert len(p.support[1][1]) == 0\n\n assert len(p.density[1][0]) == 20\n assert len(p.density[1][1]) == 1\n\n assert p.density[1][1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", False, 20)\n assert p.density[1][1].item() == 0\n\n def test_single_observation(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n p.establish_variables(x, y)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[0]) == 20\n assert len(p.support[1]) == 1\n\n assert len(p.density[0]) == 20\n assert len(p.density[1]) == 1\n\n assert p.density[1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", True, 20)\n assert p.density[1].item() == .5\n\n x = [\"b\"] * 4 + [\"a\"] * 3\n y = self.rs.randn(7)\n h = ([\"m\", \"n\"] * 4)[:-1]\n\n p.establish_variables(x, y, hue=h)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[1][0]) == 20\n assert len(p.support[1][1]) == 1\n\n assert len(p.density[1][0]) == 20\n assert len(p.density[1][1]) == 1\n\n assert p.density[1][1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", False, 20)\n assert p.density[1][1].item() == .5\n\n def test_dwidth(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", data=self.df))\n\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .4\n\n kws.update(dict(width=.4))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .2\n\n kws.update(dict(hue=\"h\", width=.8))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .2\n\n kws.update(dict(split=True))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .4\n\n def test_scale_area(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"area\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]\n max_before = np.array([d.max() for d in density])\n p.scale_area(density, max_before, False)\n max_after = np.array([d.max() for d in density])\n assert max_after[0] == 1\n\n before_ratio = max_before[1] / max_before[0]\n after_ratio = max_after[1] / max_after[0]\n assert before_ratio == after_ratio\n\n # Test nested grouping scaling across all densities\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n max_before = np.array([[r.max() for r in row] for row in density])\n p.scale_area(density, max_before, False)\n max_after = np.array([[r.max() for r in row] for row in density])\n assert max_after[0, 0] == 1\n\n before_ratio = max_before[1, 1] / max_before[0, 0]\n after_ratio = max_after[1, 1] / max_after[0, 0]\n assert before_ratio == after_ratio\n\n # Test nested grouping scaling within hue\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n max_before = np.array([[r.max() for r in row] for row in density])\n p.scale_area(density, max_before, True)\n max_after = np.array([[r.max() for r in row] for row in density])\n assert max_after[0, 0] == 1\n assert max_after[1, 0] == 1\n\n before_ratio = max_before[1, 1] / max_before[1, 0]\n after_ratio = max_after[1, 1] / max_after[1, 0]\n assert before_ratio == after_ratio\n\n def test_scale_width(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"width\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]\n p.scale_width(density)\n max_after = np.array([d.max() for d in density])\n npt.assert_array_equal(max_after, [1, 1])\n\n # Test nested grouping\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n p.scale_width(density)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[1, 1], [1, 1]])\n\n def test_scale_count(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"count\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 20), self.rs.uniform(0, .2, 40)]\n counts = np.array([20, 40])\n p.scale_count(density, counts, False)\n max_after = np.array([d.max() for d in density])\n npt.assert_array_equal(max_after, [.5, 1])\n\n # Test nested grouping scaling across all densities\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],\n [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]\n\n counts = np.array([[5, 40], [100, 50]])\n p.scale_count(density, counts, False)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[.05, .4], [1, .5]])\n\n # Test nested grouping scaling within hue\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],\n [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]\n\n counts = np.array([[5, 40], [100, 50]])\n p.scale_count(density, counts, True)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[.125, 1], [1, .5]])\n\n def test_bad_scale(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"not_a_scale_type\"\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)\n\n def test_kde_fit(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n data = self.y\n data_std = data.std(ddof=1)\n\n # Test reference rule bandwidth\n kde, bw = p.fit_kde(data, \"scott\")\n assert kde.factor == kde.scotts_factor()\n assert bw == kde.scotts_factor() * data_std\n\n # Test numeric scale factor\n kde, bw = p.fit_kde(self.y, .2)\n assert kde.factor == .2\n assert bw == .2 * data_std\n\n def test_draw_to_density(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n # p.dwidth will be 1 for easier testing\n p.width = 2\n\n # Test vertical plots\n support = np.array([.2, .6])\n density = np.array([.1, .4])\n\n # Test full vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, False)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.99 * -.4, .99 * .4])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Test left vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, \"left\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.99 * -.4, 0])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Test right vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, \"right\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [0, .99 * .4])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Switch orientation to test horizontal plots\n p.orient = \"h\"\n support = np.array([.2, .5])\n density = np.array([.3, .7])\n\n # Test full horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, False)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [.99 * -.7, .99 * .7])\n plt.close(\"all\")\n\n # Test left horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, \"left\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [.99 * -.7, 0])\n plt.close(\"all\")\n\n # Test right horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, \"right\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [0, .99 * .7])\n plt.close(\"all\")\n\n def test_draw_single_observations(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n p.width = 2\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_single_observation(ax, 1, 1.5, 1)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [0, 2])\n npt.assert_array_equal(y, [1.5, 1.5])\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_single_observation(ax, 2, 2.2, .5)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [2.2, 2.2])\n npt.assert_array_equal(y, [1.5, 2.5])\n plt.close(\"all\")\n\n def test_draw_box_lines(self):\n\n # Test vertical plot\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_box_lines(ax, self.y, 0)\n assert len(ax.lines) == 2\n\n q25, q50, q75 = np.percentile(self.y, [25, 50, 75])\n _, y = ax.lines[1].get_xydata().T\n npt.assert_array_equal(y, [q25, q75])\n\n _, y = ax.collections[0].get_offsets().T\n assert y == q50\n\n plt.close(\"all\")\n\n # Test horizontal plot\n kws = self.default_kws.copy()\n kws.update(dict(x=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_box_lines(ax, self.y, 0)\n assert len(ax.lines) == 2\n\n q25, q50, q75 = np.percentile(self.y, [25, 50, 75])\n x, _ = ax.lines[1].get_xydata().T\n npt.assert_array_equal(x, [q25, q75])\n\n x, _ = ax.collections[0].get_offsets().T\n assert x == q50\n\n plt.close(\"all\")\n\n def test_draw_quartiles(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_quartiles(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(np.percentile(self.y, [25, 50, 75]), ax.lines):\n _, y = line.get_xydata().T\n npt.assert_array_equal(y, [val, val])\n\n def test_draw_points(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_points(ax, self.y, 0)\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, np.zeros_like(self.y))\n npt.assert_array_equal(y, self.y)\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_points(ax, self.y, 0)\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.y)\n npt.assert_array_equal(y, np.zeros_like(self.y))\n plt.close(\"all\")\n\n def test_draw_sticks(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(self.y, ax.lines):\n _, y = line.get_xydata().T\n npt.assert_array_equal(y, [val, val])\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(self.y, ax.lines):\n x, _ = line.get_xydata().T\n npt.assert_array_equal(x, [val, val])\n plt.close(\"all\")\n\n def test_validate_inner(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(inner=\"bad_inner\"))\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)\n\n def test_draw_violinplots(self):\n\n kws = self.default_kws.copy()\n\n # Test single vertical violin\n kws.update(dict(y=\"y\", data=self.df, inner=None,\n saturation=1, color=(1, 0, 0, 1)))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n npt.assert_array_equal(ax.collections[0].get_facecolors(),\n [(1, 0, 0, 1)])\n plt.close(\"all\")\n\n # Test single horizontal violin\n kws.update(dict(x=\"y\", y=None, color=(0, 1, 0, 1)))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n npt.assert_array_equal(ax.collections[0].get_facecolors(),\n [(0, 1, 0, 1)])\n plt.close(\"all\")\n\n # Test multiple vertical violins\n kws.update(dict(x=\"g\", y=\"y\", color=None,))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n for violin, color in zip(ax.collections, palettes.color_palette()):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n # Test multiple violins with hue nesting\n kws.update(dict(hue=\"h\"))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 6\n for violin, color in zip(ax.collections,\n palettes.color_palette(n_colors=2) * 3):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n # Test multiple split violins\n kws.update(dict(split=True, palette=\"muted\"))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 6\n for violin, color in zip(ax.collections,\n palettes.color_palette(\"muted\",\n n_colors=2) * 3):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n def test_draw_violinplots_no_observations(self):\n\n kws = self.default_kws.copy()\n kws[\"inner\"] = None\n\n # Test single layer of grouping\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n y[-1] = np.nan\n kws.update(x=x, y=y)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n assert len(ax.lines) == 0\n plt.close(\"all\")\n\n # Test nested hue grouping\n x = [\"a\"] * 4 + [\"b\"] * 2\n y = self.rs.randn(6)\n h = [\"m\", \"n\"] * 2 + [\"m\"] * 2\n kws.update(x=x, y=y, hue=h)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 0\n plt.close(\"all\")\n\n def test_draw_violinplots_single_observations(self):\n\n kws = self.default_kws.copy()\n kws[\"inner\"] = None\n\n # Test single layer of grouping\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n kws.update(x=x, y=y)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n # Test nested hue grouping\n x = [\"b\"] * 4 + [\"a\"] * 3\n y = self.rs.randn(7)\n h = ([\"m\", \"n\"] * 4)[:-1]\n kws.update(x=x, y=y, hue=h)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n # Test nested hue grouping with split\n kws[\"split\"] = True\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n def test_violinplots(self):\n\n # Smoke test the high level violinplot options\n\n cat.violinplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n order = list(\"nabc\")\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", order=order, data=self.df)\n plt.close(\"all\")\n\n order = list(\"omn\")\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=order, data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n for inner in [\"box\", \"quart\", \"point\", \"stick\", None]:\n cat.violinplot(x=\"g\", y=\"y\", data=self.df, inner=inner)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, inner=inner)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n inner=inner, split=True)\n plt.close(\"all\")\n\n def test_split_one_each(self, rng):\n\n x = np.repeat([0, 1], 5)\n y = rng.normal(0, 1, 10)\n ax = cat.violinplot(x=x, y=y, hue=x, split=True, inner=\"box\")\n assert len(ax.lines) == 4"},{"col":4,"comment":"null","endLoc":1011,"header":"def test_split_error(self)","id":4649,"name":"test_split_error","nodeType":"Function","startLoc":1005,"text":"def test_split_error(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"h\", y=\"y\", hue=\"g\", data=self.df, split=True))\n\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)"},{"col":4,"comment":"null","endLoc":1050,"header":"def test_no_observations(self)","id":4650,"name":"test_no_observations","nodeType":"Function","startLoc":1013,"text":"def test_no_observations(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n y[-1] = np.nan\n p.establish_variables(x, y)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[0]) == 20\n assert len(p.support[1]) == 0\n\n assert len(p.density[0]) == 20\n assert len(p.density[1]) == 1\n\n assert p.density[1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", True, 20)\n assert p.density[1].item() == 0\n\n x = [\"a\"] * 4 + [\"b\"] * 2\n y = self.rs.randn(6)\n h = [\"m\", \"n\"] * 2 + [\"m\"] * 2\n\n p.establish_variables(x, y, hue=h)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[1][0]) == 20\n assert len(p.support[1][1]) == 0\n\n assert len(p.density[1][0]) == 20\n assert len(p.density[1][1]) == 1\n\n assert p.density[1][1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", False, 20)\n assert p.density[1][1].item() == 0"},{"col":4,"comment":"null","endLoc":1027,"header":"def test_png_repr(self)","id":4651,"name":"test_png_repr","nodeType":"Function","startLoc":1017,"text":"def test_png_repr(self):\n\n p = Plot()\n data, metadata = p._repr_png_()\n img = Image.open(io.BytesIO(data))\n\n assert not hasattr(p, \"_figure\")\n assert isinstance(data, bytes)\n assert img.format == \"PNG\"\n assert sorted(metadata) == [\"height\", \"width\"]\n # TODO test retina scaling"},{"col":4,"comment":"null","endLoc":1088,"header":"def test_single_observation(self)","id":4652,"name":"test_single_observation","nodeType":"Function","startLoc":1052,"text":"def test_single_observation(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n p.establish_variables(x, y)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[0]) == 20\n assert len(p.support[1]) == 1\n\n assert len(p.density[0]) == 20\n assert len(p.density[1]) == 1\n\n assert p.density[1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", True, 20)\n assert p.density[1].item() == .5\n\n x = [\"b\"] * 4 + [\"a\"] * 3\n y = self.rs.randn(7)\n h = ([\"m\", \"n\"] * 4)[:-1]\n\n p.establish_variables(x, y, hue=h)\n p.estimate_densities(\"scott\", 2, \"area\", True, 20)\n\n assert len(p.support[1][0]) == 20\n assert len(p.support[1][1]) == 1\n\n assert len(p.density[1][0]) == 20\n assert len(p.density[1][1]) == 1\n\n assert p.density[1][1].item() == 1\n\n p.estimate_densities(\"scott\", 2, \"count\", False, 20)\n assert p.density[1][1].item() == .5"},{"col":4,"comment":"null","endLoc":1108,"header":"def test_dwidth(self)","id":4653,"name":"test_dwidth","nodeType":"Function","startLoc":1090,"text":"def test_dwidth(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", data=self.df))\n\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .4\n\n kws.update(dict(width=.4))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .2\n\n kws.update(dict(hue=\"h\", width=.8))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .2\n\n kws.update(dict(split=True))\n p = cat._ViolinPlotter(**kws)\n assert p.dwidth == .4"},{"col":4,"comment":"null","endLoc":1041,"header":"def test_save(self)","id":4654,"name":"test_save","nodeType":"Function","startLoc":1029,"text":"def test_save(self):\n\n buf = io.BytesIO()\n\n p = Plot().save(buf)\n assert isinstance(p, Plot)\n img = Image.open(buf)\n assert img.format == \"PNG\"\n\n buf = io.StringIO()\n Plot().save(buf, format=\"svg\")\n tag = xml.etree.ElementTree.fromstring(buf.getvalue()).tag\n assert tag == \"{http://www.w3.org/2000/svg}svg\""},{"col":4,"comment":"null","endLoc":1047,"header":"def test_layout_size(self)","id":4657,"name":"test_layout_size","nodeType":"Function","startLoc":1043,"text":"def test_layout_size(self):\n\n size = (4, 2)\n p = Plot().layout(size=size).plot()\n assert tuple(p._figure.get_size_inches()) == size"},{"col":4,"comment":"null","endLoc":1155,"header":"def test_scale_area(self)","id":4658,"name":"test_scale_area","nodeType":"Function","startLoc":1110,"text":"def test_scale_area(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"area\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]\n max_before = np.array([d.max() for d in density])\n p.scale_area(density, max_before, False)\n max_after = np.array([d.max() for d in density])\n assert max_after[0] == 1\n\n before_ratio = max_before[1] / max_before[0]\n after_ratio = max_after[1] / max_after[0]\n assert before_ratio == after_ratio\n\n # Test nested grouping scaling across all densities\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n max_before = np.array([[r.max() for r in row] for row in density])\n p.scale_area(density, max_before, False)\n max_after = np.array([[r.max() for r in row] for row in density])\n assert max_after[0, 0] == 1\n\n before_ratio = max_before[1, 1] / max_before[0, 0]\n after_ratio = max_after[1, 1] / max_after[0, 0]\n assert before_ratio == after_ratio\n\n # Test nested grouping scaling within hue\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n max_before = np.array([[r.max() for r in row] for row in density])\n p.scale_area(density, max_before, True)\n max_after = np.array([[r.max() for r in row] for row in density])\n assert max_after[0, 0] == 1\n assert max_after[1, 0] == 1\n\n before_ratio = max_before[1, 1] / max_before[1, 0]\n after_ratio = max_after[1, 1] / max_after[1, 0]\n assert before_ratio == after_ratio"},{"col":4,"comment":"null","endLoc":1055,"header":"def test_on_axes(self)","id":4659,"name":"test_on_axes","nodeType":"Function","startLoc":1049,"text":"def test_on_axes(self):\n\n ax = mpl.figure.Figure().subplots()\n m = MockMark()\n p = Plot().on(ax).add(m).plot()\n assert m.passed_axes == [ax]\n assert p._figure is ax.figure"},{"col":4,"comment":"null","endLoc":1067,"header":"@pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_figure(self, facet)","id":4660,"name":"test_on_figure","nodeType":"Function","startLoc":1057,"text":"@pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_figure(self, facet):\n\n f = mpl.figure.Figure()\n m = MockMark()\n p = Plot().on(f).add(m)\n if facet:\n p = p.facet([\"a\", \"b\"])\n p = p.plot()\n assert m.passed_axes == f.axes\n assert p._figure is f"},{"col":4,"comment":"null","endLoc":1084,"header":"@pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"mpl<3.4 does not have SubFigure\",\n )\n @pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_subfigure(self, facet)","id":4661,"name":"test_on_subfigure","nodeType":"Function","startLoc":1069,"text":"@pytest.mark.skipif(\n Version(mpl.__version__) < Version(\"3.4\"),\n reason=\"mpl<3.4 does not have SubFigure\",\n )\n @pytest.mark.parametrize(\"facet\", [True, False])\n def test_on_subfigure(self, facet):\n\n sf1, sf2 = mpl.figure.Figure().subfigures(2)\n sf1.subplots()\n m = MockMark()\n p = Plot().on(sf2).add(m)\n if facet:\n p = p.facet([\"a\", \"b\"])\n p = p.plot()\n assert m.passed_axes == sf2.figure.axes[1:]\n assert p._figure is sf2.figure"},{"col":4,"comment":"null","endLoc":1090,"header":"def test_on_type_check(self)","id":4662,"name":"test_on_type_check","nodeType":"Function","startLoc":1086,"text":"def test_on_type_check(self):\n\n p = Plot()\n with pytest.raises(TypeError, match=\"The `Plot.on`.+\"):\n p.on([])"},{"col":4,"comment":"null","endLoc":1102,"header":"def test_on_axes_with_subplots_error(self)","id":4663,"name":"test_on_axes_with_subplots_error","nodeType":"Function","startLoc":1092,"text":"def test_on_axes_with_subplots_error(self):\n\n ax = mpl.figure.Figure().subplots()\n\n p1 = Plot().facet([\"a\", \"b\"]).on(ax)\n with pytest.raises(RuntimeError, match=\"Cannot create multiple subplots\"):\n p1.plot()\n\n p2 = Plot().pair([[\"a\", \"b\"], [\"x\", \"y\"]]).on(ax)\n with pytest.raises(RuntimeError, match=\"Cannot create multiple subplots\"):\n p2.plot()"},{"col":4,"comment":"null","endLoc":1108,"header":"def test_on_disables_layout_algo(self)","id":4664,"name":"test_on_disables_layout_algo","nodeType":"Function","startLoc":1104,"text":"def test_on_disables_layout_algo(self):\n\n f = mpl.figure.Figure()\n p = Plot().on(f).plot()\n assert not p._figure.get_tight_layout()"},{"col":4,"comment":"null","endLoc":1177,"header":"def test_scale_width(self)","id":4665,"name":"test_scale_width","nodeType":"Function","startLoc":1157,"text":"def test_scale_width(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"width\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)]\n p.scale_width(density)\n max_after = np.array([d.max() for d in density])\n npt.assert_array_equal(max_after, [1, 1])\n\n # Test nested grouping\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 50), self.rs.uniform(0, .2, 50)],\n [self.rs.uniform(0, .1, 50), self.rs.uniform(0, .02, 50)]]\n\n p.scale_width(density)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[1, 1], [1, 1]])"},{"col":4,"comment":"null","endLoc":1118,"header":"def test_axis_labels_from_constructor(self, long_df)","id":4666,"name":"test_axis_labels_from_constructor","nodeType":"Function","startLoc":1110,"text":"def test_axis_labels_from_constructor(self, long_df):\n\n ax, = Plot(long_df, x=\"a\", y=\"b\").plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n ax, = Plot(x=long_df[\"a\"], y=long_df[\"b\"].to_numpy()).plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\""},{"col":4,"comment":"null","endLoc":941,"header":"def test_iter_data_keys(self, long_df)","id":4667,"name":"test_iter_data_keys","nodeType":"Function","startLoc":881,"text":"def test_iter_data_keys(self, long_df):\n\n semantics = [\"hue\", \"size\", \"style\"]\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert sub_vars == {}\n\n # --\n\n var = \"a\"\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert list(sub_vars) == [\"hue\"]\n assert sub_vars[\"hue\"] in long_df[var].values\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", size=var),\n )\n for sub_vars, _ in p.iter_data(\"size\"):\n assert list(sub_vars) == [\"size\"]\n assert sub_vars[\"size\"] in long_df[var].values\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var, style=var),\n )\n for sub_vars, _ in p.iter_data(semantics):\n assert list(sub_vars) == [\"hue\", \"style\"]\n assert sub_vars[\"hue\"] in long_df[var].values\n assert sub_vars[\"style\"] in long_df[var].values\n assert sub_vars[\"hue\"] == sub_vars[\"style\"]\n\n var1, var2 = \"a\", \"s\"\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, size=var2),\n )\n for sub_vars, _ in p.iter_data(semantics):\n assert list(sub_vars) == [\"hue\", \"size\"]\n assert sub_vars[\"hue\"] in long_df[var1].values\n assert sub_vars[\"size\"] in long_df[var2].values\n\n semantics = [\"hue\", \"col\", \"row\"]\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=var1, col=var2),\n )\n for sub_vars, _ in p.iter_data(\"hue\"):\n assert list(sub_vars) == [\"hue\", \"col\"]\n assert sub_vars[\"hue\"] in long_df[var1].values\n assert sub_vars[\"col\"] in long_df[var2].values"},{"col":4,"comment":"null","endLoc":1131,"header":"def test_axis_labels_from_layer(self, long_df)","id":4668,"name":"test_axis_labels_from_layer","nodeType":"Function","startLoc":1120,"text":"def test_axis_labels_from_layer(self, long_df):\n\n m = MockMark()\n\n ax, = Plot(long_df).add(m, x=\"a\", y=\"b\").plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\"\n\n p = Plot().add(m, x=long_df[\"a\"], y=long_df[\"b\"].to_list())\n ax, = p.plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\""},{"col":4,"comment":"null","endLoc":1143,"header":"def test_axis_labels_are_first_name(self, long_df)","id":4669,"name":"test_axis_labels_are_first_name","nodeType":"Function","startLoc":1133,"text":"def test_axis_labels_are_first_name(self, long_df):\n\n m = MockMark()\n p = (\n Plot(long_df, x=long_df[\"z\"].to_list(), y=\"b\")\n .add(m, x=\"a\")\n .add(m, x=\"x\", y=\"y\")\n )\n ax, = p.plot()._figure.axes\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"b\""},{"col":4,"comment":"null","endLoc":1211,"header":"def test_scale_count(self)","id":4670,"name":"test_scale_count","nodeType":"Function","startLoc":1179,"text":"def test_scale_count(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"count\"\n p = cat._ViolinPlotter(**kws)\n\n # Test single layer of grouping\n p.hue_names = None\n density = [self.rs.uniform(0, .8, 20), self.rs.uniform(0, .2, 40)]\n counts = np.array([20, 40])\n p.scale_count(density, counts, False)\n max_after = np.array([d.max() for d in density])\n npt.assert_array_equal(max_after, [.5, 1])\n\n # Test nested grouping scaling across all densities\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],\n [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]\n\n counts = np.array([[5, 40], [100, 50]])\n p.scale_count(density, counts, False)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[.05, .4], [1, .5]])\n\n # Test nested grouping scaling within hue\n p.hue_names = [\"foo\", \"bar\"]\n density = [[self.rs.uniform(0, .8, 5), self.rs.uniform(0, .2, 40)],\n [self.rs.uniform(0, .1, 100), self.rs.uniform(0, .02, 50)]]\n\n counts = np.array([[5, 40], [100, 50]])\n p.scale_count(density, counts, True)\n max_after = np.array([[r.max() for r in row] for row in density])\n npt.assert_array_equal(max_after, [[.125, 1], [1, .5]])"},{"col":4,"comment":"null","endLoc":1160,"header":"def test_limits(self, long_df)","id":4671,"name":"test_limits","nodeType":"Function","startLoc":1145,"text":"def test_limits(self, long_df):\n\n limit = (-2, 24)\n p = Plot(long_df, x=\"x\", y=\"y\").limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == limit\n\n limit = (np.datetime64(\"2005-01-01\"), np.datetime64(\"2008-01-01\"))\n p = Plot(long_df, x=\"d\", y=\"y\").limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == tuple(mpl.dates.date2num(limit))\n\n limit = (\"b\", \"c\")\n p = Plot(x=[\"a\", \"b\", \"c\", \"d\"], y=[1, 2, 3, 4]).limit(x=limit).plot()\n ax = p._figure.axes[0]\n assert ax.get_xlim() == (0.5, 2.5)"},{"col":4,"comment":"null","endLoc":1172,"header":"def test_labels_axis(self, long_df)","id":4672,"name":"test_labels_axis","nodeType":"Function","startLoc":1162,"text":"def test_labels_axis(self, long_df):\n\n label = \"Y axis\"\n p = Plot(long_df, x=\"x\", y=\"y\").label(y=label).plot()\n ax = p._figure.axes[0]\n assert ax.get_ylabel() == label\n\n label = str.capitalize\n p = Plot(long_df, x=\"x\", y=\"y\").label(y=label).plot()\n ax = p._figure.axes[0]\n assert ax.get_ylabel() == \"Y\""},{"col":4,"comment":"null","endLoc":1218,"header":"def test_bad_scale(self)","id":4673,"name":"test_bad_scale","nodeType":"Function","startLoc":1213,"text":"def test_bad_scale(self):\n\n kws = self.default_kws.copy()\n kws[\"scale\"] = \"not_a_scale_type\"\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)"},{"col":4,"comment":"null","endLoc":1184,"header":"def test_labels_legend(self, long_df)","id":4674,"name":"test_labels_legend","nodeType":"Function","startLoc":1174,"text":"def test_labels_legend(self, long_df):\n\n m = MockMark()\n\n label = \"A\"\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(m).label(color=label).plot()\n assert p._figure.legends[0].get_title().get_text() == label\n\n func = str.capitalize\n p = Plot(long_df, x=\"x\", y=\"y\", color=\"a\").add(m).label(color=func).plot()\n assert p._figure.legends[0].get_title().get_text() == label"},{"col":4,"comment":"null","endLoc":1234,"header":"def test_kde_fit(self)","id":4675,"name":"test_kde_fit","nodeType":"Function","startLoc":1220,"text":"def test_kde_fit(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n data = self.y\n data_std = data.std(ddof=1)\n\n # Test reference rule bandwidth\n kde, bw = p.fit_kde(data, \"scott\")\n assert kde.factor == kde.scotts_factor()\n assert bw == kde.scotts_factor() * data_std\n\n # Test numeric scale factor\n kde, bw = p.fit_kde(self.y, .2)\n assert kde.factor == .2\n assert bw == .2 * data_std"},{"col":4,"comment":"null","endLoc":1193,"header":"def test_labels_facets(self)","id":4676,"name":"test_labels_facets","nodeType":"Function","startLoc":1186,"text":"def test_labels_facets(self):\n\n data = {\"a\": [\"b\", \"c\"], \"x\": [\"y\", \"z\"]}\n p = Plot(data).facet(\"a\", \"x\").label(col=str.capitalize, row=\"$x$\").plot()\n axs = np.reshape(p._figure.axes, (2, 2))\n for (i, j), ax in np.ndenumerate(axs):\n expected = f\"A {data['a'][j]} | $x$ {data['x'][i]}\"\n assert ax.get_title() == expected"},{"col":4,"comment":"null","endLoc":1297,"header":"def test_draw_to_density(self)","id":4677,"name":"test_draw_to_density","nodeType":"Function","startLoc":1236,"text":"def test_draw_to_density(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n # p.dwidth will be 1 for easier testing\n p.width = 2\n\n # Test vertical plots\n support = np.array([.2, .6])\n density = np.array([.1, .4])\n\n # Test full vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, False)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.99 * -.4, .99 * .4])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Test left vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, \"left\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.99 * -.4, 0])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Test right vertical plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .5, support, density, \"right\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [0, .99 * .4])\n npt.assert_array_equal(y, [.5, .5])\n plt.close(\"all\")\n\n # Switch orientation to test horizontal plots\n p.orient = \"h\"\n support = np.array([.2, .5])\n density = np.array([.3, .7])\n\n # Test full horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, False)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [.99 * -.7, .99 * .7])\n plt.close(\"all\")\n\n # Test left horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, \"left\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [.99 * -.7, 0])\n plt.close(\"all\")\n\n # Test right horizontal plot\n _, ax = plt.subplots()\n p.draw_to_density(ax, 0, .6, support, density, \"right\")\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [.6, .6])\n npt.assert_array_equal(y, [0, .99 * .7])\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1199,"header":"def test_title_single(self)","id":4678,"name":"test_title_single","nodeType":"Function","startLoc":1195,"text":"def test_title_single(self):\n\n label = \"A\"\n p = Plot().label(title=label).plot()\n assert p._figure.axes[0].get_title() == label"},{"col":4,"comment":"null","endLoc":1212,"header":"def test_title_facet_function(self)","id":4679,"name":"test_title_facet_function","nodeType":"Function","startLoc":1201,"text":"def test_title_facet_function(self):\n\n titles = [\"a\", \"b\"]\n p = Plot().facet(titles).label(title=str.capitalize).plot()\n for i, ax in enumerate(p._figure.axes):\n assert ax.get_title() == titles[i].upper()\n\n cols, rows = [\"a\", \"b\"], [\"x\", \"y\"]\n p = Plot().facet(cols, rows).label(title=str.capitalize).plot()\n for i, ax in enumerate(p._figure.axes):\n expected = \" | \".join([cols[i % 2].upper(), rows[i // 2].upper()])\n assert ax.get_title() == expected"},{"col":4,"comment":"null","endLoc":970,"header":"def test_iter_data_values(self, long_df)","id":4680,"name":"test_iter_data_values","nodeType":"Function","startLoc":943,"text":"def test_iter_data_values(self, long_df):\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\"),\n )\n\n p.sort = True\n _, sub_data = next(p.iter_data(\"hue\"))\n assert_frame_equal(sub_data, p.plot_data)\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\"),\n )\n\n for sub_vars, sub_data in p.iter_data(\"hue\"):\n rows = p.plot_data[\"hue\"] == sub_vars[\"hue\"]\n assert_frame_equal(sub_data, p.plot_data[rows])\n\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\", size=\"s\"),\n )\n for sub_vars, sub_data in p.iter_data([\"hue\", \"size\"]):\n rows = p.plot_data[\"hue\"] == sub_vars[\"hue\"]\n rows &= p.plot_data[\"size\"] == sub_vars[\"size\"]\n assert_frame_equal(sub_data, p.plot_data[rows])"},{"col":4,"comment":"null","endLoc":981,"header":"def test_iter_data_reverse(self, long_df)","id":4681,"name":"test_iter_data_reverse","nodeType":"Function","startLoc":972,"text":"def test_iter_data_reverse(self, long_df):\n\n reversed_order = categorical_order(long_df[\"a\"])[::-1]\n p = VectorPlotter(\n data=long_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n iterator = p.iter_data(\"hue\", reverse=True)\n for i, (sub_vars, _) in enumerate(iterator):\n assert sub_vars[\"hue\"] == reversed_order[i]"},{"col":4,"comment":"null","endLoc":995,"header":"def test_iter_data_dropna(self, missing_df)","id":4684,"name":"test_iter_data_dropna","nodeType":"Function","startLoc":983,"text":"def test_iter_data_dropna(self, missing_df):\n\n p = VectorPlotter(\n data=missing_df,\n variables=dict(x=\"x\", y=\"y\", hue=\"a\")\n )\n for _, sub_df in p.iter_data(\"hue\"):\n assert not sub_df.isna().any().any()\n\n some_missing = False\n for _, sub_df in p.iter_data(\"hue\", dropna=False):\n some_missing |= sub_df.isna().any().any()\n assert some_missing"},{"col":4,"comment":"null","endLoc":1319,"header":"def test_draw_single_observations(self)","id":4685,"name":"test_draw_single_observations","nodeType":"Function","startLoc":1299,"text":"def test_draw_single_observations(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n p.width = 2\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_single_observation(ax, 1, 1.5, 1)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [0, 2])\n npt.assert_array_equal(y, [1.5, 1.5])\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_single_observation(ax, 2, 2.2, .5)\n x, y = ax.lines[0].get_xydata().T\n npt.assert_array_equal(x, [2.2, 2.2])\n npt.assert_array_equal(y, [1.5, 2.5])\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1045,"header":"def test_axis_labels(self, long_df)","id":4686,"name":"test_axis_labels","nodeType":"Function","startLoc":997,"text":"def test_axis_labels(self, long_df):\n\n f, ax = plt.subplots()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"a\"))\n\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(y=\"a\"))\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"\"\n assert ax.get_ylabel() == \"a\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"a\"))\n\n p._add_axis_labels(ax, default_y=\"default\")\n assert ax.get_xlabel() == \"a\"\n assert ax.get_ylabel() == \"default\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(y=\"a\"))\n p._add_axis_labels(ax, default_x=\"default\", default_y=\"default\")\n assert ax.get_xlabel() == \"default\"\n assert ax.get_ylabel() == \"a\"\n ax.clear()\n\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"a\"))\n ax.set(xlabel=\"existing\", ylabel=\"also existing\")\n p._add_axis_labels(ax)\n assert ax.get_xlabel() == \"existing\"\n assert ax.get_ylabel() == \"also existing\"\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n p = VectorPlotter(data=long_df, variables=dict(x=\"x\", y=\"y\"))\n\n p._add_axis_labels(ax1)\n p._add_axis_labels(ax2)\n\n assert ax1.get_xlabel() == \"x\"\n assert ax1.get_ylabel() == \"y\"\n assert ax1.yaxis.label.get_visible()\n\n assert ax2.get_xlabel() == \"x\"\n assert ax2.get_ylabel() == \"y\"\n assert not ax2.yaxis.label.get_visible()"},{"col":4,"comment":"null","endLoc":1357,"header":"def test_draw_box_lines(self)","id":4687,"name":"test_draw_box_lines","nodeType":"Function","startLoc":1321,"text":"def test_draw_box_lines(self):\n\n # Test vertical plot\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_box_lines(ax, self.y, 0)\n assert len(ax.lines) == 2\n\n q25, q50, q75 = np.percentile(self.y, [25, 50, 75])\n _, y = ax.lines[1].get_xydata().T\n npt.assert_array_equal(y, [q25, q75])\n\n _, y = ax.collections[0].get_offsets().T\n assert y == q50\n\n plt.close(\"all\")\n\n # Test horizontal plot\n kws = self.default_kws.copy()\n kws.update(dict(x=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_box_lines(ax, self.y, 0)\n assert len(ax.lines) == 2\n\n q25, q50, q75 = np.percentile(self.y, [25, 50, 75])\n x, _ = ax.lines[1].get_xydata().T\n npt.assert_array_equal(x, [q25, q75])\n\n x, _ = ax.collections[0].get_offsets().T\n assert x == q50\n\n plt.close(\"all\")"},{"className":"TestFacetInterface","col":0,"comment":"null","endLoc":1377,"id":4688,"nodeType":"Class","startLoc":1215,"text":"class TestFacetInterface:\n\n @pytest.fixture(scope=\"class\", params=[\"row\", \"col\"])\n def dim(self, request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=[\"reverse\", \"subset\", \"expand\"])\n def reorder(self, request):\n return {\n \"reverse\": lambda x: x[::-1],\n \"subset\": lambda x: x[:-1],\n \"expand\": lambda x: x + [\"z\"],\n }[request.param]\n\n def check_facet_results_1d(self, p, df, dim, key, order=None):\n\n p = p.plot()\n\n order = categorical_order(df[key], order)\n assert len(p._figure.axes) == len(order)\n\n other_dim = {\"row\": \"col\", \"col\": \"row\"}[dim]\n\n for subplot, level in zip(p._subplots, order):\n assert subplot[dim] == level\n assert subplot[other_dim] is None\n assert subplot[\"ax\"].get_title() == f\"{level}\"\n assert_gridspec_shape(subplot[\"ax\"], **{f\"n{dim}s\": len(order)})\n\n def test_1d(self, long_df, dim):\n\n key = \"a\"\n p = Plot(long_df).facet(**{dim: key})\n self.check_facet_results_1d(p, long_df, dim, key)\n\n def test_1d_as_vector(self, long_df, dim):\n\n key = \"a\"\n p = Plot(long_df).facet(**{dim: long_df[key]})\n self.check_facet_results_1d(p, long_df, dim, key)\n\n def test_1d_with_order(self, long_df, dim, reorder):\n\n key = \"a\"\n order = reorder(categorical_order(long_df[key]))\n p = Plot(long_df).facet(**{dim: key, \"order\": order})\n self.check_facet_results_1d(p, long_df, dim, key, order)\n\n def check_facet_results_2d(self, p, df, variables, order=None):\n\n p = p.plot()\n\n if order is None:\n order = {dim: categorical_order(df[key]) for dim, key in variables.items()}\n\n levels = itertools.product(*[order[dim] for dim in [\"row\", \"col\"]])\n assert len(p._subplots) == len(list(levels))\n\n for subplot, (row_level, col_level) in zip(p._subplots, levels):\n assert subplot[\"row\"] == row_level\n assert subplot[\"col\"] == col_level\n assert subplot[\"axes\"].get_title() == (\n f\"{col_level} | {row_level}\"\n )\n assert_gridspec_shape(\n subplot[\"axes\"], len(levels[\"row\"]), len(levels[\"col\"])\n )\n\n def test_2d(self, long_df):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n p = Plot(long_df).facet(**variables)\n self.check_facet_results_2d(p, long_df, variables)\n\n def test_2d_with_order(self, long_df, reorder):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n order = {\n dim: reorder(categorical_order(long_df[key]))\n for dim, key in variables.items()\n }\n\n p = Plot(long_df).facet(**variables, order=order)\n self.check_facet_results_2d(p, long_df, variables, order)\n\n @pytest.mark.parametrize(\"algo\", [\"tight\", \"constrained\"])\n def test_layout_algo(self, algo):\n\n if algo == \"constrained\" and Version(mpl.__version__) < Version(\"3.3.0\"):\n pytest.skip(\"constrained_layout requires matplotlib>=3.3\")\n\n p = Plot().facet([\"a\", \"b\"]).limit(x=(.1, .9))\n\n p1 = p.layout(engine=algo).plot()\n p2 = p.layout(engine=None).plot()\n\n # Force a draw (we probably need a method for this)\n p1.save(io.BytesIO())\n p2.save(io.BytesIO())\n\n bb11, bb12 = [ax.get_position() for ax in p1._figure.axes]\n bb21, bb22 = [ax.get_position() for ax in p2._figure.axes]\n\n sep1 = bb12.corners()[0, 0] - bb11.corners()[2, 0]\n sep2 = bb22.corners()[0, 0] - bb21.corners()[2, 0]\n assert sep1 < sep2\n\n def test_axis_sharing(self, long_df):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n\n p = Plot(long_df).facet(**variables)\n\n p1 = p.plot()\n root, *other = p1._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert all(shareset.joined(root, ax) for ax in other)\n\n p2 = p.share(x=False, y=False).plot()\n root, *other = p2._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n p3 = p.share(x=\"col\", y=\"row\").plot()\n shape = (\n len(categorical_order(long_df[variables[\"row\"]])),\n len(categorical_order(long_df[variables[\"col\"]])),\n )\n axes_matrix = np.reshape(p3._figure.axes, shape)\n\n for (shared, unshared), vectors in zip(\n [\"yx\", \"xy\"], [axes_matrix, axes_matrix.T]\n ):\n for root, *other in vectors:\n shareset = {\n axis: getattr(root, f\"get_shared_{axis}_axes\")() for axis in \"xy\"\n }\n assert all(shareset[shared].joined(root, ax) for ax in other)\n assert not any(shareset[unshared].joined(root, ax) for ax in other)\n\n def test_col_wrapping(self):\n\n cols = list(\"abcd\")\n wrap = 3\n p = Plot().facet(col=cols, wrap=wrap).plot()\n\n assert len(p._figure.axes) == 4\n assert_gridspec_shape(p._figure.axes[0], len(cols) // wrap + 1, wrap)\n\n # TODO test axis labels and titles\n\n def test_row_wrapping(self):\n\n rows = list(\"abcd\")\n wrap = 3\n p = Plot().facet(row=rows, wrap=wrap).plot()\n\n assert_gridspec_shape(p._figure.axes[0], wrap, len(rows) // wrap + 1)\n assert len(p._figure.axes) == 4\n\n # TODO test axis labels and titles"},{"col":4,"comment":"null","endLoc":1219,"header":"@pytest.fixture(scope=\"class\", params=[\"row\", \"col\"])\n def dim(self, request)","id":4689,"name":"dim","nodeType":"Function","startLoc":1217,"text":"@pytest.fixture(scope=\"class\", params=[\"row\", \"col\"])\n def dim(self, request):\n return request.param"},{"col":4,"comment":"null","endLoc":1227,"header":"@pytest.fixture(scope=\"class\", params=[\"reverse\", \"subset\", \"expand\"])\n def reorder(self, request)","id":4690,"name":"reorder","nodeType":"Function","startLoc":1221,"text":"@pytest.fixture(scope=\"class\", params=[\"reverse\", \"subset\", \"expand\"])\n def reorder(self, request):\n return {\n \"reverse\": lambda x: x[::-1],\n \"subset\": lambda x: x[:-1],\n \"expand\": lambda x: x + [\"z\"],\n }[request.param]"},{"col":23,"endLoc":1224,"id":4691,"nodeType":"Lambda","startLoc":1224,"text":"lambda x: x[::-1]"},{"col":22,"endLoc":1225,"id":4692,"nodeType":"Lambda","startLoc":1225,"text":"lambda x: x[:-1]"},{"col":22,"endLoc":1226,"id":4693,"nodeType":"Lambda","startLoc":1226,"text":"lambda x: x + [\"z\"]"},{"col":4,"comment":"null","endLoc":1242,"header":"def check_facet_results_1d(self, p, df, dim, key, order=None)","id":4694,"name":"check_facet_results_1d","nodeType":"Function","startLoc":1229,"text":"def check_facet_results_1d(self, p, df, dim, key, order=None):\n\n p = p.plot()\n\n order = categorical_order(df[key], order)\n assert len(p._figure.axes) == len(order)\n\n other_dim = {\"row\": \"col\", \"col\": \"row\"}[dim]\n\n for subplot, level in zip(p._subplots, order):\n assert subplot[dim] == level\n assert subplot[other_dim] is None\n assert subplot[\"ax\"].get_title() == f\"{level}\"\n assert_gridspec_shape(subplot[\"ax\"], **{f\"n{dim}s\": len(order)})"},{"col":0,"comment":"null","endLoc":42,"header":"def assert_gridspec_shape(ax, nrows=1, ncols=1)","id":4695,"name":"assert_gridspec_shape","nodeType":"Function","startLoc":34,"text":"def assert_gridspec_shape(ax, nrows=1, ncols=1):\n\n gs = ax.get_gridspec()\n if Version(mpl.__version__) < Version(\"3.2\"):\n assert gs._nrows == nrows\n assert gs._ncols == ncols\n else:\n assert gs.nrows == nrows\n assert gs.ncols == ncols"},{"col":4,"comment":"null","endLoc":1369,"header":"def test_draw_quartiles(self)","id":4696,"name":"test_draw_quartiles","nodeType":"Function","startLoc":1359,"text":"def test_draw_quartiles(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_quartiles(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(np.percentile(self.y, [25, 50, 75]), ax.lines):\n _, y = line.get_xydata().T\n npt.assert_array_equal(y, [val, val])"},{"col":4,"comment":"null","endLoc":1248,"header":"def test_1d(self, long_df, dim)","id":4697,"name":"test_1d","nodeType":"Function","startLoc":1244,"text":"def test_1d(self, long_df, dim):\n\n key = \"a\"\n p = Plot(long_df).facet(**{dim: key})\n self.check_facet_results_1d(p, long_df, dim, key)"},{"col":4,"comment":"null","endLoc":1390,"header":"def test_draw_points(self)","id":4698,"name":"test_draw_points","nodeType":"Function","startLoc":1371,"text":"def test_draw_points(self):\n\n p = cat._ViolinPlotter(**self.default_kws)\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_points(ax, self.y, 0)\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, np.zeros_like(self.y))\n npt.assert_array_equal(y, self.y)\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_points(ax, self.y, 0)\n x, y = ax.collections[0].get_offsets().T\n npt.assert_array_equal(x, self.y)\n npt.assert_array_equal(y, np.zeros_like(self.y))\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1254,"header":"def test_1d_as_vector(self, long_df, dim)","id":4699,"name":"test_1d_as_vector","nodeType":"Function","startLoc":1250,"text":"def test_1d_as_vector(self, long_df, dim):\n\n key = \"a\"\n p = Plot(long_df).facet(**{dim: long_df[key]})\n self.check_facet_results_1d(p, long_df, dim, key)"},{"col":4,"comment":"null","endLoc":1062,"header":"@pytest.mark.parametrize(\n \"variables\",\n [\n dict(x=\"x\", y=\"y\"),\n dict(x=\"x\"),\n dict(y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"x\", y=\"a\"),\n ]\n )\n def test_attach_basics(self, long_df, variables)","id":4700,"name":"test_attach_basics","nodeType":"Function","startLoc":1047,"text":"@pytest.mark.parametrize(\n \"variables\",\n [\n dict(x=\"x\", y=\"y\"),\n dict(x=\"x\"),\n dict(y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"x\", y=\"a\"),\n ]\n )\n def test_attach_basics(self, long_df, variables):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables=variables)\n p._attach(ax)\n assert p.ax is ax"},{"col":4,"comment":"null","endLoc":1413,"header":"def test_draw_sticks(self)","id":4701,"name":"test_draw_sticks","nodeType":"Function","startLoc":1392,"text":"def test_draw_sticks(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(y=\"y\", data=self.df, inner=None))\n p = cat._ViolinPlotter(**kws)\n\n # Test vertical plot\n _, ax = plt.subplots()\n p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(self.y, ax.lines):\n _, y = line.get_xydata().T\n npt.assert_array_equal(y, [val, val])\n plt.close(\"all\")\n\n # Test horizontal plot\n p.orient = \"h\"\n _, ax = plt.subplots()\n p.draw_stick_lines(ax, self.y, p.support[0], p.density[0], 0)\n for val, line in zip(self.y, ax.lines):\n x, _ = line.get_xydata().T\n npt.assert_array_equal(x, [val, val])\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1261,"header":"def test_1d_with_order(self, long_df, dim, reorder)","id":4702,"name":"test_1d_with_order","nodeType":"Function","startLoc":1256,"text":"def test_1d_with_order(self, long_df, dim, reorder):\n\n key = \"a\"\n order = reorder(categorical_order(long_df[key]))\n p = Plot(long_df).facet(**{dim: key, \"order\": order})\n self.check_facet_results_1d(p, long_df, dim, key, order)"},{"col":4,"comment":"null","endLoc":1281,"header":"def check_facet_results_2d(self, p, df, variables, order=None)","id":4703,"name":"check_facet_results_2d","nodeType":"Function","startLoc":1263,"text":"def check_facet_results_2d(self, p, df, variables, order=None):\n\n p = p.plot()\n\n if order is None:\n order = {dim: categorical_order(df[key]) for dim, key in variables.items()}\n\n levels = itertools.product(*[order[dim] for dim in [\"row\", \"col\"]])\n assert len(p._subplots) == len(list(levels))\n\n for subplot, (row_level, col_level) in zip(p._subplots, levels):\n assert subplot[\"row\"] == row_level\n assert subplot[\"col\"] == col_level\n assert subplot[\"axes\"].get_title() == (\n f\"{col_level} | {row_level}\"\n )\n assert_gridspec_shape(\n subplot[\"axes\"], len(levels[\"row\"]), len(levels[\"col\"])\n )"},{"col":4,"comment":"null","endLoc":1085,"header":"def test_attach_disallowed(self, long_df)","id":4704,"name":"test_attach_disallowed","nodeType":"Function","startLoc":1064,"text":"def test_attach_disallowed(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=\"numeric\")\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=[\"datetime\", \"numeric\"])\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=\"categorical\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n\n with pytest.raises(TypeError):\n p._attach(ax, allowed_types=[\"numeric\", \"categorical\"])"},{"col":4,"comment":"null","endLoc":1420,"header":"def test_validate_inner(self)","id":4705,"name":"test_validate_inner","nodeType":"Function","startLoc":1415,"text":"def test_validate_inner(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(inner=\"bad_inner\"))\n with pytest.raises(ValueError):\n cat._ViolinPlotter(**kws)"},{"col":4,"comment":"null","endLoc":1287,"header":"def test_2d(self, long_df)","id":4706,"name":"test_2d","nodeType":"Function","startLoc":1283,"text":"def test_2d(self, long_df):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n p = Plot(long_df).facet(**variables)\n self.check_facet_results_2d(p, long_df, variables)"},{"col":4,"comment":"null","endLoc":1135,"header":"def test_attach_log_scale(self, long_df)","id":4707,"name":"test_attach_log_scale","nodeType":"Function","startLoc":1087,"text":"def test_attach_log_scale(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p._attach(ax, log_scale=2)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"y\": \"y\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"linear\"\n assert ax.yaxis.get_scale() == \"log\"\n assert not p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=True)\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"log\"\n assert p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=(True, False))\n assert ax.xaxis.get_scale() == \"log\"\n assert ax.yaxis.get_scale() == \"linear\"\n assert p._log_scaled(\"x\")\n assert not p._log_scaled(\"y\")\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(ax, log_scale=(False, 2))\n assert ax.xaxis.get_scale() == \"linear\"\n assert ax.yaxis.get_scale() == \"log\"\n assert not p._log_scaled(\"x\")\n assert p._log_scaled(\"y\")"},{"col":4,"comment":"null","endLoc":1298,"header":"def test_2d_with_order(self, long_df, reorder)","id":4708,"name":"test_2d_with_order","nodeType":"Function","startLoc":1289,"text":"def test_2d_with_order(self, long_df, reorder):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n order = {\n dim: reorder(categorical_order(long_df[key]))\n for dim, key in variables.items()\n }\n\n p = Plot(long_df).facet(**variables, order=order)\n self.check_facet_results_2d(p, long_df, variables, order)"},{"col":4,"comment":"null","endLoc":1320,"header":"@pytest.mark.parametrize(\"algo\", [\"tight\", \"constrained\"])\n def test_layout_algo(self, algo)","id":4709,"name":"test_layout_algo","nodeType":"Function","startLoc":1300,"text":"@pytest.mark.parametrize(\"algo\", [\"tight\", \"constrained\"])\n def test_layout_algo(self, algo):\n\n if algo == \"constrained\" and Version(mpl.__version__) < Version(\"3.3.0\"):\n pytest.skip(\"constrained_layout requires matplotlib>=3.3\")\n\n p = Plot().facet([\"a\", \"b\"]).limit(x=(.1, .9))\n\n p1 = p.layout(engine=algo).plot()\n p2 = p.layout(engine=None).plot()\n\n # Force a draw (we probably need a method for this)\n p1.save(io.BytesIO())\n p2.save(io.BytesIO())\n\n bb11, bb12 = [ax.get_position() for ax in p1._figure.axes]\n bb21, bb22 = [ax.get_position() for ax in p2._figure.axes]\n\n sep1 = bb12.corners()[0, 0] - bb11.corners()[2, 0]\n sep2 = bb22.corners()[0, 0] - bb21.corners()[2, 0]\n assert sep1 < sep2"},{"col":4,"comment":"null","endLoc":1483,"header":"def test_draw_violinplots(self)","id":4710,"name":"test_draw_violinplots","nodeType":"Function","startLoc":1422,"text":"def test_draw_violinplots(self):\n\n kws = self.default_kws.copy()\n\n # Test single vertical violin\n kws.update(dict(y=\"y\", data=self.df, inner=None,\n saturation=1, color=(1, 0, 0, 1)))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n npt.assert_array_equal(ax.collections[0].get_facecolors(),\n [(1, 0, 0, 1)])\n plt.close(\"all\")\n\n # Test single horizontal violin\n kws.update(dict(x=\"y\", y=None, color=(0, 1, 0, 1)))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n npt.assert_array_equal(ax.collections[0].get_facecolors(),\n [(0, 1, 0, 1)])\n plt.close(\"all\")\n\n # Test multiple vertical violins\n kws.update(dict(x=\"g\", y=\"y\", color=None,))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n for violin, color in zip(ax.collections, palettes.color_palette()):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n # Test multiple violins with hue nesting\n kws.update(dict(hue=\"h\"))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 6\n for violin, color in zip(ax.collections,\n palettes.color_palette(n_colors=2) * 3):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")\n\n # Test multiple split violins\n kws.update(dict(split=True, palette=\"muted\"))\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 6\n for violin, color in zip(ax.collections,\n palettes.color_palette(\"muted\",\n n_colors=2) * 3):\n npt.assert_array_equal(violin.get_facecolors()[0, :-1], color)\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1149,"header":"def test_attach_converters(self, long_df)","id":4711,"name":"test_attach_converters","nodeType":"Function","startLoc":1137,"text":"def test_attach_converters(self, long_df):\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n p._attach(ax)\n assert ax.xaxis.converter is None\n assert \"Date\" in ax.yaxis.converter.__class__.__name__\n\n _, ax = plt.subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\", \"y\": \"y\"})\n p._attach(ax)\n assert \"CategoryConverter\" in ax.xaxis.converter.__class__.__name__\n assert ax.yaxis.converter is None"},{"col":4,"comment":"null","endLoc":1157,"header":"def test_attach_facets(self, long_df)","id":4712,"name":"test_attach_facets","nodeType":"Function","startLoc":1151,"text":"def test_attach_facets(self, long_df):\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"col\": \"a\"})\n p._attach(g)\n assert p.ax is None\n assert p.facets == g"},{"col":4,"comment":"null","endLoc":1218,"header":"def test_attach_shared_axes(self, long_df)","id":4713,"name":"test_attach_shared_axes","nodeType":"Function","startLoc":1159,"text":"def test_attach_shared_axes(self, long_df):\n\n g = FacetGrid(long_df)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", sharex=False)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", sharex=False, col_wrap=2)\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\"})\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharex=False)\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == len(g.axes.flat)\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharex=\"col\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == p.plot_data[\"col\"].nunique()\n assert p.converters[\"x\"].groupby(p.plot_data[\"col\"]).nunique().max() == 1\n assert p.converters[\"y\"].nunique() == 1\n\n g = FacetGrid(long_df, col=\"a\", row=\"b\", sharey=\"row\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"y\": \"y\", \"col\": \"a\", \"row\": \"b\"},\n )\n p._attach(g)\n assert p.converters[\"x\"].nunique() == 1\n assert p.converters[\"y\"].nunique() == p.plot_data[\"row\"].nunique()\n assert p.converters[\"y\"].groupby(p.plot_data[\"row\"]).nunique().max() == 1"},{"col":4,"comment":"null","endLoc":1355,"header":"def test_axis_sharing(self, long_df)","id":4714,"name":"test_axis_sharing","nodeType":"Function","startLoc":1322,"text":"def test_axis_sharing(self, long_df):\n\n variables = {\"row\": \"a\", \"col\": \"c\"}\n\n p = Plot(long_df).facet(**variables)\n\n p1 = p.plot()\n root, *other = p1._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert all(shareset.joined(root, ax) for ax in other)\n\n p2 = p.share(x=False, y=False).plot()\n root, *other = p2._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n p3 = p.share(x=\"col\", y=\"row\").plot()\n shape = (\n len(categorical_order(long_df[variables[\"row\"]])),\n len(categorical_order(long_df[variables[\"col\"]])),\n )\n axes_matrix = np.reshape(p3._figure.axes, shape)\n\n for (shared, unshared), vectors in zip(\n [\"yx\", \"xy\"], [axes_matrix, axes_matrix.T]\n ):\n for root, *other in vectors:\n shareset = {\n axis: getattr(root, f\"get_shared_{axis}_axes\")() for axis in \"xy\"\n }\n assert all(shareset[shared].joined(root, ax) for ax in other)\n assert not any(shareset[unshared].joined(root, ax) for ax in other)"},{"col":4,"comment":"null","endLoc":1225,"header":"def test_get_axes_single(self, long_df)","id":4715,"name":"test_get_axes_single","nodeType":"Function","startLoc":1220,"text":"def test_get_axes_single(self, long_df):\n\n ax = plt.figure().subplots()\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"hue\": \"a\"})\n p._attach(ax)\n assert p._get_axes({\"hue\": \"a\"}) is ax"},{"col":4,"comment":"null","endLoc":1239,"header":"def test_get_axes_facets(self, long_df)","id":4716,"name":"test_get_axes_facets","nodeType":"Function","startLoc":1227,"text":"def test_get_axes_facets(self, long_df):\n\n g = FacetGrid(long_df, col=\"a\")\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"col\": \"a\"})\n p._attach(g)\n assert p._get_axes({\"col\": \"b\"}) is g.axes_dict[\"b\"]\n\n g = FacetGrid(long_df, col=\"a\", row=\"c\")\n p = VectorPlotter(\n data=long_df, variables={\"x\": \"x\", \"col\": \"a\", \"row\": \"c\"}\n )\n p._attach(g)\n assert p._get_axes({\"row\": 1, \"col\": \"b\"}) is g.axes_dict[(1, \"b\")]"},{"col":4,"comment":"null","endLoc":1265,"header":"def test_comp_data(self, long_df)","id":4717,"name":"test_comp_data","nodeType":"Function","startLoc":1241,"text":"def test_comp_data(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", \"y\": \"t\"})\n\n # We have disabled this check for now, while it remains part of\n # the internal API, because it will require updating a number of tests\n # with pytest.raises(AttributeError):\n # p.comp_data\n\n _, ax = plt.subplots()\n p._attach(ax)\n\n assert_array_equal(p.comp_data[\"x\"], p.plot_data[\"x\"])\n assert_array_equal(\n p.comp_data[\"y\"], ax.yaxis.convert_units(p.plot_data[\"y\"])\n )\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n\n _, ax = plt.subplots()\n p._attach(ax)\n\n assert_array_equal(\n p.comp_data[\"x\"], ax.xaxis.convert_units(p.plot_data[\"x\"])\n )"},{"col":4,"comment":"null","endLoc":1276,"header":"def test_comp_data_log(self, long_df)","id":4718,"name":"test_comp_data_log","nodeType":"Function","startLoc":1267,"text":"def test_comp_data_log(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"z\", \"y\": \"y\"})\n _, ax = plt.subplots()\n p._attach(ax, log_scale=(True, False))\n\n assert_array_equal(\n p.comp_data[\"x\"], np.log10(p.plot_data[\"x\"])\n )\n assert_array_equal(p.comp_data[\"y\"], p.plot_data[\"y\"])"},{"col":4,"comment":"null","endLoc":1289,"header":"def test_comp_data_category_order(self)","id":4719,"name":"test_comp_data_category_order","nodeType":"Function","startLoc":1278,"text":"def test_comp_data_category_order(self):\n\n s = (pd.Series([\"a\", \"b\", \"c\", \"a\"], dtype=\"category\")\n .cat.set_categories([\"b\", \"c\", \"a\"], ordered=True))\n\n p = VectorPlotter(variables={\"x\": s})\n _, ax = plt.subplots()\n p._attach(ax)\n assert_array_equal(\n p.comp_data[\"x\"],\n [2, 0, 1, 2],\n )"},{"col":4,"comment":"null","endLoc":1325,"header":"@pytest.fixture(\n params=itertools.product(\n [None, np.nan, PD_NA],\n [\"numeric\", \"category\", \"datetime\"]\n )\n )\n @pytest.mark.parametrize(\n \"NA,var_type\",\n )\n def comp_data_missing_fixture(self, request)","id":4720,"name":"comp_data_missing_fixture","nodeType":"Function","startLoc":1291,"text":"@pytest.fixture(\n params=itertools.product(\n [None, np.nan, PD_NA],\n [\"numeric\", \"category\", \"datetime\"]\n )\n )\n @pytest.mark.parametrize(\n \"NA,var_type\",\n )\n def comp_data_missing_fixture(self, request):\n\n # This fixture holds the logic for parameterizing\n # the following test (test_comp_data_missing)\n\n NA, var_type = request.param\n\n if NA is None:\n pytest.skip(\"No pandas.NA available\")\n\n comp_data = [0, 1, np.nan, 2, np.nan, 1]\n if var_type == \"numeric\":\n orig_data = [0, 1, NA, 2, np.inf, 1]\n elif var_type == \"category\":\n orig_data = [\"a\", \"b\", NA, \"c\", NA, \"b\"]\n elif var_type == \"datetime\":\n # Use 1-based numbers to avoid issue on matplotlib<3.2\n # Could simplify the test a bit when we roll off that version\n comp_data = [1, 2, np.nan, 3, np.nan, 2]\n numbers = [1, 2, 3, 2]\n\n orig_data = mpl.dates.num2date(numbers)\n orig_data.insert(2, NA)\n orig_data.insert(4, np.inf)\n\n return orig_data, comp_data"},{"col":4,"comment":"null","endLoc":1366,"header":"def test_col_wrapping(self)","id":4721,"name":"test_col_wrapping","nodeType":"Function","startLoc":1357,"text":"def test_col_wrapping(self):\n\n cols = list(\"abcd\")\n wrap = 3\n p = Plot().facet(col=cols, wrap=wrap).plot()\n\n assert len(p._figure.axes) == 4\n assert_gridspec_shape(p._figure.axes[0], len(cols) // wrap + 1, wrap)\n\n # TODO test axis labels and titles"},{"col":4,"comment":"null","endLoc":1377,"header":"def test_row_wrapping(self)","id":4722,"name":"test_row_wrapping","nodeType":"Function","startLoc":1368,"text":"def test_row_wrapping(self):\n\n rows = list(\"abcd\")\n wrap = 3\n p = Plot().facet(row=rows, wrap=wrap).plot()\n\n assert_gridspec_shape(p._figure.axes[0], wrap, len(rows) // wrap + 1)\n assert len(p._figure.axes) == 4\n\n # TODO test axis labels and titles"},{"className":"TestPairInterface","col":0,"comment":"null","endLoc":1633,"id":4723,"nodeType":"Class","startLoc":1380,"text":"class TestPairInterface:\n\n def check_pair_grid(self, p, x, y):\n\n xys = itertools.product(y, x)\n\n for (y_i, x_j), subplot in zip(xys, p._subplots):\n\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == \"\" if x_j is None else x_j\n assert ax.get_ylabel() == \"\" if y_i is None else y_i\n assert_gridspec_shape(subplot[\"ax\"], len(y), len(x))\n\n @pytest.mark.parametrize(\"vector_type\", [list, pd.Index])\n def test_all_numeric(self, long_df, vector_type):\n\n x, y = [\"x\", \"y\", \"z\"], [\"s\", \"f\"]\n p = Plot(long_df).pair(vector_type(x), vector_type(y)).plot()\n self.check_pair_grid(p, x, y)\n\n def test_single_variable_key_raises(self, long_df):\n\n p = Plot(long_df)\n err = \"You must pass a sequence of variable keys to `y`\"\n with pytest.raises(TypeError, match=err):\n p.pair(x=[\"x\", \"y\"], y=\"z\")\n\n @pytest.mark.parametrize(\"dim\", [\"x\", \"y\"])\n def test_single_dimension(self, long_df, dim):\n\n variables = {\"x\": None, \"y\": None}\n variables[dim] = [\"x\", \"y\", \"z\"]\n p = Plot(long_df).pair(**variables).plot()\n variables = {k: [v] if v is None else v for k, v in variables.items()}\n self.check_pair_grid(p, **variables)\n\n def test_non_cross(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n\n p = Plot(long_df).pair(x, y, cross=False).plot()\n\n for i, subplot in enumerate(p._subplots):\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == x[i]\n assert ax.get_ylabel() == y[i]\n assert_gridspec_shape(ax, 1, len(x))\n\n root, *other = p._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n def test_list_of_vectors(self, long_df):\n\n x_vars = [\"x\", \"z\"]\n p = Plot(long_df, y=\"y\").pair(x=[long_df[x] for x in x_vars]).plot()\n assert len(p._figure.axes) == len(x_vars)\n for ax, x_i in zip(p._figure.axes, x_vars):\n assert ax.get_xlabel() == x_i\n\n def test_with_no_variables(self, long_df):\n\n p = Plot(long_df).pair().plot()\n assert len(p._figure.axes) == 1\n\n def test_with_facets(self, long_df):\n\n x = \"x\"\n y = [\"y\", \"z\"]\n col = \"a\"\n\n p = Plot(long_df, x=x).facet(col).pair(y=y).plot()\n\n facet_levels = categorical_order(long_df[col])\n dims = itertools.product(y, facet_levels)\n\n for (y_i, col_i), subplot in zip(dims, p._subplots):\n\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == x\n assert ax.get_ylabel() == y_i\n assert ax.get_title() == f\"{col_i}\"\n assert_gridspec_shape(ax, len(y), len(facet_levels))\n\n @pytest.mark.parametrize(\"variables\", [(\"rows\", \"y\"), (\"columns\", \"x\")])\n def test_error_on_facet_overlap(self, long_df, variables):\n\n facet_dim, pair_axis = variables\n p = Plot(long_df).facet(**{facet_dim[:3]: \"a\"}).pair(**{pair_axis: [\"x\", \"y\"]})\n expected = f\"Cannot facet the {facet_dim} while pairing on `{pair_axis}`.\"\n with pytest.raises(RuntimeError, match=expected):\n p.plot()\n\n @pytest.mark.parametrize(\"variables\", [(\"columns\", \"y\"), (\"rows\", \"x\")])\n def test_error_on_wrap_overlap(self, long_df, variables):\n\n facet_dim, pair_axis = variables\n p = (\n Plot(long_df)\n .facet(wrap=2, **{facet_dim[:3]: \"a\"})\n .pair(**{pair_axis: [\"x\", \"y\"]})\n )\n expected = f\"Cannot wrap the {facet_dim} while pairing on `{pair_axis}``.\"\n with pytest.raises(RuntimeError, match=expected):\n p.plot()\n\n def test_axis_sharing(self, long_df):\n\n p = Plot(long_df).pair(x=[\"a\", \"b\"], y=[\"y\", \"z\"])\n shape = 2, 2\n\n p1 = p.plot()\n axes_matrix = np.reshape(p1._figure.axes, shape)\n\n for root, *other in axes_matrix: # Test row-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert not any(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n for root, *other in axes_matrix.T: # Test col-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert all(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert not any(y_shareset.joined(root, ax) for ax in other)\n\n p2 = p.share(x=False, y=False).plot()\n root, *other = p2._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)\n\n def test_axis_sharing_with_facets(self, long_df):\n\n p = Plot(long_df, y=\"y\").pair(x=[\"a\", \"b\"]).facet(row=\"c\").plot()\n shape = 2, 2\n\n axes_matrix = np.reshape(p._figure.axes, shape)\n\n for root, *other in axes_matrix: # Test row-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert not any(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n for root, *other in axes_matrix.T: # Test col-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert all(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n def test_x_wrapping(self, long_df):\n\n x_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n p = Plot(long_df, y=\"y\").pair(x=x_vars, wrap=wrap).plot()\n\n assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)\n assert len(p._figure.axes) == len(x_vars)\n for ax, var in zip(p._figure.axes, x_vars):\n label = ax.xaxis.get_label()\n assert label.get_visible()\n assert label.get_text() == var\n\n def test_y_wrapping(self, long_df):\n\n y_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n p = Plot(long_df, x=\"x\").pair(y=y_vars, wrap=wrap).plot()\n\n n_row, n_col = wrap, len(y_vars) // wrap + 1\n assert_gridspec_shape(p._figure.axes[0], n_row, n_col)\n assert len(p._figure.axes) == len(y_vars)\n label_array = np.empty(n_row * n_col, object)\n label_array[:len(y_vars)] = y_vars\n label_array = label_array.reshape((n_row, n_col), order=\"F\")\n label_array = [y for y in label_array.flat if y is not None]\n for i, ax in enumerate(p._figure.axes):\n label = ax.yaxis.get_label()\n assert label.get_visible()\n assert label.get_text() == label_array[i]\n\n def test_non_cross_wrapping(self, long_df):\n\n x_vars = [\"a\", \"b\", \"c\", \"t\"]\n y_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n\n p = (\n Plot(long_df, x=\"x\")\n .pair(x=x_vars, y=y_vars, wrap=wrap, cross=False)\n .plot()\n )\n\n assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)\n assert len(p._figure.axes) == len(x_vars)\n\n def test_cross_mismatched_lengths(self, long_df):\n\n p = Plot(long_df)\n with pytest.raises(ValueError, match=\"Lengths of the `x` and `y`\"):\n p.pair(x=[\"a\", \"b\"], y=[\"x\", \"y\", \"z\"], cross=False)\n\n def test_orient_inference(self, long_df):\n\n orient_list = []\n\n class CaptureOrientMove(Move):\n def __call__(self, data, groupby, orient, scales):\n orient_list.append(orient)\n return data\n\n (\n Plot(long_df, x=\"x\")\n .pair(y=[\"b\", \"z\"])\n .add(MockMark(), CaptureOrientMove())\n .plot()\n )\n\n assert orient_list == [\"y\", \"x\"]\n\n def test_computed_coordinate_orient_inference(self, long_df):\n\n class MockComputeStat(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient] * 2})\n\n m = MockMark()\n Plot(long_df, y=\"y\").add(m, MockComputeStat()).plot()\n assert m.passed_orient == \"y\"\n\n def test_two_variables_single_order_error(self, long_df):\n\n p = Plot(long_df)\n err = \"When faceting on both col= and row=, passing `order`\"\n with pytest.raises(RuntimeError, match=err):\n p.facet(col=\"a\", row=\"b\", order=[\"a\", \"b\", \"c\"])\n\n def test_limits(self, long_df):\n\n limit = (-2, 24)\n p = Plot(long_df, y=\"y\").pair(x=[\"x\", \"z\"]).limit(x1=limit).plot()\n ax1 = p._figure.axes[1]\n assert ax1.get_xlim() == limit\n\n def test_labels(self, long_df):\n\n label = \"Z\"\n p = Plot(long_df, y=\"y\").pair(x=[\"x\", \"z\"]).label(x1=label).plot()\n ax1 = p._figure.axes[1]\n assert ax1.get_xlabel() == label"},{"col":4,"comment":"null","endLoc":1391,"header":"def check_pair_grid(self, p, x, y)","id":4724,"name":"check_pair_grid","nodeType":"Function","startLoc":1382,"text":"def check_pair_grid(self, p, x, y):\n\n xys = itertools.product(y, x)\n\n for (y_i, x_j), subplot in zip(xys, p._subplots):\n\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == \"\" if x_j is None else x_j\n assert ax.get_ylabel() == \"\" if y_i is None else y_i\n assert_gridspec_shape(subplot[\"ax\"], len(y), len(x))"},{"col":4,"comment":"null","endLoc":1514,"header":"def test_draw_violinplots_no_observations(self)","id":4725,"name":"test_draw_violinplots_no_observations","nodeType":"Function","startLoc":1485,"text":"def test_draw_violinplots_no_observations(self):\n\n kws = self.default_kws.copy()\n kws[\"inner\"] = None\n\n # Test single layer of grouping\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n y[-1] = np.nan\n kws.update(x=x, y=y)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n assert len(ax.lines) == 0\n plt.close(\"all\")\n\n # Test nested hue grouping\n x = [\"a\"] * 4 + [\"b\"] * 2\n y = self.rs.randn(6)\n h = [\"m\", \"n\"] * 2 + [\"m\"] * 2\n kws.update(x=x, y=y, hue=h)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 0\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1554,"header":"def test_draw_violinplots_single_observations(self)","id":4726,"name":"test_draw_violinplots_single_observations","nodeType":"Function","startLoc":1516,"text":"def test_draw_violinplots_single_observations(self):\n\n kws = self.default_kws.copy()\n kws[\"inner\"] = None\n\n # Test single layer of grouping\n x = [\"a\", \"a\", \"b\"]\n y = self.rs.randn(3)\n kws.update(x=x, y=y)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 1\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n # Test nested hue grouping\n x = [\"b\"] * 4 + [\"a\"] * 3\n y = self.rs.randn(7)\n h = ([\"m\", \"n\"] * 4)[:-1]\n kws.update(x=x, y=y, hue=h)\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 1\n plt.close(\"all\")\n\n # Test nested hue grouping with split\n kws[\"split\"] = True\n p = cat._ViolinPlotter(**kws)\n\n _, ax = plt.subplots()\n p.draw_violins(ax)\n assert len(ax.collections) == 3\n assert len(ax.lines) == 1\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1398,"header":"@pytest.mark.parametrize(\"vector_type\", [list, pd.Index])\n def test_all_numeric(self, long_df, vector_type)","id":4727,"name":"test_all_numeric","nodeType":"Function","startLoc":1393,"text":"@pytest.mark.parametrize(\"vector_type\", [list, pd.Index])\n def test_all_numeric(self, long_df, vector_type):\n\n x, y = [\"x\", \"y\", \"z\"], [\"s\", \"f\"]\n p = Plot(long_df).pair(vector_type(x), vector_type(y)).plot()\n self.check_pair_grid(p, x, y)"},{"col":4,"comment":"null","endLoc":1595,"header":"def test_violinplots(self)","id":4728,"name":"test_violinplots","nodeType":"Function","startLoc":1556,"text":"def test_violinplots(self):\n\n # Smoke test the high level violinplot options\n\n cat.violinplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n order = list(\"nabc\")\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", order=order, data=self.df)\n plt.close(\"all\")\n\n order = list(\"omn\")\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=order, data=self.df)\n plt.close(\"all\")\n\n cat.violinplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n for inner in [\"box\", \"quart\", \"point\", \"stick\", None]:\n cat.violinplot(x=\"g\", y=\"y\", data=self.df, inner=inner)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, inner=inner)\n plt.close(\"all\")\n\n cat.violinplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n inner=inner, split=True)\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":1405,"header":"def test_single_variable_key_raises(self, long_df)","id":4729,"name":"test_single_variable_key_raises","nodeType":"Function","startLoc":1400,"text":"def test_single_variable_key_raises(self, long_df):\n\n p = Plot(long_df)\n err = \"You must pass a sequence of variable keys to `y`\"\n with pytest.raises(TypeError, match=err):\n p.pair(x=[\"x\", \"y\"], y=\"z\")"},{"col":4,"comment":"null","endLoc":1414,"header":"@pytest.mark.parametrize(\"dim\", [\"x\", \"y\"])\n def test_single_dimension(self, long_df, dim)","id":4730,"name":"test_single_dimension","nodeType":"Function","startLoc":1407,"text":"@pytest.mark.parametrize(\"dim\", [\"x\", \"y\"])\n def test_single_dimension(self, long_df, dim):\n\n variables = {\"x\": None, \"y\": None}\n variables[dim] = [\"x\", \"y\", \"z\"]\n p = Plot(long_df).pair(**variables).plot()\n variables = {k: [v] if v is None else v for k, v in variables.items()}\n self.check_pair_grid(p, **variables)"},{"col":4,"comment":"null","endLoc":1432,"header":"def test_non_cross(self, long_df)","id":4731,"name":"test_non_cross","nodeType":"Function","startLoc":1416,"text":"def test_non_cross(self, long_df):\n\n x = [\"x\", \"y\"]\n y = [\"f\", \"z\"]\n\n p = Plot(long_df).pair(x, y, cross=False).plot()\n\n for i, subplot in enumerate(p._subplots):\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == x[i]\n assert ax.get_ylabel() == y[i]\n assert_gridspec_shape(ax, 1, len(x))\n\n root, *other = p._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)"},{"col":4,"comment":"null","endLoc":1602,"header":"def test_split_one_each(self, rng)","id":4732,"name":"test_split_one_each","nodeType":"Function","startLoc":1597,"text":"def test_split_one_each(self, rng):\n\n x = np.repeat([0, 1], 5)\n y = rng.normal(0, 1, 10)\n ax = cat.violinplot(x=x, y=y, hue=x, split=True, inner=\"box\")\n assert len(ax.lines) == 4"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":998,"id":4733,"name":"default_kws","nodeType":"Attribute","startLoc":998,"text":"default_kws"},{"className":"SharedAxesLevelTests","col":0,"comment":"null","endLoc":1635,"id":4734,"nodeType":"Class","startLoc":1609,"text":"class SharedAxesLevelTests:\n\n def test_color(self, long_df):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C0\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C1\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", color=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", color=\"C3\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C3\")\n\n def test_two_calls(self):\n\n ax = plt.figure().subplots()\n self.func(x=[\"a\", \"b\", \"c\"], y=[1, 2, 3], ax=ax)\n self.func(x=[\"e\", \"f\"], y=[4, 5], ax=ax)\n assert ax.get_xlim() == (-.5, 4.5)"},{"col":4,"comment":"null","endLoc":1628,"header":"def test_color(self, long_df)","id":4735,"name":"test_color","nodeType":"Function","startLoc":1611,"text":"def test_color(self, long_df):\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C0\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n self.func(data=long_df, x=\"a\", y=\"y\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C1\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", color=\"C2\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C2\")\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", color=\"C3\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C3\")"},{"col":4,"comment":"null","endLoc":1635,"header":"def test_two_calls(self)","id":4736,"name":"test_two_calls","nodeType":"Function","startLoc":1630,"text":"def test_two_calls(self):\n\n ax = plt.figure().subplots()\n self.func(x=[\"a\", \"b\", \"c\"], y=[1, 2, 3], ax=ax)\n self.func(x=[\"e\", \"f\"], y=[4, 5], ax=ax)\n assert ax.get_xlim() == (-.5, 4.5)"},{"col":4,"comment":"null","endLoc":1440,"header":"def test_list_of_vectors(self, long_df)","id":4737,"name":"test_list_of_vectors","nodeType":"Function","startLoc":1434,"text":"def test_list_of_vectors(self, long_df):\n\n x_vars = [\"x\", \"z\"]\n p = Plot(long_df, y=\"y\").pair(x=[long_df[x] for x in x_vars]).plot()\n assert len(p._figure.axes) == len(x_vars)\n for ax, x_i in zip(p._figure.axes, x_vars):\n assert ax.get_xlabel() == x_i"},{"className":"SharedScatterTests","col":0,"comment":"Tests functionality common to stripplot and swarmplot.","endLoc":2136,"id":4738,"nodeType":"Class","startLoc":1638,"text":"class SharedScatterTests(SharedAxesLevelTests):\n \"\"\"Tests functionality common to stripplot and swarmplot.\"\"\"\n\n def get_last_color(self, ax):\n\n colors = ax.collections[-1].get_facecolors()\n unique_colors = np.unique(colors, axis=0)\n assert len(unique_colors) == 1\n return to_rgba(unique_colors.squeeze())\n\n # ------------------------------------------------------------------------------\n\n def test_color(self, long_df):\n\n super().test_color(long_df)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", facecolor=\"C4\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C4\")\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", fc=\"C5\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C5\")\n\n def test_supplied_color_array(self, long_df):\n\n cmap = get_colormap(\"Blues\")\n norm = mpl.colors.Normalize()\n colors = cmap(norm(long_df[\"y\"].to_numpy()))\n\n keys = [\"c\", \"facecolor\", \"facecolors\"]\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n keys.append(\"fc\")\n\n for key in keys:\n\n ax = plt.figure().subplots()\n self.func(x=long_df[\"y\"], **{key: colors})\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n ax = plt.figure().subplots()\n self.func(x=long_df[\"y\"], c=long_df[\"y\"], cmap=cmap)\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n @pytest.mark.parametrize(\n \"orient,data_type\",\n itertools.product([\"h\", \"v\"], [\"dataframe\", \"dict\"]),\n )\n def test_wide(self, wide_df, orient, data_type):\n\n if data_type == \"dict\":\n wide_df = {k: v.to_numpy() for k, v in wide_df.items()}\n\n ax = self.func(data=wide_df, orient=orient)\n _draw_figure(ax.figure)\n palette = color_palette()\n\n cat_idx = 0 if orient == \"v\" else 1\n val_idx = int(not cat_idx)\n\n axis_objs = ax.xaxis, ax.yaxis\n cat_axis = axis_objs[cat_idx]\n\n for i, label in enumerate(cat_axis.get_majorticklabels()):\n\n key = label.get_text()\n points = ax.collections[i]\n point_pos = points.get_offsets().T\n val_pos = point_pos[val_idx]\n cat_pos = point_pos[cat_idx]\n\n assert_array_equal(cat_pos.round(), i)\n assert_array_equal(val_pos, wide_df[key])\n\n for point_color in points.get_facecolors():\n assert tuple(point_color) == to_rgba(palette[i])\n\n @pytest.mark.parametrize(\"orient\", [\"h\", \"v\"])\n def test_flat(self, flat_series, orient):\n\n ax = self.func(data=flat_series, orient=orient)\n _draw_figure(ax.figure)\n\n cat_idx = [\"v\", \"h\"].index(orient)\n val_idx = int(not cat_idx)\n\n points = ax.collections[0]\n pos = points.get_offsets().T\n\n assert_array_equal(pos[cat_idx].round(), np.zeros(len(flat_series)))\n assert_array_equal(pos[val_idx], flat_series)\n\n @pytest.mark.parametrize(\n \"variables,orient\",\n [\n # Order matters for assigning to x/y\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": None}, None),\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": \"a\"}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": \"a\"}, None),\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": \"x\"}, None),\n ({\"cat\": \"s\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"s\", \"hue\": None}, \"h\"),\n ({\"cat\": \"a\", \"val\": \"b\", \"hue\": None}, None),\n ({\"val\": \"a\", \"cat\": \"b\", \"hue\": None}, \"h\"),\n ({\"cat\": \"a\", \"val\": \"t\", \"hue\": None}, None),\n ({\"val\": \"t\", \"cat\": \"a\", \"hue\": None}, None),\n ({\"cat\": \"d\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"d\", \"hue\": None}, None),\n ({\"cat\": \"a_cat\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"s_cat\", \"hue\": None}, None),\n ],\n )\n def test_positions(self, long_df, variables, orient):\n\n cat_var = variables[\"cat\"]\n val_var = variables[\"val\"]\n hue_var = variables[\"hue\"]\n var_names = list(variables.values())\n x_var, y_var, *_ = var_names\n\n ax = self.func(\n data=long_df, x=x_var, y=y_var, hue=hue_var, orient=orient,\n )\n\n _draw_figure(ax.figure)\n\n cat_idx = var_names.index(cat_var)\n val_idx = var_names.index(val_var)\n\n axis_objs = ax.xaxis, ax.yaxis\n cat_axis = axis_objs[cat_idx]\n val_axis = axis_objs[val_idx]\n\n cat_data = long_df[cat_var]\n cat_levels = categorical_order(cat_data)\n\n for i, label in enumerate(cat_levels):\n\n vals = long_df.loc[cat_data == label, val_var]\n\n points = ax.collections[i].get_offsets().T\n cat_pos = points[var_names.index(cat_var)]\n val_pos = points[var_names.index(val_var)]\n\n assert_array_equal(val_pos, val_axis.convert_units(vals))\n assert_array_equal(cat_pos.round(), i)\n assert 0 <= np.ptp(cat_pos) <= .8\n\n label = pd.Index([label]).astype(str)[0]\n assert cat_axis.get_majorticklabels()[i].get_text() == label\n\n @pytest.mark.parametrize(\n \"variables\",\n [\n # Order matters for assigning to x/y\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"},\n {\"val\": \"y\", \"cat\": \"a\", \"hue\": \"c\"},\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"f\"},\n ],\n )\n def test_positions_dodged(self, long_df, variables):\n\n cat_var = variables[\"cat\"]\n val_var = variables[\"val\"]\n hue_var = variables[\"hue\"]\n var_names = list(variables.values())\n x_var, y_var, *_ = var_names\n\n ax = self.func(\n data=long_df, x=x_var, y=y_var, hue=hue_var, dodge=True,\n )\n\n cat_vals = categorical_order(long_df[cat_var])\n hue_vals = categorical_order(long_df[hue_var])\n\n n_hue = len(hue_vals)\n offsets = np.linspace(0, .8, n_hue + 1)[:-1]\n offsets -= offsets.mean()\n nest_width = .8 / n_hue\n\n for i, cat_val in enumerate(cat_vals):\n for j, hue_val in enumerate(hue_vals):\n rows = (long_df[cat_var] == cat_val) & (long_df[hue_var] == hue_val)\n vals = long_df.loc[rows, val_var]\n\n points = ax.collections[n_hue * i + j].get_offsets().T\n cat_pos = points[var_names.index(cat_var)]\n val_pos = points[var_names.index(val_var)]\n\n if pd.api.types.is_datetime64_any_dtype(vals):\n vals = mpl.dates.date2num(vals)\n\n assert_array_equal(val_pos, vals)\n\n assert_array_equal(cat_pos.round(), i)\n assert_array_equal((cat_pos - (i + offsets[j])).round() / nest_width, 0)\n assert 0 <= np.ptp(cat_pos) <= nest_width\n\n @pytest.mark.parametrize(\"cat_var\", [\"a\", \"s\", \"d\"])\n def test_positions_unfixed(self, long_df, cat_var):\n\n long_df = long_df.sort_values(cat_var)\n\n kws = dict(size=.001)\n if \"stripplot\" in str(self.func): # can't use __name__ with partial\n kws[\"jitter\"] = False\n\n ax = self.func(data=long_df, x=cat_var, y=\"y\", native_scale=True, **kws)\n\n for i, (cat_level, cat_data) in enumerate(long_df.groupby(cat_var)):\n\n points = ax.collections[i].get_offsets().T\n cat_pos = points[0]\n val_pos = points[1]\n\n assert_array_equal(val_pos, cat_data[\"y\"])\n\n comp_level = np.squeeze(ax.xaxis.convert_units(cat_level)).item()\n assert_array_equal(cat_pos.round(), comp_level)\n\n @pytest.mark.parametrize(\n \"x_type,order\",\n [\n (str, None),\n (str, [\"a\", \"b\", \"c\"]),\n (str, [\"c\", \"a\"]),\n (str, [\"a\", \"b\", \"c\", \"d\"]),\n (int, None),\n (int, [3, 1, 2]),\n (int, [3, 1]),\n (int, [1, 2, 3, 4]),\n (int, [\"3\", \"1\", \"2\"]),\n ]\n )\n def test_order(self, x_type, order):\n\n if x_type is str:\n x = [\"b\", \"a\", \"c\"]\n else:\n x = [2, 1, 3]\n y = [1, 2, 3]\n\n ax = self.func(x=x, y=y, order=order)\n _draw_figure(ax.figure)\n\n if order is None:\n order = x\n if x_type is int:\n order = np.sort(order)\n\n assert len(ax.collections) == len(order)\n tick_labels = ax.xaxis.get_majorticklabels()\n\n assert ax.get_xlim()[1] == (len(order) - .5)\n\n for i, points in enumerate(ax.collections):\n cat = order[i]\n assert tick_labels[i].get_text() == str(cat)\n\n positions = points.get_offsets()\n if x_type(cat) in x:\n val = y[x.index(x_type(cat))]\n assert positions[0, 1] == val\n else:\n assert not positions.size\n\n @pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_categorical(self, long_df, hue_var):\n\n cat_var = \"b\"\n\n hue_levels = categorical_order(long_df[hue_var])\n cat_levels = categorical_order(long_df[cat_var])\n\n pal_name = \"muted\"\n palette = dict(zip(hue_levels, color_palette(pal_name)))\n ax = self.func(data=long_df, x=cat_var, y=\"y\", hue=hue_var, palette=pal_name)\n\n for i, level in enumerate(cat_levels):\n\n sub_df = long_df[long_df[cat_var] == level]\n point_hues = sub_df[hue_var]\n\n points = ax.collections[i]\n point_colors = points.get_facecolors()\n\n assert len(point_hues) == len(point_colors)\n\n for hue, color in zip(point_hues, point_colors):\n assert tuple(color) == to_rgba(palette[hue])\n\n @pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_dodged(self, long_df, hue_var):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=hue_var, dodge=True)\n colors = color_palette(n_colors=long_df[hue_var].nunique())\n collections = iter(ax.collections)\n\n # Slightly awkward logic to handle challenges of how the artists work.\n # e.g. there are empty scatter collections but the because facecolors\n # for the empty collections will return the default scatter color\n while colors:\n points = next(collections)\n if points.get_offsets().any():\n face_color = tuple(points.get_facecolors()[0])\n expected_color = to_rgba(colors.pop(0))\n assert face_color == expected_color\n\n @pytest.mark.parametrize(\n \"val_var,val_col,hue_col\",\n list(itertools.product([\"x\", \"y\"], [\"b\", \"y\", \"t\"], [None, \"a\"])),\n )\n def test_single(self, long_df, val_var, val_col, hue_col):\n\n var_kws = {val_var: val_col, \"hue\": hue_col}\n ax = self.func(data=long_df, **var_kws)\n _draw_figure(ax.figure)\n\n axis_vars = [\"x\", \"y\"]\n val_idx = axis_vars.index(val_var)\n cat_idx = int(not val_idx)\n cat_var = axis_vars[cat_idx]\n\n cat_axis = getattr(ax, f\"{cat_var}axis\")\n val_axis = getattr(ax, f\"{val_var}axis\")\n\n points = ax.collections[0]\n point_pos = points.get_offsets().T\n cat_pos = point_pos[cat_idx]\n val_pos = point_pos[val_idx]\n\n assert_array_equal(cat_pos.round(), 0)\n assert cat_pos.max() <= .4\n assert cat_pos.min() >= -.4\n\n num_vals = val_axis.convert_units(long_df[val_col])\n assert_array_equal(val_pos, num_vals)\n\n if hue_col is not None:\n palette = dict(zip(\n categorical_order(long_df[hue_col]), color_palette()\n ))\n\n facecolors = points.get_facecolors()\n for i, color in enumerate(facecolors):\n if hue_col is None:\n assert tuple(color) == to_rgba(\"C0\")\n else:\n hue_level = long_df.loc[i, hue_col]\n expected_color = palette[hue_level]\n assert tuple(color) == to_rgba(expected_color)\n\n ticklabels = cat_axis.get_majorticklabels()\n assert len(ticklabels) == 1\n assert not ticklabels[0].get_text()\n\n def test_attributes(self, long_df):\n\n kwargs = dict(\n size=2,\n linewidth=1,\n edgecolor=\"C2\",\n )\n\n ax = self.func(x=long_df[\"y\"], **kwargs)\n points, = ax.collections\n\n assert points.get_sizes().item() == kwargs[\"size\"] ** 2\n assert points.get_linewidths().item() == kwargs[\"linewidth\"]\n assert tuple(points.get_edgecolors().squeeze()) == to_rgba(kwargs[\"edgecolor\"])\n\n def test_three_points(self):\n\n x = np.arange(3)\n ax = self.func(x=x)\n for point_color in ax.collections[0].get_facecolor():\n assert tuple(point_color) == to_rgba(\"C0\")\n\n def test_legend_categorical(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"b\")\n legend_texts = [t.get_text() for t in ax.legend_.texts]\n expected = categorical_order(long_df[\"b\"])\n assert legend_texts == expected\n\n def test_legend_numeric(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"z\")\n vals = [float(t.get_text()) for t in ax.legend_.texts]\n assert (vals[1] - vals[0]) == pytest.approx(vals[2] - vals[1])\n\n def test_legend_disabled(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"b\", legend=False)\n assert ax.legend_ is None\n\n def test_palette_from_color_deprecation(self, long_df):\n\n color = (.9, .4, .5)\n hex_color = mpl.colors.to_hex(color)\n\n hue_var = \"a\"\n n_hue = long_df[hue_var].nunique()\n palette = color_palette(f\"dark:{hex_color}\", n_hue)\n\n with pytest.warns(FutureWarning, match=\"Setting a gradient palette\"):\n ax = self.func(data=long_df, x=\"z\", hue=hue_var, color=color)\n\n points = ax.collections[0]\n for point_color in points.get_facecolors():\n assert to_rgb(point_color) in palette\n\n def test_palette_with_hue_deprecation(self, long_df):\n palette = \"Blues\"\n with pytest.warns(FutureWarning, match=\"Passing `palette` without\"):\n ax = self.func(data=long_df, x=\"a\", y=long_df[\"y\"], palette=palette)\n strips = ax.collections\n colors = color_palette(palette, len(strips))\n for strip, color in zip(strips, colors):\n assert same_color(strip.get_facecolor()[0], color)\n\n def test_log_scale(self):\n\n x = [1, 10, 100, 1000]\n\n ax = plt.figure().subplots()\n ax.set_xscale(\"log\")\n self.func(x=x)\n vals = ax.collections[0].get_offsets()[:, 0]\n assert_array_equal(x, vals)\n\n y = [1, 2, 3, 4]\n\n ax = plt.figure().subplots()\n ax.set_xscale(\"log\")\n self.func(x=x, y=y, native_scale=True)\n for i, point in enumerate(ax.collections):\n val = point.get_offsets()[0, 0]\n assert val == pytest.approx(x[i])\n\n x = y = np.ones(100)\n\n # Following test fails on pinned (but not latest) matplotlib.\n # (Even though visual output is ok -- so it's not an actual bug).\n # I'm not exactly sure why, so this version check is approximate\n # and should be revisited on a version bump.\n if Version(mpl.__version__) < Version(\"3.1\"):\n pytest.xfail()\n\n ax = plt.figure().subplots()\n ax.set_yscale(\"log\")\n self.func(x=x, y=y, orient=\"h\", native_scale=True)\n cat_points = ax.collections[0].get_offsets().copy()[:, 1]\n assert np.ptp(np.log10(cat_points)) <= .8\n\n @pytest.mark.parametrize(\n \"kwargs\",\n [\n dict(data=\"wide\"),\n dict(data=\"wide\", orient=\"h\"),\n dict(data=\"long\", x=\"x\", color=\"C3\"),\n dict(data=\"long\", y=\"y\", hue=\"a\", jitter=False),\n dict(data=\"long\", x=\"a\", y=\"y\", hue=\"z\", edgecolor=\"w\", linewidth=.5),\n dict(data=\"long\", x=\"a_cat\", y=\"y\", hue=\"z\"),\n dict(data=\"long\", x=\"y\", y=\"s\", hue=\"c\", orient=\"h\", dodge=True),\n dict(data=\"long\", x=\"s\", y=\"y\", hue=\"c\", native_scale=True),\n ]\n )\n def test_vs_catplot(self, long_df, wide_df, kwargs):\n\n kwargs = kwargs.copy()\n if kwargs[\"data\"] == \"long\":\n kwargs[\"data\"] = long_df\n elif kwargs[\"data\"] == \"wide\":\n kwargs[\"data\"] = wide_df\n\n try:\n name = self.func.__name__[:-4]\n except AttributeError:\n name = self.func.func.__name__[:-4]\n if name == \"swarm\":\n kwargs.pop(\"jitter\", None)\n\n np.random.seed(0) # for jitter\n ax = self.func(**kwargs)\n\n np.random.seed(0)\n g = catplot(**kwargs, kind=name)\n\n assert_plots_equal(ax, g.ax)"},{"col":4,"comment":"null","endLoc":1646,"header":"def get_last_color(self, ax)","id":4739,"name":"get_last_color","nodeType":"Function","startLoc":1641,"text":"def get_last_color(self, ax):\n\n colors = ax.collections[-1].get_facecolors()\n unique_colors = np.unique(colors, axis=0)\n assert len(unique_colors) == 1\n return to_rgba(unique_colors.squeeze())"},{"col":4,"comment":"null","endLoc":1663,"header":"def test_color(self, long_df)","id":4740,"name":"test_color","nodeType":"Function","startLoc":1650,"text":"def test_color(self, long_df):\n\n super().test_color(long_df)\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", facecolor=\"C4\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C4\")\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n\n ax = plt.figure().subplots()\n self.func(data=long_df, x=\"a\", y=\"y\", fc=\"C5\", ax=ax)\n assert self.get_last_color(ax) == to_rgba(\"C5\")"},{"col":4,"comment":"null","endLoc":1445,"header":"def test_with_no_variables(self, long_df)","id":4741,"name":"test_with_no_variables","nodeType":"Function","startLoc":1442,"text":"def test_with_no_variables(self, long_df):\n\n p = Plot(long_df).pair().plot()\n assert len(p._figure.axes) == 1"},{"col":4,"comment":"null","endLoc":1464,"header":"def test_with_facets(self, long_df)","id":4742,"name":"test_with_facets","nodeType":"Function","startLoc":1447,"text":"def test_with_facets(self, long_df):\n\n x = \"x\"\n y = [\"y\", \"z\"]\n col = \"a\"\n\n p = Plot(long_df, x=x).facet(col).pair(y=y).plot()\n\n facet_levels = categorical_order(long_df[col])\n dims = itertools.product(y, facet_levels)\n\n for (y_i, col_i), subplot in zip(dims, p._subplots):\n\n ax = subplot[\"ax\"]\n assert ax.get_xlabel() == x\n assert ax.get_ylabel() == y_i\n assert ax.get_title() == f\"{col_i}\"\n assert_gridspec_shape(ax, len(y), len(facet_levels))"},{"col":4,"comment":"null","endLoc":1333,"header":"def test_comp_data_missing(self, comp_data_missing_fixture)","id":4743,"name":"test_comp_data_missing","nodeType":"Function","startLoc":1327,"text":"def test_comp_data_missing(self, comp_data_missing_fixture):\n\n orig_data, comp_data = comp_data_missing_fixture\n p = VectorPlotter(variables={\"x\": orig_data})\n ax = plt.figure().subplots()\n p._attach(ax)\n assert_array_equal(p.comp_data[\"x\"], comp_data)"},{"col":4,"comment":"null","endLoc":1341,"header":"def test_comp_data_duplicate_index(self)","id":4744,"name":"test_comp_data_duplicate_index","nodeType":"Function","startLoc":1335,"text":"def test_comp_data_duplicate_index(self):\n\n x = pd.Series([1, 2, 3, 4, 5], [1, 1, 1, 2, 2])\n p = VectorPlotter(variables={\"x\": x})\n ax = plt.figure().subplots()\n p._attach(ax)\n assert_array_equal(p.comp_data[\"x\"], x)"},{"col":4,"comment":"null","endLoc":1352,"header":"def test_var_order(self, long_df)","id":4745,"name":"test_var_order","nodeType":"Function","startLoc":1343,"text":"def test_var_order(self, long_df):\n\n order = [\"c\", \"b\", \"a\"]\n for var in [\"hue\", \"size\", \"style\"]:\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\", var: \"a\"})\n\n mapper = getattr(p, f\"map_{var}\")\n mapper(order=order)\n\n assert p.var_levels[var] == order"},{"col":4,"comment":"null","endLoc":1687,"header":"def test_supplied_color_array(self, long_df)","id":4746,"name":"test_supplied_color_array","nodeType":"Function","startLoc":1665,"text":"def test_supplied_color_array(self, long_df):\n\n cmap = get_colormap(\"Blues\")\n norm = mpl.colors.Normalize()\n colors = cmap(norm(long_df[\"y\"].to_numpy()))\n\n keys = [\"c\", \"facecolor\", \"facecolors\"]\n\n if Version(mpl.__version__) >= Version(\"3.1.0\"):\n # https://github.com/matplotlib/matplotlib/pull/12851\n keys.append(\"fc\")\n\n for key in keys:\n\n ax = plt.figure().subplots()\n self.func(x=long_df[\"y\"], **{key: colors})\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)\n\n ax = plt.figure().subplots()\n self.func(x=long_df[\"y\"], c=long_df[\"y\"], cmap=cmap)\n _draw_figure(ax.figure)\n assert_array_equal(ax.collections[0].get_facecolors(), colors)"},{"col":4,"comment":"null","endLoc":1358,"header":"def test_scale_native(self, long_df)","id":4747,"name":"test_scale_native","nodeType":"Function","startLoc":1354,"text":"def test_scale_native(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n with pytest.raises(NotImplementedError):\n p.scale_native(\"x\")"},{"col":4,"comment":"null","endLoc":1364,"header":"def test_scale_numeric(self, long_df)","id":4748,"name":"test_scale_numeric","nodeType":"Function","startLoc":1360,"text":"def test_scale_numeric(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"y\": \"y\"})\n with pytest.raises(NotImplementedError):\n p.scale_numeric(\"y\")"},{"col":4,"comment":"null","endLoc":1370,"header":"def test_scale_datetime(self, long_df)","id":4749,"name":"test_scale_datetime","nodeType":"Function","startLoc":1366,"text":"def test_scale_datetime(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"t\"})\n with pytest.raises(NotImplementedError):\n p.scale_datetime(\"x\")"},{"col":4,"comment":"null","endLoc":1407,"header":"def test_scale_categorical(self, long_df)","id":4750,"name":"test_scale_categorical","nodeType":"Function","startLoc":1372,"text":"def test_scale_categorical(self, long_df):\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"x\"})\n p.scale_categorical(\"y\")\n assert p.variables[\"y\"] is None\n assert p.var_types[\"y\"] == \"categorical\"\n assert (p.plot_data[\"y\"] == \"\").all()\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"s\"})\n p.scale_categorical(\"x\")\n assert p.var_types[\"x\"] == \"categorical\"\n assert hasattr(p.plot_data[\"x\"], \"str\")\n assert not p._var_ordered[\"x\"]\n assert p.plot_data[\"x\"].is_monotonic_increasing\n assert_array_equal(p.var_levels[\"x\"], p.plot_data[\"x\"].unique())\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n p.scale_categorical(\"x\")\n assert not p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], categorical_order(long_df[\"a\"]))\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a_cat\"})\n p.scale_categorical(\"x\")\n assert p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], categorical_order(long_df[\"a_cat\"]))\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"a\"})\n order = np.roll(long_df[\"a\"].unique(), 1)\n p.scale_categorical(\"x\", order=order)\n assert p._var_ordered[\"x\"]\n assert_array_equal(p.var_levels[\"x\"], order)\n\n p = VectorPlotter(data=long_df, variables={\"x\": \"s\"})\n p.scale_categorical(\"x\", formatter=lambda x: f\"{x:%}\")\n assert p.plot_data[\"x\"].str.endswith(\"%\").all()\n assert all(s.endswith(\"%\") for s in p.var_levels[\"x\"])"},{"col":43,"endLoc":1405,"id":4751,"nodeType":"Lambda","startLoc":1405,"text":"lambda x: f\"{x:%}\""},{"col":4,"comment":"null","endLoc":1720,"header":"@pytest.mark.parametrize(\n \"orient,data_type\",\n itertools.product([\"h\", \"v\"], [\"dataframe\", \"dict\"]),\n )\n def test_wide(self, wide_df, orient, data_type)","id":4752,"name":"test_wide","nodeType":"Function","startLoc":1689,"text":"@pytest.mark.parametrize(\n \"orient,data_type\",\n itertools.product([\"h\", \"v\"], [\"dataframe\", \"dict\"]),\n )\n def test_wide(self, wide_df, orient, data_type):\n\n if data_type == \"dict\":\n wide_df = {k: v.to_numpy() for k, v in wide_df.items()}\n\n ax = self.func(data=wide_df, orient=orient)\n _draw_figure(ax.figure)\n palette = color_palette()\n\n cat_idx = 0 if orient == \"v\" else 1\n val_idx = int(not cat_idx)\n\n axis_objs = ax.xaxis, ax.yaxis\n cat_axis = axis_objs[cat_idx]\n\n for i, label in enumerate(cat_axis.get_majorticklabels()):\n\n key = label.get_text()\n points = ax.collections[i]\n point_pos = points.get_offsets().T\n val_pos = point_pos[val_idx]\n cat_pos = point_pos[cat_idx]\n\n assert_array_equal(cat_pos.round(), i)\n assert_array_equal(val_pos, wide_df[key])\n\n for point_color in points.get_facecolors():\n assert tuple(point_color) == to_rgba(palette[i])"},{"className":"TestCoreFunc","col":0,"comment":"null","endLoc":1556,"id":4753,"nodeType":"Class","startLoc":1410,"text":"class TestCoreFunc:\n\n def test_unique_dashes(self):\n\n n = 24\n dashes = unique_dashes(n)\n\n assert len(dashes) == n\n assert len(set(dashes)) == n\n assert dashes[0] == \"\"\n for spec in dashes[1:]:\n assert isinstance(spec, tuple)\n assert not len(spec) % 2\n\n def test_unique_markers(self):\n\n n = 24\n markers = unique_markers(n)\n\n assert len(markers) == n\n assert len(set(markers)) == n\n for m in markers:\n assert mpl.markers.MarkerStyle(m).is_filled()\n\n def test_variable_type(self):\n\n s = pd.Series([1., 2., 3.])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s.astype(int)) == \"numeric\"\n assert variable_type(s.astype(object)) == \"numeric\"\n assert variable_type(s.to_numpy()) == \"numeric\"\n assert variable_type(s.to_list()) == \"numeric\"\n\n s = pd.Series([1, 2, 3, np.nan], dtype=object)\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([np.nan, np.nan])\n # s = pd.Series([pd.NA, pd.NA])\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([\"1\", \"2\", \"3\"])\n assert variable_type(s) == \"categorical\"\n assert variable_type(s.to_numpy()) == \"categorical\"\n assert variable_type(s.to_list()) == \"categorical\"\n\n s = pd.Series([True, False, False])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s, boolean_type=\"categorical\") == \"categorical\"\n s_cat = s.astype(\"category\")\n assert variable_type(s_cat, boolean_type=\"categorical\") == \"categorical\"\n assert variable_type(s_cat, boolean_type=\"numeric\") == \"categorical\"\n\n s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])\n assert variable_type(s) == \"datetime\"\n assert variable_type(s.astype(object)) == \"datetime\"\n assert variable_type(s.to_numpy()) == \"datetime\"\n assert variable_type(s.to_list()) == \"datetime\"\n\n def test_infer_orient(self):\n\n nums = pd.Series(np.arange(6))\n cats = pd.Series([\"a\", \"b\"] * 3)\n dates = pd.date_range(\"1999-09-22\", \"2006-05-14\", 6)\n\n assert infer_orient(cats, nums) == \"v\"\n assert infer_orient(nums, cats) == \"h\"\n\n assert infer_orient(cats, dates, require_numeric=False) == \"v\"\n assert infer_orient(dates, cats, require_numeric=False) == \"h\"\n\n assert infer_orient(nums, None) == \"h\"\n with pytest.warns(UserWarning, match=\"Vertical .+ `x`\"):\n assert infer_orient(nums, None, \"v\") == \"h\"\n\n assert infer_orient(None, nums) == \"v\"\n with pytest.warns(UserWarning, match=\"Horizontal .+ `y`\"):\n assert infer_orient(None, nums, \"h\") == \"v\"\n\n infer_orient(cats, None, require_numeric=False) == \"h\"\n with pytest.raises(TypeError, match=\"Horizontal .+ `x`\"):\n infer_orient(cats, None)\n\n infer_orient(cats, None, require_numeric=False) == \"v\"\n with pytest.raises(TypeError, match=\"Vertical .+ `y`\"):\n infer_orient(None, cats)\n\n assert infer_orient(nums, nums, \"vert\") == \"v\"\n assert infer_orient(nums, nums, \"hori\") == \"h\"\n\n assert infer_orient(cats, cats, \"h\", require_numeric=False) == \"h\"\n assert infer_orient(cats, cats, \"v\", require_numeric=False) == \"v\"\n assert infer_orient(cats, cats, require_numeric=False) == \"v\"\n\n with pytest.raises(TypeError, match=\"Vertical .+ `y`\"):\n infer_orient(cats, cats, \"v\")\n with pytest.raises(TypeError, match=\"Horizontal .+ `x`\"):\n infer_orient(cats, cats, \"h\")\n with pytest.raises(TypeError, match=\"Neither\"):\n infer_orient(cats, cats)\n\n with pytest.raises(ValueError, match=\"`orient` must start with\"):\n infer_orient(cats, nums, orient=\"bad value\")\n\n def test_categorical_order(self):\n\n x = [\"a\", \"c\", \"c\", \"b\", \"a\", \"d\"]\n y = [3, 2, 5, 1, 4]\n order = [\"a\", \"b\", \"c\", \"d\"]\n\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(x, order)\n assert out == order\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n out = categorical_order(np.array(x))\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(pd.Series(x))\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(y)\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(np.array(y))\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(pd.Series(y))\n assert out == [1, 2, 3, 4, 5]\n\n x = pd.Categorical(x, order)\n out = categorical_order(x)\n assert out == list(x.categories)\n\n x = pd.Series(x)\n out = categorical_order(x)\n assert out == list(x.cat.categories)\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n x = [\"a\", np.nan, \"c\", \"c\", \"b\", \"a\", \"d\"]\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]"},{"col":4,"comment":"null","endLoc":1422,"header":"def test_unique_dashes(self)","id":4754,"name":"test_unique_dashes","nodeType":"Function","startLoc":1412,"text":"def test_unique_dashes(self):\n\n n = 24\n dashes = unique_dashes(n)\n\n assert len(dashes) == n\n assert len(set(dashes)) == n\n assert dashes[0] == \"\"\n for spec in dashes[1:]:\n assert isinstance(spec, tuple)\n assert not len(spec) % 2"},{"col":4,"comment":"null","endLoc":1473,"header":"@pytest.mark.parametrize(\"variables\", [(\"rows\", \"y\"), (\"columns\", \"x\")])\n def test_error_on_facet_overlap(self, long_df, variables)","id":4755,"name":"test_error_on_facet_overlap","nodeType":"Function","startLoc":1466,"text":"@pytest.mark.parametrize(\"variables\", [(\"rows\", \"y\"), (\"columns\", \"x\")])\n def test_error_on_facet_overlap(self, long_df, variables):\n\n facet_dim, pair_axis = variables\n p = Plot(long_df).facet(**{facet_dim[:3]: \"a\"}).pair(**{pair_axis: [\"x\", \"y\"]})\n expected = f\"Cannot facet the {facet_dim} while pairing on `{pair_axis}`.\"\n with pytest.raises(RuntimeError, match=expected):\n p.plot()"},{"col":4,"comment":"null","endLoc":1486,"header":"@pytest.mark.parametrize(\"variables\", [(\"columns\", \"y\"), (\"rows\", \"x\")])\n def test_error_on_wrap_overlap(self, long_df, variables)","id":4756,"name":"test_error_on_wrap_overlap","nodeType":"Function","startLoc":1475,"text":"@pytest.mark.parametrize(\"variables\", [(\"columns\", \"y\"), (\"rows\", \"x\")])\n def test_error_on_wrap_overlap(self, long_df, variables):\n\n facet_dim, pair_axis = variables\n p = (\n Plot(long_df)\n .facet(wrap=2, **{facet_dim[:3]: \"a\"})\n .pair(**{pair_axis: [\"x\", \"y\"]})\n )\n expected = f\"Cannot wrap the {facet_dim} while pairing on `{pair_axis}``.\"\n with pytest.raises(RuntimeError, match=expected):\n p.plot()"},{"col":4,"comment":"null","endLoc":1432,"header":"def test_unique_markers(self)","id":4757,"name":"test_unique_markers","nodeType":"Function","startLoc":1424,"text":"def test_unique_markers(self):\n\n n = 24\n markers = unique_markers(n)\n\n assert len(markers) == n\n assert len(set(markers)) == n\n for m in markers:\n assert mpl.markers.MarkerStyle(m).is_filled()"},{"col":4,"comment":"null","endLoc":1512,"header":"def test_axis_sharing(self, long_df)","id":4758,"name":"test_axis_sharing","nodeType":"Function","startLoc":1488,"text":"def test_axis_sharing(self, long_df):\n\n p = Plot(long_df).pair(x=[\"a\", \"b\"], y=[\"y\", \"z\"])\n shape = 2, 2\n\n p1 = p.plot()\n axes_matrix = np.reshape(p1._figure.axes, shape)\n\n for root, *other in axes_matrix: # Test row-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert not any(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n for root, *other in axes_matrix.T: # Test col-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert all(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert not any(y_shareset.joined(root, ax) for ax in other)\n\n p2 = p.share(x=False, y=False).plot()\n root, *other = p2._figure.axes\n for axis in \"xy\":\n shareset = getattr(root, f\"get_shared_{axis}_axes\")()\n assert not any(shareset.joined(root, ax) for ax in other)"},{"col":4,"comment":"null","endLoc":1466,"header":"def test_variable_type(self)","id":4759,"name":"test_variable_type","nodeType":"Function","startLoc":1434,"text":"def test_variable_type(self):\n\n s = pd.Series([1., 2., 3.])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s.astype(int)) == \"numeric\"\n assert variable_type(s.astype(object)) == \"numeric\"\n assert variable_type(s.to_numpy()) == \"numeric\"\n assert variable_type(s.to_list()) == \"numeric\"\n\n s = pd.Series([1, 2, 3, np.nan], dtype=object)\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([np.nan, np.nan])\n # s = pd.Series([pd.NA, pd.NA])\n assert variable_type(s) == \"numeric\"\n\n s = pd.Series([\"1\", \"2\", \"3\"])\n assert variable_type(s) == \"categorical\"\n assert variable_type(s.to_numpy()) == \"categorical\"\n assert variable_type(s.to_list()) == \"categorical\"\n\n s = pd.Series([True, False, False])\n assert variable_type(s) == \"numeric\"\n assert variable_type(s, boolean_type=\"categorical\") == \"categorical\"\n s_cat = s.astype(\"category\")\n assert variable_type(s_cat, boolean_type=\"categorical\") == \"categorical\"\n assert variable_type(s_cat, boolean_type=\"numeric\") == \"categorical\"\n\n s = pd.Series([pd.Timestamp(1), pd.Timestamp(2)])\n assert variable_type(s) == \"datetime\"\n assert variable_type(s.astype(object)) == \"datetime\"\n assert variable_type(s.to_numpy()) == \"datetime\"\n assert variable_type(s.to_list()) == \"datetime\""},{"col":4,"comment":"null","endLoc":1511,"header":"def test_infer_orient(self)","id":4760,"name":"test_infer_orient","nodeType":"Function","startLoc":1468,"text":"def test_infer_orient(self):\n\n nums = pd.Series(np.arange(6))\n cats = pd.Series([\"a\", \"b\"] * 3)\n dates = pd.date_range(\"1999-09-22\", \"2006-05-14\", 6)\n\n assert infer_orient(cats, nums) == \"v\"\n assert infer_orient(nums, cats) == \"h\"\n\n assert infer_orient(cats, dates, require_numeric=False) == \"v\"\n assert infer_orient(dates, cats, require_numeric=False) == \"h\"\n\n assert infer_orient(nums, None) == \"h\"\n with pytest.warns(UserWarning, match=\"Vertical .+ `x`\"):\n assert infer_orient(nums, None, \"v\") == \"h\"\n\n assert infer_orient(None, nums) == \"v\"\n with pytest.warns(UserWarning, match=\"Horizontal .+ `y`\"):\n assert infer_orient(None, nums, \"h\") == \"v\"\n\n infer_orient(cats, None, require_numeric=False) == \"h\"\n with pytest.raises(TypeError, match=\"Horizontal .+ `x`\"):\n infer_orient(cats, None)\n\n infer_orient(cats, None, require_numeric=False) == \"v\"\n with pytest.raises(TypeError, match=\"Vertical .+ `y`\"):\n infer_orient(None, cats)\n\n assert infer_orient(nums, nums, \"vert\") == \"v\"\n assert infer_orient(nums, nums, \"hori\") == \"h\"\n\n assert infer_orient(cats, cats, \"h\", require_numeric=False) == \"h\"\n assert infer_orient(cats, cats, \"v\", require_numeric=False) == \"v\"\n assert infer_orient(cats, cats, require_numeric=False) == \"v\"\n\n with pytest.raises(TypeError, match=\"Vertical .+ `y`\"):\n infer_orient(cats, cats, \"v\")\n with pytest.raises(TypeError, match=\"Horizontal .+ `x`\"):\n infer_orient(cats, cats, \"h\")\n with pytest.raises(TypeError, match=\"Neither\"):\n infer_orient(cats, cats)\n\n with pytest.raises(ValueError, match=\"`orient` must start with\"):\n infer_orient(cats, nums, orient=\"bad value\")"},{"col":4,"comment":"null","endLoc":1556,"header":"def test_categorical_order(self)","id":4761,"name":"test_categorical_order","nodeType":"Function","startLoc":1513,"text":"def test_categorical_order(self):\n\n x = [\"a\", \"c\", \"c\", \"b\", \"a\", \"d\"]\n y = [3, 2, 5, 1, 4]\n order = [\"a\", \"b\", \"c\", \"d\"]\n\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(x, order)\n assert out == order\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n out = categorical_order(np.array(x))\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(pd.Series(x))\n assert out == [\"a\", \"c\", \"b\", \"d\"]\n\n out = categorical_order(y)\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(np.array(y))\n assert out == [1, 2, 3, 4, 5]\n\n out = categorical_order(pd.Series(y))\n assert out == [1, 2, 3, 4, 5]\n\n x = pd.Categorical(x, order)\n out = categorical_order(x)\n assert out == list(x.categories)\n\n x = pd.Series(x)\n out = categorical_order(x)\n assert out == list(x.cat.categories)\n\n out = categorical_order(x, [\"b\", \"a\"])\n assert out == [\"b\", \"a\"]\n\n x = [\"a\", np.nan, \"c\", \"c\", \"b\", \"a\", \"d\"]\n out = categorical_order(x)\n assert out == [\"a\", \"c\", \"b\", \"d\"]"},{"col":4,"comment":"null","endLoc":1531,"header":"def test_axis_sharing_with_facets(self, long_df)","id":4762,"name":"test_axis_sharing_with_facets","nodeType":"Function","startLoc":1514,"text":"def test_axis_sharing_with_facets(self, long_df):\n\n p = Plot(long_df, y=\"y\").pair(x=[\"a\", \"b\"]).facet(row=\"c\").plot()\n shape = 2, 2\n\n axes_matrix = np.reshape(p._figure.axes, shape)\n\n for root, *other in axes_matrix: # Test row-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert not any(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)\n\n for root, *other in axes_matrix.T: # Test col-wise sharing\n x_shareset = getattr(root, \"get_shared_x_axes\")()\n assert all(x_shareset.joined(root, ax) for ax in other)\n y_shareset = getattr(root, \"get_shared_y_axes\")()\n assert all(y_shareset.joined(root, ax) for ax in other)"},{"col":0,"comment":"null","endLoc":50,"header":"@pytest.fixture(params=[\n dict(x=\"x\", y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"a\", y=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"a\"),\n dict(x=\"x\", y=\"y\", size=\"a\"),\n dict(x=\"x\", y=\"y\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"s\"),\n dict(x=\"x\", y=\"y\", size=\"s\"),\n dict(x=\"x\", y=\"y\", style=\"s\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", size=\"b\", style=\"b\"),\n])\ndef long_variables(request)","id":4763,"name":"long_variables","nodeType":"Function","startLoc":35,"text":"@pytest.fixture(params=[\n dict(x=\"x\", y=\"y\"),\n dict(x=\"t\", y=\"y\"),\n dict(x=\"a\", y=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"y\"),\n dict(x=\"x\", y=\"y\", hue=\"a\"),\n dict(x=\"x\", y=\"y\", size=\"a\"),\n dict(x=\"x\", y=\"y\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"s\"),\n dict(x=\"x\", y=\"y\", size=\"s\"),\n dict(x=\"x\", y=\"y\", style=\"s\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", style=\"a\"),\n dict(x=\"x\", y=\"y\", hue=\"a\", size=\"b\", style=\"b\"),\n])\ndef long_variables(request):\n return request.param"},{"col":4,"comment":"null","endLoc":1735,"header":"@pytest.mark.parametrize(\"orient\", [\"h\", \"v\"])\n def test_flat(self, flat_series, orient)","id":4764,"name":"test_flat","nodeType":"Function","startLoc":1722,"text":"@pytest.mark.parametrize(\"orient\", [\"h\", \"v\"])\n def test_flat(self, flat_series, orient):\n\n ax = self.func(data=flat_series, orient=orient)\n _draw_figure(ax.figure)\n\n cat_idx = [\"v\", \"h\"].index(orient)\n val_idx = int(not cat_idx)\n\n points = ax.collections[0]\n pos = points.get_offsets().T\n\n assert_array_equal(pos[cat_idx].round(), np.zeros(len(flat_series)))\n assert_array_equal(pos[val_idx], flat_series)"},{"col":4,"comment":"null","endLoc":1544,"header":"def test_x_wrapping(self, long_df)","id":4765,"name":"test_x_wrapping","nodeType":"Function","startLoc":1533,"text":"def test_x_wrapping(self, long_df):\n\n x_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n p = Plot(long_df, y=\"y\").pair(x=x_vars, wrap=wrap).plot()\n\n assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)\n assert len(p._figure.axes) == len(x_vars)\n for ax, var in zip(p._figure.axes, x_vars):\n label = ax.xaxis.get_label()\n assert label.get_visible()\n assert label.get_text() == var"},{"col":4,"comment":"null","endLoc":1796,"header":"@pytest.mark.parametrize(\n \"variables,orient\",\n [\n # Order matters for assigning to x/y\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\"","id":4766,"name":"test_positions","nodeType":"Function","startLoc":1737,"text":"@pytest.mark.parametrize(\n \"variables,orient\",\n [\n # Order matters for assigning to x/y\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": None}, None),\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": \"a\"}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": \"a\"}, None),\n ({\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"}, None),\n ({\"val\": \"y\", \"cat\": \"a\", \"hue\": \"x\"}, None),\n ({\"cat\": \"s\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"s\", \"hue\": None}, \"h\"),\n ({\"cat\": \"a\", \"val\": \"b\", \"hue\": None}, None),\n ({\"val\": \"a\", \"cat\": \"b\", \"hue\": None}, \"h\"),\n ({\"cat\": \"a\", \"val\": \"t\", \"hue\": None}, None),\n ({\"val\": \"t\", \"cat\": \"a\", \"hue\": None}, None),\n ({\"cat\": \"d\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"d\", \"hue\": None}, None),\n ({\"cat\": \"a_cat\", \"val\": \"y\", \"hue\": None}, None),\n ({\"val\": \"y\", \"cat\": \"s_cat\", \"hue\": None}, None),\n ],\n )\n def test_positions(self, long_df, variables, orient):\n\n cat_var = variables[\"cat\"]\n val_var = variables[\"val\"]\n hue_var = variables[\"hue\"]\n var_names = list(variables.values())\n x_var, y_var, *_ = var_names\n\n ax = self.func(\n data=long_df, x=x_var, y=y_var, hue=hue_var, orient=orient,\n )\n\n _draw_figure(ax.figure)\n\n cat_idx = var_names.index(cat_var)\n val_idx = var_names.index(val_var)\n\n axis_objs = ax.xaxis, ax.yaxis\n cat_axis = axis_objs[cat_idx]\n val_axis = axis_objs[val_idx]\n\n cat_data = long_df[cat_var]\n cat_levels = categorical_order(cat_data)\n\n for i, label in enumerate(cat_levels):\n\n vals = long_df.loc[cat_data == label, val_var]\n\n points = ax.collections[i].get_offsets().T\n cat_pos = points[var_names.index(cat_var)]\n val_pos = points[var_names.index(val_var)]\n\n assert_array_equal(val_pos, val_axis.convert_units(vals))\n assert_array_equal(cat_pos.round(), i)\n assert 0 <= np.ptp(cat_pos) <= .8\n\n label = pd.Index([label]).astype(str)[0]\n assert cat_axis.get_majorticklabels()[i].get_text() == label"},{"col":0,"comment":"","endLoc":1,"header":"test_core.py#","id":4767,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n from pandas import NA as PD_NA\nexcept ImportError:\n PD_NA = None"},{"col":4,"comment":"null","endLoc":1562,"header":"def test_y_wrapping(self, long_df)","id":4768,"name":"test_y_wrapping","nodeType":"Function","startLoc":1546,"text":"def test_y_wrapping(self, long_df):\n\n y_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n p = Plot(long_df, x=\"x\").pair(y=y_vars, wrap=wrap).plot()\n\n n_row, n_col = wrap, len(y_vars) // wrap + 1\n assert_gridspec_shape(p._figure.axes[0], n_row, n_col)\n assert len(p._figure.axes) == len(y_vars)\n label_array = np.empty(n_row * n_col, object)\n label_array[:len(y_vars)] = y_vars\n label_array = label_array.reshape((n_row, n_col), order=\"F\")\n label_array = [y for y in label_array.flat if y is not None]\n for i, ax in enumerate(p._figure.axes):\n label = ax.yaxis.get_label()\n assert label.get_visible()\n assert label.get_text() == label_array[i]"},{"col":4,"comment":"null","endLoc":1577,"header":"def test_non_cross_wrapping(self, long_df)","id":4769,"name":"test_non_cross_wrapping","nodeType":"Function","startLoc":1564,"text":"def test_non_cross_wrapping(self, long_df):\n\n x_vars = [\"a\", \"b\", \"c\", \"t\"]\n y_vars = [\"f\", \"x\", \"y\", \"z\"]\n wrap = 3\n\n p = (\n Plot(long_df, x=\"x\")\n .pair(x=x_vars, y=y_vars, wrap=wrap, cross=False)\n .plot()\n )\n\n assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)\n assert len(p._figure.axes) == len(x_vars)"},{"col":4,"comment":"null","endLoc":1583,"header":"def test_cross_mismatched_lengths(self, long_df)","id":4770,"name":"test_cross_mismatched_lengths","nodeType":"Function","startLoc":1579,"text":"def test_cross_mismatched_lengths(self, long_df):\n\n p = Plot(long_df)\n with pytest.raises(ValueError, match=\"Lengths of the `x` and `y`\"):\n p.pair(x=[\"a\", \"b\"], y=[\"x\", \"y\", \"z\"], cross=False)"},{"col":4,"comment":"null","endLoc":1843,"header":"@pytest.mark.parametrize(\n \"variables\",\n [\n # Order matters for assigning to x/y\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"},\n {\"val\": \"y\", \"cat\": \"a\", \"hue\": \"c\"},\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"f\"},\n ],\n )\n def test_positions_dodged(self, long_df, variables)","id":4771,"name":"test_positions_dodged","nodeType":"Function","startLoc":1798,"text":"@pytest.mark.parametrize(\n \"variables\",\n [\n # Order matters for assigning to x/y\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"b\"},\n {\"val\": \"y\", \"cat\": \"a\", \"hue\": \"c\"},\n {\"cat\": \"a\", \"val\": \"y\", \"hue\": \"f\"},\n ],\n )\n def test_positions_dodged(self, long_df, variables):\n\n cat_var = variables[\"cat\"]\n val_var = variables[\"val\"]\n hue_var = variables[\"hue\"]\n var_names = list(variables.values())\n x_var, y_var, *_ = var_names\n\n ax = self.func(\n data=long_df, x=x_var, y=y_var, hue=hue_var, dodge=True,\n )\n\n cat_vals = categorical_order(long_df[cat_var])\n hue_vals = categorical_order(long_df[hue_var])\n\n n_hue = len(hue_vals)\n offsets = np.linspace(0, .8, n_hue + 1)[:-1]\n offsets -= offsets.mean()\n nest_width = .8 / n_hue\n\n for i, cat_val in enumerate(cat_vals):\n for j, hue_val in enumerate(hue_vals):\n rows = (long_df[cat_var] == cat_val) & (long_df[hue_var] == hue_val)\n vals = long_df.loc[rows, val_var]\n\n points = ax.collections[n_hue * i + j].get_offsets().T\n cat_pos = points[var_names.index(cat_var)]\n val_pos = points[var_names.index(val_var)]\n\n if pd.api.types.is_datetime64_any_dtype(vals):\n vals = mpl.dates.date2num(vals)\n\n assert_array_equal(val_pos, vals)\n\n assert_array_equal(cat_pos.round(), i)\n assert_array_equal((cat_pos - (i + offsets[j])).round() / nest_width, 0)\n assert 0 <= np.ptp(cat_pos) <= nest_width"},{"col":4,"comment":"null","endLoc":1601,"header":"def test_orient_inference(self, long_df)","id":4772,"name":"test_orient_inference","nodeType":"Function","startLoc":1585,"text":"def test_orient_inference(self, long_df):\n\n orient_list = []\n\n class CaptureOrientMove(Move):\n def __call__(self, data, groupby, orient, scales):\n orient_list.append(orient)\n return data\n\n (\n Plot(long_df, x=\"x\")\n .pair(y=[\"b\", \"z\"])\n .add(MockMark(), CaptureOrientMove())\n .plot()\n )\n\n assert orient_list == [\"y\", \"x\"]"},{"col":4,"comment":"null","endLoc":1612,"header":"def test_computed_coordinate_orient_inference(self, long_df)","id":4773,"name":"test_computed_coordinate_orient_inference","nodeType":"Function","startLoc":1603,"text":"def test_computed_coordinate_orient_inference(self, long_df):\n\n class MockComputeStat(Stat):\n def __call__(self, df, groupby, orient, scales):\n other = {\"x\": \"y\", \"y\": \"x\"}[orient]\n return df.assign(**{other: df[orient] * 2})\n\n m = MockMark()\n Plot(long_df, y=\"y\").add(m, MockComputeStat()).plot()\n assert m.passed_orient == \"y\""},{"col":4,"comment":"null","endLoc":1619,"header":"def test_two_variables_single_order_error(self, long_df)","id":4774,"name":"test_two_variables_single_order_error","nodeType":"Function","startLoc":1614,"text":"def test_two_variables_single_order_error(self, long_df):\n\n p = Plot(long_df)\n err = \"When faceting on both col= and row=, passing `order`\"\n with pytest.raises(RuntimeError, match=err):\n p.facet(col=\"a\", row=\"b\", order=[\"a\", \"b\", \"c\"])"},{"col":4,"comment":"null","endLoc":1626,"header":"def test_limits(self, long_df)","id":4775,"name":"test_limits","nodeType":"Function","startLoc":1621,"text":"def test_limits(self, long_df):\n\n limit = (-2, 24)\n p = Plot(long_df, y=\"y\").pair(x=[\"x\", \"z\"]).limit(x1=limit).plot()\n ax1 = p._figure.axes[1]\n assert ax1.get_xlim() == limit"},{"col":4,"comment":"null","endLoc":1633,"header":"def test_labels(self, long_df)","id":4776,"name":"test_labels","nodeType":"Function","startLoc":1628,"text":"def test_labels(self, long_df):\n\n label = \"Z\"\n p = Plot(long_df, y=\"y\").pair(x=[\"x\", \"z\"]).label(x1=label).plot()\n ax1 = p._figure.axes[1]\n assert ax1.get_xlabel() == label"},{"className":"TestLabelVisibility","col":0,"comment":"null","endLoc":1810,"id":4777,"nodeType":"Class","startLoc":1636,"text":"class TestLabelVisibility:\n\n def test_single_subplot(self, long_df):\n\n x, y = \"a\", \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n subplot, *_ = p._subplots\n ax = subplot[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n @pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"col\": \"b\"}, {}), ({}, {\"x\": [\"x\", \"y\", \"f\"]})]\n )\n def test_1d_column(self, long_df, facet_kws, pair_kws):\n\n x = None if \"x\" in pair_kws else \"a\"\n y = \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n first, *other = p._subplots\n\n ax = first[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in other:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert not ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n @pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"row\": \"b\"}, {}), ({}, {\"y\": [\"x\", \"y\", \"f\"]})]\n )\n def test_1d_row(self, long_df, facet_kws, pair_kws):\n\n x = \"z\"\n y = None if \"y\" in pair_kws else \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n first, *other = p._subplots\n\n ax = first[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in other:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n def test_1d_column_wrapped(self):\n\n p = Plot().facet(col=[\"a\", \"b\", \"c\", \"d\"], wrap=3).plot()\n subplots = list(p._subplots)\n\n for s in [subplots[0], subplots[-1]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in subplots[1:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[1:-1]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n ax = subplots[0][\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n def test_1d_row_wrapped(self):\n\n p = Plot().facet(row=[\"a\", \"b\", \"c\", \"d\"], wrap=3).plot()\n subplots = list(p._subplots)\n\n for s in subplots[:-1]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in subplots[-2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[:-2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n ax = subplots[-1][\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n def test_1d_column_wrapped_non_cross(self, long_df):\n\n p = (\n Plot(long_df)\n .pair(x=[\"a\", \"b\", \"c\"], y=[\"x\", \"y\", \"z\"], wrap=2, cross=False)\n .plot()\n )\n for s in p._subplots:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n def test_2d(self):\n\n p = Plot().facet(col=[\"a\", \"b\"], row=[\"x\", \"y\"]).plot()\n subplots = list(p._subplots)\n\n for s in subplots[:2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in [subplots[0], subplots[2]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in [subplots[1], subplots[3]]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n def test_2d_unshared(self):\n\n p = (\n Plot()\n .facet(col=[\"a\", \"b\"], row=[\"x\", \"y\"])\n .share(x=False, y=False)\n .plot()\n )\n subplots = list(p._subplots)\n\n for s in subplots[:2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in [subplots[0], subplots[2]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in [subplots[1], subplots[3]]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1647,"header":"def test_single_subplot(self, long_df)","id":4778,"name":"test_single_subplot","nodeType":"Function","startLoc":1638,"text":"def test_single_subplot(self, long_df):\n\n x, y = \"a\", \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n subplot, *_ = p._subplots\n ax = subplot[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1865,"header":"@pytest.mark.parametrize(\"cat_var\", [\"a\", \"s\", \"d\"])\n def test_positions_unfixed(self, long_df, cat_var)","id":4779,"name":"test_positions_unfixed","nodeType":"Function","startLoc":1845,"text":"@pytest.mark.parametrize(\"cat_var\", [\"a\", \"s\", \"d\"])\n def test_positions_unfixed(self, long_df, cat_var):\n\n long_df = long_df.sort_values(cat_var)\n\n kws = dict(size=.001)\n if \"stripplot\" in str(self.func): # can't use __name__ with partial\n kws[\"jitter\"] = False\n\n ax = self.func(data=long_df, x=cat_var, y=\"y\", native_scale=True, **kws)\n\n for i, (cat_level, cat_data) in enumerate(long_df.groupby(cat_var)):\n\n points = ax.collections[i].get_offsets().T\n cat_pos = points[0]\n val_pos = points[1]\n\n assert_array_equal(val_pos, cat_data[\"y\"])\n\n comp_level = np.squeeze(ax.xaxis.convert_units(cat_level)).item()\n assert_array_equal(cat_pos.round(), comp_level)"},{"col":4,"comment":"null","endLoc":1670,"header":"@pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"col\": \"b\"}, {}), ({}, {\"x\"","id":4780,"name":"test_1d_column","nodeType":"Function","startLoc":1649,"text":"@pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"col\": \"b\"}, {}), ({}, {\"x\": [\"x\", \"y\", \"f\"]})]\n )\n def test_1d_column(self, long_df, facet_kws, pair_kws):\n\n x = None if \"x\" in pair_kws else \"a\"\n y = \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n first, *other = p._subplots\n\n ax = first[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in other:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert not ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert not any(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1693,"header":"@pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"row\": \"b\"}, {}), ({}, {\"y\"","id":4781,"name":"test_1d_row","nodeType":"Function","startLoc":1672,"text":"@pytest.mark.parametrize(\n \"facet_kws,pair_kws\", [({\"row\": \"b\"}, {}), ({}, {\"y\": [\"x\", \"y\", \"f\"]})]\n )\n def test_1d_row(self, long_df, facet_kws, pair_kws):\n\n x = \"z\"\n y = None if \"y\" in pair_kws else \"z\"\n p = Plot(long_df, x=x, y=y).plot()\n first, *other = p._subplots\n\n ax = first[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in other:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n assert all(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1717,"header":"def test_1d_column_wrapped(self)","id":4782,"name":"test_1d_column_wrapped","nodeType":"Function","startLoc":1695,"text":"def test_1d_column_wrapped(self):\n\n p = Plot().facet(col=[\"a\", \"b\", \"c\", \"d\"], wrap=3).plot()\n subplots = list(p._subplots)\n\n for s in [subplots[0], subplots[-1]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in subplots[1:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[1:-1]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())\n\n ax = subplots[0][\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())"},{"col":4,"comment":"null","endLoc":1911,"header":"@pytest.mark.parametrize(\n \"x_type,order\",\n [\n (str, None),\n (str, [\"a\", \"b\", \"c\"]),\n (str, [\"c\", \"a\"]),\n (str, [\"a\", \"b\", \"c\", \"d\"]),\n (int, None),\n (int, [3, 1, 2]),\n (int, [3, 1]),\n (int, [1, 2, 3, 4]),\n (int, [\"3\", \"1\", \"2\"]),\n ]\n )\n def test_order(self, x_type, order)","id":4783,"name":"test_order","nodeType":"Function","startLoc":1867,"text":"@pytest.mark.parametrize(\n \"x_type,order\",\n [\n (str, None),\n (str, [\"a\", \"b\", \"c\"]),\n (str, [\"c\", \"a\"]),\n (str, [\"a\", \"b\", \"c\", \"d\"]),\n (int, None),\n (int, [3, 1, 2]),\n (int, [3, 1]),\n (int, [1, 2, 3, 4]),\n (int, [\"3\", \"1\", \"2\"]),\n ]\n )\n def test_order(self, x_type, order):\n\n if x_type is str:\n x = [\"b\", \"a\", \"c\"]\n else:\n x = [2, 1, 3]\n y = [1, 2, 3]\n\n ax = self.func(x=x, y=y, order=order)\n _draw_figure(ax.figure)\n\n if order is None:\n order = x\n if x_type is int:\n order = np.sort(order)\n\n assert len(ax.collections) == len(order)\n tick_labels = ax.xaxis.get_majorticklabels()\n\n assert ax.get_xlim()[1] == (len(order) - .5)\n\n for i, points in enumerate(ax.collections):\n cat = order[i]\n assert tick_labels[i].get_text() == str(cat)\n\n positions = points.get_offsets()\n if x_type(cat) in x:\n val = y[x.index(x_type(cat))]\n assert positions[0, 1] == val\n else:\n assert not positions.size"},{"col":4,"comment":"null","endLoc":1741,"header":"def test_1d_row_wrapped(self)","id":4784,"name":"test_1d_row_wrapped","nodeType":"Function","startLoc":1719,"text":"def test_1d_row_wrapped(self):\n\n p = Plot().facet(row=[\"a\", \"b\", \"c\", \"d\"], wrap=3).plot()\n subplots = list(p._subplots)\n\n for s in subplots[:-1]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in subplots[-2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[:-2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n ax = subplots[-1][\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1936,"header":"@pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_categorical(self, long_df, hue_var)","id":4785,"name":"test_hue_categorical","nodeType":"Function","startLoc":1913,"text":"@pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_categorical(self, long_df, hue_var):\n\n cat_var = \"b\"\n\n hue_levels = categorical_order(long_df[hue_var])\n cat_levels = categorical_order(long_df[cat_var])\n\n pal_name = \"muted\"\n palette = dict(zip(hue_levels, color_palette(pal_name)))\n ax = self.func(data=long_df, x=cat_var, y=\"y\", hue=hue_var, palette=pal_name)\n\n for i, level in enumerate(cat_levels):\n\n sub_df = long_df[long_df[cat_var] == level]\n point_hues = sub_df[hue_var]\n\n points = ax.collections[i]\n point_colors = points.get_facecolors()\n\n assert len(point_hues) == len(point_colors)\n\n for hue, color in zip(point_hues, point_colors):\n assert tuple(color) == to_rgba(palette[hue])"},{"col":4,"comment":"null","endLoc":1755,"header":"def test_1d_column_wrapped_non_cross(self, long_df)","id":4786,"name":"test_1d_column_wrapped_non_cross","nodeType":"Function","startLoc":1743,"text":"def test_1d_column_wrapped_non_cross(self, long_df):\n\n p = (\n Plot(long_df)\n .pair(x=[\"a\", \"b\", \"c\"], y=[\"x\", \"y\", \"z\"], wrap=2, cross=False)\n .plot()\n )\n for s in p._subplots:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1780,"header":"def test_2d(self)","id":4787,"name":"test_2d","nodeType":"Function","startLoc":1757,"text":"def test_2d(self):\n\n p = Plot().facet(col=[\"a\", \"b\"], row=[\"x\", \"y\"]).plot()\n subplots = list(p._subplots)\n\n for s in subplots[:2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in [subplots[0], subplots[2]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in [subplots[1], subplots[3]]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert not any(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":1953,"header":"@pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_dodged(self, long_df, hue_var)","id":4788,"name":"test_hue_dodged","nodeType":"Function","startLoc":1938,"text":"@pytest.mark.parametrize(\"hue_var\", [\"a\", \"b\"])\n def test_hue_dodged(self, long_df, hue_var):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=hue_var, dodge=True)\n colors = color_palette(n_colors=long_df[hue_var].nunique())\n collections = iter(ax.collections)\n\n # Slightly awkward logic to handle challenges of how the artists work.\n # e.g. there are empty scatter collections but the because facecolors\n # for the empty collections will return the default scatter color\n while colors:\n points = next(collections)\n if points.get_offsets().any():\n face_color = tuple(points.get_facecolors()[0])\n expected_color = to_rgba(colors.pop(0))\n assert face_color == expected_color"},{"col":4,"comment":"null","endLoc":1810,"header":"def test_2d_unshared(self)","id":4789,"name":"test_2d_unshared","nodeType":"Function","startLoc":1782,"text":"def test_2d_unshared(self):\n\n p = (\n Plot()\n .facet(col=[\"a\", \"b\"], row=[\"x\", \"y\"])\n .share(x=False, y=False)\n .plot()\n )\n subplots = list(p._subplots)\n\n for s in subplots[:2]:\n ax = s[\"ax\"]\n assert not ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in subplots[2:]:\n ax = s[\"ax\"]\n assert ax.xaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_xticklabels())\n\n for s in [subplots[0], subplots[2]]:\n ax = s[\"ax\"]\n assert ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())\n\n for s in [subplots[1], subplots[3]]:\n ax = s[\"ax\"]\n assert not ax.yaxis.get_label().get_visible()\n assert all(t.get_visible() for t in ax.get_yticklabels())"},{"col":4,"comment":"null","endLoc":2001,"header":"@pytest.mark.parametrize(\n \"val_var,val_col,hue_col\",\n list(itertools.product([\"x\", \"y\"], [\"b\", \"y\", \"t\"], [None, \"a\"])),\n )\n def test_single(self, long_df, val_var, val_col, hue_col)","id":4790,"name":"test_single","nodeType":"Function","startLoc":1955,"text":"@pytest.mark.parametrize(\n \"val_var,val_col,hue_col\",\n list(itertools.product([\"x\", \"y\"], [\"b\", \"y\", \"t\"], [None, \"a\"])),\n )\n def test_single(self, long_df, val_var, val_col, hue_col):\n\n var_kws = {val_var: val_col, \"hue\": hue_col}\n ax = self.func(data=long_df, **var_kws)\n _draw_figure(ax.figure)\n\n axis_vars = [\"x\", \"y\"]\n val_idx = axis_vars.index(val_var)\n cat_idx = int(not val_idx)\n cat_var = axis_vars[cat_idx]\n\n cat_axis = getattr(ax, f\"{cat_var}axis\")\n val_axis = getattr(ax, f\"{val_var}axis\")\n\n points = ax.collections[0]\n point_pos = points.get_offsets().T\n cat_pos = point_pos[cat_idx]\n val_pos = point_pos[val_idx]\n\n assert_array_equal(cat_pos.round(), 0)\n assert cat_pos.max() <= .4\n assert cat_pos.min() >= -.4\n\n num_vals = val_axis.convert_units(long_df[val_col])\n assert_array_equal(val_pos, num_vals)\n\n if hue_col is not None:\n palette = dict(zip(\n categorical_order(long_df[hue_col]), color_palette()\n ))\n\n facecolors = points.get_facecolors()\n for i, color in enumerate(facecolors):\n if hue_col is None:\n assert tuple(color) == to_rgba(\"C0\")\n else:\n hue_level = long_df.loc[i, hue_col]\n expected_color = palette[hue_level]\n assert tuple(color) == to_rgba(expected_color)\n\n ticklabels = cat_axis.get_majorticklabels()\n assert len(ticklabels) == 1\n assert not ticklabels[0].get_text()"},{"className":"TestLegend","col":0,"comment":"null","endLoc":2005,"id":4791,"nodeType":"Class","startLoc":1813,"text":"class TestLegend:\n\n @pytest.fixture\n def xy(self):\n return dict(x=[1, 2, 3, 4], y=[1, 2, 3, 4])\n\n def test_single_layer_single_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy).add(MockMark(), color=s).plot()\n e, = p._legend_contents\n\n labels = categorical_order(s)\n\n assert e[0] == (s.name, s.name)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [\"color\"]\n\n def test_single_layer_common_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n sem = dict(color=s, marker=s)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n e, = p._legend_contents\n\n labels = categorical_order(s)\n\n assert e[0] == (s.name, s.name)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == list(sem)\n\n def test_single_layer_common_unnamed_variable(self, xy):\n\n s = np.array([\"a\", \"b\", \"a\", \"c\"])\n sem = dict(color=s, marker=s)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n\n e, = p._legend_contents\n\n labels = list(np.unique(s)) # assumes sorted order\n\n assert e[0] == (\"\", id(s))\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == list(sem)\n\n def test_single_layer_multi_variable(self, xy):\n\n s1 = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s1\")\n s2 = pd.Series([\"m\", \"m\", \"p\", \"m\"], name=\"s2\")\n sem = dict(color=s1, marker=s2)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n e1, e2 = p._legend_contents\n\n variables = {v.name: k for k, v in sem.items()}\n\n for e, s in zip([e1, e2], [s1, s2]):\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [variables[s.name]]\n\n def test_multi_layer_single_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s).add(MockMark()).add(MockMark()).plot()\n e1, e2 = p._legend_contents\n\n labels = categorical_order(s)\n\n for e in [e1, e2]:\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [\"color\"]\n\n def test_multi_layer_multi_variable(self, xy):\n\n s1 = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s1\")\n s2 = pd.Series([\"m\", \"m\", \"p\", \"m\"], name=\"s2\")\n sem = dict(color=s1), dict(marker=s2)\n variables = {\"s1\": \"color\", \"s2\": \"marker\"}\n p = Plot(**xy).add(MockMark(), **sem[0]).add(MockMark(), **sem[1]).plot()\n e1, e2 = p._legend_contents\n\n for e, s in zip([e1, e2], [s1, s2]):\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [variables[s.name]]\n\n def test_multi_layer_different_artists(self, xy):\n\n class MockMark1(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.lines.Line2D([], [])\n\n class MockMark2(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.patches.Patch()\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s).add(MockMark1()).add(MockMark2()).plot()\n\n legend, = p._figure.legends\n\n names = categorical_order(s)\n labels = [t.get_text() for t in legend.get_texts()]\n assert labels == names\n\n if Version(mpl.__version__) >= Version(\"3.2\"):\n contents = legend.get_children()[0]\n assert len(contents.findobj(mpl.lines.Line2D)) == len(names)\n assert len(contents.findobj(mpl.patches.Patch)) == len(names)\n\n def test_three_layers(self, xy):\n\n class MockMarkLine(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.lines.Line2D([], [])\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s)\n for _ in range(3):\n p = p.add(MockMarkLine())\n p = p.plot()\n texts = p._figure.legends[0].get_texts()\n assert len(texts) == len(s.unique())\n\n def test_identity_scale_ignored(self, xy):\n\n s = pd.Series([\"r\", \"g\", \"b\", \"g\"])\n p = Plot(**xy).add(MockMark(), color=s).scale(color=None).plot()\n assert not p._legend_contents\n\n def test_suppression_in_add_method(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy).add(MockMark(), color=s, legend=False).plot()\n assert not p._legend_contents\n\n def test_anonymous_title(self, xy):\n\n p = Plot(**xy, color=[\"a\", \"b\", \"c\", \"d\"]).add(MockMark()).plot()\n legend, = p._figure.legends\n assert legend.get_title().get_text() == \"\"\n\n def test_legendless_mark(self, xy):\n\n class NoLegendMark(MockMark):\n def _legend_artist(self, variables, value, scales):\n return None\n\n p = Plot(**xy, color=[\"a\", \"b\", \"c\", \"d\"]).add(NoLegendMark()).plot()\n assert not p._figure.legends"},{"col":4,"comment":"null","endLoc":1817,"header":"@pytest.fixture\n def xy(self)","id":4792,"name":"xy","nodeType":"Function","startLoc":1815,"text":"@pytest.fixture\n def xy(self):\n return dict(x=[1, 2, 3, 4], y=[1, 2, 3, 4])"},{"col":4,"comment":"null","endLoc":1835,"header":"def test_single_layer_single_variable(self, xy)","id":4793,"name":"test_single_layer_single_variable","nodeType":"Function","startLoc":1819,"text":"def test_single_layer_single_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy).add(MockMark(), color=s).plot()\n e, = p._legend_contents\n\n labels = categorical_order(s)\n\n assert e[0] == (s.name, s.name)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [\"color\"]"},{"col":4,"comment":"null","endLoc":1854,"header":"def test_single_layer_common_variable(self, xy)","id":4794,"name":"test_single_layer_common_variable","nodeType":"Function","startLoc":1837,"text":"def test_single_layer_common_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n sem = dict(color=s, marker=s)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n e, = p._legend_contents\n\n labels = categorical_order(s)\n\n assert e[0] == (s.name, s.name)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == list(sem)"},{"col":4,"comment":"null","endLoc":1874,"header":"def test_single_layer_common_unnamed_variable(self, xy)","id":4795,"name":"test_single_layer_common_unnamed_variable","nodeType":"Function","startLoc":1856,"text":"def test_single_layer_common_unnamed_variable(self, xy):\n\n s = np.array([\"a\", \"b\", \"a\", \"c\"])\n sem = dict(color=s, marker=s)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n\n e, = p._legend_contents\n\n labels = list(np.unique(s)) # assumes sorted order\n\n assert e[0] == (\"\", id(s))\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == list(sem)"},{"col":4,"comment":"null","endLoc":2016,"header":"def test_attributes(self, long_df)","id":4796,"name":"test_attributes","nodeType":"Function","startLoc":2003,"text":"def test_attributes(self, long_df):\n\n kwargs = dict(\n size=2,\n linewidth=1,\n edgecolor=\"C2\",\n )\n\n ax = self.func(x=long_df[\"y\"], **kwargs)\n points, = ax.collections\n\n assert points.get_sizes().item() == kwargs[\"size\"] ** 2\n assert points.get_linewidths().item() == kwargs[\"linewidth\"]\n assert tuple(points.get_edgecolors().squeeze()) == to_rgba(kwargs[\"edgecolor\"])"},{"col":4,"comment":"null","endLoc":2023,"header":"def test_three_points(self)","id":4797,"name":"test_three_points","nodeType":"Function","startLoc":2018,"text":"def test_three_points(self):\n\n x = np.arange(3)\n ax = self.func(x=x)\n for point_color in ax.collections[0].get_facecolor():\n assert tuple(point_color) == to_rgba(\"C0\")"},{"col":4,"comment":"null","endLoc":2030,"header":"def test_legend_categorical(self, long_df)","id":4798,"name":"test_legend_categorical","nodeType":"Function","startLoc":2025,"text":"def test_legend_categorical(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"b\")\n legend_texts = [t.get_text() for t in ax.legend_.texts]\n expected = categorical_order(long_df[\"b\"])\n assert legend_texts == expected"},{"col":4,"comment":"null","endLoc":2036,"header":"def test_legend_numeric(self, long_df)","id":4799,"name":"test_legend_numeric","nodeType":"Function","startLoc":2032,"text":"def test_legend_numeric(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"z\")\n vals = [float(t.get_text()) for t in ax.legend_.texts]\n assert (vals[1] - vals[0]) == pytest.approx(vals[2] - vals[1])"},{"col":4,"comment":"null","endLoc":1897,"header":"def test_single_layer_multi_variable(self, xy)","id":4800,"name":"test_single_layer_multi_variable","nodeType":"Function","startLoc":1876,"text":"def test_single_layer_multi_variable(self, xy):\n\n s1 = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s1\")\n s2 = pd.Series([\"m\", \"m\", \"p\", \"m\"], name=\"s2\")\n sem = dict(color=s1, marker=s2)\n p = Plot(**xy).add(MockMark(), **sem).plot()\n e1, e2 = p._legend_contents\n\n variables = {v.name: k for k, v in sem.items()}\n\n for e, s in zip([e1, e2], [s1, s2]):\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [variables[s.name]]"},{"col":4,"comment":"null","endLoc":2041,"header":"def test_legend_disabled(self, long_df)","id":4801,"name":"test_legend_disabled","nodeType":"Function","startLoc":2038,"text":"def test_legend_disabled(self, long_df):\n\n ax = self.func(data=long_df, x=\"y\", y=\"a\", hue=\"b\", legend=False)\n assert ax.legend_ is None"},{"col":4,"comment":"null","endLoc":2057,"header":"def test_palette_from_color_deprecation(self, long_df)","id":4802,"name":"test_palette_from_color_deprecation","nodeType":"Function","startLoc":2043,"text":"def test_palette_from_color_deprecation(self, long_df):\n\n color = (.9, .4, .5)\n hex_color = mpl.colors.to_hex(color)\n\n hue_var = \"a\"\n n_hue = long_df[hue_var].nunique()\n palette = color_palette(f\"dark:{hex_color}\", n_hue)\n\n with pytest.warns(FutureWarning, match=\"Setting a gradient palette\"):\n ax = self.func(data=long_df, x=\"z\", hue=hue_var, color=color)\n\n points = ax.collections[0]\n for point_color in points.get_facecolors():\n assert to_rgb(point_color) in palette"},{"col":4,"comment":"null","endLoc":2066,"header":"def test_palette_with_hue_deprecation(self, long_df)","id":4803,"name":"test_palette_with_hue_deprecation","nodeType":"Function","startLoc":2059,"text":"def test_palette_with_hue_deprecation(self, long_df):\n palette = \"Blues\"\n with pytest.warns(FutureWarning, match=\"Passing `palette` without\"):\n ax = self.func(data=long_df, x=\"a\", y=long_df[\"y\"], palette=palette)\n strips = ax.collections\n colors = color_palette(palette, len(strips))\n for strip, color in zip(strips, colors):\n assert same_color(strip.get_facecolor()[0], color)"},{"col":4,"comment":"null","endLoc":2100,"header":"def test_log_scale(self)","id":4804,"name":"test_log_scale","nodeType":"Function","startLoc":2068,"text":"def test_log_scale(self):\n\n x = [1, 10, 100, 1000]\n\n ax = plt.figure().subplots()\n ax.set_xscale(\"log\")\n self.func(x=x)\n vals = ax.collections[0].get_offsets()[:, 0]\n assert_array_equal(x, vals)\n\n y = [1, 2, 3, 4]\n\n ax = plt.figure().subplots()\n ax.set_xscale(\"log\")\n self.func(x=x, y=y, native_scale=True)\n for i, point in enumerate(ax.collections):\n val = point.get_offsets()[0, 0]\n assert val == pytest.approx(x[i])\n\n x = y = np.ones(100)\n\n # Following test fails on pinned (but not latest) matplotlib.\n # (Even though visual output is ok -- so it's not an actual bug).\n # I'm not exactly sure why, so this version check is approximate\n # and should be revisited on a version bump.\n if Version(mpl.__version__) < Version(\"3.1\"):\n pytest.xfail()\n\n ax = plt.figure().subplots()\n ax.set_yscale(\"log\")\n self.func(x=x, y=y, orient=\"h\", native_scale=True)\n cat_points = ax.collections[0].get_offsets().copy()[:, 1]\n assert np.ptp(np.log10(cat_points)) <= .8"},{"col":4,"comment":"null","endLoc":2136,"header":"@pytest.mark.parametrize(\n \"kwargs\",\n [\n dict(data=\"wide\"),\n dict(data=\"wide\", orient=\"h\"),\n dict(data=\"long\", x=\"x\", color=\"C3\"),\n dict(data=\"long\", y=\"y\", hue=\"a\", jitter=False),\n dict(data=\"long\", x=\"a\", y=\"y\", hue=\"z\", edgecolor=\"w\", linewidth=.5),\n dict(data=\"long\", x=\"a_cat\", y=\"y\", hue=\"z\"),\n dict(data=\"long\", x=\"y\", y=\"s\", hue=\"c\", orient=\"h\", dodge=True),\n dict(data=\"long\", x=\"s\", y=\"y\", hue=\"c\", native_scale=True),\n ]\n )\n def test_vs_catplot(self, long_df, wide_df, kwargs)","id":4805,"name":"test_vs_catplot","nodeType":"Function","startLoc":2102,"text":"@pytest.mark.parametrize(\n \"kwargs\",\n [\n dict(data=\"wide\"),\n dict(data=\"wide\", orient=\"h\"),\n dict(data=\"long\", x=\"x\", color=\"C3\"),\n dict(data=\"long\", y=\"y\", hue=\"a\", jitter=False),\n dict(data=\"long\", x=\"a\", y=\"y\", hue=\"z\", edgecolor=\"w\", linewidth=.5),\n dict(data=\"long\", x=\"a_cat\", y=\"y\", hue=\"z\"),\n dict(data=\"long\", x=\"y\", y=\"s\", hue=\"c\", orient=\"h\", dodge=True),\n dict(data=\"long\", x=\"s\", y=\"y\", hue=\"c\", native_scale=True),\n ]\n )\n def test_vs_catplot(self, long_df, wide_df, kwargs):\n\n kwargs = kwargs.copy()\n if kwargs[\"data\"] == \"long\":\n kwargs[\"data\"] = long_df\n elif kwargs[\"data\"] == \"wide\":\n kwargs[\"data\"] = wide_df\n\n try:\n name = self.func.__name__[:-4]\n except AttributeError:\n name = self.func.func.__name__[:-4]\n if name == \"swarm\":\n kwargs.pop(\"jitter\", None)\n\n np.random.seed(0) # for jitter\n ax = self.func(**kwargs)\n\n np.random.seed(0)\n g = catplot(**kwargs, kind=name)\n\n assert_plots_equal(ax, g.ax)"},{"col":4,"comment":"null","endLoc":1918,"header":"def test_multi_layer_single_variable(self, xy)","id":4806,"name":"test_multi_layer_single_variable","nodeType":"Function","startLoc":1899,"text":"def test_multi_layer_single_variable(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s).add(MockMark()).add(MockMark()).plot()\n e1, e2 = p._legend_contents\n\n labels = categorical_order(s)\n\n for e in [e1, e2]:\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [\"color\"]"},{"col":4,"comment":"null","endLoc":1940,"header":"def test_multi_layer_multi_variable(self, xy)","id":4807,"name":"test_multi_layer_multi_variable","nodeType":"Function","startLoc":1920,"text":"def test_multi_layer_multi_variable(self, xy):\n\n s1 = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s1\")\n s2 = pd.Series([\"m\", \"m\", \"p\", \"m\"], name=\"s2\")\n sem = dict(color=s1), dict(marker=s2)\n variables = {\"s1\": \"color\", \"s2\": \"marker\"}\n p = Plot(**xy).add(MockMark(), **sem[0]).add(MockMark(), **sem[1]).plot()\n e1, e2 = p._legend_contents\n\n for e, s in zip([e1, e2], [s1, s2]):\n assert e[0] == (s.name, s.name)\n\n labels = categorical_order(s)\n assert e[-1] == labels\n\n artists = e[1]\n assert len(artists) == len(labels)\n for a, label in zip(artists, labels):\n assert isinstance(a, mpl.artist.Artist)\n assert a.value == label\n assert a.variables == [variables[s.name]]"},{"className":"TestStripPlot","col":0,"comment":"null","endLoc":2193,"id":4808,"nodeType":"Class","startLoc":2139,"text":"class TestStripPlot(SharedScatterTests):\n\n func = staticmethod(stripplot)\n\n def test_jitter_unfixed(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n kws = dict(data=long_df, x=\"y\", orient=\"h\", native_scale=True)\n\n np.random.seed(0)\n stripplot(**kws, y=\"s\", ax=ax1)\n\n np.random.seed(0)\n stripplot(**kws, y=long_df[\"s\"] * 2, ax=ax2)\n\n p1 = ax1.collections[0].get_offsets()[1]\n p2 = ax2.collections[0].get_offsets()[1]\n\n assert p2.std() > p1.std()\n\n @pytest.mark.parametrize(\n \"orient,jitter\",\n itertools.product([\"v\", \"h\"], [True, .1]),\n )\n def test_jitter(self, long_df, orient, jitter):\n\n cat_var, val_var = \"a\", \"y\"\n if orient == \"v\":\n x_var, y_var = cat_var, val_var\n cat_idx, val_idx = 0, 1\n else:\n x_var, y_var = val_var, cat_var\n cat_idx, val_idx = 1, 0\n\n cat_vals = categorical_order(long_df[cat_var])\n\n ax = stripplot(\n data=long_df, x=x_var, y=y_var, jitter=jitter,\n )\n\n if jitter is True:\n jitter_range = .4\n else:\n jitter_range = 2 * jitter\n\n for i, level in enumerate(cat_vals):\n\n vals = long_df.loc[long_df[cat_var] == level, val_var]\n points = ax.collections[i].get_offsets().T\n cat_points = points[cat_idx]\n val_points = points[val_idx]\n\n assert_array_equal(val_points, vals)\n assert np.std(cat_points) > 0\n assert np.ptp(cat_points) <= jitter_range"},{"col":4,"comment":"null","endLoc":2157,"header":"def test_jitter_unfixed(self, long_df)","id":4809,"name":"test_jitter_unfixed","nodeType":"Function","startLoc":2143,"text":"def test_jitter_unfixed(self, long_df):\n\n ax1, ax2 = plt.figure().subplots(2)\n kws = dict(data=long_df, x=\"y\", orient=\"h\", native_scale=True)\n\n np.random.seed(0)\n stripplot(**kws, y=\"s\", ax=ax1)\n\n np.random.seed(0)\n stripplot(**kws, y=long_df[\"s\"] * 2, ax=ax2)\n\n p1 = ax1.collections[0].get_offsets()[1]\n p2 = ax2.collections[0].get_offsets()[1]\n\n assert p2.std() > p1.std()"},{"col":4,"comment":"null","endLoc":2193,"header":"@pytest.mark.parametrize(\n \"orient,jitter\",\n itertools.product([\"v\", \"h\"], [True, .1]),\n )\n def test_jitter(self, long_df, orient, jitter)","id":4810,"name":"test_jitter","nodeType":"Function","startLoc":2159,"text":"@pytest.mark.parametrize(\n \"orient,jitter\",\n itertools.product([\"v\", \"h\"], [True, .1]),\n )\n def test_jitter(self, long_df, orient, jitter):\n\n cat_var, val_var = \"a\", \"y\"\n if orient == \"v\":\n x_var, y_var = cat_var, val_var\n cat_idx, val_idx = 0, 1\n else:\n x_var, y_var = val_var, cat_var\n cat_idx, val_idx = 1, 0\n\n cat_vals = categorical_order(long_df[cat_var])\n\n ax = stripplot(\n data=long_df, x=x_var, y=y_var, jitter=jitter,\n )\n\n if jitter is True:\n jitter_range = .4\n else:\n jitter_range = 2 * jitter\n\n for i, level in enumerate(cat_vals):\n\n vals = long_df.loc[long_df[cat_var] == level, val_var]\n points = ax.collections[i].get_offsets().T\n cat_points = points[cat_idx]\n val_points = points[val_idx]\n\n assert_array_equal(val_points, vals)\n assert np.std(cat_points) > 0\n assert np.ptp(cat_points) <= jitter_range"},{"col":4,"comment":"null","endLoc":1964,"header":"def test_multi_layer_different_artists(self, xy)","id":4811,"name":"test_multi_layer_different_artists","nodeType":"Function","startLoc":1942,"text":"def test_multi_layer_different_artists(self, xy):\n\n class MockMark1(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.lines.Line2D([], [])\n\n class MockMark2(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.patches.Patch()\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s).add(MockMark1()).add(MockMark2()).plot()\n\n legend, = p._figure.legends\n\n names = categorical_order(s)\n labels = [t.get_text() for t in legend.get_texts()]\n assert labels == names\n\n if Version(mpl.__version__) >= Version(\"3.2\"):\n contents = legend.get_children()[0]\n assert len(contents.findobj(mpl.lines.Line2D)) == len(names)\n assert len(contents.findobj(mpl.patches.Patch)) == len(names)"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":2141,"id":4812,"name":"func","nodeType":"Attribute","startLoc":2141,"text":"func"},{"className":"TestSwarmPlot","col":0,"comment":"null","endLoc":2198,"id":4813,"nodeType":"Class","startLoc":2196,"text":"class TestSwarmPlot(SharedScatterTests):\n\n func = staticmethod(partial(swarmplot, warn_thresh=1))"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":2198,"id":4814,"name":"func","nodeType":"Attribute","startLoc":2198,"text":"func"},{"col":4,"comment":"null","endLoc":1978,"header":"def test_three_layers(self, xy)","id":4815,"name":"test_three_layers","nodeType":"Function","startLoc":1966,"text":"def test_three_layers(self, xy):\n\n class MockMarkLine(MockMark):\n def _legend_artist(self, variables, value, scales):\n return mpl.lines.Line2D([], [])\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy, color=s)\n for _ in range(3):\n p = p.add(MockMarkLine())\n p = p.plot()\n texts = p._figure.legends[0].get_texts()\n assert len(texts) == len(s.unique())"},{"className":"TestBarPlotter","col":0,"comment":"null","endLoc":2466,"id":4816,"nodeType":"Class","startLoc":2201,"text":"class TestBarPlotter(CategoricalFixture):\n\n default_kws = dict(\n data=None, x=None, y=None, hue=None, units=None,\n estimator=\"mean\", errorbar=(\"ci\", 95), n_boot=100, seed=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None,\n saturation=.75, width=0.8,\n errcolor=\".26\", errwidth=None,\n capsize=None, dodge=True\n )\n\n def test_nested_width(self):\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"h\")\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.8 / 2)\n ax.clear()\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"g\", width=.5)\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.5 / 3)\n ax.clear()\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"g\", dodge=False)\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.8)\n ax.clear()\n\n def test_draw_vertical_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data)\n assert len(ax.lines) == len(p.plot_data)\n\n for bar, color in zip(ax.patches, p.colors):\n assert bar.get_facecolor()[:-1] == color\n\n positions = np.arange(len(p.plot_data)) - p.width / 2\n for bar, pos, stat in zip(ax.patches, positions, p.statistic):\n assert bar.get_x() == pos\n assert bar.get_width() == p.width\n assert bar.get_y() == 0\n assert bar.get_height() == stat\n\n def test_draw_horizontal_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data)\n assert len(ax.lines) == len(p.plot_data)\n\n for bar, color in zip(ax.patches, p.colors):\n assert bar.get_facecolor()[:-1] == color\n\n positions = np.arange(len(p.plot_data)) - p.width / 2\n for bar, pos, stat in zip(ax.patches, positions, p.statistic):\n assert bar.get_y() == pos\n assert bar.get_height() == p.width\n assert bar.get_x() == 0\n assert bar.get_width() == stat\n\n def test_draw_nested_vertical_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n n_groups, n_hues = len(p.plot_data), len(p.hue_names)\n assert len(ax.patches) == n_groups * n_hues\n assert len(ax.lines) == n_groups * n_hues\n\n for bar in ax.patches[:n_groups]:\n assert bar.get_facecolor()[:-1] == p.colors[0]\n for bar in ax.patches[n_groups:]:\n assert bar.get_facecolor()[:-1] == p.colors[1]\n\n positions = np.arange(len(p.plot_data))\n for bar, pos in zip(ax.patches[:n_groups], positions):\n assert bar.get_x() == approx(pos - p.width / 2)\n assert bar.get_width() == approx(p.nested_width)\n\n for bar, stat in zip(ax.patches, p.statistic.T.flat):\n assert bar.get_y() == approx(0)\n assert bar.get_height() == approx(stat)\n\n def test_draw_nested_horizontal_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n n_groups, n_hues = len(p.plot_data), len(p.hue_names)\n assert len(ax.patches) == n_groups * n_hues\n assert len(ax.lines) == n_groups * n_hues\n\n for bar in ax.patches[:n_groups]:\n assert bar.get_facecolor()[:-1] == p.colors[0]\n for bar in ax.patches[n_groups:]:\n assert bar.get_facecolor()[:-1] == p.colors[1]\n\n positions = np.arange(len(p.plot_data))\n for bar, pos in zip(ax.patches[:n_groups], positions):\n assert bar.get_y() == approx(pos - p.width / 2)\n assert bar.get_height() == approx(p.nested_width)\n\n for bar, stat in zip(ax.patches, p.statistic.T.flat):\n assert bar.get_x() == approx(0)\n assert bar.get_width() == approx(stat)\n\n def test_draw_missing_bars(self):\n\n kws = self.default_kws.copy()\n\n order = list(\"abcd\")\n kws.update(x=\"g\", y=\"y\", order=order, data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(order)\n assert len(ax.lines) == len(order)\n\n plt.close(\"all\")\n\n hue_order = list(\"mno\")\n kws.update(x=\"g\", y=\"y\", hue=\"h\", hue_order=hue_order, data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data) * len(hue_order)\n assert len(ax.lines) == len(p.plot_data) * len(hue_order)\n\n plt.close(\"all\")\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.barplot(x=self.g, y=self.y, errorbar=\"sd\", ax=ax1)\n cat.barplot(x=self.g, y=self.y_perm, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.patches, ax2.patches):\n assert approx(p1.get_xy()) == p2.get_xy()\n assert approx(p1.get_height()) == p2.get_height()\n assert approx(p1.get_width()) == p2.get_width()\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.barplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax1)\n cat.barplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.patches, ax2.patches):\n assert approx(p1.get_xy()) == p2.get_xy()\n assert approx(p1.get_height()) == p2.get_height()\n assert approx(p1.get_width()) == p2.get_width()\n\n def test_barplot_colors(self):\n\n # Test unnested palette colors\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df,\n saturation=1, palette=\"muted\")\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n palette = palettes.color_palette(\"muted\", len(self.g.unique()))\n for patch, pal_color in zip(ax.patches, palette):\n assert patch.get_facecolor()[:-1] == pal_color\n\n plt.close(\"all\")\n\n # Test single color\n color = (.2, .2, .3, 1)\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df,\n saturation=1, color=color)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n for patch in ax.patches:\n assert patch.get_facecolor() == color\n\n plt.close(\"all\")\n\n # Test nested palette colors\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n saturation=1, palette=\"Set2\")\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n palette = palettes.color_palette(\"Set2\", len(self.h.unique()))\n for patch in ax.patches[:len(self.g.unique())]:\n assert patch.get_facecolor()[:-1] == palette[0]\n for patch in ax.patches[len(self.g.unique()):]:\n assert patch.get_facecolor()[:-1] == palette[1]\n\n plt.close(\"all\")\n\n def test_simple_barplots(self):\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df)\n assert len(ax.patches) == len(self.g.unique())\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique())\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n def test_errorbar(self, long_df):\n\n ax = cat.barplot(data=long_df, x=\"a\", y=\"y\", errorbar=(\"sd\", 2))\n order = categorical_order(long_df[\"a\"])\n\n for i, line in enumerate(ax.lines):\n sub_df = long_df.loc[long_df[\"a\"] == order[i], \"y\"]\n mean = sub_df.mean()\n sd = sub_df.std()\n expected = mean - 2 * sd, mean + 2 * sd\n assert_array_equal(line.get_ydata(), expected)"},{"col":4,"comment":"null","endLoc":2228,"header":"def test_nested_width(self)","id":4817,"name":"test_nested_width","nodeType":"Function","startLoc":2213,"text":"def test_nested_width(self):\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"h\")\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.8 / 2)\n ax.clear()\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"g\", width=.5)\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.5 / 3)\n ax.clear()\n\n ax = cat.barplot(data=self.df, x=\"g\", y=\"y\", hue=\"g\", dodge=False)\n for bar in ax.patches:\n assert bar.get_width() == pytest.approx(.8)\n ax.clear()"},{"col":4,"comment":"null","endLoc":2250,"header":"def test_draw_vertical_bars(self)","id":4818,"name":"test_draw_vertical_bars","nodeType":"Function","startLoc":2230,"text":"def test_draw_vertical_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data)\n assert len(ax.lines) == len(p.plot_data)\n\n for bar, color in zip(ax.patches, p.colors):\n assert bar.get_facecolor()[:-1] == color\n\n positions = np.arange(len(p.plot_data)) - p.width / 2\n for bar, pos, stat in zip(ax.patches, positions, p.statistic):\n assert bar.get_x() == pos\n assert bar.get_width() == p.width\n assert bar.get_y() == 0\n assert bar.get_height() == stat"},{"col":4,"comment":"null","endLoc":1984,"header":"def test_identity_scale_ignored(self, xy)","id":4819,"name":"test_identity_scale_ignored","nodeType":"Function","startLoc":1980,"text":"def test_identity_scale_ignored(self, xy):\n\n s = pd.Series([\"r\", \"g\", \"b\", \"g\"])\n p = Plot(**xy).add(MockMark(), color=s).scale(color=None).plot()\n assert not p._legend_contents"},{"col":4,"comment":"null","endLoc":1990,"header":"def test_suppression_in_add_method(self, xy)","id":4820,"name":"test_suppression_in_add_method","nodeType":"Function","startLoc":1986,"text":"def test_suppression_in_add_method(self, xy):\n\n s = pd.Series([\"a\", \"b\", \"a\", \"c\"], name=\"s\")\n p = Plot(**xy).add(MockMark(), color=s, legend=False).plot()\n assert not p._legend_contents"},{"col":4,"comment":"null","endLoc":1996,"header":"def test_anonymous_title(self, xy)","id":4821,"name":"test_anonymous_title","nodeType":"Function","startLoc":1992,"text":"def test_anonymous_title(self, xy):\n\n p = Plot(**xy, color=[\"a\", \"b\", \"c\", \"d\"]).add(MockMark()).plot()\n legend, = p._figure.legends\n assert legend.get_title().get_text() == \"\""},{"col":4,"comment":"null","endLoc":2005,"header":"def test_legendless_mark(self, xy)","id":4822,"name":"test_legendless_mark","nodeType":"Function","startLoc":1998,"text":"def test_legendless_mark(self, xy):\n\n class NoLegendMark(MockMark):\n def _legend_artist(self, variables, value, scales):\n return None\n\n p = Plot(**xy, color=[\"a\", \"b\", \"c\", \"d\"]).add(NoLegendMark()).plot()\n assert not p._figure.legends"},{"className":"TestDefaultObject","col":0,"comment":"null","endLoc":2012,"id":4823,"nodeType":"Class","startLoc":2008,"text":"class TestDefaultObject:\n\n def test_default_repr(self):\n\n assert repr(Default()) == \"\""},{"col":4,"comment":"null","endLoc":2012,"header":"def test_default_repr(self)","id":4824,"name":"test_default_repr","nodeType":"Function","startLoc":2010,"text":"def test_default_repr(self):\n\n assert repr(Default()) == \"\""},{"attributeType":"null","col":16,"comment":"null","endLoc":7,"id":4825,"name":"np","nodeType":"Attribute","startLoc":7,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":8,"id":4826,"name":"pd","nodeType":"Attribute","startLoc":8,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":9,"id":4827,"name":"mpl","nodeType":"Attribute","startLoc":9,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":10,"id":4828,"name":"plt","nodeType":"Attribute","startLoc":10,"text":"plt"},{"attributeType":"partial","col":0,"comment":"null","endLoc":26,"id":4829,"name":"assert_vector_equal","nodeType":"Attribute","startLoc":26,"text":"assert_vector_equal"},{"col":0,"comment":"","endLoc":1,"header":"test_plot.py#","id":4830,"name":"","nodeType":"Function","startLoc":1,"text":"assert_vector_equal = functools.partial(\n # TODO do we care about int/float dtype consistency?\n # Eventually most variables become floats ... but does it matter when?\n # (Or rather, does it matter if it happens too early?)\n assert_series_equal, check_names=False, check_dtype=False,\n)"},{"col":4,"comment":"null","endLoc":2272,"header":"def test_draw_horizontal_bars(self)","id":4831,"name":"test_draw_horizontal_bars","nodeType":"Function","startLoc":2252,"text":"def test_draw_horizontal_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data)\n assert len(ax.lines) == len(p.plot_data)\n\n for bar, color in zip(ax.patches, p.colors):\n assert bar.get_facecolor()[:-1] == color\n\n positions = np.arange(len(p.plot_data)) - p.width / 2\n for bar, pos, stat in zip(ax.patches, positions, p.statistic):\n assert bar.get_y() == pos\n assert bar.get_height() == p.width\n assert bar.get_x() == 0\n assert bar.get_width() == stat"},{"col":4,"comment":"null","endLoc":2299,"header":"def test_draw_nested_vertical_bars(self)","id":4832,"name":"test_draw_nested_vertical_bars","nodeType":"Function","startLoc":2274,"text":"def test_draw_nested_vertical_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n n_groups, n_hues = len(p.plot_data), len(p.hue_names)\n assert len(ax.patches) == n_groups * n_hues\n assert len(ax.lines) == n_groups * n_hues\n\n for bar in ax.patches[:n_groups]:\n assert bar.get_facecolor()[:-1] == p.colors[0]\n for bar in ax.patches[n_groups:]:\n assert bar.get_facecolor()[:-1] == p.colors[1]\n\n positions = np.arange(len(p.plot_data))\n for bar, pos in zip(ax.patches[:n_groups], positions):\n assert bar.get_x() == approx(pos - p.width / 2)\n assert bar.get_width() == approx(p.nested_width)\n\n for bar, stat in zip(ax.patches, p.statistic.T.flat):\n assert bar.get_y() == approx(0)\n assert bar.get_height() == approx(stat)"},{"col":4,"comment":"null","endLoc":2326,"header":"def test_draw_nested_horizontal_bars(self)","id":4833,"name":"test_draw_nested_horizontal_bars","nodeType":"Function","startLoc":2301,"text":"def test_draw_nested_horizontal_bars(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n n_groups, n_hues = len(p.plot_data), len(p.hue_names)\n assert len(ax.patches) == n_groups * n_hues\n assert len(ax.lines) == n_groups * n_hues\n\n for bar in ax.patches[:n_groups]:\n assert bar.get_facecolor()[:-1] == p.colors[0]\n for bar in ax.patches[n_groups:]:\n assert bar.get_facecolor()[:-1] == p.colors[1]\n\n positions = np.arange(len(p.plot_data))\n for bar, pos in zip(ax.patches[:n_groups], positions):\n assert bar.get_y() == approx(pos - p.width / 2)\n assert bar.get_height() == approx(p.nested_width)\n\n for bar, stat in zip(ax.patches, p.statistic.T.flat):\n assert bar.get_x() == approx(0)\n assert bar.get_width() == approx(stat)"},{"col":4,"comment":"null","endLoc":2354,"header":"def test_draw_missing_bars(self)","id":4834,"name":"test_draw_missing_bars","nodeType":"Function","startLoc":2328,"text":"def test_draw_missing_bars(self):\n\n kws = self.default_kws.copy()\n\n order = list(\"abcd\")\n kws.update(x=\"g\", y=\"y\", order=order, data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(order)\n assert len(ax.lines) == len(order)\n\n plt.close(\"all\")\n\n hue_order = list(\"mno\")\n kws.update(x=\"g\", y=\"y\", hue=\"h\", hue_order=hue_order, data=self.df)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n assert len(ax.patches) == len(p.plot_data) * len(hue_order)\n assert len(ax.lines) == len(p.plot_data) * len(hue_order)\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2379,"header":"def test_unaligned_index(self)","id":4835,"name":"test_unaligned_index","nodeType":"Function","startLoc":2356,"text":"def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.barplot(x=self.g, y=self.y, errorbar=\"sd\", ax=ax1)\n cat.barplot(x=self.g, y=self.y_perm, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.patches, ax2.patches):\n assert approx(p1.get_xy()) == p2.get_xy()\n assert approx(p1.get_height()) == p2.get_height()\n assert approx(p1.get_width()) == p2.get_width()\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.barplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax1)\n cat.barplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.patches, ax2.patches):\n assert approx(p1.get_xy()) == p2.get_xy()\n assert approx(p1.get_height()) == p2.get_height()\n assert approx(p1.get_width()) == p2.get_width()"},{"col":4,"comment":"null","endLoc":2428,"header":"def test_barplot_colors(self)","id":4836,"name":"test_barplot_colors","nodeType":"Function","startLoc":2381,"text":"def test_barplot_colors(self):\n\n # Test unnested palette colors\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df,\n saturation=1, palette=\"muted\")\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n palette = palettes.color_palette(\"muted\", len(self.g.unique()))\n for patch, pal_color in zip(ax.patches, palette):\n assert patch.get_facecolor()[:-1] == pal_color\n\n plt.close(\"all\")\n\n # Test single color\n color = (.2, .2, .3, 1)\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df,\n saturation=1, color=color)\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n for patch in ax.patches:\n assert patch.get_facecolor() == color\n\n plt.close(\"all\")\n\n # Test nested palette colors\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n saturation=1, palette=\"Set2\")\n p = cat._BarPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_bars(ax, {})\n\n palette = palettes.color_palette(\"Set2\", len(self.h.unique()))\n for patch in ax.patches[:len(self.g.unique())]:\n assert patch.get_facecolor()[:-1] == palette[0]\n for patch in ax.patches[len(self.g.unique()):]:\n assert patch.get_facecolor()[:-1] == palette[1]\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2454,"header":"def test_simple_barplots(self)","id":4837,"name":"test_simple_barplots","nodeType":"Function","startLoc":2430,"text":"def test_simple_barplots(self):\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df)\n assert len(ax.patches) == len(self.g.unique())\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique())\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n assert len(ax.patches) == len(self.g.unique()) * len(self.h.unique())\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2466,"header":"def test_errorbar(self, long_df)","id":4838,"name":"test_errorbar","nodeType":"Function","startLoc":2456,"text":"def test_errorbar(self, long_df):\n\n ax = cat.barplot(data=long_df, x=\"a\", y=\"y\", errorbar=(\"sd\", 2))\n order = categorical_order(long_df[\"a\"])\n\n for i, line in enumerate(ax.lines):\n sub_df = long_df.loc[long_df[\"a\"] == order[i], \"y\"]\n mean = sub_df.mean()\n sd = sub_df.std()\n expected = mean - 2 * sd, mean + 2 * sd\n assert_array_equal(line.get_ydata(), expected)"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":2203,"id":4839,"name":"default_kws","nodeType":"Attribute","startLoc":2203,"text":"default_kws"},{"className":"TestPointPlotter","col":0,"comment":"null","endLoc":2746,"id":4840,"nodeType":"Class","startLoc":2469,"text":"class TestPointPlotter(CategoricalFixture):\n\n default_kws = dict(\n x=None, y=None, hue=None, data=None,\n estimator=\"mean\", errorbar=(\"ci\", 95),\n n_boot=100, units=None, seed=None,\n order=None, hue_order=None,\n markers=\"o\", linestyles=\"-\", dodge=0,\n join=True, scale=1,\n orient=None, color=None, palette=None,\n )\n\n def test_different_defualt_colors(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", data=self.df))\n p = cat._PointPlotter(**kws)\n color = palettes.color_palette()[0]\n npt.assert_array_equal(p.colors, [color, color, color])\n\n def test_hue_offsets(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", hue=\"h\", data=self.df))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [0, 0])\n\n kws.update(dict(dodge=.5))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [-.25, .25])\n\n kws.update(dict(x=\"h\", hue=\"g\", dodge=0))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [0, 0, 0])\n\n kws.update(dict(dodge=.3))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [-.15, 0, .15])\n\n def test_draw_vertical_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(p.plot_data) + 1\n points = ax.collections[0]\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, np.arange(len(p.plot_data)))\n npt.assert_array_equal(y, p.statistic)\n\n for got_color, want_color in zip(points.get_facecolors(),\n p.colors):\n npt.assert_array_equal(got_color[:-1], want_color)\n\n def test_draw_horizontal_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(p.plot_data) + 1\n points = ax.collections[0]\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, p.statistic)\n npt.assert_array_equal(y, np.arange(len(p.plot_data)))\n\n for got_color, want_color in zip(points.get_facecolors(),\n p.colors):\n npt.assert_array_equal(got_color[:-1], want_color)\n\n def test_draw_vertical_nested_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 2\n assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)\n\n for points, numbers, color in zip(ax.collections,\n p.statistic.T,\n p.colors):\n\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, np.arange(len(p.plot_data)))\n npt.assert_array_equal(y, numbers)\n\n for got_color in points.get_facecolors():\n npt.assert_array_equal(got_color[:-1], color)\n\n def test_draw_horizontal_nested_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 2\n assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)\n\n for points, numbers, color in zip(ax.collections,\n p.statistic.T,\n p.colors):\n\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, numbers)\n npt.assert_array_equal(y, np.arange(len(p.plot_data)))\n\n for got_color in points.get_facecolors():\n npt.assert_array_equal(got_color[:-1], color)\n\n def test_draw_missing_points(self):\n\n kws = self.default_kws.copy()\n df = self.df.copy()\n\n kws.update(x=\"g\", y=\"y\", hue=\"h\", hue_order=[\"x\", \"y\"], data=df)\n p = cat._PointPlotter(**kws)\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n df.loc[df[\"h\"] == \"m\", \"y\"] = np.nan\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=df)\n p = cat._PointPlotter(**kws)\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.pointplot(x=self.g, y=self.y, errorbar=\"sd\", ax=ax1)\n cat.pointplot(x=self.g, y=self.y_perm, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.collections, ax2.collections):\n assert approx(p1.get_offsets()) == p2.get_offsets()\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.pointplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax1)\n cat.pointplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.collections, ax2.collections):\n assert approx(p1.get_offsets()) == p2.get_offsets()\n\n def test_pointplot_colors(self):\n\n # Test a single-color unnested plot\n color = (.2, .2, .3, 1)\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df, color=color)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line in ax.lines:\n assert line.get_color() == color[:-1]\n\n for got_color in ax.collections[0].get_facecolors():\n npt.assert_array_equal(rgb2hex(got_color), rgb2hex(color))\n\n plt.close(\"all\")\n\n # Test a multi-color unnested plot\n palette = palettes.color_palette(\"Set1\", 3)\n kws.update(x=\"g\", y=\"y\", data=self.df, palette=\"Set1\")\n p = cat._PointPlotter(**kws)\n\n assert not p.join\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line, pal_color in zip(ax.lines, palette):\n npt.assert_array_equal(line.get_color(), pal_color)\n\n for point_color, pal_color in zip(ax.collections[0].get_facecolors(),\n palette):\n npt.assert_array_equal(rgb2hex(point_color), rgb2hex(pal_color))\n\n plt.close(\"all\")\n\n # Test a multi-colored nested plot\n palette = palettes.color_palette(\"dark\", 2)\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df, palette=\"dark\")\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line in ax.lines[:(len(p.plot_data) + 1)]:\n assert line.get_color() == palette[0]\n for line in ax.lines[(len(p.plot_data) + 1):]:\n assert line.get_color() == palette[1]\n\n for i, pal_color in enumerate(palette):\n for point_color in ax.collections[i].get_facecolors():\n npt.assert_array_equal(point_color[:-1], pal_color)\n\n plt.close(\"all\")\n\n def test_simple_pointplots(self):\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df)\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(self.g.unique()) + 1\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(self.g.unique()) + 1\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(ax.collections) == len(self.h.unique())\n assert len(ax.lines) == (\n len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())\n )\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n assert len(ax.collections) == len(self.h.unique())\n assert len(ax.lines) == (\n len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())\n )\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n def test_errorbar(self, long_df):\n\n ax = cat.pointplot(\n data=long_df, x=\"a\", y=\"y\", errorbar=(\"sd\", 2), join=False\n )\n order = categorical_order(long_df[\"a\"])\n\n for i, line in enumerate(ax.lines):\n sub_df = long_df.loc[long_df[\"a\"] == order[i], \"y\"]\n mean = sub_df.mean()\n sd = sub_df.std()\n expected = mean - 2 * sd, mean + 2 * sd\n assert_array_equal(line.get_ydata(), expected)"},{"col":4,"comment":"null","endLoc":2487,"header":"def test_different_defualt_colors(self)","id":4841,"name":"test_different_defualt_colors","nodeType":"Function","startLoc":2481,"text":"def test_different_defualt_colors(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", data=self.df))\n p = cat._PointPlotter(**kws)\n color = palettes.color_palette()[0]\n npt.assert_array_equal(p.colors, [color, color, color])"},{"col":4,"comment":"null","endLoc":2510,"header":"def test_hue_offsets(self)","id":4842,"name":"test_hue_offsets","nodeType":"Function","startLoc":2489,"text":"def test_hue_offsets(self):\n\n kws = self.default_kws.copy()\n kws.update(dict(x=\"g\", y=\"y\", hue=\"h\", data=self.df))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [0, 0])\n\n kws.update(dict(dodge=.5))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [-.25, .25])\n\n kws.update(dict(x=\"h\", hue=\"g\", dodge=0))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [0, 0, 0])\n\n kws.update(dict(dodge=.3))\n\n p = cat._PointPlotter(**kws)\n npt.assert_array_equal(p.hue_offsets, [-.15, 0, .15])"},{"col":4,"comment":"null","endLoc":2532,"header":"def test_draw_vertical_points(self)","id":4843,"name":"test_draw_vertical_points","nodeType":"Function","startLoc":2512,"text":"def test_draw_vertical_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(p.plot_data) + 1\n points = ax.collections[0]\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, np.arange(len(p.plot_data)))\n npt.assert_array_equal(y, p.statistic)\n\n for got_color, want_color in zip(points.get_facecolors(),\n p.colors):\n npt.assert_array_equal(got_color[:-1], want_color)"},{"col":4,"comment":"null","endLoc":2554,"header":"def test_draw_horizontal_points(self)","id":4844,"name":"test_draw_horizontal_points","nodeType":"Function","startLoc":2534,"text":"def test_draw_horizontal_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(p.plot_data) + 1\n points = ax.collections[0]\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, p.statistic)\n npt.assert_array_equal(y, np.arange(len(p.plot_data)))\n\n for got_color, want_color in zip(points.get_facecolors(),\n p.colors):\n npt.assert_array_equal(got_color[:-1], want_color)"},{"col":4,"comment":"null","endLoc":2579,"header":"def test_draw_vertical_nested_points(self)","id":4845,"name":"test_draw_vertical_nested_points","nodeType":"Function","startLoc":2556,"text":"def test_draw_vertical_nested_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 2\n assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)\n\n for points, numbers, color in zip(ax.collections,\n p.statistic.T,\n p.colors):\n\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, np.arange(len(p.plot_data)))\n npt.assert_array_equal(y, numbers)\n\n for got_color in points.get_facecolors():\n npt.assert_array_equal(got_color[:-1], color)"},{"col":4,"comment":"null","endLoc":2604,"header":"def test_draw_horizontal_nested_points(self)","id":4846,"name":"test_draw_horizontal_nested_points","nodeType":"Function","startLoc":2581,"text":"def test_draw_horizontal_nested_points(self):\n\n kws = self.default_kws.copy()\n kws.update(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n assert len(ax.collections) == 2\n assert len(ax.lines) == len(p.plot_data) * len(p.hue_names) + len(p.hue_names)\n\n for points, numbers, color in zip(ax.collections,\n p.statistic.T,\n p.colors):\n\n assert len(points.get_offsets()) == len(p.plot_data)\n\n x, y = points.get_offsets().T\n npt.assert_array_equal(x, numbers)\n npt.assert_array_equal(y, np.arange(len(p.plot_data)))\n\n for got_color in points.get_facecolors():\n npt.assert_array_equal(got_color[:-1], color)"},{"col":4,"comment":"null","endLoc":2620,"header":"def test_draw_missing_points(self)","id":4847,"name":"test_draw_missing_points","nodeType":"Function","startLoc":2606,"text":"def test_draw_missing_points(self):\n\n kws = self.default_kws.copy()\n df = self.df.copy()\n\n kws.update(x=\"g\", y=\"y\", hue=\"h\", hue_order=[\"x\", \"y\"], data=df)\n p = cat._PointPlotter(**kws)\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n df.loc[df[\"h\"] == \"m\", \"y\"] = np.nan\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=df)\n p = cat._PointPlotter(**kws)\n f, ax = plt.subplots()\n p.draw_points(ax)"},{"col":4,"comment":"null","endLoc":2641,"header":"def test_unaligned_index(self)","id":4848,"name":"test_unaligned_index","nodeType":"Function","startLoc":2622,"text":"def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.pointplot(x=self.g, y=self.y, errorbar=\"sd\", ax=ax1)\n cat.pointplot(x=self.g, y=self.y_perm, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.collections, ax2.collections):\n assert approx(p1.get_offsets()) == p2.get_offsets()\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.pointplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax1)\n cat.pointplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, errorbar=\"sd\", ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert approx(l1.get_xydata()) == l2.get_xydata()\n for p1, p2 in zip(ax1.collections, ax2.collections):\n assert approx(p1.get_offsets()) == p2.get_offsets()"},{"col":4,"comment":"null","endLoc":2698,"header":"def test_pointplot_colors(self)","id":4849,"name":"test_pointplot_colors","nodeType":"Function","startLoc":2643,"text":"def test_pointplot_colors(self):\n\n # Test a single-color unnested plot\n color = (.2, .2, .3, 1)\n kws = self.default_kws.copy()\n kws.update(x=\"g\", y=\"y\", data=self.df, color=color)\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line in ax.lines:\n assert line.get_color() == color[:-1]\n\n for got_color in ax.collections[0].get_facecolors():\n npt.assert_array_equal(rgb2hex(got_color), rgb2hex(color))\n\n plt.close(\"all\")\n\n # Test a multi-color unnested plot\n palette = palettes.color_palette(\"Set1\", 3)\n kws.update(x=\"g\", y=\"y\", data=self.df, palette=\"Set1\")\n p = cat._PointPlotter(**kws)\n\n assert not p.join\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line, pal_color in zip(ax.lines, palette):\n npt.assert_array_equal(line.get_color(), pal_color)\n\n for point_color, pal_color in zip(ax.collections[0].get_facecolors(),\n palette):\n npt.assert_array_equal(rgb2hex(point_color), rgb2hex(pal_color))\n\n plt.close(\"all\")\n\n # Test a multi-colored nested plot\n palette = palettes.color_palette(\"dark\", 2)\n kws.update(x=\"g\", y=\"y\", hue=\"h\", data=self.df, palette=\"dark\")\n p = cat._PointPlotter(**kws)\n\n f, ax = plt.subplots()\n p.draw_points(ax)\n\n for line in ax.lines[:(len(p.plot_data) + 1)]:\n assert line.get_color() == palette[0]\n for line in ax.lines[(len(p.plot_data) + 1):]:\n assert line.get_color() == palette[1]\n\n for i, pal_color in enumerate(palette):\n for point_color in ax.collections[i].get_facecolors():\n npt.assert_array_equal(point_color[:-1], pal_color)\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2732,"header":"def test_simple_pointplots(self)","id":4850,"name":"test_simple_pointplots","nodeType":"Function","startLoc":2700,"text":"def test_simple_pointplots(self):\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df)\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(self.g.unique()) + 1\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"y\", y=\"g\", orient=\"h\", data=self.df)\n assert len(ax.collections) == 1\n assert len(ax.lines) == len(self.g.unique()) + 1\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert len(ax.collections) == len(self.h.unique())\n assert len(ax.lines) == (\n len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())\n )\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"y\", y=\"g\", hue=\"h\", orient=\"h\", data=self.df)\n assert len(ax.collections) == len(self.h.unique())\n assert len(ax.lines) == (\n len(self.g.unique()) * len(self.h.unique()) + len(self.h.unique())\n )\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2746,"header":"def test_errorbar(self, long_df)","id":4851,"name":"test_errorbar","nodeType":"Function","startLoc":2734,"text":"def test_errorbar(self, long_df):\n\n ax = cat.pointplot(\n data=long_df, x=\"a\", y=\"y\", errorbar=(\"sd\", 2), join=False\n )\n order = categorical_order(long_df[\"a\"])\n\n for i, line in enumerate(ax.lines):\n sub_df = long_df.loc[long_df[\"a\"] == order[i], \"y\"]\n mean = sub_df.mean()\n sd = sub_df.std()\n expected = mean - 2 * sd, mean + 2 * sd\n assert_array_equal(line.get_ydata(), expected)"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":2471,"id":4852,"name":"default_kws","nodeType":"Attribute","startLoc":2471,"text":"default_kws"},{"className":"TestCountPlot","col":0,"comment":"null","endLoc":2778,"id":4853,"nodeType":"Class","startLoc":2749,"text":"class TestCountPlot(CategoricalFixture):\n\n def test_plot_elements(self):\n\n ax = cat.countplot(x=\"g\", data=self.df)\n assert len(ax.patches) == self.g.unique().size\n for p in ax.patches:\n assert p.get_y() == 0\n assert p.get_height() == self.g.size / self.g.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(y=\"g\", data=self.df)\n assert len(ax.patches) == self.g.unique().size\n for p in ax.patches:\n assert p.get_x() == 0\n assert p.get_width() == self.g.size / self.g.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(x=\"g\", hue=\"h\", data=self.df)\n assert len(ax.patches) == self.g.unique().size * self.h.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(y=\"g\", hue=\"h\", data=self.df)\n assert len(ax.patches) == self.g.unique().size * self.h.unique().size\n plt.close(\"all\")\n\n def test_input_error(self):\n\n with pytest.raises(ValueError):\n cat.countplot(x=\"g\", y=\"h\", data=self.df)"},{"col":4,"comment":"null","endLoc":2773,"header":"def test_plot_elements(self)","id":4854,"name":"test_plot_elements","nodeType":"Function","startLoc":2751,"text":"def test_plot_elements(self):\n\n ax = cat.countplot(x=\"g\", data=self.df)\n assert len(ax.patches) == self.g.unique().size\n for p in ax.patches:\n assert p.get_y() == 0\n assert p.get_height() == self.g.size / self.g.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(y=\"g\", data=self.df)\n assert len(ax.patches) == self.g.unique().size\n for p in ax.patches:\n assert p.get_x() == 0\n assert p.get_width() == self.g.size / self.g.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(x=\"g\", hue=\"h\", data=self.df)\n assert len(ax.patches) == self.g.unique().size * self.h.unique().size\n plt.close(\"all\")\n\n ax = cat.countplot(y=\"g\", hue=\"h\", data=self.df)\n assert len(ax.patches) == self.g.unique().size * self.h.unique().size\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2778,"header":"def test_input_error(self)","id":4855,"name":"test_input_error","nodeType":"Function","startLoc":2775,"text":"def test_input_error(self):\n\n with pytest.raises(ValueError):\n cat.countplot(x=\"g\", y=\"h\", data=self.df)"},{"className":"TestCatPlot","col":0,"comment":"null","endLoc":2980,"id":4856,"nodeType":"Class","startLoc":2781,"text":"class TestCatPlot(CategoricalFixture):\n\n def test_facet_organization(self):\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df)\n assert g.axes.shape == (1, 1)\n\n g = cat.catplot(x=\"g\", y=\"y\", col=\"h\", data=self.df)\n assert g.axes.shape == (1, 2)\n\n g = cat.catplot(x=\"g\", y=\"y\", row=\"h\", data=self.df)\n assert g.axes.shape == (2, 1)\n\n g = cat.catplot(x=\"g\", y=\"y\", col=\"u\", row=\"h\", data=self.df)\n assert g.axes.shape == (2, 3)\n\n def test_plot_elements(self):\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"point\")\n assert len(g.ax.collections) == 1\n want_lines = self.g.unique().size + 1\n assert len(g.ax.lines) == want_lines\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"point\")\n want_collections = self.h.unique().size\n assert len(g.ax.collections) == want_collections\n want_lines = (self.g.unique().size + 1) * self.h.unique().size\n assert len(g.ax.lines) == want_lines\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"bar\")\n want_elements = self.g.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"bar\")\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == want_elements\n\n g = cat.catplot(x=\"g\", data=self.df, kind=\"count\")\n want_elements = self.g.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == 0\n\n g = cat.catplot(x=\"g\", hue=\"h\", data=self.df, kind=\"count\")\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == 0\n\n g = cat.catplot(y=\"y\", data=self.df, kind=\"box\")\n want_artists = 1\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"box\")\n want_artists = self.g.unique().size\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"box\")\n want_artists = self.g.unique().size * self.h.unique().size\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"violin\", inner=None)\n want_elements = self.g.unique().size\n assert len(g.ax.collections) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n kind=\"violin\", inner=None)\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.collections) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"strip\")\n want_elements = self.g.unique().size\n assert len(g.ax.collections) == want_elements\n for strip in g.ax.collections:\n assert same_color(strip.get_facecolors(), \"C0\")\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"strip\")\n want_elements = self.g.unique().size + self.h.unique().size\n assert len(g.ax.collections) == want_elements\n\n def test_bad_plot_kind_error(self):\n\n with pytest.raises(ValueError):\n cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"not_a_kind\")\n\n def test_count_x_and_y(self):\n\n with pytest.raises(ValueError):\n cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"count\")\n\n def test_plot_colors(self):\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df)\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"bar\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"bar\", color=\"purple\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"bar\", palette=\"Set2\", hue=\"h\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df)\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df)\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n def test_ax_kwarg_removal(self):\n\n f, ax = plt.subplots()\n with pytest.warns(UserWarning, match=\"catplot is a figure-level\"):\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, ax=ax)\n assert len(ax.collections) == 0\n assert len(g.ax.collections) > 0\n\n def test_share_xy(self):\n\n # Test default behavior works\n g = cat.catplot(x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=True)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n g = cat.catplot(x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=True)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n # Test unsharing workscol\n with pytest.warns(UserWarning):\n g = cat.catplot(\n x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, kind=\"bar\",\n )\n for ax in g.axes.flat:\n assert len(ax.patches) == 1\n\n with pytest.warns(UserWarning):\n g = cat.catplot(\n x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, kind=\"bar\",\n )\n for ax in g.axes.flat:\n assert len(ax.patches) == 1\n\n # Make sure no warning is raised if color is provided on unshared plot\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n g = cat.catplot(\n x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, color=\"b\"\n )\n for ax in g.axes.flat:\n assert ax.get_xlim() == (-.5, .5)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n g = cat.catplot(\n x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, color=\"r\"\n )\n for ax in g.axes.flat:\n assert ax.get_ylim() == (.5, -.5)\n\n # Make sure order is used if given, regardless of sharex value\n order = self.df.g.unique()\n g = cat.catplot(x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, order=order)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n g = cat.catplot(x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, order=order)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n @pytest.mark.parametrize(\"var\", [\"col\", \"row\"])\n def test_array_faceter(self, long_df, var):\n\n g1 = catplot(data=long_df, x=\"y\", **{var: \"a\"})\n g2 = catplot(data=long_df, x=\"y\", **{var: long_df[\"a\"].to_numpy()})\n\n for ax1, ax2 in zip(g1.axes.flat, g2.axes.flat):\n assert_plots_equal(ax1, ax2)"},{"col":4,"comment":"null","endLoc":2795,"header":"def test_facet_organization(self)","id":4857,"name":"test_facet_organization","nodeType":"Function","startLoc":2783,"text":"def test_facet_organization(self):\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df)\n assert g.axes.shape == (1, 1)\n\n g = cat.catplot(x=\"g\", y=\"y\", col=\"h\", data=self.df)\n assert g.axes.shape == (1, 2)\n\n g = cat.catplot(x=\"g\", y=\"y\", row=\"h\", data=self.df)\n assert g.axes.shape == (2, 1)\n\n g = cat.catplot(x=\"g\", y=\"y\", col=\"u\", row=\"h\", data=self.df)\n assert g.axes.shape == (2, 3)"},{"col":4,"comment":"null","endLoc":2860,"header":"def test_plot_elements(self)","id":4858,"name":"test_plot_elements","nodeType":"Function","startLoc":2797,"text":"def test_plot_elements(self):\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"point\")\n assert len(g.ax.collections) == 1\n want_lines = self.g.unique().size + 1\n assert len(g.ax.lines) == want_lines\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"point\")\n want_collections = self.h.unique().size\n assert len(g.ax.collections) == want_collections\n want_lines = (self.g.unique().size + 1) * self.h.unique().size\n assert len(g.ax.lines) == want_lines\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"bar\")\n want_elements = self.g.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"bar\")\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == want_elements\n\n g = cat.catplot(x=\"g\", data=self.df, kind=\"count\")\n want_elements = self.g.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == 0\n\n g = cat.catplot(x=\"g\", hue=\"h\", data=self.df, kind=\"count\")\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.patches) == want_elements\n assert len(g.ax.lines) == 0\n\n g = cat.catplot(y=\"y\", data=self.df, kind=\"box\")\n want_artists = 1\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"box\")\n want_artists = self.g.unique().size\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"box\")\n want_artists = self.g.unique().size * self.h.unique().size\n assert len(self.get_box_artists(g.ax)) == want_artists\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"violin\", inner=None)\n want_elements = self.g.unique().size\n assert len(g.ax.collections) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df,\n kind=\"violin\", inner=None)\n want_elements = self.g.unique().size * self.h.unique().size\n assert len(g.ax.collections) == want_elements\n\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"strip\")\n want_elements = self.g.unique().size\n assert len(g.ax.collections) == want_elements\n for strip in g.ax.collections:\n assert same_color(strip.get_facecolors(), \"C0\")\n\n g = cat.catplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df, kind=\"strip\")\n want_elements = self.g.unique().size + self.h.unique().size\n assert len(g.ax.collections) == want_elements"},{"col":4,"comment":"null","endLoc":2865,"header":"def test_bad_plot_kind_error(self)","id":4859,"name":"test_bad_plot_kind_error","nodeType":"Function","startLoc":2862,"text":"def test_bad_plot_kind_error(self):\n\n with pytest.raises(ValueError):\n cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"not_a_kind\")"},{"col":4,"comment":"null","endLoc":2870,"header":"def test_count_x_and_y(self)","id":4860,"name":"test_count_x_and_y","nodeType":"Function","startLoc":2867,"text":"def test_count_x_and_y(self):\n\n with pytest.raises(ValueError):\n cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"count\")"},{"col":4,"comment":"null","endLoc":2910,"header":"def test_plot_colors(self)","id":4861,"name":"test_plot_colors","nodeType":"Function","startLoc":2872,"text":"def test_plot_colors(self):\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df)\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, kind=\"bar\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"bar\", color=\"purple\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.barplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df,\n kind=\"bar\", palette=\"Set2\", hue=\"h\")\n for p1, p2 in zip(ax.patches, g.ax.patches):\n assert p1.get_facecolor() == p2.get_facecolor()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df)\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df)\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, color=\"purple\")\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")\n\n ax = cat.pointplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, palette=\"Set2\", hue=\"h\")\n for l1, l2 in zip(ax.lines, g.ax.lines):\n assert l1.get_color() == l2.get_color()\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2918,"header":"def test_ax_kwarg_removal(self)","id":4862,"name":"test_ax_kwarg_removal","nodeType":"Function","startLoc":2912,"text":"def test_ax_kwarg_removal(self):\n\n f, ax = plt.subplots()\n with pytest.warns(UserWarning, match=\"catplot is a figure-level\"):\n g = cat.catplot(x=\"g\", y=\"y\", data=self.df, ax=ax)\n assert len(ax.collections) == 0\n assert len(g.ax.collections) > 0"},{"col":4,"comment":"null","endLoc":2971,"header":"def test_share_xy(self)","id":4863,"name":"test_share_xy","nodeType":"Function","startLoc":2920,"text":"def test_share_xy(self):\n\n # Test default behavior works\n g = cat.catplot(x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=True)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n g = cat.catplot(x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=True)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n # Test unsharing workscol\n with pytest.warns(UserWarning):\n g = cat.catplot(\n x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, kind=\"bar\",\n )\n for ax in g.axes.flat:\n assert len(ax.patches) == 1\n\n with pytest.warns(UserWarning):\n g = cat.catplot(\n x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, kind=\"bar\",\n )\n for ax in g.axes.flat:\n assert len(ax.patches) == 1\n\n # Make sure no warning is raised if color is provided on unshared plot\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n g = cat.catplot(\n x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, color=\"b\"\n )\n for ax in g.axes.flat:\n assert ax.get_xlim() == (-.5, .5)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n g = cat.catplot(\n x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, color=\"r\"\n )\n for ax in g.axes.flat:\n assert ax.get_ylim() == (.5, -.5)\n\n # Make sure order is used if given, regardless of sharex value\n order = self.df.g.unique()\n g = cat.catplot(x=\"g\", y=\"y\", col=\"g\", data=self.df, sharex=False, order=order)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())\n\n g = cat.catplot(x=\"y\", y=\"g\", col=\"g\", data=self.df, sharey=False, order=order)\n for ax in g.axes.flat:\n assert len(ax.collections) == len(self.df.g.unique())"},{"col":4,"comment":"null","endLoc":2980,"header":"@pytest.mark.parametrize(\"var\", [\"col\", \"row\"])\n def test_array_faceter(self, long_df, var)","id":4864,"name":"test_array_faceter","nodeType":"Function","startLoc":2973,"text":"@pytest.mark.parametrize(\"var\", [\"col\", \"row\"])\n def test_array_faceter(self, long_df, var):\n\n g1 = catplot(data=long_df, x=\"y\", **{var: \"a\"})\n g2 = catplot(data=long_df, x=\"y\", **{var: long_df[\"a\"].to_numpy()})\n\n for ax1, ax2 in zip(g1.axes.flat, g2.axes.flat):\n assert_plots_equal(ax1, ax2)"},{"className":"TestBoxenPlotter","col":0,"comment":"null","endLoc":3418,"id":4865,"nodeType":"Class","startLoc":2983,"text":"class TestBoxenPlotter(CategoricalFixture):\n\n default_kws = dict(x=None, y=None, hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None,\n saturation=.75, width=.8, dodge=True,\n k_depth='tukey', linewidth=None,\n scale='exponential', outlier_prop=0.007,\n trust_alpha=0.05, showfliers=True)\n\n def ispatch(self, c):\n\n return isinstance(c, mpl.collections.PatchCollection)\n\n def ispath(self, c):\n\n return isinstance(c, mpl.collections.PathCollection)\n\n def edge_calc(self, n, data):\n\n q = np.asanyarray([0.5 ** n, 1 - 0.5 ** n]) * 100\n q = list(np.unique(q))\n return np.percentile(data, q)\n\n def test_box_ends_finite(self):\n\n p = cat._LVPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", data=self.df)\n box_ends = []\n k_vals = []\n for s in p.plot_data:\n b, k = p._lv_box_ends(s)\n box_ends.append(b)\n k_vals.append(k)\n\n # Check that all the box ends are finite and are within\n # the bounds of the data\n b_e = map(lambda a: np.all(np.isfinite(a)), box_ends)\n assert np.sum(list(b_e)) == len(box_ends)\n\n def within(t):\n a, d = t\n return ((np.ravel(a) <= d.max())\n & (np.ravel(a) >= d.min())).all()\n\n b_w = map(within, zip(box_ends, p.plot_data))\n assert np.sum(list(b_w)) == len(box_ends)\n\n k_f = map(lambda k: (k > 0.) & np.isfinite(k), k_vals)\n assert np.sum(list(k_f)) == len(k_vals)\n\n def test_box_ends_correct_tukey(self):\n\n n = 100\n linear_data = np.arange(n)\n expected_k = max(int(np.log2(n)) - 3, 1)\n expected_edges = [self.edge_calc(i, linear_data)\n for i in range(expected_k + 1, 1, -1)]\n\n p = cat._LVPlotter(**self.default_kws)\n calc_edges, calc_k = p._lv_box_ends(linear_data)\n\n npt.assert_array_equal(expected_edges, calc_edges)\n assert expected_k == calc_k\n\n def test_box_ends_correct_proportion(self):\n\n n = 100\n linear_data = np.arange(n)\n expected_k = int(np.log2(n)) - int(np.log2(n * 0.007)) + 1\n expected_edges = [self.edge_calc(i, linear_data)\n for i in range(expected_k + 1, 1, -1)]\n\n kws = self.default_kws.copy()\n kws[\"k_depth\"] = \"proportion\"\n p = cat._LVPlotter(**kws)\n calc_edges, calc_k = p._lv_box_ends(linear_data)\n\n npt.assert_array_equal(expected_edges, calc_edges)\n assert expected_k == calc_k\n\n @pytest.mark.parametrize(\n \"n,exp_k\",\n [(491, 6), (492, 7), (983, 7), (984, 8), (1966, 8), (1967, 9)],\n )\n def test_box_ends_correct_trustworthy(self, n, exp_k):\n\n linear_data = np.arange(n)\n kws = self.default_kws.copy()\n kws[\"k_depth\"] = \"trustworthy\"\n p = cat._LVPlotter(**kws)\n _, calc_k = p._lv_box_ends(linear_data)\n\n assert exp_k == calc_k\n\n def test_outliers(self):\n\n n = 100\n outlier_data = np.append(np.arange(n - 1), 2 * n)\n expected_k = max(int(np.log2(n)) - 3, 1)\n expected_edges = [self.edge_calc(i, outlier_data)\n for i in range(expected_k + 1, 1, -1)]\n\n p = cat._LVPlotter(**self.default_kws)\n calc_edges, calc_k = p._lv_box_ends(outlier_data)\n\n npt.assert_array_equal(calc_edges, expected_edges)\n assert calc_k == expected_k\n\n out_calc = p._lv_outliers(outlier_data, calc_k)\n out_exp = p._lv_outliers(outlier_data, expected_k)\n\n npt.assert_equal(out_calc, out_exp)\n\n def test_showfliers(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df, k_depth=\"proportion\",\n showfliers=True)\n ax_collections = list(filter(self.ispath, ax.collections))\n for c in ax_collections:\n assert len(c.get_offsets()) == 2\n\n # Test that all data points are in the plot\n assert ax.get_ylim()[0] < self.df[\"y\"].min()\n assert ax.get_ylim()[1] > self.df[\"y\"].max()\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df, showfliers=False)\n assert len(list(filter(self.ispath, ax.collections))) == 0\n\n plt.close(\"all\")\n\n def test_invalid_depths(self):\n\n kws = self.default_kws.copy()\n\n # Make sure illegal depth raises\n kws[\"k_depth\"] = \"nosuchdepth\"\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n # Make sure illegal outlier_prop raises\n kws[\"k_depth\"] = \"proportion\"\n for p in (-13, 37):\n kws[\"outlier_prop\"] = p\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n kws[\"k_depth\"] = \"trustworthy\"\n for alpha in (-13, 37):\n kws[\"trust_alpha\"] = alpha\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n @pytest.mark.parametrize(\"power\", [1, 3, 7, 11, 13, 17])\n def test_valid_depths(self, power):\n\n x = np.random.standard_t(10, 2 ** power)\n\n valid_depths = [\"proportion\", \"tukey\", \"trustworthy\", \"full\"]\n kws = self.default_kws.copy()\n\n for depth in valid_depths + [4]:\n kws[\"k_depth\"] = depth\n box_ends, k = cat._LVPlotter(**kws)._lv_box_ends(x)\n\n if depth == \"full\":\n assert k == int(np.log2(len(x))) + 1\n\n def test_valid_scales(self):\n\n valid_scales = [\"linear\", \"exponential\", \"area\"]\n kws = self.default_kws.copy()\n\n for scale in valid_scales + [\"unknown_scale\"]:\n kws[\"scale\"] = scale\n if scale not in valid_scales:\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n else:\n cat._LVPlotter(**kws)\n\n def test_hue_offsets(self):\n\n p = cat._LVPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.2, .2])\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._LVPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.15, .15])\n\n p = cat._LVPlotter(**kws)\n p.establish_variables(\"h\", \"y\", \"g\", data=self.df)\n npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])\n\n def test_axes_data(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 3\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 6\n\n plt.close(\"all\")\n\n def test_box_colors(self):\n\n pal = palettes.color_palette()\n\n ax = cat.boxenplot(\n x=\"g\", y=\"y\", data=self.df, saturation=1, showfliers=False\n )\n ax.figure.canvas.draw()\n for i, box in enumerate(ax.collections):\n assert same_color(box.get_facecolor()[0], pal[i])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(\n x=\"g\", y=\"y\", hue=\"h\", data=self.df, saturation=1, showfliers=False\n )\n ax.figure.canvas.draw()\n for i, box in enumerate(ax.collections):\n assert same_color(box.get_facecolor()[0], pal[i % 2])\n\n plt.close(\"all\")\n\n def test_draw_missing_boxes(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df,\n order=[\"a\", \"b\", \"c\", \"d\"])\n\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 3\n plt.close(\"all\")\n\n def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.boxenplot(x=self.g, y=self.y, ax=ax1)\n cat.boxenplot(x=self.g, y=self.y_perm, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.boxenplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, ax=ax1)\n cat.boxenplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n def test_missing_data(self):\n\n x = [\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"d\"]\n h = [\"x\", \"y\", \"x\", \"y\", \"x\", \"y\", \"x\", \"y\"]\n y = self.rs.randn(8)\n y[-2:] = np.nan\n\n ax = cat.boxenplot(x=x, y=y)\n assert len(ax.lines) == 3\n\n plt.close(\"all\")\n\n y[-1] = 0\n ax = cat.boxenplot(x=x, y=y, hue=h)\n assert len(ax.lines) == 7\n\n plt.close(\"all\")\n\n def test_boxenplots(self):\n\n # Smoke test the high level boxenplot options\n\n cat.boxenplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n for scale in (\"linear\", \"area\", \"exponential\"):\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", scale=scale, data=self.df)\n plt.close(\"all\")\n\n for depth in (\"proportion\", \"tukey\", \"trustworthy\"):\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", k_depth=depth, data=self.df)\n plt.close(\"all\")\n\n order = list(\"nabc\")\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", order=order, data=self.df)\n plt.close(\"all\")\n\n order = list(\"omn\")\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=order, data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\",\n palette=\"Set2\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df,\n orient=\"h\", color=\"b\")\n plt.close(\"all\")\n\n def test_axes_annotation(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n assert ax.get_xlim() == (-.5, 2.5)\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],\n [\"m\", \"n\"])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n assert ax.get_ylim() == (2.5, -.5)\n npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n @pytest.mark.parametrize(\"size\", [\"large\", \"medium\", \"small\", 22, 12])\n def test_legend_titlesize(self, size):\n\n rc_ctx = {\"legend.title_fontsize\": size}\n exp = mpl.font_manager.FontProperties(size=size).get_size()\n\n with plt.rc_context(rc=rc_ctx):\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n obs = ax.get_legend().get_title().get_fontproperties().get_size()\n assert obs == exp\n\n plt.close(\"all\")\n\n @pytest.mark.skipif(\n Version(pd.__version__) < Version(\"1.2\"),\n reason=\"Test requires pandas>=1.2\")\n def test_Float64_input(self):\n data = pd.DataFrame(\n {\"x\": np.random.choice([\"a\", \"b\"], 20), \"y\": np.random.random(20)}\n )\n data['y'] = data['y'].astype(pd.Float64Dtype())\n _ = cat.boxenplot(x=\"x\", y=\"y\", data=data)\n\n plt.close(\"all\")\n\n def test_line_kws(self):\n line_kws = {'linewidth': 5, 'color': 'purple',\n 'linestyle': '-.'}\n\n ax = cat.boxenplot(data=self.df, y='y', line_kws=line_kws)\n\n median_line = ax.lines[0]\n\n assert median_line.get_linewidth() == line_kws['linewidth']\n assert median_line.get_linestyle() == line_kws['linestyle']\n assert median_line.get_color() == line_kws['color']\n\n plt.close(\"all\")\n\n def test_flier_kws(self):\n flier_kws = {\n 'marker': 'v',\n 'color': np.array([[1, 0, 0, 1]]),\n 's': 5,\n }\n\n ax = cat.boxenplot(data=self.df, y='y', x='g', flier_kws=flier_kws)\n\n outliers_scatter = ax.findobj(mpl.collections.PathCollection)[0]\n\n # The number of vertices for a triangle is 3, the length of Path\n # collection objects is defined as n + 1 vertices.\n assert len(outliers_scatter.get_paths()[0]) == 4\n assert len(outliers_scatter.get_paths()[-1]) == 4\n\n assert (outliers_scatter.get_facecolor() == flier_kws['color']).all()\n\n assert np.unique(outliers_scatter.get_sizes()) == flier_kws['s']\n\n plt.close(\"all\")\n\n def test_box_kws(self):\n\n box_kws = {'linewidth': 5, 'edgecolor': np.array([[0, 1, 0, 1]])}\n\n ax = cat.boxenplot(data=self.df, y='y', x='g',\n box_kws=box_kws)\n\n boxes = ax.findobj(mpl.collections.PatchCollection)[0]\n\n # The number of vertices for a triangle is 3, the length of Path\n # collection objects is defined as n + 1 vertices.\n assert len(boxes.get_paths()[0]) == 5\n assert len(boxes.get_paths()[-1]) == 5\n\n assert np.unique(boxes.get_linewidth() == box_kws['linewidth'])\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":2995,"header":"def ispatch(self, c)","id":4866,"name":"ispatch","nodeType":"Function","startLoc":2993,"text":"def ispatch(self, c):\n\n return isinstance(c, mpl.collections.PatchCollection)"},{"col":4,"comment":"null","endLoc":2999,"header":"def ispath(self, c)","id":4867,"name":"ispath","nodeType":"Function","startLoc":2997,"text":"def ispath(self, c):\n\n return isinstance(c, mpl.collections.PathCollection)"},{"col":4,"comment":"null","endLoc":3005,"header":"def edge_calc(self, n, data)","id":4868,"name":"edge_calc","nodeType":"Function","startLoc":3001,"text":"def edge_calc(self, n, data):\n\n q = np.asanyarray([0.5 ** n, 1 - 0.5 ** n]) * 100\n q = list(np.unique(q))\n return np.percentile(data, q)"},{"col":4,"comment":"null","endLoc":3032,"header":"def test_box_ends_finite(self)","id":4869,"name":"test_box_ends_finite","nodeType":"Function","startLoc":3007,"text":"def test_box_ends_finite(self):\n\n p = cat._LVPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", data=self.df)\n box_ends = []\n k_vals = []\n for s in p.plot_data:\n b, k = p._lv_box_ends(s)\n box_ends.append(b)\n k_vals.append(k)\n\n # Check that all the box ends are finite and are within\n # the bounds of the data\n b_e = map(lambda a: np.all(np.isfinite(a)), box_ends)\n assert np.sum(list(b_e)) == len(box_ends)\n\n def within(t):\n a, d = t\n return ((np.ravel(a) <= d.max())\n & (np.ravel(a) >= d.min())).all()\n\n b_w = map(within, zip(box_ends, p.plot_data))\n assert np.sum(list(b_w)) == len(box_ends)\n\n k_f = map(lambda k: (k > 0.) & np.isfinite(k), k_vals)\n assert np.sum(list(k_f)) == len(k_vals)"},{"col":18,"endLoc":3020,"id":4870,"nodeType":"Lambda","startLoc":3020,"text":"lambda a: np.all(np.isfinite(a))"},{"col":18,"endLoc":3031,"id":4871,"nodeType":"Lambda","startLoc":3031,"text":"lambda k: (k > 0.) & np.isfinite(k)"},{"col":4,"comment":"null","endLoc":3046,"header":"def test_box_ends_correct_tukey(self)","id":4872,"name":"test_box_ends_correct_tukey","nodeType":"Function","startLoc":3034,"text":"def test_box_ends_correct_tukey(self):\n\n n = 100\n linear_data = np.arange(n)\n expected_k = max(int(np.log2(n)) - 3, 1)\n expected_edges = [self.edge_calc(i, linear_data)\n for i in range(expected_k + 1, 1, -1)]\n\n p = cat._LVPlotter(**self.default_kws)\n calc_edges, calc_k = p._lv_box_ends(linear_data)\n\n npt.assert_array_equal(expected_edges, calc_edges)\n assert expected_k == calc_k"},{"col":4,"comment":"null","endLoc":3062,"header":"def test_box_ends_correct_proportion(self)","id":4873,"name":"test_box_ends_correct_proportion","nodeType":"Function","startLoc":3048,"text":"def test_box_ends_correct_proportion(self):\n\n n = 100\n linear_data = np.arange(n)\n expected_k = int(np.log2(n)) - int(np.log2(n * 0.007)) + 1\n expected_edges = [self.edge_calc(i, linear_data)\n for i in range(expected_k + 1, 1, -1)]\n\n kws = self.default_kws.copy()\n kws[\"k_depth\"] = \"proportion\"\n p = cat._LVPlotter(**kws)\n calc_edges, calc_k = p._lv_box_ends(linear_data)\n\n npt.assert_array_equal(expected_edges, calc_edges)\n assert expected_k == calc_k"},{"col":4,"comment":"null","endLoc":3076,"header":"@pytest.mark.parametrize(\n \"n,exp_k\",\n [(491, 6), (492, 7), (983, 7), (984, 8), (1966, 8), (1967, 9)],\n )\n def test_box_ends_correct_trustworthy(self, n, exp_k)","id":4874,"name":"test_box_ends_correct_trustworthy","nodeType":"Function","startLoc":3064,"text":"@pytest.mark.parametrize(\n \"n,exp_k\",\n [(491, 6), (492, 7), (983, 7), (984, 8), (1966, 8), (1967, 9)],\n )\n def test_box_ends_correct_trustworthy(self, n, exp_k):\n\n linear_data = np.arange(n)\n kws = self.default_kws.copy()\n kws[\"k_depth\"] = \"trustworthy\"\n p = cat._LVPlotter(**kws)\n _, calc_k = p._lv_box_ends(linear_data)\n\n assert exp_k == calc_k"},{"col":4,"comment":"null","endLoc":3095,"header":"def test_outliers(self)","id":4875,"name":"test_outliers","nodeType":"Function","startLoc":3078,"text":"def test_outliers(self):\n\n n = 100\n outlier_data = np.append(np.arange(n - 1), 2 * n)\n expected_k = max(int(np.log2(n)) - 3, 1)\n expected_edges = [self.edge_calc(i, outlier_data)\n for i in range(expected_k + 1, 1, -1)]\n\n p = cat._LVPlotter(**self.default_kws)\n calc_edges, calc_k = p._lv_box_ends(outlier_data)\n\n npt.assert_array_equal(calc_edges, expected_edges)\n assert calc_k == expected_k\n\n out_calc = p._lv_outliers(outlier_data, calc_k)\n out_exp = p._lv_outliers(outlier_data, expected_k)\n\n npt.assert_equal(out_calc, out_exp)"},{"col":4,"comment":"null","endLoc":3114,"header":"def test_showfliers(self)","id":4876,"name":"test_showfliers","nodeType":"Function","startLoc":3097,"text":"def test_showfliers(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df, k_depth=\"proportion\",\n showfliers=True)\n ax_collections = list(filter(self.ispath, ax.collections))\n for c in ax_collections:\n assert len(c.get_offsets()) == 2\n\n # Test that all data points are in the plot\n assert ax.get_ylim()[0] < self.df[\"y\"].min()\n assert ax.get_ylim()[1] > self.df[\"y\"].max()\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df, showfliers=False)\n assert len(list(filter(self.ispath, ax.collections))) == 0\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3136,"header":"def test_invalid_depths(self)","id":4877,"name":"test_invalid_depths","nodeType":"Function","startLoc":3116,"text":"def test_invalid_depths(self):\n\n kws = self.default_kws.copy()\n\n # Make sure illegal depth raises\n kws[\"k_depth\"] = \"nosuchdepth\"\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n # Make sure illegal outlier_prop raises\n kws[\"k_depth\"] = \"proportion\"\n for p in (-13, 37):\n kws[\"outlier_prop\"] = p\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n\n kws[\"k_depth\"] = \"trustworthy\"\n for alpha in (-13, 37):\n kws[\"trust_alpha\"] = alpha\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)"},{"col":4,"comment":"null","endLoc":3151,"header":"@pytest.mark.parametrize(\"power\", [1, 3, 7, 11, 13, 17])\n def test_valid_depths(self, power)","id":4878,"name":"test_valid_depths","nodeType":"Function","startLoc":3138,"text":"@pytest.mark.parametrize(\"power\", [1, 3, 7, 11, 13, 17])\n def test_valid_depths(self, power):\n\n x = np.random.standard_t(10, 2 ** power)\n\n valid_depths = [\"proportion\", \"tukey\", \"trustworthy\", \"full\"]\n kws = self.default_kws.copy()\n\n for depth in valid_depths + [4]:\n kws[\"k_depth\"] = depth\n box_ends, k = cat._LVPlotter(**kws)._lv_box_ends(x)\n\n if depth == \"full\":\n assert k == int(np.log2(len(x))) + 1"},{"col":4,"comment":"null","endLoc":3164,"header":"def test_valid_scales(self)","id":4879,"name":"test_valid_scales","nodeType":"Function","startLoc":3153,"text":"def test_valid_scales(self):\n\n valid_scales = [\"linear\", \"exponential\", \"area\"]\n kws = self.default_kws.copy()\n\n for scale in valid_scales + [\"unknown_scale\"]:\n kws[\"scale\"] = scale\n if scale not in valid_scales:\n with pytest.raises(ValueError):\n cat._LVPlotter(**kws)\n else:\n cat._LVPlotter(**kws)"},{"col":4,"comment":"null","endLoc":3180,"header":"def test_hue_offsets(self)","id":4880,"name":"test_hue_offsets","nodeType":"Function","startLoc":3166,"text":"def test_hue_offsets(self):\n\n p = cat._LVPlotter(**self.default_kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.2, .2])\n\n kws = self.default_kws.copy()\n kws[\"width\"] = .6\n p = cat._LVPlotter(**kws)\n p.establish_variables(\"g\", \"y\", hue=\"h\", data=self.df)\n npt.assert_array_equal(p.hue_offsets, [-.15, .15])\n\n p = cat._LVPlotter(**kws)\n p.establish_variables(\"h\", \"y\", \"g\", data=self.df)\n npt.assert_array_almost_equal(p.hue_offsets, [-.2, 0, .2])"},{"col":4,"comment":"null","endLoc":3194,"header":"def test_axes_data(self)","id":4881,"name":"test_axes_data","nodeType":"Function","startLoc":3182,"text":"def test_axes_data(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 3\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 6\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3216,"header":"def test_box_colors(self)","id":4882,"name":"test_box_colors","nodeType":"Function","startLoc":3196,"text":"def test_box_colors(self):\n\n pal = palettes.color_palette()\n\n ax = cat.boxenplot(\n x=\"g\", y=\"y\", data=self.df, saturation=1, showfliers=False\n )\n ax.figure.canvas.draw()\n for i, box in enumerate(ax.collections):\n assert same_color(box.get_facecolor()[0], pal[i])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(\n x=\"g\", y=\"y\", hue=\"h\", data=self.df, saturation=1, showfliers=False\n )\n ax.figure.canvas.draw()\n for i, box in enumerate(ax.collections):\n assert same_color(box.get_facecolor()[0], pal[i % 2])\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3225,"header":"def test_draw_missing_boxes(self)","id":4883,"name":"test_draw_missing_boxes","nodeType":"Function","startLoc":3218,"text":"def test_draw_missing_boxes(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df,\n order=[\"a\", \"b\", \"c\", \"d\"])\n\n patches = filter(self.ispatch, ax.collections)\n assert len(list(patches)) == 3\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3242,"header":"def test_unaligned_index(self)","id":4884,"name":"test_unaligned_index","nodeType":"Function","startLoc":3227,"text":"def test_unaligned_index(self):\n\n f, (ax1, ax2) = plt.subplots(2)\n cat.boxenplot(x=self.g, y=self.y, ax=ax1)\n cat.boxenplot(x=self.g, y=self.y_perm, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())\n\n f, (ax1, ax2) = plt.subplots(2)\n hue_order = self.h.unique()\n cat.boxenplot(x=self.g, y=self.y, hue=self.h,\n hue_order=hue_order, ax=ax1)\n cat.boxenplot(x=self.g, y=self.y_perm, hue=self.h,\n hue_order=hue_order, ax=ax2)\n for l1, l2 in zip(ax1.lines, ax2.lines):\n assert np.array_equal(l1.get_xydata(), l2.get_xydata())"},{"col":4,"comment":"null","endLoc":3260,"header":"def test_missing_data(self)","id":4885,"name":"test_missing_data","nodeType":"Function","startLoc":3244,"text":"def test_missing_data(self):\n\n x = [\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"d\"]\n h = [\"x\", \"y\", \"x\", \"y\", \"x\", \"y\", \"x\", \"y\"]\n y = self.rs.randn(8)\n y[-2:] = np.nan\n\n ax = cat.boxenplot(x=x, y=y)\n assert len(ax.lines) == 3\n\n plt.close(\"all\")\n\n y[-1] = 0\n ax = cat.boxenplot(x=x, y=y, hue=h)\n assert len(ax.lines) == 7\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3306,"header":"def test_boxenplots(self)","id":4886,"name":"test_boxenplots","nodeType":"Function","startLoc":3262,"text":"def test_boxenplots(self):\n\n # Smoke test the high level boxenplot options\n\n cat.boxenplot(x=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n plt.close(\"all\")\n\n for scale in (\"linear\", \"area\", \"exponential\"):\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", scale=scale, data=self.df)\n plt.close(\"all\")\n\n for depth in (\"proportion\", \"tukey\", \"trustworthy\"):\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", k_depth=depth, data=self.df)\n plt.close(\"all\")\n\n order = list(\"nabc\")\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", order=order, data=self.df)\n plt.close(\"all\")\n\n order = list(\"omn\")\n cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", hue_order=order, data=self.df)\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df, orient=\"h\",\n palette=\"Set2\")\n plt.close(\"all\")\n\n cat.boxenplot(x=\"y\", y=\"g\", hue=\"h\", data=self.df,\n orient=\"h\", color=\"b\")\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3339,"header":"def test_axes_annotation(self)","id":4887,"name":"test_axes_annotation","nodeType":"Function","startLoc":3308,"text":"def test_axes_annotation(self):\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n assert ax.get_xlim() == (-.5, 2.5)\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n assert ax.get_xlabel() == \"g\"\n assert ax.get_ylabel() == \"y\"\n npt.assert_array_equal(ax.get_xticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_xticklabels()],\n [\"a\", \"b\", \"c\"])\n npt.assert_array_equal([l.get_text() for l in ax.legend_.get_texts()],\n [\"m\", \"n\"])\n\n plt.close(\"all\")\n\n ax = cat.boxenplot(x=\"y\", y=\"g\", data=self.df, orient=\"h\")\n assert ax.get_xlabel() == \"y\"\n assert ax.get_ylabel() == \"g\"\n assert ax.get_ylim() == (2.5, -.5)\n npt.assert_array_equal(ax.get_yticks(), [0, 1, 2])\n npt.assert_array_equal([l.get_text() for l in ax.get_yticklabels()],\n [\"a\", \"b\", \"c\"])\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3352,"header":"@pytest.mark.parametrize(\"size\", [\"large\", \"medium\", \"small\", 22, 12])\n def test_legend_titlesize(self, size)","id":4888,"name":"test_legend_titlesize","nodeType":"Function","startLoc":3341,"text":"@pytest.mark.parametrize(\"size\", [\"large\", \"medium\", \"small\", 22, 12])\n def test_legend_titlesize(self, size):\n\n rc_ctx = {\"legend.title_fontsize\": size}\n exp = mpl.font_manager.FontProperties(size=size).get_size()\n\n with plt.rc_context(rc=rc_ctx):\n ax = cat.boxenplot(x=\"g\", y=\"y\", hue=\"h\", data=self.df)\n obs = ax.get_legend().get_title().get_fontproperties().get_size()\n assert obs == exp\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3364,"header":"@pytest.mark.skipif(\n Version(pd.__version__) < Version(\"1.2\"),\n reason=\"Test requires pandas>=1.2\")\n def test_Float64_input(self)","id":4889,"name":"test_Float64_input","nodeType":"Function","startLoc":3354,"text":"@pytest.mark.skipif(\n Version(pd.__version__) < Version(\"1.2\"),\n reason=\"Test requires pandas>=1.2\")\n def test_Float64_input(self):\n data = pd.DataFrame(\n {\"x\": np.random.choice([\"a\", \"b\"], 20), \"y\": np.random.random(20)}\n )\n data['y'] = data['y'].astype(pd.Float64Dtype())\n _ = cat.boxenplot(x=\"x\", y=\"y\", data=data)\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3378,"header":"def test_line_kws(self)","id":4890,"name":"test_line_kws","nodeType":"Function","startLoc":3366,"text":"def test_line_kws(self):\n line_kws = {'linewidth': 5, 'color': 'purple',\n 'linestyle': '-.'}\n\n ax = cat.boxenplot(data=self.df, y='y', line_kws=line_kws)\n\n median_line = ax.lines[0]\n\n assert median_line.get_linewidth() == line_kws['linewidth']\n assert median_line.get_linestyle() == line_kws['linestyle']\n assert median_line.get_color() == line_kws['color']\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3400,"header":"def test_flier_kws(self)","id":4891,"name":"test_flier_kws","nodeType":"Function","startLoc":3380,"text":"def test_flier_kws(self):\n flier_kws = {\n 'marker': 'v',\n 'color': np.array([[1, 0, 0, 1]]),\n 's': 5,\n }\n\n ax = cat.boxenplot(data=self.df, y='y', x='g', flier_kws=flier_kws)\n\n outliers_scatter = ax.findobj(mpl.collections.PathCollection)[0]\n\n # The number of vertices for a triangle is 3, the length of Path\n # collection objects is defined as n + 1 vertices.\n assert len(outliers_scatter.get_paths()[0]) == 4\n assert len(outliers_scatter.get_paths()[-1]) == 4\n\n assert (outliers_scatter.get_facecolor() == flier_kws['color']).all()\n\n assert np.unique(outliers_scatter.get_sizes()) == flier_kws['s']\n\n plt.close(\"all\")"},{"col":4,"comment":"null","endLoc":3418,"header":"def test_box_kws(self)","id":4892,"name":"test_box_kws","nodeType":"Function","startLoc":3402,"text":"def test_box_kws(self):\n\n box_kws = {'linewidth': 5, 'edgecolor': np.array([[0, 1, 0, 1]])}\n\n ax = cat.boxenplot(data=self.df, y='y', x='g',\n box_kws=box_kws)\n\n boxes = ax.findobj(mpl.collections.PatchCollection)[0]\n\n # The number of vertices for a triangle is 3, the length of Path\n # collection objects is defined as n + 1 vertices.\n assert len(boxes.get_paths()[0]) == 5\n assert len(boxes.get_paths()[-1]) == 5\n\n assert np.unique(boxes.get_linewidth() == box_kws['linewidth'])\n\n plt.close(\"all\")"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":2985,"id":4893,"name":"default_kws","nodeType":"Attribute","startLoc":2985,"text":"default_kws"},{"className":"TestBeeswarm","col":0,"comment":"null","endLoc":3482,"id":4894,"nodeType":"Class","startLoc":3421,"text":"class TestBeeswarm:\n\n def test_could_overlap(self):\n\n p = Beeswarm()\n neighbors = p.could_overlap(\n (1, 1, .5),\n [(0, 0, .5),\n (1, .1, .2),\n (.5, .5, .5)]\n )\n assert_array_equal(neighbors, [(.5, .5, .5)])\n\n def test_position_candidates(self):\n\n p = Beeswarm()\n xy_i = (0, 1, .5)\n neighbors = [(0, 1, .5), (0, 1.5, .5)]\n candidates = p.position_candidates(xy_i, neighbors)\n dx1 = 1.05\n dx2 = np.sqrt(1 - .5 ** 2) * 1.05\n assert_array_equal(\n candidates,\n [(0, 1, .5), (-dx1, 1, .5), (dx1, 1, .5), (dx2, 1, .5), (-dx2, 1, .5)]\n )\n\n def test_find_first_non_overlapping_candidate(self):\n\n p = Beeswarm()\n candidates = [(.5, 1, .5), (1, 1, .5), (1.5, 1, .5)]\n neighbors = np.array([(0, 1, .5)])\n\n first = p.first_non_overlapping_candidate(candidates, neighbors)\n assert_array_equal(first, (1, 1, .5))\n\n def test_beeswarm(self, long_df):\n\n p = Beeswarm()\n data = long_df[\"y\"]\n d = data.diff().mean() * 1.5\n x = np.zeros(data.size)\n y = np.sort(data)\n r = np.full_like(y, d)\n orig_xyr = np.c_[x, y, r]\n swarm = p.beeswarm(orig_xyr)[:, :2]\n dmat = np.sqrt(np.sum(np.square(swarm[:, np.newaxis] - swarm), axis=-1))\n triu = dmat[np.triu_indices_from(dmat, 1)]\n assert_array_less(d, triu)\n assert_array_equal(y, swarm[:, 1])\n\n def test_add_gutters(self):\n\n p = Beeswarm(width=1)\n\n points = np.zeros(10)\n assert_array_equal(points, p.add_gutters(points, 0))\n\n points = np.array([0, -1, .4, .8])\n msg = r\"50.0% of the points cannot be placed.+$\"\n with pytest.warns(UserWarning, match=msg):\n new_points = p.add_gutters(points, 0)\n assert_array_equal(new_points, np.array([0, -.5, .4, .5]))"},{"col":4,"comment":"null","endLoc":3432,"header":"def test_could_overlap(self)","id":4895,"name":"test_could_overlap","nodeType":"Function","startLoc":3423,"text":"def test_could_overlap(self):\n\n p = Beeswarm()\n neighbors = p.could_overlap(\n (1, 1, .5),\n [(0, 0, .5),\n (1, .1, .2),\n (.5, .5, .5)]\n )\n assert_array_equal(neighbors, [(.5, .5, .5)])"},{"col":4,"comment":"null","endLoc":3445,"header":"def test_position_candidates(self)","id":4896,"name":"test_position_candidates","nodeType":"Function","startLoc":3434,"text":"def test_position_candidates(self):\n\n p = Beeswarm()\n xy_i = (0, 1, .5)\n neighbors = [(0, 1, .5), (0, 1.5, .5)]\n candidates = p.position_candidates(xy_i, neighbors)\n dx1 = 1.05\n dx2 = np.sqrt(1 - .5 ** 2) * 1.05\n assert_array_equal(\n candidates,\n [(0, 1, .5), (-dx1, 1, .5), (dx1, 1, .5), (dx2, 1, .5), (-dx2, 1, .5)]\n )"},{"col":4,"comment":"null","endLoc":3454,"header":"def test_find_first_non_overlapping_candidate(self)","id":4897,"name":"test_find_first_non_overlapping_candidate","nodeType":"Function","startLoc":3447,"text":"def test_find_first_non_overlapping_candidate(self):\n\n p = Beeswarm()\n candidates = [(.5, 1, .5), (1, 1, .5), (1.5, 1, .5)]\n neighbors = np.array([(0, 1, .5)])\n\n first = p.first_non_overlapping_candidate(candidates, neighbors)\n assert_array_equal(first, (1, 1, .5))"},{"col":4,"comment":"null","endLoc":3469,"header":"def test_beeswarm(self, long_df)","id":4898,"name":"test_beeswarm","nodeType":"Function","startLoc":3456,"text":"def test_beeswarm(self, long_df):\n\n p = Beeswarm()\n data = long_df[\"y\"]\n d = data.diff().mean() * 1.5\n x = np.zeros(data.size)\n y = np.sort(data)\n r = np.full_like(y, d)\n orig_xyr = np.c_[x, y, r]\n swarm = p.beeswarm(orig_xyr)[:, :2]\n dmat = np.sqrt(np.sum(np.square(swarm[:, np.newaxis] - swarm), axis=-1))\n triu = dmat[np.triu_indices_from(dmat, 1)]\n assert_array_less(d, triu)\n assert_array_equal(y, swarm[:, 1])"},{"col":4,"comment":"null","endLoc":3482,"header":"def test_add_gutters(self)","id":4899,"name":"test_add_gutters","nodeType":"Function","startLoc":3471,"text":"def test_add_gutters(self):\n\n p = Beeswarm(width=1)\n\n points = np.zeros(10)\n assert_array_equal(points, p.add_gutters(points, 0))\n\n points = np.array([0, -1, .4, .8])\n msg = r\"50.0% of the points cannot be placed.+$\"\n with pytest.warns(UserWarning, match=msg):\n new_points = p.add_gutters(points, 0)\n assert_array_equal(new_points, np.array([0, -.5, .4, .5]))"},{"attributeType":"null","col":16,"comment":"null","endLoc":5,"id":4900,"name":"np","nodeType":"Attribute","startLoc":5,"text":"np"},{"attributeType":"null","col":17,"comment":"null","endLoc":6,"id":4901,"name":"pd","nodeType":"Attribute","startLoc":6,"text":"pd"},{"attributeType":"null","col":21,"comment":"null","endLoc":7,"id":4902,"name":"mpl","nodeType":"Attribute","startLoc":7,"text":"mpl"},{"attributeType":"null","col":28,"comment":"null","endLoc":8,"id":4903,"name":"plt","nodeType":"Attribute","startLoc":8,"text":"plt"},{"attributeType":"null","col":24,"comment":"null","endLoc":13,"id":4904,"name":"npt","nodeType":"Attribute","startLoc":13,"text":"npt"},{"attributeType":"null","col":35,"comment":"null","endLoc":19,"id":4905,"name":"cat","nodeType":"Attribute","startLoc":19,"text":"cat"},{"attributeType":"list","col":0,"comment":"null","endLoc":37,"id":4906,"name":"PLOT_FUNCS","nodeType":"Attribute","startLoc":37,"text":"PLOT_FUNCS"},{"col":0,"comment":"","endLoc":1,"header":"test_categorical.py#","id":4907,"name":"","nodeType":"Function","startLoc":1,"text":"PLOT_FUNCS = [\n catplot,\n stripplot,\n swarmplot,\n]"}]} \ No newline at end of file